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