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