r11770: BUG 2718: don't use qpathinfo_basic() call when remote server is Win9x or...
[sfrench/samba-autobuild/.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    Copyright (C) Gerald (Jerry) Carter    2004
8    
9    This program is free software; you can redistribute it and/or modify
10    it under the terms of the GNU General Public License as published by
11    the Free Software Foundation; either version 2 of the License, or
12    (at your option) any later version.
13    
14    This program is distributed in the hope that it will be useful,
15    but WITHOUT ANY WARRANTY; without even the implied warranty of
16    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17    GNU General Public License for more details.
18    
19    You should have received a copy of the GNU General Public License
20    along with this program; if not, write to the Free Software
21    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
22 */
23
24 #include "includes.h"
25 #include "client/client_proto.h"
26 #ifndef REGISTER
27 #define REGISTER 0
28 #endif
29
30 extern BOOL AllowDebugChange;
31 extern BOOL override_logfile;
32 extern char tar_type;
33 extern BOOL in_client;
34 static int port = 0;
35 pstring cur_dir = "\\";
36 static pstring cd_path = "";
37 static pstring service;
38 static pstring desthost;
39 static pstring username;
40 static pstring calling_name;
41 static BOOL grepable=False;
42 static char *cmdstr = NULL;
43
44 static int io_bufsize = 64512;
45
46 static int name_type = 0x20;
47 extern int max_protocol;
48
49 static int process_tok(pstring 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 static BOOL have_ip;
64
65 /* clitar bits insert */
66 extern int blocksize;
67 extern BOOL tar_inc;
68 extern BOOL tar_reset;
69 /* clitar bits end */
70  
71
72 static BOOL prompt = True;
73
74 static BOOL recurse = False;
75 BOOL lowercase = False;
76
77 static struct in_addr dest_ip;
78
79 #define SEPARATORS " \t\n\r"
80
81 static BOOL abort_mget = True;
82
83 static pstring fileselection = "";
84
85 extern file_info def_finfo;
86
87 /* timing globals */
88 SMB_BIG_UINT get_total_size = 0;
89 unsigned int get_total_time_ms = 0;
90 static SMB_BIG_UINT put_total_size = 0;
91 static unsigned int put_total_time_ms = 0;
92
93 /* totals globals */
94 static double dir_total;
95
96 /* root cli_state connection */
97
98 struct cli_state *cli;
99
100
101
102 /****************************************************************************
103  Write to a local file with CR/LF->LF translation if appropriate. Return the 
104  number taken from the buffer. This may not equal the number written.
105 ****************************************************************************/
106
107 static int writefile(int f, char *b, int n)
108 {
109         int i;
110
111         if (!translation) {
112                 return write(f,b,n);
113         }
114
115         i = 0;
116         while (i < n) {
117                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
118                         b++;i++;
119                 }
120                 if (write(f, b, 1) != 1) {
121                         break;
122                 }
123                 b++;
124                 i++;
125         }
126   
127         return(i);
128 }
129
130 /****************************************************************************
131  Read from a file with LF->CR/LF translation if appropriate. Return the 
132  number read. read approx n bytes.
133 ****************************************************************************/
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  Send a message.
161 ****************************************************************************/
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  Check the space on a device.
211 ****************************************************************************/
212
213 static int do_dskattr(void)
214 {
215         int total, bsize, avail;
216         struct cli_state *targetcli;
217         pstring targetpath;
218
219         if ( !cli_resolve_path( "", cli, cur_dir, &targetcli, targetpath ) ) {
220                 d_printf("Error in dskattr: %s\n", cli_errstr(cli));
221                 return 1;
222         }
223
224         if (!cli_dskattr(targetcli, &bsize, &total, &avail)) {
225                 d_printf("Error in dskattr: %s\n",cli_errstr(targetcli)); 
226                 return 1;
227         }
228
229         d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
230                  total, bsize, avail);
231
232         return 0;
233 }
234
235 /****************************************************************************
236  Show cd/pwd.
237 ****************************************************************************/
238
239 static int cmd_pwd(void)
240 {
241         d_printf("Current directory is %s",service);
242         d_printf("%s\n",cur_dir);
243         return 0;
244 }
245
246 /****************************************************************************
247  Change directory - inner section.
248 ****************************************************************************/
249
250 static int do_cd(char *newdir)
251 {
252         char *p = newdir;
253         pstring saved_dir;
254         pstring dname;
255         pstring targetpath;
256         struct cli_state *targetcli;
257         SMB_STRUCT_STAT sbuf;
258         uint32 attributes;
259         int ret = 1;
260       
261         dos_format(newdir);
262
263         /* Save the current directory in case the new directory is invalid */
264
265         pstrcpy(saved_dir, cur_dir);
266
267         if (*p == '\\')
268                 pstrcpy(cur_dir,p);
269         else
270                 pstrcat(cur_dir,p);
271
272         if (*(cur_dir+strlen(cur_dir)-1) != '\\') {
273                 pstrcat(cur_dir, "\\");
274         }
275         
276         dos_clean_name(cur_dir);
277         pstrcpy( dname, cur_dir );
278         pstrcat(cur_dir,"\\");
279         dos_clean_name(cur_dir);
280         
281         if ( !cli_resolve_path( "", cli, dname, &targetcli, targetpath ) ) {
282                 d_printf("cd %s: %s\n", dname, cli_errstr(cli));
283                 pstrcpy(cur_dir,saved_dir);
284                 goto out;
285         }
286
287         
288         if ( strequal(targetpath,"\\" ) )
289                 return 0;   
290                 
291         /* Use a trans2_qpathinfo to test directories for modern servers.
292            Except Win9x doesn't support the qpathinfo_basic() call..... */ 
293         
294         if ( targetcli->protocol >= PROTOCOL_LANMAN2 && !targetcli->win95 ) {
295                 if ( !cli_qpathinfo_basic( targetcli, targetpath, &sbuf, &attributes ) ) {
296                         d_printf("cd %s: %s\n", dname, cli_errstr(targetcli));
297                         pstrcpy(cur_dir,saved_dir);
298                         goto out;
299                 }
300                 
301                 if ( !(attributes&FILE_ATTRIBUTE_DIRECTORY) ) {
302                         d_printf("cd %s: not a directory\n", dname);
303                         pstrcpy(cur_dir,saved_dir);
304                         goto out;
305                 }               
306         } else {
307                 pstrcat( targetpath, "\\" );
308                 dos_clean_name( targetpath );
309                 
310                 if ( !cli_chkpath(targetcli, targetpath) ) {
311                         d_printf("cd %s: %s\n", dname, cli_errstr(targetcli));
312                         pstrcpy(cur_dir,saved_dir);
313                         goto out;
314                 }
315         }
316
317         ret = 0;
318
319 out:
320         
321         pstrcpy(cd_path,cur_dir);
322         return ret;
323 }
324
325 /****************************************************************************
326  Change directory.
327 ****************************************************************************/
328
329 static int cmd_cd(void)
330 {
331         pstring buf;
332         int rc = 0;
333                 
334         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
335                 rc = do_cd(buf);
336         else
337                 d_printf("Current directory is %s\n",cur_dir);
338
339         return rc;
340 }
341
342 /*******************************************************************
343  Decide if a file should be operated on.
344 ********************************************************************/
345
346 static BOOL do_this_one(file_info *finfo)
347 {
348         if (finfo->mode & aDIR)
349                 return(True);
350
351         if (*fileselection && 
352             !mask_match(finfo->name,fileselection,False)) {
353                 DEBUG(3,("mask_match %s failed\n", finfo->name));
354                 return False;
355         }
356
357         if (newer_than && finfo->mtime < newer_than) {
358                 DEBUG(3,("newer_than %s failed\n", finfo->name));
359                 return(False);
360         }
361
362         if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
363                 DEBUG(3,("archive %s failed\n", finfo->name));
364                 return(False);
365         }
366         
367         return(True);
368 }
369
370 /****************************************************************************
371  Display info about a file.
372 ****************************************************************************/
373
374 static void display_finfo(file_info *finfo)
375 {
376         if (do_this_one(finfo)) {
377                 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
378                 d_printf("  %-30s%7.7s %8.0f  %s",
379                          finfo->name,
380                          attrib_string(finfo->mode),
381                          (double)finfo->size,
382                          asctime(localtime(&t)));
383                 dir_total += finfo->size;
384         }
385 }
386
387 /****************************************************************************
388  Accumulate size of a file.
389 ****************************************************************************/
390
391 static void do_du(file_info *finfo)
392 {
393         if (do_this_one(finfo)) {
394                 dir_total += finfo->size;
395         }
396 }
397
398 static BOOL do_list_recurse;
399 static BOOL do_list_dirs;
400 static char *do_list_queue = 0;
401 static long do_list_queue_size = 0;
402 static long do_list_queue_start = 0;
403 static long do_list_queue_end = 0;
404 static void (*do_list_fn)(file_info *);
405
406 /****************************************************************************
407  Functions for do_list_queue.
408 ****************************************************************************/
409
410 /*
411  * The do_list_queue is a NUL-separated list of strings stored in a
412  * char*.  Since this is a FIFO, we keep track of the beginning and
413  * ending locations of the data in the queue.  When we overflow, we
414  * double the size of the char*.  When the start of the data passes
415  * the midpoint, we move everything back.  This is logically more
416  * complex than a linked list, but easier from a memory management
417  * angle.  In any memory error condition, do_list_queue is reset.
418  * Functions check to ensure that do_list_queue is non-NULL before
419  * accessing it.
420  */
421
422 static void reset_do_list_queue(void)
423 {
424         SAFE_FREE(do_list_queue);
425         do_list_queue_size = 0;
426         do_list_queue_start = 0;
427         do_list_queue_end = 0;
428 }
429
430 static void init_do_list_queue(void)
431 {
432         reset_do_list_queue();
433         do_list_queue_size = 1024;
434         do_list_queue = SMB_MALLOC(do_list_queue_size);
435         if (do_list_queue == 0) { 
436                 d_printf("malloc fail for size %d\n",
437                          (int)do_list_queue_size);
438                 reset_do_list_queue();
439         } else {
440                 memset(do_list_queue, 0, do_list_queue_size);
441         }
442 }
443
444 static void adjust_do_list_queue(void)
445 {
446         /*
447          * If the starting point of the queue is more than half way through,
448          * move everything toward the beginning.
449          */
450         if (do_list_queue && (do_list_queue_start == do_list_queue_end)) {
451                 DEBUG(4,("do_list_queue is empty\n"));
452                 do_list_queue_start = do_list_queue_end = 0;
453                 *do_list_queue = '\0';
454         } else if (do_list_queue_start > (do_list_queue_size / 2)) {
455                 DEBUG(4,("sliding do_list_queue backward\n"));
456                 memmove(do_list_queue,
457                         do_list_queue + do_list_queue_start,
458                         do_list_queue_end - do_list_queue_start);
459                 do_list_queue_end -= do_list_queue_start;
460                 do_list_queue_start = 0;
461         }
462 }
463
464 static void add_to_do_list_queue(const char* entry)
465 {
466         char *dlq;
467         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
468         while (new_end > do_list_queue_size) {
469                 do_list_queue_size *= 2;
470                 DEBUG(4,("enlarging do_list_queue to %d\n",
471                          (int)do_list_queue_size));
472                 dlq = SMB_REALLOC(do_list_queue, do_list_queue_size);
473                 if (! dlq) {
474                         d_printf("failure enlarging do_list_queue to %d bytes\n",
475                                  (int)do_list_queue_size);
476                         reset_do_list_queue();
477                 } else {
478                         do_list_queue = dlq;
479                         memset(do_list_queue + do_list_queue_size / 2,
480                                0, do_list_queue_size / 2);
481                 }
482         }
483         if (do_list_queue) {
484                 safe_strcpy_base(do_list_queue + do_list_queue_end, 
485                                  entry, do_list_queue, do_list_queue_size);
486                 do_list_queue_end = new_end;
487                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
488                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
489         }
490 }
491
492 static char *do_list_queue_head(void)
493 {
494         return do_list_queue + do_list_queue_start;
495 }
496
497 static void remove_do_list_queue_head(void)
498 {
499         if (do_list_queue_end > do_list_queue_start) {
500                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
501                 adjust_do_list_queue();
502                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
503                          (int)do_list_queue_start, (int)do_list_queue_end));
504         }
505 }
506
507 static int do_list_queue_empty(void)
508 {
509         return (! (do_list_queue && *do_list_queue));
510 }
511
512 /****************************************************************************
513  A helper for do_list.
514 ****************************************************************************/
515
516 static void do_list_helper(const char *mntpoint, file_info *f, const char *mask, void *state)
517 {
518         char *dir_end;
519
520         /* save the directory */
521         pstrcpy( f->dir, mask );
522         if ( (dir_end = strrchr( f->dir, '\\' )) != NULL ) {
523                 *dir_end = '\0';
524         }
525
526         if (f->mode & aDIR) {
527                 if (do_list_dirs && do_this_one(f)) {
528                         do_list_fn(f);
529                 }
530                 if (do_list_recurse && 
531                     !strequal(f->name,".") && 
532                     !strequal(f->name,"..")) {
533                         pstring mask2;
534                         char *p;
535
536                         if (!f->name[0]) {
537                                 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
538                                 return;
539                         }
540
541                         pstrcpy(mask2, mntpoint);
542                         pstrcat(mask2, mask);
543                         p = strrchr_m(mask2,'\\');
544                         if (!p)
545                                 return;
546                         p[1] = 0;
547                         pstrcat(mask2, f->name);
548                         pstrcat(mask2,"\\*");
549                         add_to_do_list_queue(mask2);
550                 }
551                 return;
552         }
553
554         if (do_this_one(f)) {
555                 do_list_fn(f);
556         }
557 }
558
559 /****************************************************************************
560  A wrapper around cli_list that adds recursion.
561 ****************************************************************************/
562
563 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
564 {
565         static int in_do_list = 0;
566         struct cli_state *targetcli;
567         pstring targetpath;
568
569         if (in_do_list && rec) {
570                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
571                 exit(1);
572         }
573
574         in_do_list = 1;
575
576         do_list_recurse = rec;
577         do_list_dirs = dirs;
578         do_list_fn = fn;
579
580         if (rec) {
581                 init_do_list_queue();
582                 add_to_do_list_queue(mask);
583                 
584                 while (! do_list_queue_empty()) {
585                         /*
586                          * Need to copy head so that it doesn't become
587                          * invalid inside the call to cli_list.  This
588                          * would happen if the list were expanded
589                          * during the call.
590                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
591                          */
592                         pstring head;
593                         pstrcpy(head, do_list_queue_head());
594                         
595                         /* check for dfs */
596                         
597                         if ( !cli_resolve_path( "", cli, head, &targetcli, targetpath ) ) {
598                                 d_printf("do_list: [%s] %s\n", head, cli_errstr(cli));
599                                 remove_do_list_queue_head();
600                                 continue;
601                         }
602                         
603                         cli_list(targetcli, targetpath, attribute, do_list_helper, NULL);
604                         remove_do_list_queue_head();
605                         if ((! do_list_queue_empty()) && (fn == display_finfo)) {
606                                 char* next_file = do_list_queue_head();
607                                 char* save_ch = 0;
608                                 if ((strlen(next_file) >= 2) &&
609                                     (next_file[strlen(next_file) - 1] == '*') &&
610                                     (next_file[strlen(next_file) - 2] == '\\')) {
611                                         save_ch = next_file +
612                                                 strlen(next_file) - 2;
613                                         *save_ch = '\0';
614                                 }
615                                 d_printf("\n%s\n",next_file);
616                                 if (save_ch) {
617                                         *save_ch = '\\';
618                                 }
619                         }
620                 }
621         } else {
622                 /* check for dfs */
623                         
624                 if ( cli_resolve_path( "", cli, mask, &targetcli, targetpath ) ) {
625                         if (cli_list(targetcli, targetpath, attribute, do_list_helper, NULL) == -1) 
626                                 d_printf("%s listing %s\n", cli_errstr(targetcli), targetpath);
627                 }
628                 else
629                         d_printf("do_list: [%s] %s\n", mask, cli_errstr(cli));
630                 
631         }
632
633         in_do_list = 0;
634         reset_do_list_queue();
635 }
636
637 /****************************************************************************
638  Get a directory listing.
639 ****************************************************************************/
640
641 static int cmd_dir(void)
642 {
643         uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
644         pstring mask;
645         pstring buf;
646         char *p=buf;
647         int rc;
648         
649         dir_total = 0;
650         if (strcmp(cur_dir, "\\") != 0) {
651                 pstrcpy(mask,cur_dir);
652                 if(mask[strlen(mask)-1]!='\\')
653                         pstrcat(mask,"\\");
654         } else {
655                 pstrcpy(mask, "\\");
656         }
657         
658         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
659                 dos_format(p);
660                 if (*p == '\\')
661                         pstrcpy(mask,p + 1);
662                 else
663                         pstrcat(mask,p);
664         } else {
665                 pstrcat(mask,"*");
666         }
667
668         do_list(mask, attribute, display_finfo, recurse, True);
669
670         rc = do_dskattr();
671
672         DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
673
674         return rc;
675 }
676
677 /****************************************************************************
678  Get a directory listing.
679 ****************************************************************************/
680
681 static int cmd_du(void)
682 {
683         uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
684         pstring mask;
685         pstring buf;
686         char *p=buf;
687         int rc;
688         
689         dir_total = 0;
690         pstrcpy(mask,cur_dir);
691         if(mask[strlen(mask)-1]!='\\')
692                 pstrcat(mask,"\\");
693         
694         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
695                 dos_format(p);
696                 if (*p == '\\')
697                         pstrcpy(mask,p);
698                 else
699                         pstrcat(mask,p);
700         } else {
701                 pstrcat(mask,"*");
702         }
703
704         do_list(mask, attribute, do_du, recurse, True);
705
706         rc = do_dskattr();
707
708         d_printf("Total number of bytes: %.0f\n", dir_total);
709
710         return rc;
711 }
712
713 /****************************************************************************
714  Get a file from rname to lname
715 ****************************************************************************/
716
717 static int do_get(char *rname, char *lname, BOOL reget)
718 {  
719         int handle = 0, fnum;
720         BOOL newhandle = False;
721         char *data;
722         struct timeval tp_start;
723         int read_size = io_bufsize;
724         uint16 attr;
725         SMB_OFF_T size;
726         off_t start = 0;
727         off_t nread = 0;
728         int rc = 0;
729         struct cli_state *targetcli;
730         pstring targetname;
731
732
733         if (lowercase) {
734                 strlower_m(lname);
735         }
736
737         if ( !cli_resolve_path( "", cli, rname, &targetcli, targetname ) ) {
738                 d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
739                 return 1;
740         }
741
742         GetTimeOfDay(&tp_start);
743         
744         if ( targetcli->dfsroot ) {
745                 pstring path;
746
747                 /* we need to refer to the full \server\share\path format 
748                    for dfs shares */
749
750                 pstrcpy( path, targetname );
751                 cli_dfs_make_full_path( targetname, targetcli->desthost, 
752                         targetcli->share, path);
753         }
754
755         fnum = cli_open(targetcli, targetname, O_RDONLY, DENY_NONE);
756
757         if (fnum == -1) {
758                 d_printf("%s opening remote file %s\n",cli_errstr(cli),rname);
759                 return 1;
760         }
761
762         if(!strcmp(lname,"-")) {
763                 handle = fileno(stdout);
764         } else {
765                 if (reget) {
766                         handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
767                         if (handle >= 0) {
768                                 start = sys_lseek(handle, 0, SEEK_END);
769                                 if (start == -1) {
770                                         d_printf("Error seeking local file\n");
771                                         return 1;
772                                 }
773                         }
774                 } else {
775                         handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
776                 }
777                 newhandle = True;
778         }
779         if (handle < 0) {
780                 d_printf("Error opening local file %s\n",lname);
781                 return 1;
782         }
783
784
785         if (!cli_qfileinfo(targetcli, fnum, 
786                            &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
787             !cli_getattrE(targetcli, fnum, 
788                           &attr, &size, NULL, NULL, NULL)) {
789                 d_printf("getattrib: %s\n",cli_errstr(targetcli));
790                 return 1;
791         }
792
793         DEBUG(1,("getting file %s of size %.0f as %s ", 
794                  rname, (double)size, lname));
795
796         if(!(data = (char *)SMB_MALLOC(read_size))) { 
797                 d_printf("malloc fail for size %d\n", read_size);
798                 cli_close(targetcli, fnum);
799                 return 1;
800         }
801
802         while (1) {
803                 int n = cli_read(targetcli, fnum, data, nread + start, read_size);
804
805                 if (n <= 0)
806                         break;
807  
808                 if (writefile(handle,data, n) != n) {
809                         d_printf("Error writing local file\n");
810                         rc = 1;
811                         break;
812                 }
813       
814                 nread += n;
815         }
816
817         if (nread + start < size) {
818                 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
819                             rname, (long)nread));
820
821                 rc = 1;
822         }
823
824         SAFE_FREE(data);
825         
826         if (!cli_close(targetcli, fnum)) {
827                 d_printf("Error %s closing remote file\n",cli_errstr(cli));
828                 rc = 1;
829         }
830
831         if (newhandle) {
832                 close(handle);
833         }
834
835         if (archive_level >= 2 && (attr & aARCH)) {
836                 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
837         }
838
839         {
840                 struct timeval tp_end;
841                 int this_time;
842                 
843                 GetTimeOfDay(&tp_end);
844                 this_time = 
845                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
846                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
847                 get_total_time_ms += this_time;
848                 get_total_size += nread;
849                 
850                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
851                          nread / (1.024*this_time + 1.0e-4),
852                          get_total_size / (1.024*get_total_time_ms)));
853         }
854         
855         return rc;
856 }
857
858 /****************************************************************************
859  Get a file.
860 ****************************************************************************/
861
862 static int cmd_get(void)
863 {
864         pstring lname;
865         pstring rname;
866         char *p;
867
868         pstrcpy(rname,cur_dir);
869         pstrcat(rname,"\\");
870         
871         p = rname + strlen(rname);
872         
873         if (!next_token_nr(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
874                 d_printf("get <filename>\n");
875                 return 1;
876         }
877         pstrcpy(lname,p);
878         dos_clean_name(rname);
879         
880         next_token_nr(NULL,lname,NULL,sizeof(lname));
881         
882         return do_get(rname, lname, False);
883 }
884
885 /****************************************************************************
886  Do an mget operation on one file.
887 ****************************************************************************/
888
889 static void do_mget(file_info *finfo)
890 {
891         pstring rname;
892         pstring quest;
893         pstring saved_curdir;
894         pstring mget_mask;
895
896         if (strequal(finfo->name,".") || strequal(finfo->name,".."))
897                 return;
898
899         if (abort_mget) {
900                 d_printf("mget aborted\n");
901                 return;
902         }
903
904         if (finfo->mode & aDIR)
905                 slprintf(quest,sizeof(pstring)-1,
906                          "Get directory %s? ",finfo->name);
907         else
908                 slprintf(quest,sizeof(pstring)-1,
909                          "Get file %s? ",finfo->name);
910
911         if (prompt && !yesno(quest))
912                 return;
913
914         if (!(finfo->mode & aDIR)) {
915                 pstrcpy(rname,cur_dir);
916                 pstrcat(rname,finfo->name);
917                 do_get(rname, finfo->name, False);
918                 return;
919         }
920
921         /* handle directories */
922         pstrcpy(saved_curdir,cur_dir);
923
924         pstrcat(cur_dir,finfo->name);
925         pstrcat(cur_dir,"\\");
926
927         unix_format(finfo->name);
928         if (lowercase)
929                 strlower_m(finfo->name);
930         
931         if (!directory_exist(finfo->name,NULL) && 
932             mkdir(finfo->name,0777) != 0) {
933                 d_printf("failed to create directory %s\n",finfo->name);
934                 pstrcpy(cur_dir,saved_curdir);
935                 return;
936         }
937         
938         if (chdir(finfo->name) != 0) {
939                 d_printf("failed to chdir to directory %s\n",finfo->name);
940                 pstrcpy(cur_dir,saved_curdir);
941                 return;
942         }
943
944         pstrcpy(mget_mask,cur_dir);
945         pstrcat(mget_mask,"*");
946         
947         do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,False, True);
948         chdir("..");
949         pstrcpy(cur_dir,saved_curdir);
950 }
951
952 /****************************************************************************
953  View the file using the pager.
954 ****************************************************************************/
955
956 static int cmd_more(void)
957 {
958         pstring rname,lname,pager_cmd;
959         char *pager;
960         int fd;
961         int rc = 0;
962
963         pstrcpy(rname,cur_dir);
964         pstrcat(rname,"\\");
965         
966         slprintf(lname,sizeof(lname)-1, "%s/smbmore.XXXXXX",tmpdir());
967         fd = smb_mkstemp(lname);
968         if (fd == -1) {
969                 d_printf("failed to create temporary file for more\n");
970                 return 1;
971         }
972         close(fd);
973
974         if (!next_token_nr(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
975                 d_printf("more <filename>\n");
976                 unlink(lname);
977                 return 1;
978         }
979         dos_clean_name(rname);
980
981         rc = do_get(rname, lname, False);
982
983         pager=getenv("PAGER");
984
985         slprintf(pager_cmd,sizeof(pager_cmd)-1,
986                  "%s %s",(pager? pager:PAGER), lname);
987         system(pager_cmd);
988         unlink(lname);
989         
990         return rc;
991 }
992
993 /****************************************************************************
994  Do a mget command.
995 ****************************************************************************/
996
997 static int cmd_mget(void)
998 {
999         uint16 attribute = aSYSTEM | aHIDDEN;
1000         pstring mget_mask;
1001         pstring buf;
1002         char *p=buf;
1003
1004         *mget_mask = 0;
1005
1006         if (recurse)
1007                 attribute |= aDIR;
1008         
1009         abort_mget = False;
1010
1011         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1012                 pstrcpy(mget_mask,cur_dir);
1013                 if(mget_mask[strlen(mget_mask)-1]!='\\')
1014                         pstrcat(mget_mask,"\\");
1015                 
1016                 if (*p == '\\')
1017                         pstrcpy(mget_mask,p);
1018                 else
1019                         pstrcat(mget_mask,p);
1020                 do_list(mget_mask, attribute,do_mget,False,True);
1021         }
1022
1023         if (!*mget_mask) {
1024                 pstrcpy(mget_mask,cur_dir);
1025                 if(mget_mask[strlen(mget_mask)-1]!='\\')
1026                         pstrcat(mget_mask,"\\");
1027                 pstrcat(mget_mask,"*");
1028                 do_list(mget_mask, attribute,do_mget,False,True);
1029         }
1030         
1031         return 0;
1032 }
1033
1034 /****************************************************************************
1035  Make a directory of name "name".
1036 ****************************************************************************/
1037
1038 static BOOL do_mkdir(char *name)
1039 {
1040         struct cli_state *targetcli;
1041         pstring targetname;
1042         
1043         if ( !cli_resolve_path( "", cli, name, &targetcli, targetname ) ) {
1044                 d_printf("mkdir %s: %s\n", name, cli_errstr(cli));
1045                 return False;
1046         }
1047
1048         if (!cli_mkdir(targetcli, targetname)) {
1049                 d_printf("%s making remote directory %s\n",
1050                          cli_errstr(targetcli),name);
1051                 return(False);
1052         }
1053
1054         return(True);
1055 }
1056
1057 /****************************************************************************
1058  Show 8.3 name of a file.
1059 ****************************************************************************/
1060
1061 static BOOL do_altname(char *name)
1062 {
1063         pstring altname;
1064         if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
1065                 d_printf("%s getting alt name for %s\n",
1066                          cli_errstr(cli),name);
1067                 return(False);
1068         }
1069         d_printf("%s\n", altname);
1070
1071         return(True);
1072 }
1073
1074 /****************************************************************************
1075  Exit client.
1076 ****************************************************************************/
1077
1078 static int cmd_quit(void)
1079 {
1080         cli_cm_shutdown();
1081         exit(0);
1082         /* NOTREACHED */
1083         return 0;
1084 }
1085
1086 /****************************************************************************
1087  Make a directory.
1088 ****************************************************************************/
1089
1090 static int cmd_mkdir(void)
1091 {
1092         pstring mask;
1093         pstring buf;
1094         char *p=buf;
1095   
1096         pstrcpy(mask,cur_dir);
1097
1098         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1099                 if (!recurse)
1100                         d_printf("mkdir <dirname>\n");
1101                 return 1;
1102         }
1103         pstrcat(mask,p);
1104
1105         if (recurse) {
1106                 pstring ddir;
1107                 pstring ddir2;
1108                 *ddir2 = 0;
1109                 
1110                 pstrcpy(ddir,mask);
1111                 trim_char(ddir,'.','\0');
1112                 p = strtok(ddir,"/\\");
1113                 while (p) {
1114                         pstrcat(ddir2,p);
1115                         if (!cli_chkpath(cli, ddir2)) { 
1116                                 do_mkdir(ddir2);
1117                         }
1118                         pstrcat(ddir2,"\\");
1119                         p = strtok(NULL,"/\\");
1120                 }        
1121         } else {
1122                 do_mkdir(mask);
1123         }
1124         
1125         return 0;
1126 }
1127
1128 /****************************************************************************
1129  Show alt name.
1130 ****************************************************************************/
1131
1132 static int cmd_altname(void)
1133 {
1134         pstring name;
1135         pstring buf;
1136         char *p=buf;
1137   
1138         pstrcpy(name,cur_dir);
1139
1140         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1141                 d_printf("altname <file>\n");
1142                 return 1;
1143         }
1144         pstrcat(name,p);
1145
1146         do_altname(name);
1147
1148         return 0;
1149 }
1150
1151 /****************************************************************************
1152  Put a single file.
1153 ****************************************************************************/
1154
1155 static int do_put(char *rname, char *lname, BOOL reput)
1156 {
1157         int fnum;
1158         XFILE *f;
1159         SMB_OFF_T start = 0;
1160         off_t nread = 0;
1161         char *buf = NULL;
1162         int maxwrite = io_bufsize;
1163         int rc = 0;
1164         struct timeval tp_start;
1165         struct cli_state *targetcli;
1166         pstring targetname;
1167         
1168         if ( !cli_resolve_path( "", cli, rname, &targetcli, targetname ) ) {
1169                 d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
1170                 return 1;
1171         }
1172         
1173         GetTimeOfDay(&tp_start);
1174
1175         if (reput) {
1176                 fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT, DENY_NONE);
1177                 if (fnum >= 0) {
1178                         if (!cli_qfileinfo(targetcli, fnum, NULL, &start, NULL, NULL, NULL, NULL, NULL) &&
1179                             !cli_getattrE(targetcli, fnum, NULL, &start, NULL, NULL, NULL)) {
1180                                 d_printf("getattrib: %s\n",cli_errstr(cli));
1181                                 return 1;
1182                         }
1183                 }
1184         } else {
1185                 fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
1186         }
1187   
1188         if (fnum == -1) {
1189                 d_printf("%s opening remote file %s\n",cli_errstr(targetcli),rname);
1190                 return 1;
1191         }
1192
1193         /* allow files to be piped into smbclient
1194            jdblair 24.jun.98
1195
1196            Note that in this case this function will exit(0) rather
1197            than returning. */
1198         if (!strcmp(lname, "-")) {
1199                 f = x_stdin;
1200                 /* size of file is not known */
1201         } else {
1202                 f = x_fopen(lname,O_RDONLY, 0);
1203                 if (f && reput) {
1204                         if (x_tseek(f, start, SEEK_SET) == -1) {
1205                                 d_printf("Error seeking local file\n");
1206                                 return 1;
1207                         }
1208                 }
1209         }
1210
1211         if (!f) {
1212                 d_printf("Error opening local file %s\n",lname);
1213                 return 1;
1214         }
1215   
1216         DEBUG(1,("putting file %s as %s ",lname,
1217                  rname));
1218   
1219         buf = (char *)SMB_MALLOC(maxwrite);
1220         if (!buf) {
1221                 d_printf("ERROR: Not enough memory!\n");
1222                 return 1;
1223         }
1224         while (!x_feof(f)) {
1225                 int n = maxwrite;
1226                 int ret;
1227
1228                 if ((n = readfile(buf,n,f)) < 1) {
1229                         if((n == 0) && x_feof(f))
1230                                 break; /* Empty local file. */
1231
1232                         d_printf("Error reading local file: %s\n", strerror(errno));
1233                         rc = 1;
1234                         break;
1235                 }
1236
1237                 ret = cli_write(targetcli, fnum, 0, buf, nread + start, n);
1238
1239                 if (n != ret) {
1240                         d_printf("Error writing file: %s\n", cli_errstr(cli));
1241                         rc = 1;
1242                         break;
1243                 } 
1244
1245                 nread += n;
1246         }
1247
1248         if (!cli_close(targetcli, fnum)) {
1249                 d_printf("%s closing remote file %s\n",cli_errstr(cli),rname);
1250                 x_fclose(f);
1251                 SAFE_FREE(buf);
1252                 return 1;
1253         }
1254
1255         
1256         if (f != x_stdin) {
1257                 x_fclose(f);
1258         }
1259
1260         SAFE_FREE(buf);
1261
1262         {
1263                 struct timeval tp_end;
1264                 int this_time;
1265                 
1266                 GetTimeOfDay(&tp_end);
1267                 this_time = 
1268                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1269                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
1270                 put_total_time_ms += this_time;
1271                 put_total_size += nread;
1272                 
1273                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1274                          nread / (1.024*this_time + 1.0e-4),
1275                          put_total_size / (1.024*put_total_time_ms)));
1276         }
1277
1278         if (f == x_stdin) {
1279                 cli_cm_shutdown();
1280                 exit(0);
1281         }
1282         
1283         return rc;
1284 }
1285
1286 /****************************************************************************
1287  Put a file.
1288 ****************************************************************************/
1289
1290 static int cmd_put(void)
1291 {
1292         pstring lname;
1293         pstring rname;
1294         pstring buf;
1295         char *p=buf;
1296         
1297         pstrcpy(rname,cur_dir);
1298         pstrcat(rname,"\\");
1299   
1300         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1301                 d_printf("put <filename>\n");
1302                 return 1;
1303         }
1304         pstrcpy(lname,p);
1305   
1306         if (next_token_nr(NULL,p,NULL,sizeof(buf)))
1307                 pstrcat(rname,p);      
1308         else
1309                 pstrcat(rname,lname);
1310         
1311         dos_clean_name(rname);
1312
1313         {
1314                 SMB_STRUCT_STAT st;
1315                 /* allow '-' to represent stdin
1316                    jdblair, 24.jun.98 */
1317                 if (!file_exist(lname,&st) &&
1318                     (strcmp(lname,"-"))) {
1319                         d_printf("%s does not exist\n",lname);
1320                         return 1;
1321                 }
1322         }
1323
1324         return do_put(rname, lname, False);
1325 }
1326
1327 /*************************************
1328  File list structure.
1329 *************************************/
1330
1331 static struct file_list {
1332         struct file_list *prev, *next;
1333         char *file_path;
1334         BOOL isdir;
1335 } *file_list;
1336
1337 /****************************************************************************
1338  Free a file_list structure.
1339 ****************************************************************************/
1340
1341 static void free_file_list (struct file_list * list)
1342 {
1343         struct file_list *tmp;
1344         
1345         while (list) {
1346                 tmp = list;
1347                 DLIST_REMOVE(list, list);
1348                 SAFE_FREE(tmp->file_path);
1349                 SAFE_FREE(tmp);
1350         }
1351 }
1352
1353 /****************************************************************************
1354  Seek in a directory/file list until you get something that doesn't start with
1355  the specified name.
1356 ****************************************************************************/
1357
1358 static BOOL seek_list(struct file_list *list, char *name)
1359 {
1360         while (list) {
1361                 trim_string(list->file_path,"./","\n");
1362                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1363                         return(True);
1364                 }
1365                 list = list->next;
1366         }
1367       
1368         return(False);
1369 }
1370
1371 /****************************************************************************
1372  Set the file selection mask.
1373 ****************************************************************************/
1374
1375 static int cmd_select(void)
1376 {
1377         pstrcpy(fileselection,"");
1378         next_token_nr(NULL,fileselection,NULL,sizeof(fileselection));
1379
1380         return 0;
1381 }
1382
1383 /****************************************************************************
1384   Recursive file matching function act as find
1385   match must be always set to True when calling this function
1386 ****************************************************************************/
1387
1388 static int file_find(struct file_list **list, const char *directory, 
1389                       const char *expression, BOOL match)
1390 {
1391         SMB_STRUCT_DIR *dir;
1392         struct file_list *entry;
1393         struct stat statbuf;
1394         int ret;
1395         char *path;
1396         BOOL isdir;
1397         const char *dname;
1398
1399         dir = sys_opendir(directory);
1400         if (!dir)
1401                 return -1;
1402         
1403         while ((dname = readdirname(dir))) {
1404                 if (!strcmp("..", dname))
1405                         continue;
1406                 if (!strcmp(".", dname))
1407                         continue;
1408                 
1409                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1410                         continue;
1411                 }
1412
1413                 isdir = False;
1414                 if (!match || !gen_fnmatch(expression, dname)) {
1415                         if (recurse) {
1416                                 ret = stat(path, &statbuf);
1417                                 if (ret == 0) {
1418                                         if (S_ISDIR(statbuf.st_mode)) {
1419                                                 isdir = True;
1420                                                 ret = file_find(list, path, expression, False);
1421                                         }
1422                                 } else {
1423                                         d_printf("file_find: cannot stat file %s\n", path);
1424                                 }
1425                                 
1426                                 if (ret == -1) {
1427                                         SAFE_FREE(path);
1428                                         sys_closedir(dir);
1429                                         return -1;
1430                                 }
1431                         }
1432                         entry = SMB_MALLOC_P(struct file_list);
1433                         if (!entry) {
1434                                 d_printf("Out of memory in file_find\n");
1435                                 sys_closedir(dir);
1436                                 return -1;
1437                         }
1438                         entry->file_path = path;
1439                         entry->isdir = isdir;
1440                         DLIST_ADD(*list, entry);
1441                 } else {
1442                         SAFE_FREE(path);
1443                 }
1444         }
1445
1446         sys_closedir(dir);
1447         return 0;
1448 }
1449
1450 /****************************************************************************
1451  mput some files.
1452 ****************************************************************************/
1453
1454 static int cmd_mput(void)
1455 {
1456         pstring buf;
1457         char *p=buf;
1458         
1459         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1460                 int ret;
1461                 struct file_list *temp_list;
1462                 char *quest, *lname, *rname;
1463         
1464                 file_list = NULL;
1465
1466                 ret = file_find(&file_list, ".", p, True);
1467                 if (ret) {
1468                         free_file_list(file_list);
1469                         continue;
1470                 }
1471                 
1472                 quest = NULL;
1473                 lname = NULL;
1474                 rname = NULL;
1475                                 
1476                 for (temp_list = file_list; temp_list; 
1477                      temp_list = temp_list->next) {
1478
1479                         SAFE_FREE(lname);
1480                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1481                                 continue;
1482                         trim_string(lname, "./", "/");
1483                         
1484                         /* check if it's a directory */
1485                         if (temp_list->isdir) {
1486                                 /* if (!recurse) continue; */
1487                                 
1488                                 SAFE_FREE(quest);
1489                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) break;
1490                                 if (prompt && !yesno(quest)) { /* No */
1491                                         /* Skip the directory */
1492                                         lname[strlen(lname)-1] = '/';
1493                                         if (!seek_list(temp_list, lname))
1494                                                 break;              
1495                                 } else { /* Yes */
1496                                         SAFE_FREE(rname);
1497                                         if(asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1498                                         dos_format(rname);
1499                                         if (!cli_chkpath(cli, rname) && 
1500                                             !do_mkdir(rname)) {
1501                                                 DEBUG (0, ("Unable to make dir, skipping..."));
1502                                                 /* Skip the directory */
1503                                                 lname[strlen(lname)-1] = '/';
1504                                                 if (!seek_list(temp_list, lname))
1505                                                         break;
1506                                         }
1507                                 }
1508                                 continue;
1509                         } else {
1510                                 SAFE_FREE(quest);
1511                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) break;
1512                                 if (prompt && !yesno(quest)) /* No */
1513                                         continue;
1514                                 
1515                                 /* Yes */
1516                                 SAFE_FREE(rname);
1517                                 if (asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1518                         }
1519
1520                         dos_format(rname);
1521
1522                         do_put(rname, lname, False);
1523                 }
1524                 free_file_list(file_list);
1525                 SAFE_FREE(quest);
1526                 SAFE_FREE(lname);
1527                 SAFE_FREE(rname);
1528         }
1529
1530         return 0;
1531 }
1532
1533 /****************************************************************************
1534  Cancel a print job.
1535 ****************************************************************************/
1536
1537 static int do_cancel(int job)
1538 {
1539         if (cli_printjob_del(cli, job)) {
1540                 d_printf("Job %d cancelled\n",job);
1541                 return 0;
1542         } else {
1543                 d_printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1544                 return 1;
1545         }
1546 }
1547
1548 /****************************************************************************
1549  Cancel a print job.
1550 ****************************************************************************/
1551
1552 static int cmd_cancel(void)
1553 {
1554         pstring buf;
1555         int job; 
1556
1557         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1558                 d_printf("cancel <jobid> ...\n");
1559                 return 1;
1560         }
1561         do {
1562                 job = atoi(buf);
1563                 do_cancel(job);
1564         } while (next_token_nr(NULL,buf,NULL,sizeof(buf)));
1565         
1566         return 0;
1567 }
1568
1569 /****************************************************************************
1570  Print a file.
1571 ****************************************************************************/
1572
1573 static int cmd_print(void)
1574 {
1575         pstring lname;
1576         pstring rname;
1577         char *p;
1578
1579         if (!next_token_nr(NULL,lname,NULL, sizeof(lname))) {
1580                 d_printf("print <filename>\n");
1581                 return 1;
1582         }
1583
1584         pstrcpy(rname,lname);
1585         p = strrchr_m(rname,'/');
1586         if (p) {
1587                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)sys_getpid());
1588         }
1589
1590         if (strequal(lname,"-")) {
1591                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)sys_getpid());
1592         }
1593
1594         return do_put(rname, lname, False);
1595 }
1596
1597 /****************************************************************************
1598  Show a print queue entry.
1599 ****************************************************************************/
1600
1601 static void queue_fn(struct print_job_info *p)
1602 {
1603         d_printf("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name);
1604 }
1605
1606 /****************************************************************************
1607  Show a print queue.
1608 ****************************************************************************/
1609
1610 static int cmd_queue(void)
1611 {
1612         cli_print_queue(cli, queue_fn);
1613         
1614         return 0;
1615 }
1616
1617 /****************************************************************************
1618  Delete some files.
1619 ****************************************************************************/
1620
1621 static void do_del(file_info *finfo)
1622 {
1623         pstring mask;
1624
1625         pstr_sprintf( mask, "%s\\%s", finfo->dir, finfo->name );
1626
1627         if (finfo->mode & aDIR) 
1628                 return;
1629
1630         if (!cli_unlink(cli, mask)) {
1631                 d_printf("%s deleting remote file %s\n",cli_errstr(cli),mask);
1632         }
1633 }
1634
1635 /****************************************************************************
1636  Delete some files.
1637 ****************************************************************************/
1638
1639 static int cmd_del(void)
1640 {
1641         pstring mask;
1642         pstring buf;
1643         uint16 attribute = aSYSTEM | aHIDDEN;
1644
1645         if (recurse)
1646                 attribute |= aDIR;
1647         
1648         pstrcpy(mask,cur_dir);
1649         
1650         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1651                 d_printf("del <filename>\n");
1652                 return 1;
1653         }
1654         pstrcat(mask,buf);
1655
1656         do_list(mask, attribute,do_del,False,False);
1657         
1658         return 0;
1659 }
1660
1661 /****************************************************************************
1662 ****************************************************************************/
1663
1664 static int cmd_open(void)
1665 {
1666         pstring mask;
1667         pstring buf;
1668         struct cli_state *targetcli;
1669         pstring targetname;
1670         
1671         pstrcpy(mask,cur_dir);
1672         
1673         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1674                 d_printf("open <filename>\n");
1675                 return 1;
1676         }
1677         pstrcat(mask,buf);
1678
1679         if ( !cli_resolve_path( "", cli, mask, &targetcli, targetname ) ) {
1680                 d_printf("open %s: %s\n", mask, cli_errstr(cli));
1681                 return 1;
1682         }
1683         
1684         cli_nt_create(targetcli, targetname, FILE_READ_DATA);
1685
1686         return 0;
1687 }
1688
1689
1690 /****************************************************************************
1691  Remove a directory.
1692 ****************************************************************************/
1693
1694 static int cmd_rmdir(void)
1695 {
1696         pstring mask;
1697         pstring buf;
1698         struct cli_state *targetcli;
1699         pstring targetname;
1700   
1701         pstrcpy(mask,cur_dir);
1702         
1703         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1704                 d_printf("rmdir <dirname>\n");
1705                 return 1;
1706         }
1707         pstrcat(mask,buf);
1708
1709         if ( !cli_resolve_path( "", cli, mask, &targetcli, targetname ) ) {
1710                 d_printf("rmdir %s: %s\n", mask, cli_errstr(cli));
1711                 return 1;
1712         }
1713         
1714         if (!cli_rmdir(targetcli, targetname)) {
1715                 d_printf("%s removing remote directory file %s\n",
1716                          cli_errstr(targetcli),mask);
1717         }
1718         
1719         return 0;
1720 }
1721
1722 /****************************************************************************
1723  UNIX hardlink.
1724 ****************************************************************************/
1725
1726 static int cmd_link(void)
1727 {
1728         pstring oldname,newname;
1729         pstring buf,buf2;
1730         struct cli_state *targetcli;
1731         pstring targetname;
1732   
1733         pstrcpy(oldname,cur_dir);
1734         pstrcpy(newname,cur_dir);
1735   
1736         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1737             !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1738                 d_printf("link <oldname> <newname>\n");
1739                 return 1;
1740         }
1741
1742         pstrcat(oldname,buf);
1743         pstrcat(newname,buf2);
1744
1745         if ( !cli_resolve_path( "", cli, oldname, &targetcli, targetname ) ) {
1746                 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
1747                 return 1;
1748         }
1749         
1750         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
1751                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1752                 return 1;
1753         }
1754         
1755         if (!cli_unix_hardlink(targetcli, targetname, newname)) {
1756                 d_printf("%s linking files (%s -> %s)\n", cli_errstr(targetcli), newname, oldname);
1757                 return 1;
1758         }  
1759
1760         return 0;
1761 }
1762
1763 /****************************************************************************
1764  UNIX symlink.
1765 ****************************************************************************/
1766
1767 static int cmd_symlink(void)
1768 {
1769         pstring oldname,newname;
1770         pstring buf,buf2;
1771   
1772         if (!SERVER_HAS_UNIX_CIFS(cli)) {
1773                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1774                 return 1;
1775         }
1776
1777         pstrcpy(newname,cur_dir);
1778         
1779         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1780             !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1781                 d_printf("symlink <oldname> <newname>\n");
1782                 return 1;
1783         }
1784
1785         pstrcpy(oldname,buf);
1786         pstrcat(newname,buf2);
1787
1788         if (!cli_unix_symlink(cli, oldname, newname)) {
1789                 d_printf("%s symlinking files (%s -> %s)\n",
1790                         cli_errstr(cli), newname, oldname);
1791                 return 1;
1792         } 
1793
1794         return 0;
1795 }
1796
1797 /****************************************************************************
1798  UNIX chmod.
1799 ****************************************************************************/
1800
1801 static int cmd_chmod(void)
1802 {
1803         pstring src;
1804         mode_t mode;
1805         pstring buf, buf2;
1806         struct cli_state *targetcli;
1807         pstring targetname;
1808   
1809         pstrcpy(src,cur_dir);
1810         
1811         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1812             !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1813                 d_printf("chmod mode file\n");
1814                 return 1;
1815         }
1816
1817         mode = (mode_t)strtol(buf, NULL, 8);
1818         pstrcat(src,buf2);
1819
1820         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
1821                 d_printf("chmod %s: %s\n", src, cli_errstr(cli));
1822                 return 1;
1823         }
1824         
1825         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
1826                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1827                 return 1;
1828         }
1829         
1830         if (!cli_unix_chmod(targetcli, targetname, mode)) {
1831                 d_printf("%s chmod file %s 0%o\n",
1832                         cli_errstr(targetcli), src, (unsigned int)mode);
1833                 return 1;
1834         } 
1835
1836         return 0;
1837 }
1838
1839 static const char *filetype_to_str(mode_t mode)
1840 {
1841         if (S_ISREG(mode)) {
1842                 return "regular file";
1843         } else if (S_ISDIR(mode)) {
1844                 return "directory";
1845         } else 
1846 #ifdef S_ISCHR
1847         if (S_ISCHR(mode)) {
1848                 return "character device";
1849         } else
1850 #endif
1851 #ifdef S_ISBLK
1852         if (S_ISBLK(mode)) {
1853                 return "block device";
1854         } else
1855 #endif
1856 #ifdef S_ISFIFO
1857         if (S_ISFIFO(mode)) {
1858                 return "fifo";
1859         } else
1860 #endif
1861 #ifdef S_ISLNK
1862         if (S_ISLNK(mode)) {
1863                 return "symbolic link";
1864         } else
1865 #endif
1866 #ifdef S_ISSOCK
1867         if (S_ISSOCK(mode)) {
1868                 return "socket";
1869         } else
1870 #endif
1871         return "";
1872 }
1873
1874 static char rwx_to_str(mode_t m, mode_t bt, char ret)
1875 {
1876         if (m & bt) {
1877                 return ret;
1878         } else {
1879                 return '-';
1880         }
1881 }
1882
1883 static char *unix_mode_to_str(char *s, mode_t m)
1884 {
1885         char *p = s;
1886         const char *str = filetype_to_str(m);
1887
1888         switch(str[0]) {
1889                 case 'd':
1890                         *p++ = 'd';
1891                         break;
1892                 case 'c':
1893                         *p++ = 'c';
1894                         break;
1895                 case 'b':
1896                         *p++ = 'b';
1897                         break;
1898                 case 'f':
1899                         *p++ = 'p';
1900                         break;
1901                 case 's':
1902                         *p++ = str[1] == 'y' ? 'l' : 's';
1903                         break;
1904                 case 'r':
1905                 default:
1906                         *p++ = '-';
1907                         break;
1908         }
1909         *p++ = rwx_to_str(m, S_IRUSR, 'r');
1910         *p++ = rwx_to_str(m, S_IWUSR, 'w');
1911         *p++ = rwx_to_str(m, S_IXUSR, 'x');
1912         *p++ = rwx_to_str(m, S_IRGRP, 'r');
1913         *p++ = rwx_to_str(m, S_IWGRP, 'w');
1914         *p++ = rwx_to_str(m, S_IXGRP, 'x');
1915         *p++ = rwx_to_str(m, S_IROTH, 'r');
1916         *p++ = rwx_to_str(m, S_IWOTH, 'w');
1917         *p++ = rwx_to_str(m, S_IXOTH, 'x');
1918         *p++ = '\0';
1919         return s;
1920 }
1921
1922 /****************************************************************************
1923  Utility function for UNIX getfacl.
1924 ****************************************************************************/
1925
1926 static char *perms_to_string(fstring permstr, unsigned char perms)
1927 {
1928         fstrcpy(permstr, "---");
1929         if (perms & SMB_POSIX_ACL_READ) {
1930                 permstr[0] = 'r';
1931         }
1932         if (perms & SMB_POSIX_ACL_WRITE) {
1933                 permstr[1] = 'w';
1934         }
1935         if (perms & SMB_POSIX_ACL_EXECUTE) {
1936                 permstr[2] = 'x';
1937         }
1938         return permstr;
1939 }
1940
1941 /****************************************************************************
1942  UNIX getfacl.
1943 ****************************************************************************/
1944
1945 static int cmd_getfacl(void)
1946 {
1947         pstring src, name;
1948         uint16 major, minor;
1949         uint32 caplow, caphigh;
1950         char *retbuf = NULL;
1951         size_t rb_size = 0;
1952         SMB_STRUCT_STAT sbuf;
1953         uint16 num_file_acls = 0;
1954         uint16 num_dir_acls = 0;
1955         uint16 i;
1956         struct cli_state *targetcli;
1957         pstring targetname;
1958  
1959         pstrcpy(src,cur_dir);
1960         
1961         if (!next_token_nr(NULL,name,NULL,sizeof(name))) {
1962                 d_printf("stat file\n");
1963                 return 1;
1964         }
1965
1966         pstrcat(src,name);
1967         
1968         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
1969                 d_printf("stat %s: %s\n", src, cli_errstr(cli));
1970                 return 1;
1971         }
1972         
1973         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
1974                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1975                 return 1;
1976         }
1977         
1978         if (!cli_unix_extensions_version(targetcli, &major, &minor, &caplow, &caphigh)) {
1979                 d_printf("Can't get UNIX CIFS version from server.\n");
1980                 return 1;
1981         }
1982
1983         if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
1984                 d_printf("This server supports UNIX extensions but doesn't support POSIX ACLs.\n");
1985                 return 1;
1986         }
1987
1988
1989         if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
1990                 d_printf("%s getfacl doing a stat on file %s\n",
1991                         cli_errstr(targetcli), src);
1992                 return 1;
1993         } 
1994
1995         if (!cli_unix_getfacl(targetcli, targetname, &rb_size, &retbuf)) {
1996                 d_printf("%s getfacl file %s\n",
1997                         cli_errstr(targetcli), src);
1998                 return 1;
1999         } 
2000
2001         /* ToDo : Print out the ACL values. */
2002         if (SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION || rb_size < 6) {
2003                 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
2004                         src, (unsigned int)CVAL(retbuf,0) );
2005                 SAFE_FREE(retbuf);
2006                 return 1;
2007         }
2008
2009         num_file_acls = SVAL(retbuf,2);
2010         num_dir_acls = SVAL(retbuf,4);
2011         if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
2012                 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
2013                         src,
2014                         (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
2015                         (unsigned int)rb_size);
2016
2017                 SAFE_FREE(retbuf);
2018                 return 1;
2019         }
2020
2021         d_printf("# file: %s\n", src);
2022         d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_uid, (unsigned int)sbuf.st_gid);
2023
2024         if (num_file_acls == 0 && num_dir_acls == 0) {
2025                 d_printf("No acls found.\n");
2026         }
2027
2028         for (i = 0; i < num_file_acls; i++) {
2029                 uint32 uorg;
2030                 fstring permstring;
2031                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
2032                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2033
2034                 switch(tagtype) {
2035                         case SMB_POSIX_ACL_USER_OBJ:
2036                                 d_printf("user::");
2037                                 break;
2038                         case SMB_POSIX_ACL_USER:
2039                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2040                                 d_printf("user:%u:", uorg);
2041                                 break;
2042                         case SMB_POSIX_ACL_GROUP_OBJ:
2043                                 d_printf("group::");
2044                                 break;
2045                         case SMB_POSIX_ACL_GROUP:
2046                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2047                                 d_printf("group:%u", uorg);
2048                                 break;
2049                         case SMB_POSIX_ACL_MASK:
2050                                 d_printf("mask::");
2051                                 break;
2052                         case SMB_POSIX_ACL_OTHER:
2053                                 d_printf("other::");
2054                                 break;
2055                         default:
2056                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2057                                         src, (unsigned int)tagtype );
2058                                 SAFE_FREE(retbuf);
2059                                 return 1;
2060                 }
2061
2062                 d_printf("%s\n", perms_to_string(permstring, perms));
2063         }
2064
2065         for (i = 0; i < num_dir_acls; i++) {
2066                 uint32 uorg;
2067                 fstring permstring;
2068                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
2069                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2070
2071                 switch(tagtype) {
2072                         case SMB_POSIX_ACL_USER_OBJ:
2073                                 d_printf("default:user::");
2074                                 break;
2075                         case SMB_POSIX_ACL_USER:
2076                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2077                                 d_printf("default:user:%u:", uorg);
2078                                 break;
2079                         case SMB_POSIX_ACL_GROUP_OBJ:
2080                                 d_printf("default:group::");
2081                                 break;
2082                         case SMB_POSIX_ACL_GROUP:
2083                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2084                                 d_printf("default:group:%u", uorg);
2085                                 break;
2086                         case SMB_POSIX_ACL_MASK:
2087                                 d_printf("default:mask::");
2088                                 break;
2089                         case SMB_POSIX_ACL_OTHER:
2090                                 d_printf("default:other::");
2091                                 break;
2092                         default:
2093                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2094                                         src, (unsigned int)tagtype );
2095                                 SAFE_FREE(retbuf);
2096                                 return 1;
2097                 }
2098
2099                 d_printf("%s\n", perms_to_string(permstring, perms));
2100         }
2101
2102         SAFE_FREE(retbuf);
2103         return 0;
2104 }
2105
2106 /****************************************************************************
2107  UNIX stat.
2108 ****************************************************************************/
2109
2110 static int cmd_stat(void)
2111 {
2112         pstring src, name;
2113         fstring mode_str;
2114         SMB_STRUCT_STAT sbuf;
2115         struct cli_state *targetcli;
2116         pstring targetname;
2117  
2118         if (!SERVER_HAS_UNIX_CIFS(cli)) {
2119                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2120                 return 1;
2121         }
2122
2123         pstrcpy(src,cur_dir);
2124         
2125         if (!next_token_nr(NULL,name,NULL,sizeof(name))) {
2126                 d_printf("stat file\n");
2127                 return 1;
2128         }
2129
2130         pstrcat(src,name);
2131
2132         
2133         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2134                 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2135                 return 1;
2136         }
2137         
2138         if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2139                 d_printf("%s stat file %s\n",
2140                         cli_errstr(targetcli), src);
2141                 return 1;
2142         } 
2143
2144         /* Print out the stat values. */
2145         d_printf("File: %s\n", src);
2146         d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
2147                 (double)sbuf.st_size,
2148                 (unsigned int)sbuf.st_blocks,
2149                 filetype_to_str(sbuf.st_mode));
2150
2151 #if defined(S_ISCHR) && defined(S_ISBLK)
2152         if (S_ISCHR(sbuf.st_mode) || S_ISBLK(sbuf.st_mode)) {
2153                 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
2154                         (double)sbuf.st_ino,
2155                         (unsigned int)sbuf.st_nlink,
2156                         unix_dev_major(sbuf.st_rdev),
2157                         unix_dev_minor(sbuf.st_rdev));
2158         } else 
2159 #endif
2160                 d_printf("Inode: %.0f\tLinks: %u\n",
2161                         (double)sbuf.st_ino,
2162                         (unsigned int)sbuf.st_nlink);
2163
2164         d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
2165                 ((int)sbuf.st_mode & 0777),
2166                 unix_mode_to_str(mode_str, sbuf.st_mode),
2167                 (unsigned int)sbuf.st_uid, 
2168                 (unsigned int)sbuf.st_gid);
2169
2170         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_atime));
2171         d_printf("Access: %s\n", mode_str);
2172
2173         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_mtime));
2174         d_printf("Modify: %s\n", mode_str);
2175
2176         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_ctime));
2177         d_printf("Change: %s\n", mode_str);
2178         
2179         return 0;
2180 }
2181
2182
2183 /****************************************************************************
2184  UNIX chown.
2185 ****************************************************************************/
2186
2187 static int cmd_chown(void)
2188 {
2189         pstring src;
2190         uid_t uid;
2191         gid_t gid;
2192         pstring buf, buf2, buf3;
2193         struct cli_state *targetcli;
2194         pstring targetname;
2195   
2196         pstrcpy(src,cur_dir);
2197         
2198         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2199             !next_token_nr(NULL,buf2,NULL, sizeof(buf2)) ||
2200             !next_token_nr(NULL,buf3,NULL, sizeof(buf3))) {
2201                 d_printf("chown uid gid file\n");
2202                 return 1;
2203         }
2204
2205         uid = (uid_t)atoi(buf);
2206         gid = (gid_t)atoi(buf2);
2207         pstrcat(src,buf3);
2208
2209         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2210                 d_printf("chown %s: %s\n", src, cli_errstr(cli));
2211                 return 1;
2212         }
2213
2214
2215         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2216                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2217                 return 1;
2218         }
2219         
2220         if (!cli_unix_chown(targetcli, targetname, uid, gid)) {
2221                 d_printf("%s chown file %s uid=%d, gid=%d\n",
2222                         cli_errstr(targetcli), src, (int)uid, (int)gid);
2223                 return 1;
2224         } 
2225
2226         return 0;
2227 }
2228
2229 /****************************************************************************
2230  Rename some file.
2231 ****************************************************************************/
2232
2233 static int cmd_rename(void)
2234 {
2235         pstring src,dest;
2236         pstring buf,buf2;
2237   
2238         pstrcpy(src,cur_dir);
2239         pstrcpy(dest,cur_dir);
2240         
2241         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2242             !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
2243                 d_printf("rename <src> <dest>\n");
2244                 return 1;
2245         }
2246
2247         pstrcat(src,buf);
2248         pstrcat(dest,buf2);
2249
2250         if (!cli_rename(cli, src, dest)) {
2251                 d_printf("%s renaming files\n",cli_errstr(cli));
2252                 return 1;
2253         }
2254         
2255         return 0;
2256 }
2257
2258 /****************************************************************************
2259  Print the volume name.
2260 ****************************************************************************/
2261
2262 static int cmd_volume(void)
2263 {
2264         fstring volname;
2265         uint32 serial_num;
2266         time_t create_date;
2267   
2268         if (!cli_get_fs_volume_info(cli, volname, &serial_num, &create_date)) {
2269                 d_printf("Errr %s getting volume info\n",cli_errstr(cli));
2270                 return 1;
2271         }
2272         
2273         d_printf("Volume: |%s| serial number 0x%x\n", volname, (unsigned int)serial_num);
2274         return 0;
2275 }
2276
2277 /****************************************************************************
2278  Hard link files using the NT call.
2279 ****************************************************************************/
2280
2281 static int cmd_hardlink(void)
2282 {
2283         pstring src,dest;
2284         pstring buf,buf2;
2285         struct cli_state *targetcli;
2286         pstring targetname;
2287   
2288         pstrcpy(src,cur_dir);
2289         pstrcpy(dest,cur_dir);
2290         
2291         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2292             !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
2293                 d_printf("hardlink <src> <dest>\n");
2294                 return 1;
2295         }
2296
2297         pstrcat(src,buf);
2298         pstrcat(dest,buf2);
2299
2300         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2301                 d_printf("hardlink %s: %s\n", src, cli_errstr(cli));
2302                 return 1;
2303         }
2304         
2305         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2306                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2307                 return 1;
2308         }
2309         
2310         if (!cli_nt_hardlink(targetcli, targetname, dest)) {
2311                 d_printf("%s doing an NT hard link of files\n",cli_errstr(targetcli));
2312                 return 1;
2313         }
2314         
2315         return 0;
2316 }
2317
2318 /****************************************************************************
2319  Toggle the prompt flag.
2320 ****************************************************************************/
2321
2322 static int cmd_prompt(void)
2323 {
2324         prompt = !prompt;
2325         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
2326         
2327         return 1;
2328 }
2329
2330 /****************************************************************************
2331  Set the newer than time.
2332 ****************************************************************************/
2333
2334 static int cmd_newer(void)
2335 {
2336         pstring buf;
2337         BOOL ok;
2338         SMB_STRUCT_STAT sbuf;
2339
2340         ok = next_token_nr(NULL,buf,NULL,sizeof(buf));
2341         if (ok && (sys_stat(buf,&sbuf) == 0)) {
2342                 newer_than = sbuf.st_mtime;
2343                 DEBUG(1,("Getting files newer than %s",
2344                          asctime(localtime(&newer_than))));
2345         } else {
2346                 newer_than = 0;
2347         }
2348
2349         if (ok && newer_than == 0) {
2350                 d_printf("Error setting newer-than time\n");
2351                 return 1;
2352         }
2353
2354         return 0;
2355 }
2356
2357 /****************************************************************************
2358  Set the archive level.
2359 ****************************************************************************/
2360
2361 static int cmd_archive(void)
2362 {
2363         pstring buf;
2364
2365         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2366                 archive_level = atoi(buf);
2367         } else
2368                 d_printf("Archive level is %d\n",archive_level);
2369
2370         return 0;
2371 }
2372
2373 /****************************************************************************
2374  Toggle the lowercaseflag.
2375 ****************************************************************************/
2376
2377 static int cmd_lowercase(void)
2378 {
2379         lowercase = !lowercase;
2380         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
2381
2382         return 0;
2383 }
2384
2385 /****************************************************************************
2386  Toggle the case sensitive flag.
2387 ****************************************************************************/
2388
2389 static int cmd_setcase(void)
2390 {
2391         BOOL orig_case_sensitive = cli_set_case_sensitive(cli, False);
2392
2393         cli_set_case_sensitive(cli, !orig_case_sensitive);
2394         DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
2395                 "on":"off"));
2396
2397         return 0;
2398 }
2399
2400 /****************************************************************************
2401  Toggle the recurse flag.
2402 ****************************************************************************/
2403
2404 static int cmd_recurse(void)
2405 {
2406         recurse = !recurse;
2407         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
2408
2409         return 0;
2410 }
2411
2412 /****************************************************************************
2413  Toggle the translate flag.
2414 ****************************************************************************/
2415
2416 static int cmd_translate(void)
2417 {
2418         translation = !translation;
2419         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
2420                  translation?"on":"off"));
2421
2422         return 0;
2423 }
2424
2425 /****************************************************************************
2426  Do the lcd command.
2427  ****************************************************************************/
2428
2429 static int cmd_lcd(void)
2430 {
2431         pstring buf;
2432         pstring d;
2433         
2434         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
2435                 chdir(buf);
2436         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
2437
2438         return 0;
2439 }
2440
2441 /****************************************************************************
2442  Get a file restarting at end of local file.
2443  ****************************************************************************/
2444
2445 static int cmd_reget(void)
2446 {
2447         pstring local_name;
2448         pstring remote_name;
2449         char *p;
2450
2451         pstrcpy(remote_name, cur_dir);
2452         pstrcat(remote_name, "\\");
2453         
2454         p = remote_name + strlen(remote_name);
2455         
2456         if (!next_token_nr(NULL, p, NULL, sizeof(remote_name) - strlen(remote_name))) {
2457                 d_printf("reget <filename>\n");
2458                 return 1;
2459         }
2460         pstrcpy(local_name, p);
2461         dos_clean_name(remote_name);
2462         
2463         next_token_nr(NULL, local_name, NULL, sizeof(local_name));
2464         
2465         return do_get(remote_name, local_name, True);
2466 }
2467
2468 /****************************************************************************
2469  Put a file restarting at end of local file.
2470  ****************************************************************************/
2471
2472 static int cmd_reput(void)
2473 {
2474         pstring local_name;
2475         pstring remote_name;
2476         pstring buf;
2477         char *p = buf;
2478         SMB_STRUCT_STAT st;
2479         
2480         pstrcpy(remote_name, cur_dir);
2481         pstrcat(remote_name, "\\");
2482   
2483         if (!next_token_nr(NULL, p, NULL, sizeof(buf))) {
2484                 d_printf("reput <filename>\n");
2485                 return 1;
2486         }
2487         pstrcpy(local_name, p);
2488   
2489         if (!file_exist(local_name, &st)) {
2490                 d_printf("%s does not exist\n", local_name);
2491                 return 1;
2492         }
2493
2494         if (next_token_nr(NULL, p, NULL, sizeof(buf)))
2495                 pstrcat(remote_name, p);
2496         else
2497                 pstrcat(remote_name, local_name);
2498         
2499         dos_clean_name(remote_name);
2500
2501         return do_put(remote_name, local_name, True);
2502 }
2503
2504 /****************************************************************************
2505  List a share name.
2506  ****************************************************************************/
2507
2508 static void browse_fn(const char *name, uint32 m, 
2509                       const char *comment, void *state)
2510 {
2511         fstring typestr;
2512
2513         *typestr=0;
2514
2515         switch (m)
2516         {
2517           case STYPE_DISKTREE:
2518             fstrcpy(typestr,"Disk"); break;
2519           case STYPE_PRINTQ:
2520             fstrcpy(typestr,"Printer"); break;
2521           case STYPE_DEVICE:
2522             fstrcpy(typestr,"Device"); break;
2523           case STYPE_IPC:
2524             fstrcpy(typestr,"IPC"); break;
2525         }
2526         /* FIXME: If the remote machine returns non-ascii characters
2527            in any of these fields, they can corrupt the output.  We
2528            should remove them. */
2529         if (!grepable) {
2530                 d_printf("\t%-15s %-10.10s%s\n",
2531                         name,typestr,comment);
2532         } else {
2533                 d_printf ("%s|%s|%s\n",typestr,name,comment);
2534         }
2535 }
2536
2537 /****************************************************************************
2538  Try and browse available connections on a host.
2539 ****************************************************************************/
2540
2541 static BOOL browse_host(BOOL sort)
2542 {
2543         int ret;
2544         if (!grepable) {
2545                 d_printf("\n\tSharename       Type      Comment\n");
2546                 d_printf("\t---------       ----      -------\n");
2547         }
2548
2549         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
2550                 d_printf("Error returning browse list: %s\n", cli_errstr(cli));
2551
2552         return (ret != -1);
2553 }
2554
2555 /****************************************************************************
2556  List a server name.
2557 ****************************************************************************/
2558
2559 static void server_fn(const char *name, uint32 m, 
2560                       const char *comment, void *state)
2561 {
2562         
2563         if (!grepable){
2564                 d_printf("\t%-16s     %s\n", name, comment);
2565         } else {
2566                 d_printf("%s|%s|%s\n",(char *)state, name, comment);
2567         }
2568 }
2569
2570 /****************************************************************************
2571  Try and browse available connections on a host.
2572 ****************************************************************************/
2573
2574 static BOOL list_servers(const char *wk_grp)
2575 {
2576         fstring state;
2577
2578         if (!cli->server_domain)
2579                 return False;
2580
2581         if (!grepable) {
2582                 d_printf("\n\tServer               Comment\n");
2583                 d_printf("\t---------            -------\n");
2584         };
2585         fstrcpy( state, "Server" );
2586         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
2587                           state);
2588
2589         if (!grepable) {
2590                 d_printf("\n\tWorkgroup            Master\n");
2591                 d_printf("\t---------            -------\n");
2592         }; 
2593
2594         fstrcpy( state, "Workgroup" );
2595         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
2596                           server_fn, state);
2597         return True;
2598 }
2599
2600 /****************************************************************************
2601  Print or set current VUID
2602 ****************************************************************************/
2603
2604 static int cmd_vuid(void)
2605 {
2606         fstring buf;
2607         
2608         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2609                 d_printf("Current VUID is %d\n", cli->vuid);
2610                 return 0;
2611         }
2612
2613         cli->vuid = atoi(buf);
2614         return 0;
2615 }
2616
2617 /****************************************************************************
2618  Setup a new VUID, by issuing a session setup
2619 ****************************************************************************/
2620
2621 static int cmd_logon(void)
2622 {
2623         pstring l_username, l_password;
2624         pstring buf,buf2;
2625   
2626         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2627                 d_printf("logon <username> [<password>]\n");
2628                 return 0;
2629         }
2630
2631         pstrcpy(l_username, buf);
2632
2633         if (!next_token_nr(NULL,buf2,NULL,sizeof(buf))) 
2634         {
2635                 char *pass = getpass("Password: ");
2636                 if (pass) 
2637                         pstrcpy(l_password, pass);
2638         } 
2639         else
2640                 pstrcpy(l_password, buf2);
2641
2642         if (!cli_session_setup(cli, l_username, 
2643                                l_password, strlen(l_password),
2644                                l_password, strlen(l_password),
2645                                lp_workgroup())) {
2646                 d_printf("session setup failed: %s\n", cli_errstr(cli));
2647                 return -1;
2648         }
2649
2650         d_printf("Current VUID is %d\n", cli->vuid);
2651         return 0;
2652 }
2653
2654
2655 /****************************************************************************
2656  list active connections
2657 ****************************************************************************/
2658
2659 static int cmd_list_connect(void)
2660 {
2661         cli_cm_display();
2662
2663         return 0;
2664 }
2665
2666 /****************************************************************************
2667  display the current active client connection
2668 ****************************************************************************/
2669
2670 static int cmd_show_connect( void )
2671 {
2672         struct cli_state *targetcli;
2673         pstring targetpath;
2674         
2675         if ( !cli_resolve_path( "", cli, cur_dir, &targetcli, targetpath ) ) {
2676                 d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
2677                 return 1;
2678         }
2679         
2680         d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
2681         return 0;
2682 }
2683
2684 /* Some constants for completing filename arguments */
2685
2686 #define COMPL_NONE        0          /* No completions */
2687 #define COMPL_REMOTE      1          /* Complete remote filename */
2688 #define COMPL_LOCAL       2          /* Complete local filename */
2689
2690 /* This defines the commands supported by this client.
2691  * NOTE: The "!" must be the last one in the list because it's fn pointer
2692  *       field is NULL, and NULL in that field is used in process_tok()
2693  *       (below) to indicate the end of the list.  crh
2694  */
2695 static struct
2696 {
2697   const char *name;
2698   int (*fn)(void);
2699   const char *description;
2700   char compl_args[2];      /* Completion argument info */
2701 } commands[] = {
2702   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2703   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
2704   {"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}},
2705   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
2706   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
2707   {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
2708   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2709   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
2710   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
2711   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2712   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2713   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2714   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2715   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2716   {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}},
2717   {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
2718   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2719   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2720   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2721   {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
2722   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2723   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2724   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
2725   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2726   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2727   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2728   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
2729   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2730   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2731   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
2732   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
2733   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2734   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2735   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2736   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2737   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
2738   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2739   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2740   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2741   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
2742   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2743   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
2744   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2745   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2746   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
2747   {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},
2748   {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
2749   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
2750   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
2751   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2752   {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
2753   {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
2754   {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
2755   {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
2756   {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
2757   
2758   /* Yes, this must be here, see crh's comment above. */
2759   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2760   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2761 };
2762
2763 /*******************************************************************
2764  Lookup a command string in the list of commands, including 
2765  abbreviations.
2766 ******************************************************************/
2767
2768 static int process_tok(pstring tok)
2769 {
2770         int i = 0, matches = 0;
2771         int cmd=0;
2772         int tok_len = strlen(tok);
2773         
2774         while (commands[i].fn != NULL) {
2775                 if (strequal(commands[i].name,tok)) {
2776                         matches = 1;
2777                         cmd = i;
2778                         break;
2779                 } else if (strnequal(commands[i].name, tok, tok_len)) {
2780                         matches++;
2781                         cmd = i;
2782                 }
2783                 i++;
2784         }
2785   
2786         if (matches == 0)
2787                 return(-1);
2788         else if (matches == 1)
2789                 return(cmd);
2790         else
2791                 return(-2);
2792 }
2793
2794 /****************************************************************************
2795  Help.
2796 ****************************************************************************/
2797
2798 static int cmd_help(void)
2799 {
2800         int i=0,j;
2801         pstring buf;
2802         
2803         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2804                 if ((i = process_tok(buf)) >= 0)
2805                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
2806         } else {
2807                 while (commands[i].description) {
2808                         for (j=0; commands[i].description && (j<5); j++) {
2809                                 d_printf("%-15s",commands[i].name);
2810                                 i++;
2811                         }
2812                         d_printf("\n");
2813                 }
2814         }
2815         return 0;
2816 }
2817
2818 /****************************************************************************
2819  Process a -c command string.
2820 ****************************************************************************/
2821
2822 static int process_command_string(char *cmd)
2823 {
2824         pstring line;
2825         const char *ptr;
2826         int rc = 0;
2827
2828         /* establish the connection if not already */
2829         
2830         if (!cli) {
2831                 cli = cli_cm_open(desthost, service, True);
2832                 if (!cli)
2833                         return 0;
2834         }
2835         
2836         while (cmd[0] != '\0')    {
2837                 char *p;
2838                 pstring tok;
2839                 int i;
2840                 
2841                 if ((p = strchr_m(cmd, ';')) == 0) {
2842                         strncpy(line, cmd, 999);
2843                         line[1000] = '\0';
2844                         cmd += strlen(cmd);
2845                 } else {
2846                         if (p - cmd > 999)
2847                                 p = cmd + 999;
2848                         strncpy(line, cmd, p - cmd);
2849                         line[p - cmd] = '\0';
2850                         cmd = p + 1;
2851                 }
2852                 
2853                 /* and get the first part of the command */
2854                 ptr = line;
2855                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
2856                 
2857                 if ((i = process_tok(tok)) >= 0) {
2858                         rc = commands[i].fn();
2859                 } else if (i == -2) {
2860                         d_printf("%s: command abbreviation ambiguous\n",tok);
2861                 } else {
2862                         d_printf("%s: command not found\n",tok);
2863                 }
2864         }
2865         
2866         return rc;
2867 }       
2868
2869 #define MAX_COMPLETIONS 100
2870
2871 typedef struct {
2872         pstring dirmask;
2873         char **matches;
2874         int count, samelen;
2875         const char *text;
2876         int len;
2877 } completion_remote_t;
2878
2879 static void completion_remote_filter(const char *mnt, file_info *f, const char *mask, void *state)
2880 {
2881         completion_remote_t *info = (completion_remote_t *)state;
2882
2883         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
2884                 if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
2885                         info->matches[info->count] = SMB_STRDUP(f->name);
2886                 else {
2887                         pstring tmp;
2888
2889                         if (info->dirmask[0] != 0)
2890                                 pstrcpy(tmp, info->dirmask);
2891                         else
2892                                 tmp[0] = 0;
2893                         pstrcat(tmp, f->name);
2894                         if (f->mode & aDIR)
2895                                 pstrcat(tmp, "/");
2896                         info->matches[info->count] = SMB_STRDUP(tmp);
2897                 }
2898                 if (info->matches[info->count] == NULL)
2899                         return;
2900                 if (f->mode & aDIR)
2901                         smb_readline_ca_char(0);
2902
2903                 if (info->count == 1)
2904                         info->samelen = strlen(info->matches[info->count]);
2905                 else
2906                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
2907                                 info->samelen--;
2908                 info->count++;
2909         }
2910 }
2911
2912 static char **remote_completion(const char *text, int len)
2913 {
2914         pstring dirmask;
2915         int i;
2916         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
2917
2918         /* can't have non-static intialisation on Sun CC, so do it
2919            at run time here */
2920         info.samelen = len;
2921         info.text = text;
2922         info.len = len;
2923                 
2924         if (len >= PATH_MAX)
2925                 return(NULL);
2926
2927         info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
2928         if (!info.matches) return NULL;
2929         info.matches[0] = NULL;
2930
2931         for (i = len-1; i >= 0; i--)
2932                 if ((text[i] == '/') || (text[i] == '\\'))
2933                         break;
2934         info.text = text+i+1;
2935         info.samelen = info.len = len-i-1;
2936
2937         if (i > 0) {
2938                 strncpy(info.dirmask, text, i+1);
2939                 info.dirmask[i+1] = 0;
2940                 pstr_sprintf(dirmask, "%s%*s*", cur_dir, i-1, text);
2941         } else
2942                 pstr_sprintf(dirmask, "%s*", cur_dir);
2943
2944         if (cli_list(cli, dirmask, aDIR | aSYSTEM | aHIDDEN, completion_remote_filter, &info) < 0)
2945                 goto cleanup;
2946
2947         if (info.count == 2)
2948                 info.matches[0] = SMB_STRDUP(info.matches[1]);
2949         else {
2950                 info.matches[0] = SMB_MALLOC(info.samelen+1);
2951                 if (!info.matches[0])
2952                         goto cleanup;
2953                 strncpy(info.matches[0], info.matches[1], info.samelen);
2954                 info.matches[0][info.samelen] = 0;
2955         }
2956         info.matches[info.count] = NULL;
2957         return info.matches;
2958
2959 cleanup:
2960         for (i = 0; i < info.count; i++)
2961                 free(info.matches[i]);
2962         free(info.matches);
2963         return NULL;
2964 }
2965
2966 static char **completion_fn(const char *text, int start, int end)
2967 {
2968         smb_readline_ca_char(' ');
2969
2970         if (start) {
2971                 const char *buf, *sp;
2972                 int i;
2973                 char compl_type;
2974
2975                 buf = smb_readline_get_line_buffer();
2976                 if (buf == NULL)
2977                         return NULL;
2978                 
2979                 sp = strchr(buf, ' ');
2980                 if (sp == NULL)
2981                         return NULL;
2982                 
2983                 for (i = 0; commands[i].name; i++)
2984                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
2985                                 break;
2986                 if (commands[i].name == NULL)
2987                         return NULL;
2988
2989                 while (*sp == ' ')
2990                         sp++;
2991
2992                 if (sp == (buf + start))
2993                         compl_type = commands[i].compl_args[0];
2994                 else
2995                         compl_type = commands[i].compl_args[1];
2996
2997                 if (compl_type == COMPL_REMOTE)
2998                         return remote_completion(text, end - start);
2999                 else /* fall back to local filename completion */
3000                         return NULL;
3001         } else {
3002                 char **matches;
3003                 int i, len, samelen = 0, count=1;
3004
3005                 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
3006                 if (!matches) {
3007                         return NULL;
3008                 }
3009                 matches[0] = NULL;
3010
3011                 len = strlen(text);
3012                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
3013                         if (strncmp(text, commands[i].name, len) == 0) {
3014                                 matches[count] = SMB_STRDUP(commands[i].name);
3015                                 if (!matches[count])
3016                                         goto cleanup;
3017                                 if (count == 1)
3018                                         samelen = strlen(matches[count]);
3019                                 else
3020                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
3021                                                 samelen--;
3022                                 count++;
3023                         }
3024                 }
3025
3026                 switch (count) {
3027                 case 0: /* should never happen */
3028                 case 1:
3029                         goto cleanup;
3030                 case 2:
3031                         matches[0] = SMB_STRDUP(matches[1]);
3032                         break;
3033                 default:
3034                         matches[0] = SMB_MALLOC(samelen+1);
3035                         if (!matches[0])
3036                                 goto cleanup;
3037                         strncpy(matches[0], matches[1], samelen);
3038                         matches[0][samelen] = 0;
3039                 }
3040                 matches[count] = NULL;
3041                 return matches;
3042
3043 cleanup:
3044                 for (i = 0; i < count; i++)
3045                         free(matches[i]);
3046
3047                 free(matches);
3048                 return NULL;
3049         }
3050 }
3051
3052 /****************************************************************************
3053  Make sure we swallow keepalives during idle time.
3054 ****************************************************************************/
3055
3056 static void readline_callback(void)
3057 {
3058         fd_set fds;
3059         struct timeval timeout;
3060         static time_t last_t;
3061         time_t t;
3062
3063         t = time(NULL);
3064
3065         if (t - last_t < 5)
3066                 return;
3067
3068         last_t = t;
3069
3070  again:
3071
3072         if (cli->fd == -1)
3073                 return;
3074
3075         FD_ZERO(&fds);
3076         FD_SET(cli->fd,&fds);
3077
3078         timeout.tv_sec = 0;
3079         timeout.tv_usec = 0;
3080         sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
3081                 
3082         /* We deliberately use receive_smb instead of
3083            client_receive_smb as we want to receive
3084            session keepalives and then drop them here.
3085         */
3086         if (FD_ISSET(cli->fd,&fds)) {
3087                 receive_smb(cli->fd,cli->inbuf,0);
3088                 goto again;
3089         }
3090       
3091         cli_chkpath(cli, "\\");
3092 }
3093
3094 /****************************************************************************
3095  Process commands on stdin.
3096 ****************************************************************************/
3097
3098 static int process_stdin(void)
3099 {
3100         const char *ptr;
3101         int rc = 0;
3102
3103         while (1) {
3104                 pstring tok;
3105                 pstring the_prompt;
3106                 char *cline;
3107                 pstring line;
3108                 int i;
3109                 
3110                 /* display a prompt */
3111                 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);
3112                 cline = smb_readline(the_prompt, readline_callback, completion_fn);
3113                         
3114                 if (!cline) break;
3115                 
3116                 pstrcpy(line, cline);
3117
3118                 /* special case - first char is ! */
3119                 if (*line == '!') {
3120                         system(line + 1);
3121                         continue;
3122                 }
3123       
3124                 /* and get the first part of the command */
3125                 ptr = line;
3126                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
3127
3128                 if ((i = process_tok(tok)) >= 0) {
3129                         rc = commands[i].fn();
3130                 } else if (i == -2) {
3131                         d_printf("%s: command abbreviation ambiguous\n",tok);
3132                 } else {
3133                         d_printf("%s: command not found\n",tok);
3134                 }
3135         }
3136         return rc;
3137 }
3138
3139 /****************************************************************************
3140  Process commands from the client.
3141 ****************************************************************************/
3142
3143 static int process(char *base_directory)
3144 {
3145         int rc = 0;
3146
3147         cli = cli_cm_open(desthost, service, True);
3148         if (!cli) {
3149                 return 1;
3150         }
3151
3152         if (*base_directory) {
3153                 rc = do_cd(base_directory);
3154                 if (rc) {
3155                         cli_cm_shutdown();
3156                         return rc;
3157                 }
3158         }
3159         
3160         if (cmdstr) {
3161                 rc = process_command_string(cmdstr);
3162         } else {
3163                 process_stdin();
3164         }
3165   
3166         cli_cm_shutdown();
3167         return rc;
3168 }
3169
3170 /****************************************************************************
3171  Handle a -L query.
3172 ****************************************************************************/
3173
3174 static int do_host_query(char *query_host)
3175 {
3176         cli = cli_cm_open(query_host, "IPC$", True);
3177         if (!cli)
3178                 return 1;
3179
3180         browse_host(True);
3181
3182         if (port != 139) {
3183
3184                 /* Workgroups simply don't make sense over anything
3185                    else but port 139... */
3186
3187                 cli_cm_shutdown();
3188                 cli_cm_set_port( 139 );
3189                 cli = cli_cm_open(query_host, "IPC$", True);
3190         }
3191
3192         if (cli == NULL) {
3193                 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
3194                 return 1;
3195         }
3196
3197         list_servers(lp_workgroup());
3198
3199         cli_cm_shutdown();
3200         
3201         return(0);
3202 }
3203
3204 /****************************************************************************
3205  Handle a tar operation.
3206 ****************************************************************************/
3207
3208 static int do_tar_op(char *base_directory)
3209 {
3210         int ret;
3211
3212         /* do we already have a connection? */
3213         if (!cli) {
3214                 cli = cli_cm_open(desthost, service, True);
3215                 if (!cli)
3216                         return 1;
3217         }
3218
3219         recurse=True;
3220
3221         if (*base_directory)  {
3222                 ret = do_cd(base_directory);
3223                 if (ret) {
3224                         cli_cm_shutdown();
3225                         return ret;
3226                 }
3227         }
3228         
3229         ret=process_tar();
3230
3231         cli_cm_shutdown();
3232
3233         return(ret);
3234 }
3235
3236 /****************************************************************************
3237  Handle a message operation.
3238 ****************************************************************************/
3239
3240 static int do_message_op(void)
3241 {
3242         struct in_addr ip;
3243         struct nmb_name called, calling;
3244         fstring server_name;
3245         char name_type_hex[10];
3246         int msg_port;
3247
3248         make_nmb_name(&calling, calling_name, 0x0);
3249         make_nmb_name(&called , desthost, name_type);
3250
3251         fstrcpy(server_name, desthost);
3252         snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
3253         fstrcat(server_name, name_type_hex);
3254
3255         zero_ip(&ip);
3256         if (have_ip) 
3257                 ip = dest_ip;
3258
3259         /* we can only do messages over port 139 (to windows clients at least) */
3260
3261         msg_port = port ? port : 139;
3262
3263         if (!(cli=cli_initialise(NULL)) || (cli_set_port(cli, msg_port) != msg_port) ||
3264             !cli_connect(cli, server_name, &ip)) {
3265                 d_printf("Connection to %s failed\n", desthost);
3266                 return 1;
3267         }
3268
3269         if (!cli_session_request(cli, &calling, &called)) {
3270                 d_printf("session request failed\n");
3271                 cli_cm_shutdown();
3272                 return 1;
3273         }
3274
3275         send_message();
3276         cli_cm_shutdown();
3277
3278         return 0;
3279 }
3280
3281
3282 /****************************************************************************
3283   main program
3284 ****************************************************************************/
3285
3286  int main(int argc,char *argv[])
3287 {
3288         pstring base_directory;
3289         int opt;
3290         pstring query_host;
3291         BOOL message = False;
3292         pstring term_code;
3293         static const char *new_name_resolve_order = NULL;
3294         poptContext pc;
3295         char *p;
3296         int rc = 0;
3297         fstring new_workgroup;
3298         struct poptOption long_options[] = {
3299                 POPT_AUTOHELP
3300
3301                 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
3302                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
3303                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
3304                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
3305                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
3306                 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
3307                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
3308                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
3309                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
3310                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
3311                 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
3312                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
3313                 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
3314                 POPT_COMMON_SAMBA
3315                 POPT_COMMON_CONNECTION
3316                 POPT_COMMON_CREDENTIALS
3317                 POPT_TABLEEND
3318         };
3319         
3320
3321 #ifdef KANJI
3322         pstrcpy(term_code, KANJI);
3323 #else /* KANJI */
3324         *term_code = 0;
3325 #endif /* KANJI */
3326
3327         *query_host = 0;
3328         *base_directory = 0;
3329         
3330         /* initialize the workgroup name so we can determine whether or 
3331            not it was set by a command line option */
3332            
3333         set_global_myworkgroup( "" );
3334         set_global_myname( "" );
3335
3336         /* set default debug level to 0 regardless of what smb.conf sets */
3337         setup_logging( "smbclient", True );
3338         DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
3339         dbf = x_stderr;
3340         x_setbuf( x_stderr, NULL );
3341
3342         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 
3343                                 POPT_CONTEXT_KEEP_FIRST);
3344         poptSetOtherOptionHelp(pc, "service <password>");
3345
3346         in_client = True;   /* Make sure that we tell lp_load we are */
3347
3348         while ((opt = poptGetNextOpt(pc)) != -1) {
3349                 switch (opt) {
3350                 case 'M':
3351                         /* Messages are sent to NetBIOS name type 0x3
3352                          * (Messenger Service).  Make sure we default
3353                          * to port 139 instead of port 445. srl,crh
3354                          */
3355                         name_type = 0x03; 
3356                         cli_cm_set_dest_name_type( name_type );
3357                         pstrcpy(desthost,poptGetOptArg(pc));
3358                         if( !port )
3359                                 cli_cm_set_port( 139 );
3360                         message = True;
3361                         break;
3362                 case 'I':
3363                         {
3364                                 dest_ip = *interpret_addr2(poptGetOptArg(pc));
3365                                 if (is_zero_ip(dest_ip))
3366                                         exit(1);
3367                                 have_ip = True;
3368
3369                                 cli_cm_set_dest_ip( dest_ip );
3370                         }
3371                         break;
3372                 case 'E':
3373                         dbf = x_stderr;
3374                         display_set_stderr();
3375                         break;
3376
3377                 case 'L':
3378                         pstrcpy(query_host, poptGetOptArg(pc));
3379                         break;
3380                 case 't':
3381                         pstrcpy(term_code, poptGetOptArg(pc));
3382                         break;
3383                 case 'm':
3384                         max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
3385                         break;
3386                 case 'T':
3387                         /* We must use old option processing for this. Find the
3388                          * position of the -T option in the raw argv[]. */
3389                         {
3390                                 int i, optnum;
3391                                 for (i = 1; i < argc; i++) {
3392                                         if (strncmp("-T", argv[i],2)==0)
3393                                                 break;
3394                                 }
3395                                 i++;
3396                                 if (!(optnum = tar_parseargs(argc, argv, poptGetOptArg(pc), i))) {
3397                                         poptPrintUsage(pc, stderr, 0);
3398                                         exit(1);
3399                                 }
3400                                 /* Now we must eat (optnum - i) options - they have
3401                                  * been processed by tar_parseargs().
3402                                  */
3403                                 optnum -= i;
3404                                 for (i = 0; i < optnum; i++)
3405                                         poptGetOptArg(pc);
3406                         }
3407                         break;
3408                 case 'D':
3409                         pstrcpy(base_directory,poptGetOptArg(pc));
3410                         break;
3411                 case 'g':
3412                         grepable=True;
3413                         break;
3414                 }
3415         }
3416
3417         poptGetArg(pc);
3418
3419         /* check for the -P option */
3420
3421         if ( port != 0 )
3422                 cli_cm_set_port( port );
3423
3424         /*
3425          * Don't load debug level from smb.conf. It should be
3426          * set by cmdline arg or remain default (0)
3427          */
3428         AllowDebugChange = False;
3429         
3430         /* save the workgroup...
3431         
3432            FIXME!! do we need to do this for other options as well 
3433            (or maybe a generic way to keep lp_load() from overwriting 
3434            everything)?  */
3435         
3436         fstrcpy( new_workgroup, lp_workgroup() );
3437         pstrcpy( calling_name, global_myname() );
3438         
3439         if ( override_logfile )
3440                 setup_logging( lp_logfile(), False );
3441         
3442         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
3443                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
3444                         argv[0], dyn_CONFIGFILE);
3445         }
3446         
3447         load_interfaces();
3448         
3449         if ( strlen(new_workgroup) != 0 )
3450                 set_global_myworkgroup( new_workgroup );
3451
3452         if ( strlen(calling_name) != 0 )
3453                 set_global_myname( calling_name );
3454         else
3455                 pstrcpy( calling_name, global_myname() );
3456
3457         if(poptPeekArg(pc)) {
3458                 pstrcpy(service,poptGetArg(pc));  
3459                 /* Convert any '/' characters in the service name to '\' characters */
3460                 string_replace(service, '/','\\');
3461
3462                 if (count_chars(service,'\\') < 3) {
3463                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
3464                         poptPrintUsage(pc, stderr, 0);
3465                         exit(1);
3466                 }
3467         }
3468
3469         if (poptPeekArg(pc) && !cmdline_auth_info.got_pass) { 
3470                 cmdline_auth_info.got_pass = True;
3471                 pstrcpy(cmdline_auth_info.password,poptGetArg(pc));  
3472         }
3473
3474         init_names();
3475
3476         if(new_name_resolve_order)
3477                 lp_set_name_resolve_order(new_name_resolve_order);
3478
3479         if (!tar_type && !*query_host && !*service && !message) {
3480                 poptPrintUsage(pc, stderr, 0);
3481                 exit(1);
3482         }
3483
3484         poptFreeContext(pc);
3485
3486         /* store the username an password for dfs support */
3487
3488         cli_cm_set_credentials( &cmdline_auth_info );
3489         pstrcpy(username, cmdline_auth_info.username);
3490
3491         DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
3492
3493         if (tar_type) {
3494                 if (cmdstr)
3495                         process_command_string(cmdstr);
3496                 return do_tar_op(base_directory);
3497         }
3498
3499         if (*query_host) {
3500                 char *qhost = query_host;
3501                 char *slash;
3502
3503                 while (*qhost == '\\' || *qhost == '/')
3504                         qhost++;
3505
3506                 if ((slash = strchr_m(qhost, '/'))
3507                     || (slash = strchr_m(qhost, '\\'))) {
3508                         *slash = 0;
3509                 }
3510
3511                 if ((p=strchr_m(qhost, '#'))) {
3512                         *p = 0;
3513                         p++;
3514                         sscanf(p, "%x", &name_type);
3515                         cli_cm_set_dest_name_type( name_type );
3516                 }
3517
3518                 return do_host_query(qhost);
3519         }
3520
3521         if (message) {
3522                 return do_message_op();
3523         }
3524         
3525         if (process(base_directory)) {
3526                 return 1;
3527         }
3528
3529         return rc;
3530 }