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