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