r10509: Some more sconscript fixes. Now getting to link stage for smbclient
[bbaumbach/samba-autobuild/.git] / source4 / 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-2004
7    Copyright (C) James J Myers   2003 <myersjj@samba.org>
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 "version.h"
26 #include "clilist.h"
27 #include "lib/cmdline/popt_common.h"
28 #include "librpc/gen_ndr/ndr_srvsvc.h"
29 #include "librpc/gen_ndr/ndr_lsa.h"
30 #include "libcli/raw/libcliraw.h"
31 #include "system/time.h"
32 #include "system/dir.h"
33 #include "system/filesys.h"
34 #include "dlinklist.h"
35
36 #ifndef REGISTER
37 #define REGISTER 0
38 #endif
39
40 static struct smbcli_state *cli;
41 static int port = 0;
42 static pstring cur_dir = "\\";
43 static pstring cd_path = "";
44 static pstring service;
45 static pstring desthost;
46 static char *cmdstr = NULL;
47
48 static int io_bufsize = 64512;
49
50 static int name_type = 0x20;
51
52 static int process_tok(fstring tok);
53 static int cmd_help(const char **cmd_ptr);
54
55 /* 30 second timeout on most commands */
56 #define CLIENT_TIMEOUT (30*1000)
57 #define SHORT_TIMEOUT (5*1000)
58
59 /* value for unused fid field in trans2 secondary request */
60 #define FID_UNUSED (0xFFFF)
61
62 time_t newer_than = 0;
63 static int archive_level = 0;
64
65 static BOOL translation = False;
66
67 /* clitar bits insert */
68 extern int blocksize;
69 extern BOOL tar_inc;
70 extern BOOL tar_reset;
71 /* clitar bits end */
72  
73
74 static BOOL prompt = True;
75
76 static int printmode = 1;
77
78 static BOOL recurse = False;
79 BOOL lowercase = False;
80
81 static const char *dest_ip;
82
83 #define SEPARATORS " \t\n\r"
84
85 static BOOL abort_mget = True;
86
87 static pstring fileselection = "";
88
89 /* timing globals */
90 uint64_t get_total_size = 0;
91 uint_t get_total_time_ms = 0;
92 static uint64_t put_total_size = 0;
93 static uint_t put_total_time_ms = 0;
94
95 /* totals globals */
96 static double dir_total;
97
98 #define USENMB
99
100 /* some forward declarations */
101 static struct smbcli_state *do_connect(const char *server, const char *share, struct cli_credentials *cred);
102
103
104 /*******************************************************************
105  Reduce a file name, removing .. elements.
106 ********************************************************************/
107 void dos_clean_name(char *s)
108 {
109         char *p=NULL;
110
111         DEBUG(3,("dos_clean_name [%s]\n",s));
112
113         /* remove any double slashes */
114         all_string_sub(s, "\\\\", "\\", 0);
115
116         while ((p = strstr(s,"\\..\\")) != NULL) {
117                 pstring s1;
118
119                 *p = 0;
120                 pstrcpy(s1,p+3);
121
122                 if ((p=strrchr_m(s,'\\')) != NULL)
123                         *p = 0;
124                 else
125                         *s = 0;
126                 pstrcat(s,s1);
127         }  
128
129         trim_string(s,NULL,"\\..");
130
131         all_string_sub(s, "\\.\\", "\\", 0);
132 }
133
134 /****************************************************************************
135 write to a local file with CR/LF->LF translation if appropriate. return the 
136 number taken from the buffer. This may not equal the number written.
137 ****************************************************************************/
138 static int writefile(int f, const void *_b, int n)
139 {
140         const uint8_t *b = _b;
141         int i;
142
143         if (!translation) {
144                 return write(f,b,n);
145         }
146
147         i = 0;
148         while (i < n) {
149                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
150                         b++;i++;
151                 }
152                 if (write(f, b, 1) != 1) {
153                         break;
154                 }
155                 b++;
156                 i++;
157         }
158   
159         return(i);
160 }
161
162 /****************************************************************************
163   read from a file with LF->CR/LF translation if appropriate. return the 
164   number read. read approx n bytes.
165 ****************************************************************************/
166 static int readfile(void *_b, int n, XFILE *f)
167 {
168         uint8_t *b = _b;
169         int i;
170         int c;
171
172         if (!translation)
173                 return x_fread(b,1,n,f);
174   
175         i = 0;
176         while (i < (n - 1)) {
177                 if ((c = x_getc(f)) == EOF) {
178                         break;
179                 }
180       
181                 if (c == '\n') { /* change all LFs to CR/LF */
182                         b[i++] = '\r';
183                 }
184       
185                 b[i++] = c;
186         }
187   
188         return(i);
189 }
190  
191
192 /****************************************************************************
193 send a message
194 ****************************************************************************/
195 static void send_message(void)
196 {
197         int total_len = 0;
198         int grp_id;
199
200         if (!smbcli_message_start(cli->tree, desthost, cli_credentials_get_username(cmdline_credentials), &grp_id)) {
201                 d_printf("message start: %s\n", smbcli_errstr(cli->tree));
202                 return;
203         }
204
205
206         d_printf("Connected. Type your message, ending it with a Control-D\n");
207
208         while (!feof(stdin) && total_len < 1600) {
209                 int maxlen = MIN(1600 - total_len,127);
210                 pstring msg;
211                 int l=0;
212                 int c;
213
214                 ZERO_STRUCT(msg);
215
216                 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
217                         if (c == '\n')
218                                 msg[l++] = '\r';
219                         msg[l] = c;   
220                 }
221
222                 if (!smbcli_message_text(cli->tree, msg, l, grp_id)) {
223                         d_printf("SMBsendtxt failed (%s)\n",smbcli_errstr(cli->tree));
224                         return;
225                 }      
226                 
227                 total_len += l;
228         }
229
230         if (total_len >= 1600)
231                 d_printf("the message was truncated to 1600 bytes\n");
232         else
233                 d_printf("sent %d bytes\n",total_len);
234
235         if (!smbcli_message_end(cli->tree, grp_id)) {
236                 d_printf("SMBsendend failed (%s)\n",smbcli_errstr(cli->tree));
237                 return;
238         }      
239 }
240
241
242
243 /****************************************************************************
244 check the space on a device
245 ****************************************************************************/
246 static int do_dskattr(void)
247 {
248         int total, bsize, avail;
249
250         if (NT_STATUS_IS_ERR(smbcli_dskattr(cli->tree, &bsize, &total, &avail))) {
251                 d_printf("Error in dskattr: %s\n",smbcli_errstr(cli->tree)); 
252                 return 1;
253         }
254
255         d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
256                  total, bsize, avail);
257
258         return 0;
259 }
260
261 /****************************************************************************
262 show cd/pwd
263 ****************************************************************************/
264 static int cmd_pwd(const char **cmd_ptr)
265 {
266         d_printf("Current directory is %s",service);
267         d_printf("%s\n",cur_dir);
268         return 0;
269 }
270
271 /*
272   convert a string to dos format
273 */
274 static void dos_format(char *s)
275 {
276         string_replace(s, '/', '\\');
277 }
278
279 /****************************************************************************
280 change directory - inner section
281 ****************************************************************************/
282 static int do_cd(char *newdir)
283 {
284         char *p = newdir;
285         pstring saved_dir;
286         pstring dname;
287       
288         dos_format(newdir);
289
290         /* Save the current directory in case the
291            new directory is invalid */
292         pstrcpy(saved_dir, cur_dir);
293         if (*p == '\\')
294                 pstrcpy(cur_dir,p);
295         else
296                 pstrcat(cur_dir,p);
297         if (*(cur_dir+strlen(cur_dir)-1) != '\\') {
298                 pstrcat(cur_dir, "\\");
299         }
300         dos_clean_name(cur_dir);
301         pstrcpy(dname,cur_dir);
302         pstrcat(cur_dir,"\\");
303         dos_clean_name(cur_dir);
304         
305         if (!strequal(cur_dir,"\\")) {
306                 if (NT_STATUS_IS_ERR(smbcli_chkpath(cli->tree, dname))) {
307                         d_printf("cd %s: %s\n", dname, smbcli_errstr(cli->tree));
308                         pstrcpy(cur_dir,saved_dir);
309                 }
310         }
311         
312         pstrcpy(cd_path,cur_dir);
313
314         return 0;
315 }
316
317 /****************************************************************************
318 change directory
319 ****************************************************************************/
320 static int cmd_cd(const char **cmd_ptr)
321 {
322         fstring buf;
323         int rc = 0;
324
325         if (next_token(cmd_ptr,buf,NULL,sizeof(buf)))
326                 rc = do_cd(buf);
327         else
328                 d_printf("Current directory is %s\n",cur_dir);
329
330         return rc;
331 }
332
333
334 BOOL mask_match(struct smbcli_state *c, const char *string, char *pattern, 
335                 BOOL is_case_sensitive)
336 {
337         fstring p2, s2;
338
339         if (strcmp(string,"..") == 0)
340                 string = ".";
341         if (strcmp(pattern,".") == 0)
342                 return False;
343         
344         if (is_case_sensitive)
345                 return ms_fnmatch(pattern, string, 
346                                   c->transport->negotiate.protocol) == 0;
347
348         fstrcpy(p2, pattern);
349         fstrcpy(s2, string);
350         strlower(p2); 
351         strlower(s2);
352         return ms_fnmatch(p2, s2, c->transport->negotiate.protocol) == 0;
353 }
354
355
356
357 /*******************************************************************
358   decide if a file should be operated on
359   ********************************************************************/
360 static BOOL do_this_one(struct clilist_file_info *finfo)
361 {
362         if (finfo->attrib & FILE_ATTRIBUTE_DIRECTORY) return(True);
363
364         if (*fileselection && 
365             !mask_match(cli, finfo->name,fileselection,False)) {
366                 DEBUG(3,("mask_match %s failed\n", finfo->name));
367                 return False;
368         }
369
370         if (newer_than && finfo->mtime < newer_than) {
371                 DEBUG(3,("newer_than %s failed\n", finfo->name));
372                 return(False);
373         }
374
375         if ((archive_level==1 || archive_level==2) && !(finfo->attrib & FILE_ATTRIBUTE_ARCHIVE)) {
376                 DEBUG(3,("archive %s failed\n", finfo->name));
377                 return(False);
378         }
379         
380         return(True);
381 }
382
383 /****************************************************************************
384   display info about a file
385   ****************************************************************************/
386 static void display_finfo(struct clilist_file_info *finfo)
387 {
388         if (do_this_one(finfo)) {
389                 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
390                 char *astr = attrib_string(NULL, finfo->attrib);
391                 d_printf("  %-30s%7.7s %8.0f  %s",
392                          finfo->name,
393                          astr,
394                          (double)finfo->size,
395                          asctime(localtime(&t)));
396                 dir_total += finfo->size;
397                 talloc_free(astr);
398         }
399 }
400
401
402 /****************************************************************************
403    accumulate size of a file
404   ****************************************************************************/
405 static void do_du(struct clilist_file_info *finfo)
406 {
407         if (do_this_one(finfo)) {
408                 dir_total += finfo->size;
409         }
410 }
411
412 static BOOL do_list_recurse;
413 static BOOL do_list_dirs;
414 static char *do_list_queue = 0;
415 static long do_list_queue_size = 0;
416 static long do_list_queue_start = 0;
417 static long do_list_queue_end = 0;
418 static void (*do_list_fn)(struct clilist_file_info *);
419
420 /****************************************************************************
421 functions for do_list_queue
422   ****************************************************************************/
423
424 /*
425  * The do_list_queue is a NUL-separated list of strings stored in a
426  * char*.  Since this is a FIFO, we keep track of the beginning and
427  * ending locations of the data in the queue.  When we overflow, we
428  * double the size of the char*.  When the start of the data passes
429  * the midpoint, we move everything back.  This is logically more
430  * complex than a linked list, but easier from a memory management
431  * angle.  In any memory error condition, do_list_queue is reset.
432  * Functions check to ensure that do_list_queue is non-NULL before
433  * accessing it.
434  */
435 static void reset_do_list_queue(void)
436 {
437         SAFE_FREE(do_list_queue);
438         do_list_queue_size = 0;
439         do_list_queue_start = 0;
440         do_list_queue_end = 0;
441 }
442
443 static void init_do_list_queue(void)
444 {
445         reset_do_list_queue();
446         do_list_queue_size = 1024;
447         do_list_queue = malloc(do_list_queue_size);
448         if (do_list_queue == 0) { 
449                 d_printf("malloc fail for size %d\n",
450                          (int)do_list_queue_size);
451                 reset_do_list_queue();
452         } else {
453                 memset(do_list_queue, 0, do_list_queue_size);
454         }
455 }
456
457 static void adjust_do_list_queue(void)
458 {
459         /*
460          * If the starting point of the queue is more than half way through,
461          * move everything toward the beginning.
462          */
463         if (do_list_queue && (do_list_queue_start == do_list_queue_end))
464         {
465                 DEBUG(4,("do_list_queue is empty\n"));
466                 do_list_queue_start = do_list_queue_end = 0;
467                 *do_list_queue = '\0';
468         }
469         else if (do_list_queue_start > (do_list_queue_size / 2))
470         {
471                 DEBUG(4,("sliding do_list_queue backward\n"));
472                 memmove(do_list_queue,
473                         do_list_queue + do_list_queue_start,
474                         do_list_queue_end - do_list_queue_start);
475                 do_list_queue_end -= do_list_queue_start;
476                 do_list_queue_start = 0;
477         }
478            
479 }
480
481 static void add_to_do_list_queue(const char* entry)
482 {
483         char *dlq;
484         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
485         while (new_end > do_list_queue_size)
486         {
487                 do_list_queue_size *= 2;
488                 DEBUG(4,("enlarging do_list_queue to %d\n",
489                          (int)do_list_queue_size));
490                 dlq = realloc_p(do_list_queue, char, do_list_queue_size);
491                 if (! dlq) {
492                         d_printf("failure enlarging do_list_queue to %d bytes\n",
493                                  (int)do_list_queue_size);
494                         reset_do_list_queue();
495                 }
496                 else
497                 {
498                         do_list_queue = dlq;
499                         memset(do_list_queue + do_list_queue_size / 2,
500                                0, do_list_queue_size / 2);
501                 }
502         }
503         if (do_list_queue)
504         {
505                 safe_strcpy(do_list_queue + do_list_queue_end, entry, 
506                             do_list_queue_size - do_list_queue_end - 1);
507                 do_list_queue_end = new_end;
508                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
509                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
510         }
511 }
512
513 static char *do_list_queue_head(void)
514 {
515         return do_list_queue + do_list_queue_start;
516 }
517
518 static void remove_do_list_queue_head(void)
519 {
520         if (do_list_queue_end > do_list_queue_start)
521         {
522                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
523                 adjust_do_list_queue();
524                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
525                          (int)do_list_queue_start, (int)do_list_queue_end));
526         }
527 }
528
529 static int do_list_queue_empty(void)
530 {
531         return (! (do_list_queue && *do_list_queue));
532 }
533
534 /****************************************************************************
535 a helper for do_list
536   ****************************************************************************/
537 static void do_list_helper(struct clilist_file_info *f, const char *mask, void *state)
538 {
539         if (f->attrib & FILE_ATTRIBUTE_DIRECTORY) {
540                 if (do_list_dirs && do_this_one(f)) {
541                         do_list_fn(f);
542                 }
543                 if (do_list_recurse && 
544                     !strequal(f->name,".") && 
545                     !strequal(f->name,"..")) {
546                         pstring mask2;
547                         char *p;
548
549                         pstrcpy(mask2, mask);
550                         p = strrchr_m(mask2,'\\');
551                         if (!p) return;
552                         p[1] = 0;
553                         pstrcat(mask2, f->name);
554                         pstrcat(mask2,"\\*");
555                         add_to_do_list_queue(mask2);
556                 }
557                 return;
558         }
559
560         if (do_this_one(f)) {
561                 do_list_fn(f);
562         }
563 }
564
565
566 /****************************************************************************
567 a wrapper around smbcli_list that adds recursion
568   ****************************************************************************/
569 void do_list(const char *mask,uint16_t attribute,
570              void (*fn)(struct clilist_file_info *),BOOL rec, BOOL dirs)
571 {
572         static int in_do_list = 0;
573
574         if (in_do_list && rec)
575         {
576                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
577                 exit(1);
578         }
579
580         in_do_list = 1;
581
582         do_list_recurse = rec;
583         do_list_dirs = dirs;
584         do_list_fn = fn;
585
586         if (rec)
587         {
588                 init_do_list_queue();
589                 add_to_do_list_queue(mask);
590                 
591                 while (! do_list_queue_empty())
592                 {
593                         /*
594                          * Need to copy head so that it doesn't become
595                          * invalid inside the call to smbcli_list.  This
596                          * would happen if the list were expanded
597                          * during the call.
598                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
599                          */
600                         pstring head;
601                         pstrcpy(head, do_list_queue_head());
602                         smbcli_list(cli->tree, head, attribute, do_list_helper, NULL);
603                         remove_do_list_queue_head();
604                         if ((! do_list_queue_empty()) && (fn == display_finfo))
605                         {
606                                 char* next_file = do_list_queue_head();
607                                 char* save_ch = 0;
608                                 if ((strlen(next_file) >= 2) &&
609                                     (next_file[strlen(next_file) - 1] == '*') &&
610                                     (next_file[strlen(next_file) - 2] == '\\'))
611                                 {
612                                         save_ch = next_file +
613                                                 strlen(next_file) - 2;
614                                         *save_ch = '\0';
615                                 }
616                                 d_printf("\n%s\n",next_file);
617                                 if (save_ch)
618                                 {
619                                         *save_ch = '\\';
620                                 }
621                         }
622                 }
623         }
624         else
625         {
626                 if (smbcli_list(cli->tree, mask, attribute, do_list_helper, NULL) == -1)
627                 {
628                         d_printf("%s listing %s\n", smbcli_errstr(cli->tree), mask);
629                 }
630         }
631
632         in_do_list = 0;
633         reset_do_list_queue();
634 }
635
636 /****************************************************************************
637   get a directory listing
638   ****************************************************************************/
639 static int cmd_dir(const char **cmd_ptr)
640 {
641         uint16_t attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
642         pstring mask;
643         fstring buf;
644         char *p=buf;
645         int rc;
646         
647         dir_total = 0;
648         pstrcpy(mask,cur_dir);
649         if(mask[strlen(mask)-1]!='\\')
650                 pstrcat(mask,"\\");
651         
652         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
653                 dos_format(p);
654                 if (*p == '\\')
655                         pstrcpy(mask,p);
656                 else
657                         pstrcat(mask,p);
658         }
659         else {
660                 if (cli->tree->session->transport->negotiate.protocol <= 
661                     PROTOCOL_LANMAN1) { 
662                         pstrcat(mask,"*.*");
663                 } else {
664                         pstrcat(mask,"*");
665                 }
666         }
667
668         do_list(mask, attribute, display_finfo, recurse, True);
669
670         rc = do_dskattr();
671
672         DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
673
674         return rc;
675 }
676
677
678 /****************************************************************************
679   get a directory listing
680   ****************************************************************************/
681 static int cmd_du(const char **cmd_ptr)
682 {
683         uint16_t attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
684         pstring mask;
685         fstring buf;
686         char *p=buf;
687         int rc;
688         
689         dir_total = 0;
690         pstrcpy(mask,cur_dir);
691         if(mask[strlen(mask)-1]!='\\')
692                 pstrcat(mask,"\\");
693         
694         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
695                 dos_format(p);
696                 if (*p == '\\')
697                         pstrcpy(mask,p);
698                 else
699                         pstrcat(mask,p);
700         } else {
701                 pstrcat(mask,"\\*");
702         }
703
704         do_list(mask, attribute, do_du, recurse, True);
705
706         rc = do_dskattr();
707
708         d_printf("Total number of bytes: %.0f\n", dir_total);
709
710         return rc;
711 }
712
713
714 /****************************************************************************
715   get a file from rname to lname
716   ****************************************************************************/
717 static int do_get(char *rname, const char *lname, BOOL reget)
718 {  
719         int handle = 0, fnum;
720         BOOL newhandle = False;
721         uint8_t *data;
722         struct timeval tp_start;
723         int read_size = io_bufsize;
724         uint16_t attr;
725         size_t size;
726         off_t start = 0;
727         off_t nread = 0;
728         int rc = 0;
729
730         GetTimeOfDay(&tp_start);
731
732         if (lowercase) {
733                 strlower(discard_const_p(char, lname));
734         }
735
736         fnum = smbcli_open(cli->tree, rname, O_RDONLY, DENY_NONE);
737
738         if (fnum == -1) {
739                 d_printf("%s opening remote file %s\n",smbcli_errstr(cli->tree),rname);
740                 return 1;
741         }
742
743         if(!strcmp(lname,"-")) {
744                 handle = fileno(stdout);
745         } else {
746                 if (reget) {
747                         handle = open(lname, O_WRONLY|O_CREAT, 0644);
748                         if (handle >= 0) {
749                                 start = lseek(handle, 0, SEEK_END);
750                                 if (start == -1) {
751                                         d_printf("Error seeking local file\n");
752                                         return 1;
753                                 }
754                         }
755                 } else {
756                         handle = open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
757                 }
758                 newhandle = True;
759         }
760         if (handle < 0) {
761                 d_printf("Error opening local file %s\n",lname);
762                 return 1;
763         }
764
765
766         if (NT_STATUS_IS_ERR(smbcli_qfileinfo(cli->tree, fnum, 
767                            &attr, &size, NULL, NULL, NULL, NULL, NULL)) &&
768             NT_STATUS_IS_ERR(smbcli_getattrE(cli->tree, fnum, 
769                           &attr, &size, NULL, NULL, NULL))) {
770                 d_printf("getattrib: %s\n",smbcli_errstr(cli->tree));
771                 return 1;
772         }
773
774         DEBUG(2,("getting file %s of size %.0f as %s ", 
775                  rname, (double)size, lname));
776
777         if(!(data = (uint8_t *)malloc(read_size))) { 
778                 d_printf("malloc fail for size %d\n", read_size);
779                 smbcli_close(cli->tree, fnum);
780                 return 1;
781         }
782
783         while (1) {
784                 int n = smbcli_read(cli->tree, fnum, data, nread + start, read_size);
785
786                 if (n <= 0) break;
787  
788                 if (writefile(handle,data, n) != n) {
789                         d_printf("Error writing local file\n");
790                         rc = 1;
791                         break;
792                 }
793       
794                 nread += n;
795         }
796
797         if (nread + start < size) {
798                 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
799                             rname, (long)nread));
800
801                 rc = 1;
802         }
803
804         SAFE_FREE(data);
805         
806         if (NT_STATUS_IS_ERR(smbcli_close(cli->tree, fnum))) {
807                 d_printf("Error %s closing remote file\n",smbcli_errstr(cli->tree));
808                 rc = 1;
809         }
810
811         if (newhandle) {
812                 close(handle);
813         }
814
815         if (archive_level >= 2 && (attr & FILE_ATTRIBUTE_ARCHIVE)) {
816                 smbcli_setatr(cli->tree, rname, attr & ~(uint16_t)FILE_ATTRIBUTE_ARCHIVE, 0);
817         }
818
819         {
820                 struct timeval tp_end;
821                 int this_time;
822                 
823                 GetTimeOfDay(&tp_end);
824                 this_time = 
825                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
826                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
827                 get_total_time_ms += this_time;
828                 get_total_size += nread;
829                 
830                 DEBUG(2,("(%3.1f kb/s) (average %3.1f kb/s)\n",
831                          nread / (1.024*this_time + 1.0e-4),
832                          get_total_size / (1.024*get_total_time_ms)));
833         }
834         
835         return rc;
836 }
837
838
839 /****************************************************************************
840   get a file
841   ****************************************************************************/
842 static int cmd_get(const char **cmd_ptr)
843 {
844         pstring lname;
845         pstring rname;
846         char *p;
847
848         pstrcpy(rname,cur_dir);
849         pstrcat(rname,"\\");
850         
851         p = rname + strlen(rname);
852         
853         if (!next_token(cmd_ptr,p,NULL,sizeof(rname)-strlen(rname))) {
854                 d_printf("get <filename>\n");
855                 return 1;
856         }
857         pstrcpy(lname,p);
858         dos_clean_name(rname);
859         
860         next_token(cmd_ptr,lname,NULL,sizeof(lname));
861         
862         return do_get(rname, lname, False);
863 }
864
865 /****************************************************************************
866  Put up a yes/no prompt.
867 ****************************************************************************/
868 static BOOL yesno(char *p)
869 {
870         pstring ans;
871         printf("%s",p);
872
873         if (!fgets(ans,sizeof(ans)-1,stdin))
874                 return(False);
875
876         if (*ans == 'y' || *ans == 'Y')
877                 return(True);
878
879         return(False);
880 }
881
882 /****************************************************************************
883   do a mget operation on one file
884   ****************************************************************************/
885 static void do_mget(struct clilist_file_info *finfo)
886 {
887         pstring rname;
888         pstring quest;
889         pstring saved_curdir;
890         pstring mget_mask;
891
892         if (strequal(finfo->name,".") || strequal(finfo->name,".."))
893                 return;
894
895         if (abort_mget) {
896                 d_printf("mget aborted\n");
897                 return;
898         }
899
900         if (finfo->attrib & FILE_ATTRIBUTE_DIRECTORY)
901                 slprintf(quest,sizeof(pstring)-1,
902                          "Get directory %s? ",finfo->name);
903         else
904                 slprintf(quest,sizeof(pstring)-1,
905                          "Get file %s? ",finfo->name);
906
907         if (prompt && !yesno(quest)) return;
908
909         if (!(finfo->attrib & FILE_ATTRIBUTE_DIRECTORY)) {
910                 pstrcpy(rname,cur_dir);
911                 pstrcat(rname,finfo->name);
912                 do_get(rname, finfo->name, False);
913                 return;
914         }
915
916         /* handle directories */
917         pstrcpy(saved_curdir,cur_dir);
918
919         pstrcat(cur_dir,finfo->name);
920         pstrcat(cur_dir,"\\");
921
922         string_replace(discard_const_p(char, finfo->name), '\\', '/');
923         if (lowercase) {
924                 strlower(discard_const_p(char, finfo->name));
925         }
926         
927         if (!directory_exist(finfo->name) && 
928             mkdir(finfo->name,0777) != 0) {
929                 d_printf("failed to create directory %s\n",finfo->name);
930                 pstrcpy(cur_dir,saved_curdir);
931                 return;
932         }
933         
934         if (chdir(finfo->name) != 0) {
935                 d_printf("failed to chdir to directory %s\n",finfo->name);
936                 pstrcpy(cur_dir,saved_curdir);
937                 return;
938         }
939
940         pstrcpy(mget_mask,cur_dir);
941         pstrcat(mget_mask,"*");
942         
943         do_list(mget_mask, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_DIRECTORY,do_mget,False, True);
944         chdir("..");
945         pstrcpy(cur_dir,saved_curdir);
946 }
947
948
949 /****************************************************************************
950 view the file using the pager
951 ****************************************************************************/
952 static int cmd_more(const char **cmd_ptr)
953 {
954         fstring rname,lname,pager_cmd;
955         char *pager;
956         int fd;
957         int rc = 0;
958
959         fstrcpy(rname,cur_dir);
960         fstrcat(rname,"\\");
961         
962         slprintf(lname,sizeof(lname)-1, "%s/smbmore.XXXXXX",tmpdir());
963         fd = mkstemp(lname);
964         if (fd == -1) {
965                 d_printf("failed to create temporary file for more\n");
966                 return 1;
967         }
968         close(fd);
969
970         if (!next_token(cmd_ptr,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
971                 d_printf("more <filename>\n");
972                 unlink(lname);
973                 return 1;
974         }
975         dos_clean_name(rname);
976
977         rc = do_get(rname, lname, False);
978
979         pager=getenv("PAGER");
980
981         slprintf(pager_cmd,sizeof(pager_cmd)-1,
982                  "%s %s",(pager? pager:PAGER), lname);
983         system(pager_cmd);
984         unlink(lname);
985         
986         return rc;
987 }
988
989
990
991 /****************************************************************************
992 do a mget command
993 ****************************************************************************/
994 static int cmd_mget(const char **cmd_ptr)
995 {
996         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
997         pstring mget_mask;
998         fstring buf;
999         char *p=buf;
1000
1001         *mget_mask = 0;
1002
1003         if (recurse)
1004                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
1005         
1006         abort_mget = False;
1007
1008         while (next_token(cmd_ptr,p,NULL,sizeof(buf))) {
1009                 pstrcpy(mget_mask,cur_dir);
1010                 if(mget_mask[strlen(mget_mask)-1]!='\\')
1011                         pstrcat(mget_mask,"\\");
1012                 
1013                 if (*p == '\\')
1014                         pstrcpy(mget_mask,p);
1015                 else
1016                         pstrcat(mget_mask,p);
1017                 do_list(mget_mask, attribute,do_mget,False,True);
1018         }
1019
1020         if (!*mget_mask) {
1021                 pstrcpy(mget_mask,cur_dir);
1022                 if(mget_mask[strlen(mget_mask)-1]!='\\')
1023                         pstrcat(mget_mask,"\\");
1024                 pstrcat(mget_mask,"*");
1025                 do_list(mget_mask, attribute,do_mget,False,True);
1026         }
1027         
1028         return 0;
1029 }
1030
1031
1032 /****************************************************************************
1033 make a directory of name "name"
1034 ****************************************************************************/
1035 static NTSTATUS do_mkdir(char *name)
1036 {
1037         NTSTATUS status;
1038
1039         if (NT_STATUS_IS_ERR(status = smbcli_mkdir(cli->tree, name))) {
1040                 d_printf("%s making remote directory %s\n",
1041                          smbcli_errstr(cli->tree),name);
1042                 return status;
1043         }
1044
1045         return status;
1046 }
1047
1048 /****************************************************************************
1049 show 8.3 name of a file
1050 ****************************************************************************/
1051 static BOOL do_altname(char *name)
1052 {
1053         const char *altname;
1054         if (!NT_STATUS_IS_OK(smbcli_qpathinfo_alt_name(cli->tree, name, &altname))) {
1055                 d_printf("%s getting alt name for %s\n",
1056                          smbcli_errstr(cli->tree),name);
1057                 return(False);
1058         }
1059         d_printf("%s\n", altname);
1060
1061         return(True);
1062 }
1063
1064
1065 /****************************************************************************
1066  Exit client.
1067 ****************************************************************************/
1068 static int cmd_quit(const char **cmd_ptr)
1069 {
1070         talloc_free(cli);
1071         exit(0);
1072         /* NOTREACHED */
1073         return 0;
1074 }
1075
1076
1077 /****************************************************************************
1078   make a directory
1079   ****************************************************************************/
1080 static int cmd_mkdir(const char **cmd_ptr)
1081 {
1082         pstring mask;
1083         fstring buf;
1084         char *p=buf;
1085   
1086         pstrcpy(mask,cur_dir);
1087
1088         if (!next_token(cmd_ptr,p,NULL,sizeof(buf))) {
1089                 if (!recurse)
1090                         d_printf("mkdir <dirname>\n");
1091                 return 1;
1092         }
1093         pstrcat(mask,p);
1094
1095         if (recurse) {
1096                 pstring ddir;
1097                 pstring ddir2;
1098                 *ddir2 = 0;
1099                 
1100                 pstrcpy(ddir,mask);
1101                 trim_string(ddir,".",NULL);
1102                 p = strtok(ddir,"/\\");
1103                 while (p) {
1104                         pstrcat(ddir2,p);
1105                         if (NT_STATUS_IS_ERR(smbcli_chkpath(cli->tree, ddir2))) { 
1106                                 do_mkdir(ddir2);
1107                         }
1108                         pstrcat(ddir2,"\\");
1109                         p = strtok(NULL,"/\\");
1110                 }        
1111         } else {
1112                 do_mkdir(mask);
1113         }
1114         
1115         return 0;
1116 }
1117
1118
1119 /****************************************************************************
1120   show alt name
1121   ****************************************************************************/
1122 static int cmd_altname(const char **cmd_ptr)
1123 {
1124         pstring name;
1125         fstring buf;
1126         char *p=buf;
1127   
1128         pstrcpy(name,cur_dir);
1129
1130         if (!next_token(cmd_ptr,p,NULL,sizeof(buf))) {
1131                 d_printf("altname <file>\n");
1132                 return 1;
1133         }
1134         pstrcat(name,p);
1135
1136         do_altname(name);
1137
1138         return 0;
1139 }
1140
1141
1142 /****************************************************************************
1143   put a single file
1144   ****************************************************************************/
1145 static int do_put(char *rname, char *lname, BOOL reput)
1146 {
1147         int fnum;
1148         XFILE *f;
1149         size_t start = 0;
1150         off_t nread = 0;
1151         uint8_t *buf = NULL;
1152         int maxwrite = io_bufsize;
1153         int rc = 0;
1154         
1155         struct timeval tp_start;
1156         GetTimeOfDay(&tp_start);
1157
1158         if (reput) {
1159                 fnum = smbcli_open(cli->tree, rname, O_RDWR|O_CREAT, DENY_NONE);
1160                 if (fnum >= 0) {
1161                         if (NT_STATUS_IS_ERR(smbcli_qfileinfo(cli->tree, fnum, NULL, &start, NULL, NULL, NULL, NULL, NULL)) &&
1162                             NT_STATUS_IS_ERR(smbcli_getattrE(cli->tree, fnum, NULL, &start, NULL, NULL, NULL))) {
1163                                 d_printf("getattrib: %s\n",smbcli_errstr(cli->tree));
1164                                 return 1;
1165                         }
1166                 }
1167         } else {
1168                 fnum = smbcli_open(cli->tree, rname, O_RDWR|O_CREAT|O_TRUNC, 
1169                                 DENY_NONE);
1170         }
1171   
1172         if (fnum == -1) {
1173                 d_printf("%s opening remote file %s\n",smbcli_errstr(cli->tree),rname);
1174                 return 1;
1175         }
1176
1177         /* allow files to be piped into smbclient
1178            jdblair 24.jun.98
1179
1180            Note that in this case this function will exit(0) rather
1181            than returning. */
1182         if (!strcmp(lname, "-")) {
1183                 f = x_stdin;
1184                 /* size of file is not known */
1185         } else {
1186                 f = x_fopen(lname,O_RDONLY, 0);
1187                 if (f && reput) {
1188                         if (x_tseek(f, start, SEEK_SET) == -1) {
1189                                 d_printf("Error seeking local file\n");
1190                                 return 1;
1191                         }
1192                 }
1193         }
1194
1195         if (!f) {
1196                 d_printf("Error opening local file %s\n",lname);
1197                 return 1;
1198         }
1199
1200   
1201         DEBUG(1,("putting file %s as %s ",lname,
1202                  rname));
1203   
1204         buf = (uint8_t *)malloc(maxwrite);
1205         if (!buf) {
1206                 d_printf("ERROR: Not enough memory!\n");
1207                 return 1;
1208         }
1209         while (!x_feof(f)) {
1210                 int n = maxwrite;
1211                 int ret;
1212
1213                 if ((n = readfile(buf,n,f)) < 1) {
1214                         if((n == 0) && x_feof(f))
1215                                 break; /* Empty local file. */
1216
1217                         d_printf("Error reading local file: %s\n", strerror(errno));
1218                         rc = 1;
1219                         break;
1220                 }
1221
1222                 ret = smbcli_write(cli->tree, fnum, 0, buf, nread + start, n);
1223
1224                 if (n != ret) {
1225                         d_printf("Error writing file: %s\n", smbcli_errstr(cli->tree));
1226                         rc = 1;
1227                         break;
1228                 } 
1229
1230                 nread += n;
1231         }
1232
1233         if (NT_STATUS_IS_ERR(smbcli_close(cli->tree, fnum))) {
1234                 d_printf("%s closing remote file %s\n",smbcli_errstr(cli->tree),rname);
1235                 x_fclose(f);
1236                 SAFE_FREE(buf);
1237                 return 1;
1238         }
1239
1240         
1241         if (f != x_stdin) {
1242                 x_fclose(f);
1243         }
1244
1245         SAFE_FREE(buf);
1246
1247         {
1248                 struct timeval tp_end;
1249                 int this_time;
1250                 
1251                 GetTimeOfDay(&tp_end);
1252                 this_time = 
1253                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1254                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
1255                 put_total_time_ms += this_time;
1256                 put_total_size += nread;
1257                 
1258                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1259                          nread / (1.024*this_time + 1.0e-4),
1260                          put_total_size / (1.024*put_total_time_ms)));
1261         }
1262
1263         if (f == x_stdin) {
1264                 talloc_free(cli);
1265                 exit(0);
1266         }
1267         
1268         return rc;
1269 }
1270
1271  
1272
1273 /****************************************************************************
1274   put a file
1275   ****************************************************************************/
1276 static int cmd_put(const char **cmd_ptr)
1277 {
1278         pstring lname;
1279         pstring rname;
1280         fstring buf;
1281         char *p=buf;
1282         
1283         pstrcpy(rname,cur_dir);
1284         pstrcat(rname,"\\");
1285   
1286         if (!next_token(cmd_ptr,p,NULL,sizeof(buf))) {
1287                 d_printf("put <filename>\n");
1288                 return 1;
1289         }
1290         pstrcpy(lname,p);
1291   
1292         if (next_token(cmd_ptr,p,NULL,sizeof(buf)))
1293                 pstrcat(rname,p);      
1294         else
1295                 pstrcat(rname,lname);
1296         
1297         dos_clean_name(rname);
1298
1299         /* allow '-' to represent stdin
1300            jdblair, 24.jun.98 */
1301         if (!file_exist(lname) && (strcmp(lname,"-"))) {
1302                 d_printf("%s does not exist\n",lname);
1303                 return 1;
1304         }
1305
1306         return do_put(rname, lname, False);
1307 }
1308
1309 /*************************************
1310   File list structure
1311 *************************************/
1312
1313 static struct file_list {
1314         struct file_list *prev, *next;
1315         char *file_path;
1316         BOOL isdir;
1317 } *file_list;
1318
1319 /****************************************************************************
1320   Free a file_list structure
1321 ****************************************************************************/
1322
1323 static void free_file_list (struct file_list * list)
1324 {
1325         struct file_list *tmp;
1326         
1327         while (list)
1328         {
1329                 tmp = list;
1330                 DLIST_REMOVE(list, list);
1331                 SAFE_FREE(tmp->file_path);
1332                 SAFE_FREE(tmp);
1333         }
1334 }
1335
1336 /****************************************************************************
1337   seek in a directory/file list until you get something that doesn't start with
1338   the specified name
1339   ****************************************************************************/
1340 static BOOL seek_list(struct file_list *list, char *name)
1341 {
1342         while (list) {
1343                 trim_string(list->file_path,"./","\n");
1344                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1345                         return(True);
1346                 }
1347                 list = list->next;
1348         }
1349       
1350         return(False);
1351 }
1352
1353 /****************************************************************************
1354   set the file selection mask
1355   ****************************************************************************/
1356 static int cmd_select(const char **cmd_ptr)
1357 {
1358         pstrcpy(fileselection,"");
1359         next_token(cmd_ptr,fileselection,NULL,sizeof(fileselection));
1360
1361         return 0;
1362 }
1363
1364 /*******************************************************************
1365   A readdir wrapper which just returns the file name.
1366  ********************************************************************/
1367 static const char *readdirname(DIR *p)
1368 {
1369         struct dirent *ptr;
1370         char *dname;
1371
1372         if (!p)
1373                 return(NULL);
1374   
1375         ptr = (struct dirent *)readdir(p);
1376         if (!ptr)
1377                 return(NULL);
1378
1379         dname = ptr->d_name;
1380
1381 #ifdef NEXT2
1382         if (telldir(p) < 0)
1383                 return(NULL);
1384 #endif
1385
1386 #ifdef HAVE_BROKEN_READDIR
1387         /* using /usr/ucb/cc is BAD */
1388         dname = dname - 2;
1389 #endif
1390
1391         {
1392                 static pstring buf;
1393                 int len = NAMLEN(ptr);
1394                 memcpy(buf, dname, len);
1395                 buf[len] = 0;
1396                 dname = buf;
1397         }
1398
1399         return(dname);
1400 }
1401
1402 /****************************************************************************
1403   Recursive file matching function act as find
1404   match must be always set to True when calling this function
1405 ****************************************************************************/
1406 static int file_find(struct file_list **list, const char *directory, 
1407                       const char *expression, BOOL match)
1408 {
1409         DIR *dir;
1410         struct file_list *entry;
1411         struct stat statbuf;
1412         int ret;
1413         char *path;
1414         BOOL isdir;
1415         const char *dname;
1416
1417         dir = opendir(directory);
1418         if (!dir) return -1;
1419         
1420         while ((dname = readdirname(dir))) {
1421                 if (!strcmp("..", dname)) continue;
1422                 if (!strcmp(".", dname)) continue;
1423                 
1424                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1425                         continue;
1426                 }
1427
1428                 isdir = False;
1429                 if (!match || !gen_fnmatch(expression, dname)) {
1430                         if (recurse) {
1431                                 ret = stat(path, &statbuf);
1432                                 if (ret == 0) {
1433                                         if (S_ISDIR(statbuf.st_mode)) {
1434                                                 isdir = True;
1435                                                 ret = file_find(list, path, expression, False);
1436                                         }
1437                                 } else {
1438                                         d_printf("file_find: cannot stat file %s\n", path);
1439                                 }
1440                                 
1441                                 if (ret == -1) {
1442                                         SAFE_FREE(path);
1443                                         closedir(dir);
1444                                         return -1;
1445                                 }
1446                         }
1447                         entry = malloc_p(struct file_list);
1448                         if (!entry) {
1449                                 d_printf("Out of memory in file_find\n");
1450                                 closedir(dir);
1451                                 return -1;
1452                         }
1453                         entry->file_path = path;
1454                         entry->isdir = isdir;
1455                         DLIST_ADD(*list, entry);
1456                 } else {
1457                         SAFE_FREE(path);
1458                 }
1459         }
1460
1461         closedir(dir);
1462         return 0;
1463 }
1464
1465 /****************************************************************************
1466   mput some files
1467   ****************************************************************************/
1468 static int cmd_mput(const char **cmd_ptr)
1469 {
1470         fstring buf;
1471         char *p=buf;
1472         
1473         while (next_token(cmd_ptr,p,NULL,sizeof(buf))) {
1474                 int ret;
1475                 struct file_list *temp_list;
1476                 char *quest, *lname, *rname;
1477         
1478                 file_list = NULL;
1479
1480                 ret = file_find(&file_list, ".", p, True);
1481                 if (ret) {
1482                         free_file_list(file_list);
1483                         continue;
1484                 }
1485                 
1486                 quest = NULL;
1487                 lname = NULL;
1488                 rname = NULL;
1489                                 
1490                 for (temp_list = file_list; temp_list; 
1491                      temp_list = temp_list->next) {
1492
1493                         SAFE_FREE(lname);
1494                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1495                                 continue;
1496                         trim_string(lname, "./", "/");
1497                         
1498                         /* check if it's a directory */
1499                         if (temp_list->isdir) {
1500                                 /* if (!recurse) continue; */
1501                                 
1502                                 SAFE_FREE(quest);
1503                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) break;
1504                                 if (prompt && !yesno(quest)) { /* No */
1505                                         /* Skip the directory */
1506                                         lname[strlen(lname)-1] = '/';
1507                                         if (!seek_list(temp_list, lname))
1508                                                 break;              
1509                                 } else { /* Yes */
1510                                         SAFE_FREE(rname);
1511                                         if(asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1512                                         dos_format(rname);
1513                                         if (NT_STATUS_IS_ERR(smbcli_chkpath(cli->tree, rname)) && 
1514                                             NT_STATUS_IS_ERR(do_mkdir(rname))) {
1515                                                 DEBUG (0, ("Unable to make dir, skipping..."));
1516                                                 /* Skip the directory */
1517                                                 lname[strlen(lname)-1] = '/';
1518                                                 if (!seek_list(temp_list, lname))
1519                                                         break;
1520                                         }
1521                                 }
1522                                 continue;
1523                         } else {
1524                                 SAFE_FREE(quest);
1525                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) break;
1526                                 if (prompt && !yesno(quest)) /* No */
1527                                         continue;
1528                                 
1529                                 /* Yes */
1530                                 SAFE_FREE(rname);
1531                                 if (asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1532                         }
1533
1534                         dos_format(rname);
1535
1536                         do_put(rname, lname, False);
1537                 }
1538                 free_file_list(file_list);
1539                 SAFE_FREE(quest);
1540                 SAFE_FREE(lname);
1541                 SAFE_FREE(rname);
1542         }
1543
1544         return 0;
1545 }
1546
1547
1548 /****************************************************************************
1549   cancel a print job
1550   ****************************************************************************/
1551 static int do_cancel(int job)
1552 {
1553         d_printf("REWRITE: print job cancel not implemented\n");
1554         return 1;
1555 }
1556
1557
1558 /****************************************************************************
1559   cancel a print job
1560   ****************************************************************************/
1561 static int cmd_cancel(const char **cmd_ptr)
1562 {
1563         fstring buf;
1564         int job; 
1565
1566         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1567                 d_printf("cancel <jobid> ...\n");
1568                 return 1;
1569         }
1570         do {
1571                 job = atoi(buf);
1572                 do_cancel(job);
1573         } while (next_token(cmd_ptr,buf,NULL,sizeof(buf)));
1574         
1575         return 0;
1576 }
1577
1578
1579 /****************************************************************************
1580   print a file
1581   ****************************************************************************/
1582 static int cmd_print(const char **cmd_ptr)
1583 {
1584         pstring lname;
1585         pstring rname;
1586         char *p;
1587
1588         if (!next_token(cmd_ptr,lname,NULL, sizeof(lname))) {
1589                 d_printf("print <filename>\n");
1590                 return 1;
1591         }
1592
1593         pstrcpy(rname,lname);
1594         p = strrchr_m(rname,'/');
1595         if (p) {
1596                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)getpid());
1597         }
1598
1599         if (strequal(lname,"-")) {
1600                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)getpid());
1601         }
1602
1603         return do_put(rname, lname, False);
1604 }
1605
1606
1607 /****************************************************************************
1608  show a print queue
1609 ****************************************************************************/
1610 static int cmd_queue(const char **cmd_ptr)
1611 {
1612         d_printf("REWRITE: print job queue not implemented\n");
1613         
1614         return 0;
1615 }
1616
1617 /****************************************************************************
1618 delete some files
1619 ****************************************************************************/
1620 static int cmd_del(const char **cmd_ptr)
1621 {
1622         pstring mask;
1623         fstring buf;
1624         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
1625
1626         if (recurse)
1627                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
1628         
1629         pstrcpy(mask,cur_dir);
1630         
1631         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1632                 d_printf("del <filename>\n");
1633                 return 1;
1634         }
1635         pstrcat(mask,buf);
1636
1637         if (NT_STATUS_IS_ERR(smbcli_unlink(cli->tree, mask))) {
1638                 d_printf("%s deleting remote file %s\n",smbcli_errstr(cli->tree),mask);
1639         }
1640         
1641         return 0;
1642 }
1643
1644
1645 /****************************************************************************
1646 delete a whole directory tree
1647 ****************************************************************************/
1648 static int cmd_deltree(const char **cmd_ptr)
1649 {
1650         pstring dname;
1651         fstring buf;
1652         int ret;
1653
1654         pstrcpy(dname,cur_dir);
1655         
1656         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1657                 d_printf("deltree <dirname>\n");
1658                 return 1;
1659         }
1660         pstrcat(dname,buf);
1661         
1662         ret = smbcli_deltree(cli->tree, dname);
1663
1664         if (ret == -1) {
1665                 printf("Failed to delete tree %s - %s\n", dname, smbcli_errstr(cli->tree));
1666                 return -1;
1667         }
1668
1669         printf("Deleted %d files in %s\n", ret, dname);
1670         
1671         return 0;
1672 }
1673
1674 typedef struct {
1675         const char  *level_name;
1676         enum smb_fsinfo_level level;
1677 } fsinfo_level_t;
1678
1679 fsinfo_level_t fsinfo_levels[] = {
1680         {"dskattr", RAW_QFS_DSKATTR},
1681         {"allocation", RAW_QFS_ALLOCATION},
1682         {"volume", RAW_QFS_VOLUME},
1683         {"volumeinfo", RAW_QFS_VOLUME_INFO},
1684         {"sizeinfo", RAW_QFS_SIZE_INFO},
1685         {"deviceinfo", RAW_QFS_DEVICE_INFO},
1686         {"attributeinfo", RAW_QFS_ATTRIBUTE_INFO},
1687         {"unixinfo", RAW_QFS_UNIX_INFO},
1688         {"volume-information", RAW_QFS_VOLUME_INFORMATION},
1689         {"size-information", RAW_QFS_SIZE_INFORMATION},
1690         {"device-information", RAW_QFS_DEVICE_INFORMATION},
1691         {"attribute-information", RAW_QFS_ATTRIBUTE_INFORMATION},
1692         {"quota-information", RAW_QFS_QUOTA_INFORMATION},
1693         {"fullsize-information", RAW_QFS_FULL_SIZE_INFORMATION},
1694         {"objectid", RAW_QFS_OBJECTID_INFORMATION},
1695         {NULL, RAW_QFS_GENERIC}
1696 };
1697
1698
1699 static int cmd_fsinfo(const char **cmd_ptr)
1700 {
1701         fstring buf;
1702         int ret = 0;
1703         union smb_fsinfo fsinfo;
1704         NTSTATUS status;
1705         TALLOC_CTX *mem_ctx;
1706         fsinfo_level_t *fsinfo_level;
1707         
1708         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1709                 d_printf("fsinfo <level>, where level is one of following:\n");
1710                 fsinfo_level = fsinfo_levels;
1711                 while(fsinfo_level->level_name) {
1712                         d_printf("%s\n", fsinfo_level->level_name);
1713                         fsinfo_level++;
1714                 }
1715                 return 1;
1716         }
1717         
1718         fsinfo_level = fsinfo_levels;
1719         while(fsinfo_level->level_name && !strequal(buf,fsinfo_level->level_name)) {
1720                 fsinfo_level++;
1721         }
1722   
1723         if (!fsinfo_level->level_name) {
1724                 d_printf("wrong level name!\n");
1725                 return 1;
1726         }
1727   
1728         mem_ctx = talloc_init("fsinfo-level-%s", fsinfo_level->level_name);
1729         fsinfo.generic.level = fsinfo_level->level;
1730         status = smb_raw_fsinfo(cli->tree, mem_ctx, &fsinfo);
1731         if (!NT_STATUS_IS_OK(status)) {
1732                 d_printf("fsinfo-level-%s - %s\n", fsinfo_level->level_name, nt_errstr(status));
1733                 ret = 1;
1734                 goto done;
1735         }
1736
1737         d_printf("fsinfo-level-%s:\n", fsinfo_level->level_name);
1738         switch(fsinfo.generic.level) {
1739         case RAW_QFS_DSKATTR:
1740                 d_printf("\tunits_total:                %hu\n", 
1741                          (unsigned short) fsinfo.dskattr.out.units_total);
1742                 d_printf("\tblocks_per_unit:            %hu\n", 
1743                          (unsigned short) fsinfo.dskattr.out.blocks_per_unit);
1744                 d_printf("\tblocks_size:                %hu\n", 
1745                          (unsigned short) fsinfo.dskattr.out.block_size);
1746                 d_printf("\tunits_free:                 %hu\n", 
1747                          (unsigned short) fsinfo.dskattr.out.units_free);
1748                 break;
1749         case RAW_QFS_ALLOCATION:
1750                 d_printf("\tfs_id:                      %lu\n", 
1751                          (unsigned long) fsinfo.allocation.out.fs_id);
1752                 d_printf("\tsectors_per_unit:           %lu\n", 
1753                          (unsigned long) fsinfo.allocation.out.sectors_per_unit);
1754                 d_printf("\ttotal_alloc_units:          %lu\n", 
1755                          (unsigned long) fsinfo.allocation.out.total_alloc_units);
1756                 d_printf("\tavail_alloc_units:          %lu\n", 
1757                          (unsigned long) fsinfo.allocation.out.avail_alloc_units);
1758                 d_printf("\tbytes_per_sector:           %hu\n", 
1759                          (unsigned short) fsinfo.allocation.out.bytes_per_sector);
1760                 break;
1761         case RAW_QFS_VOLUME:
1762                 d_printf("\tserial_number:              %lu\n", 
1763                          (unsigned long) fsinfo.volume.out.serial_number);
1764                 d_printf("\tvolume_name:                %s\n", fsinfo.volume.out.volume_name.s);
1765                 break;
1766         case RAW_QFS_VOLUME_INFO:
1767         case RAW_QFS_VOLUME_INFORMATION:
1768                 d_printf("\tcreate_time:                %s\n",
1769                          nt_time_string(mem_ctx,fsinfo.volume_info.out.create_time));
1770                 d_printf("\tserial_number:              %lu\n", 
1771                          (unsigned long) fsinfo.volume_info.out.serial_number);
1772                 d_printf("\tvolume_name:                %s\n", fsinfo.volume_info.out.volume_name.s);
1773                 break;
1774         case RAW_QFS_SIZE_INFO:
1775         case RAW_QFS_SIZE_INFORMATION:
1776                 d_printf("\ttotal_alloc_units:          %llu\n", 
1777                          (unsigned long long) fsinfo.size_info.out.total_alloc_units);
1778                 d_printf("\tavail_alloc_units:          %llu\n", 
1779                          (unsigned long long) fsinfo.size_info.out.avail_alloc_units);
1780                 d_printf("\tsectors_per_unit:           %lu\n", 
1781                          (unsigned long) fsinfo.size_info.out.sectors_per_unit);
1782                 d_printf("\tbytes_per_sector:           %lu\n", 
1783                          (unsigned long) fsinfo.size_info.out.bytes_per_sector);
1784                 break;
1785         case RAW_QFS_DEVICE_INFO:
1786         case RAW_QFS_DEVICE_INFORMATION:
1787                 d_printf("\tdevice_type:                %lu\n", 
1788                          (unsigned long) fsinfo.device_info.out.device_type);
1789                 d_printf("\tcharacteristics:            0x%lx\n", 
1790                          (unsigned long) fsinfo.device_info.out.characteristics);
1791                 break;
1792         case RAW_QFS_ATTRIBUTE_INFORMATION:
1793         case RAW_QFS_ATTRIBUTE_INFO:
1794                 d_printf("\tfs_attr:                    0x%lx\n", 
1795                          (unsigned long) fsinfo.attribute_info.out.fs_attr);
1796                 d_printf("\tmax_file_component_length:  %lu\n", 
1797                          (unsigned long) fsinfo.attribute_info.out.max_file_component_length);
1798                 d_printf("\tfs_type:                    %s\n", fsinfo.attribute_info.out.fs_type.s);
1799                 break;
1800         case RAW_QFS_UNIX_INFO:
1801                 d_printf("\tmajor_version:              %hu\n", 
1802                          (unsigned short) fsinfo.unix_info.out.major_version);
1803                 d_printf("\tminor_version:              %hu\n", 
1804                          (unsigned short) fsinfo.unix_info.out.minor_version);
1805                 d_printf("\tcapability:                 0x%llx\n", 
1806                          (unsigned long long) fsinfo.unix_info.out.capability);
1807                 break;
1808         case RAW_QFS_QUOTA_INFORMATION:
1809                 d_printf("\tunknown[3]:                 [%llu,%llu,%llu]\n", 
1810                          (unsigned long long) fsinfo.quota_information.out.unknown[0],
1811                          (unsigned long long) fsinfo.quota_information.out.unknown[1],
1812                          (unsigned long long) fsinfo.quota_information.out.unknown[2]);
1813                 d_printf("\tquota_soft:                 %llu\n", 
1814                          (unsigned long long) fsinfo.quota_information.out.quota_soft);
1815                 d_printf("\tquota_hard:                 %llu\n", 
1816                          (unsigned long long) fsinfo.quota_information.out.quota_hard);
1817                 d_printf("\tquota_flags:                0x%llx\n", 
1818                          (unsigned long long) fsinfo.quota_information.out.quota_flags);
1819                 break;
1820         case RAW_QFS_FULL_SIZE_INFORMATION:
1821                 d_printf("\ttotal_alloc_units:          %llu\n", 
1822                          (unsigned long long) fsinfo.full_size_information.out.total_alloc_units);
1823                 d_printf("\tcall_avail_alloc_units:     %llu\n", 
1824                          (unsigned long long) fsinfo.full_size_information.out.call_avail_alloc_units);
1825                 d_printf("\tactual_avail_alloc_units:   %llu\n", 
1826                          (unsigned long long) fsinfo.full_size_information.out.actual_avail_alloc_units);
1827                 d_printf("\tsectors_per_unit:           %lu\n", 
1828                          (unsigned long) fsinfo.full_size_information.out.sectors_per_unit);
1829                 d_printf("\tbytes_per_sector:           %lu\n", 
1830                          (unsigned long) fsinfo.full_size_information.out.bytes_per_sector);
1831                 break;
1832         case RAW_QFS_OBJECTID_INFORMATION:
1833                 d_printf("\tGUID:                       %s\n", 
1834                          GUID_string(mem_ctx,&fsinfo.objectid_information.out.guid));
1835                 d_printf("\tunknown[6]:                 [%llu,%llu,%llu,%llu,%llu,%llu]\n", 
1836                          (unsigned long long) fsinfo.objectid_information.out.unknown[0],
1837                          (unsigned long long) fsinfo.objectid_information.out.unknown[2],
1838                          (unsigned long long) fsinfo.objectid_information.out.unknown[3],
1839                          (unsigned long long) fsinfo.objectid_information.out.unknown[4],
1840                          (unsigned long long) fsinfo.objectid_information.out.unknown[5],
1841                          (unsigned long long) fsinfo.objectid_information.out.unknown[6] );
1842                 break;
1843         }
1844   
1845  done:
1846         talloc_free(mem_ctx);
1847         return ret;
1848 }
1849
1850 /****************************************************************************
1851 show as much information as possible about a file
1852 ****************************************************************************/
1853 static int cmd_allinfo(const char **cmd_ptr)
1854 {
1855         pstring fname;
1856         fstring buf;
1857         int ret = 0;
1858         TALLOC_CTX *mem_ctx;
1859         union smb_fileinfo finfo;
1860         NTSTATUS status;
1861
1862         pstrcpy(fname,cur_dir);
1863         
1864         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1865                 d_printf("allinfo <filename>\n");
1866                 return 1;
1867         }
1868         pstrcat(fname,buf);
1869
1870         mem_ctx = talloc_init("%s", fname);
1871
1872         /* first a ALL_INFO QPATHINFO */
1873         finfo.generic.level = RAW_FILEINFO_ALL_INFO;
1874         finfo.generic.in.fname = fname;
1875         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1876         if (!NT_STATUS_IS_OK(status)) {
1877                 d_printf("%s - %s\n", fname, nt_errstr(status));
1878                 ret = 1;
1879                 goto done;
1880         }
1881
1882         d_printf("\tcreate_time:    %s\n", nt_time_string(mem_ctx, finfo.all_info.out.create_time));
1883         d_printf("\taccess_time:    %s\n", nt_time_string(mem_ctx, finfo.all_info.out.access_time));
1884         d_printf("\twrite_time:     %s\n", nt_time_string(mem_ctx, finfo.all_info.out.write_time));
1885         d_printf("\tchange_time:    %s\n", nt_time_string(mem_ctx, finfo.all_info.out.change_time));
1886         d_printf("\tattrib:         0x%x\n", finfo.all_info.out.attrib);
1887         d_printf("\talloc_size:     %lu\n", (unsigned long)finfo.all_info.out.alloc_size);
1888         d_printf("\tsize:           %lu\n", (unsigned long)finfo.all_info.out.size);
1889         d_printf("\tnlink:          %u\n", finfo.all_info.out.nlink);
1890         d_printf("\tdelete_pending: %u\n", finfo.all_info.out.delete_pending);
1891         d_printf("\tdirectory:      %u\n", finfo.all_info.out.directory);
1892         d_printf("\tea_size:        %u\n", finfo.all_info.out.ea_size);
1893         d_printf("\tfname:          '%s'\n", finfo.all_info.out.fname.s);
1894
1895         /* 8.3 name if any */
1896         finfo.generic.level = RAW_FILEINFO_ALT_NAME_INFO;
1897         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1898         if (NT_STATUS_IS_OK(status)) {
1899                 d_printf("\talt_name:       %s\n", finfo.alt_name_info.out.fname.s);
1900         }
1901
1902         /* file_id if available */
1903         finfo.generic.level = RAW_FILEINFO_INTERNAL_INFORMATION;
1904         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1905         if (NT_STATUS_IS_OK(status)) {
1906                 d_printf("\tfile_id         %.0f\n", 
1907                          (double)finfo.internal_information.out.file_id);
1908         }
1909
1910         /* the EAs, if any */
1911         finfo.generic.level = RAW_FILEINFO_ALL_EAS;
1912         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1913         if (NT_STATUS_IS_OK(status)) {
1914                 int i;
1915                 for (i=0;i<finfo.all_eas.out.num_eas;i++) {
1916                         d_printf("\tEA[%d] flags=%d len=%d '%s'\n", i,
1917                                  finfo.all_eas.out.eas[i].flags,
1918                                  (int)finfo.all_eas.out.eas[i].value.length,
1919                                  finfo.all_eas.out.eas[i].name.s);
1920                 }
1921         }
1922
1923         /* streams, if available */
1924         finfo.generic.level = RAW_FILEINFO_STREAM_INFO;
1925         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1926         if (NT_STATUS_IS_OK(status)) {
1927                 int i;
1928                 for (i=0;i<finfo.stream_info.out.num_streams;i++) {
1929                         d_printf("\tstream %d:\n", i);
1930                         d_printf("\t\tsize       %ld\n", 
1931                                  (long)finfo.stream_info.out.streams[i].size);
1932                         d_printf("\t\talloc size %ld\n", 
1933                                  (long)finfo.stream_info.out.streams[i].alloc_size);
1934                         d_printf("\t\tname       %s\n", finfo.stream_info.out.streams[i].stream_name.s);
1935                 }
1936         }       
1937
1938         /* dev/inode if available */
1939         finfo.generic.level = RAW_FILEINFO_COMPRESSION_INFORMATION;
1940         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1941         if (NT_STATUS_IS_OK(status)) {
1942                 d_printf("\tcompressed size %ld\n", (long)finfo.compression_info.out.compressed_size);
1943                 d_printf("\tformat          %ld\n", (long)finfo.compression_info.out.format);
1944                 d_printf("\tunit_shift      %ld\n", (long)finfo.compression_info.out.unit_shift);
1945                 d_printf("\tchunk_shift     %ld\n", (long)finfo.compression_info.out.chunk_shift);
1946                 d_printf("\tcluster_shift   %ld\n", (long)finfo.compression_info.out.cluster_shift);
1947         }
1948
1949         talloc_free(mem_ctx);
1950
1951 done:
1952         return ret;
1953 }
1954
1955
1956 /****************************************************************************
1957 shows EA contents
1958 ****************************************************************************/
1959 static int cmd_eainfo(const char **cmd_ptr)
1960 {
1961         pstring fname;
1962         fstring buf;
1963         int ret = 0;
1964         TALLOC_CTX *mem_ctx;
1965         union smb_fileinfo finfo;
1966         NTSTATUS status;
1967         int i;
1968
1969         pstrcpy(fname,cur_dir);
1970         
1971         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1972                 d_printf("eainfo <filename>\n");
1973                 return 1;
1974         }
1975         pstrcat(fname,buf);
1976
1977         mem_ctx = talloc_init("%s", fname);
1978
1979         finfo.generic.in.fname = fname;
1980         finfo.generic.level = RAW_FILEINFO_ALL_EAS;
1981         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1982         
1983         if (!NT_STATUS_IS_OK(status)) {
1984                 d_printf("RAW_FILEINFO_ALL_EAS - %s\n", nt_errstr(status));
1985                 talloc_free(mem_ctx);
1986                 return 1;
1987         }
1988
1989         d_printf("%s has %d EAs\n", fname, finfo.all_eas.out.num_eas);
1990
1991         for (i=0;i<finfo.all_eas.out.num_eas;i++) {
1992                 d_printf("\tEA[%d] flags=%d len=%d '%s'\n", i,
1993                          finfo.all_eas.out.eas[i].flags,
1994                          (int)finfo.all_eas.out.eas[i].value.length,
1995                          finfo.all_eas.out.eas[i].name.s);
1996                 fflush(stdout);
1997                 dump_data(0, 
1998                           finfo.all_eas.out.eas[i].value.data,
1999                           finfo.all_eas.out.eas[i].value.length);
2000         }
2001
2002         talloc_free(mem_ctx);
2003
2004         return ret;
2005 }
2006
2007
2008 /****************************************************************************
2009 show any ACL on a file
2010 ****************************************************************************/
2011 static int cmd_acl(const char **cmd_ptr)
2012 {
2013         pstring fname;
2014         fstring buf;
2015         int ret = 0;
2016         TALLOC_CTX *mem_ctx;
2017         union smb_fileinfo query;
2018         NTSTATUS status;
2019         int fnum;
2020
2021         pstrcpy(fname,cur_dir);
2022         
2023         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2024                 d_printf("acl <filename>\n");
2025                 return 1;
2026         }
2027         pstrcat(fname,buf);
2028
2029         fnum = smbcli_nt_create_full(cli->tree, fname, 0, 
2030                                      SEC_STD_READ_CONTROL,
2031                                      0,
2032                                      NTCREATEX_SHARE_ACCESS_DELETE|
2033                                      NTCREATEX_SHARE_ACCESS_READ|
2034                                      NTCREATEX_SHARE_ACCESS_WRITE, 
2035                                      NTCREATEX_DISP_OPEN,
2036                                      0, 0);
2037         if (fnum == -1) {
2038                 d_printf("%s - %s\n", fname, smbcli_errstr(cli->tree));
2039                 return -1;
2040         }
2041
2042         mem_ctx = talloc_init("%s", fname);
2043
2044         query.query_secdesc.level = RAW_FILEINFO_SEC_DESC;
2045         query.query_secdesc.in.fnum = fnum;
2046         query.query_secdesc.secinfo_flags = 0x7;
2047
2048         status = smb_raw_fileinfo(cli->tree, mem_ctx, &query);
2049         if (!NT_STATUS_IS_OK(status)) {
2050                 d_printf("%s - %s\n", fname, nt_errstr(status));
2051                 ret = 1;
2052                 goto done;
2053         }
2054
2055         NDR_PRINT_DEBUG(security_descriptor, query.query_secdesc.out.sd);
2056
2057         talloc_free(mem_ctx);
2058
2059 done:
2060         return ret;
2061 }
2062
2063 /****************************************************************************
2064 lookup a name or sid
2065 ****************************************************************************/
2066 static int cmd_lookup(const char **cmd_ptr)
2067 {
2068         fstring buf;
2069         TALLOC_CTX *mem_ctx = talloc_new(NULL);
2070         NTSTATUS status;
2071         struct dom_sid *sid;
2072
2073         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2074                 d_printf("lookup <sid|name>\n");
2075                 talloc_free(mem_ctx);
2076                 return 1;
2077         }
2078
2079         sid = dom_sid_parse_talloc(mem_ctx, buf);
2080         if (sid == NULL) {
2081                 const char *sidstr;
2082                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sidstr);
2083                 if (!NT_STATUS_IS_OK(status)) {
2084                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
2085                         talloc_free(mem_ctx);
2086                         return 1;
2087                 }
2088
2089                 d_printf("%s\n", sidstr);
2090         } else {
2091                 const char *name;
2092                 status = smblsa_lookup_sid(cli, buf, mem_ctx, &name);
2093                 if (!NT_STATUS_IS_OK(status)) {
2094                         d_printf("lsa_LookupSids - %s\n", nt_errstr(status));
2095                         talloc_free(mem_ctx);
2096                         return 1;
2097                 }
2098
2099                 d_printf("%s\n", name);
2100         }
2101
2102         talloc_free(mem_ctx);
2103
2104         return 0;
2105 }
2106
2107 /****************************************************************************
2108 show privileges for a user
2109 ****************************************************************************/
2110 static int cmd_privileges(const char **cmd_ptr)
2111 {
2112         fstring buf;
2113         TALLOC_CTX *mem_ctx = talloc_new(NULL);
2114         NTSTATUS status;
2115         struct dom_sid *sid;
2116         struct lsa_RightSet rights;
2117         unsigned i;
2118
2119         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2120                 d_printf("privileges <sid|name>\n");
2121                 talloc_free(mem_ctx);
2122                 return 1;
2123         }
2124
2125         sid = dom_sid_parse_talloc(mem_ctx, buf);
2126         if (sid == NULL) {
2127                 const char *sid_str;
2128                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sid_str);
2129                 if (!NT_STATUS_IS_OK(status)) {
2130                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
2131                         talloc_free(mem_ctx);
2132                         return 1;
2133                 }
2134                 sid = dom_sid_parse_talloc(mem_ctx, sid_str);
2135         }
2136
2137         status = smblsa_sid_privileges(cli, sid, mem_ctx, &rights);
2138         if (!NT_STATUS_IS_OK(status)) {
2139                 d_printf("lsa_EnumAccountRights - %s\n", nt_errstr(status));
2140                 talloc_free(mem_ctx);
2141                 return 1;
2142         }
2143
2144         for (i=0;i<rights.count;i++) {
2145                 d_printf("\t%s\n", rights.names[i].string);
2146         }
2147
2148         talloc_free(mem_ctx);
2149
2150         return 0;
2151 }
2152
2153
2154 /****************************************************************************
2155 add privileges for a user
2156 ****************************************************************************/
2157 static int cmd_addprivileges(const char **cmd_ptr)
2158 {
2159         fstring buf;
2160         TALLOC_CTX *mem_ctx = talloc_new(NULL);
2161         NTSTATUS status;
2162         struct dom_sid *sid;
2163         struct lsa_RightSet rights;
2164
2165         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2166                 d_printf("addprivileges <sid|name> <privilege...>\n");
2167                 talloc_free(mem_ctx);
2168                 return 1;
2169         }
2170
2171         sid = dom_sid_parse_talloc(mem_ctx, buf);
2172         if (sid == NULL) {
2173                 const char *sid_str;
2174                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sid_str);
2175                 if (!NT_STATUS_IS_OK(status)) {
2176                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
2177                         talloc_free(mem_ctx);
2178                         return 1;
2179                 }
2180                 sid = dom_sid_parse_talloc(mem_ctx, sid_str);
2181         }
2182
2183         ZERO_STRUCT(rights);
2184         while (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2185                 rights.names = talloc_realloc(mem_ctx, rights.names, 
2186                                                 struct lsa_String, rights.count+1);
2187                 rights.names[rights.count].string = talloc_strdup(mem_ctx, buf);
2188                 rights.count++;
2189         }
2190
2191
2192         status = smblsa_sid_add_privileges(cli, sid, mem_ctx, &rights);
2193         if (!NT_STATUS_IS_OK(status)) {
2194                 d_printf("lsa_AddAccountRights - %s\n", nt_errstr(status));
2195                 talloc_free(mem_ctx);
2196                 return 1;
2197         }
2198
2199         talloc_free(mem_ctx);
2200
2201         return 0;
2202 }
2203
2204 /****************************************************************************
2205 delete privileges for a user
2206 ****************************************************************************/
2207 static int cmd_delprivileges(const char **cmd_ptr)
2208 {
2209         fstring buf;
2210         TALLOC_CTX *mem_ctx = talloc_new(NULL);
2211         NTSTATUS status;
2212         struct dom_sid *sid;
2213         struct lsa_RightSet rights;
2214
2215         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2216                 d_printf("delprivileges <sid|name> <privilege...>\n");
2217                 talloc_free(mem_ctx);
2218                 return 1;
2219         }
2220
2221         sid = dom_sid_parse_talloc(mem_ctx, buf);
2222         if (sid == NULL) {
2223                 const char *sid_str;
2224                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sid_str);
2225                 if (!NT_STATUS_IS_OK(status)) {
2226                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
2227                         talloc_free(mem_ctx);
2228                         return 1;
2229                 }
2230                 sid = dom_sid_parse_talloc(mem_ctx, sid_str);
2231         }
2232
2233         ZERO_STRUCT(rights);
2234         while (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2235                 rights.names = talloc_realloc(mem_ctx, rights.names, 
2236                                                 struct lsa_String, rights.count+1);
2237                 rights.names[rights.count].string = talloc_strdup(mem_ctx, buf);
2238                 rights.count++;
2239         }
2240
2241
2242         status = smblsa_sid_del_privileges(cli, sid, mem_ctx, &rights);
2243         if (!NT_STATUS_IS_OK(status)) {
2244                 d_printf("lsa_RemoveAccountRights - %s\n", nt_errstr(status));
2245                 talloc_free(mem_ctx);
2246                 return 1;
2247         }
2248
2249         talloc_free(mem_ctx);
2250
2251         return 0;
2252 }
2253
2254
2255 /****************************************************************************
2256 ****************************************************************************/
2257 static int cmd_open(const char **cmd_ptr)
2258 {
2259         pstring mask;
2260         fstring buf;
2261         
2262         pstrcpy(mask,cur_dir);
2263         
2264         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2265                 d_printf("open <filename>\n");
2266                 return 1;
2267         }
2268         pstrcat(mask,buf);
2269
2270         smbcli_open(cli->tree, mask, O_RDWR, DENY_ALL);
2271
2272         return 0;
2273 }
2274
2275
2276 /****************************************************************************
2277 remove a directory
2278 ****************************************************************************/
2279 static int cmd_rmdir(const char **cmd_ptr)
2280 {
2281         pstring mask;
2282         fstring buf;
2283   
2284         pstrcpy(mask,cur_dir);
2285         
2286         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2287                 d_printf("rmdir <dirname>\n");
2288                 return 1;
2289         }
2290         pstrcat(mask,buf);
2291
2292         if (NT_STATUS_IS_ERR(smbcli_rmdir(cli->tree, mask))) {
2293                 d_printf("%s removing remote directory file %s\n",
2294                          smbcli_errstr(cli->tree),mask);
2295         }
2296         
2297         return 0;
2298 }
2299
2300 /****************************************************************************
2301  UNIX hardlink.
2302 ****************************************************************************/
2303 static int cmd_link(const char **cmd_ptr)
2304 {
2305         pstring src,dest;
2306         fstring buf,buf2;
2307   
2308         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2309                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2310                 return 1;
2311         }
2312
2313         pstrcpy(src,cur_dir);
2314         pstrcpy(dest,cur_dir);
2315   
2316         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2317             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2318                 d_printf("link <src> <dest>\n");
2319                 return 1;
2320         }
2321
2322         pstrcat(src,buf);
2323         pstrcat(dest,buf2);
2324
2325         if (NT_STATUS_IS_ERR(smbcli_unix_hardlink(cli->tree, src, dest))) {
2326                 d_printf("%s linking files (%s -> %s)\n", smbcli_errstr(cli->tree), src, dest);
2327                 return 1;
2328         }  
2329
2330         return 0;
2331 }
2332
2333 /****************************************************************************
2334  UNIX symlink.
2335 ****************************************************************************/
2336
2337 static int cmd_symlink(const char **cmd_ptr)
2338 {
2339         pstring src,dest;
2340         fstring buf,buf2;
2341   
2342         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2343                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2344                 return 1;
2345         }
2346
2347         pstrcpy(src,cur_dir);
2348         pstrcpy(dest,cur_dir);
2349         
2350         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2351             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2352                 d_printf("symlink <src> <dest>\n");
2353                 return 1;
2354         }
2355
2356         pstrcat(src,buf);
2357         pstrcat(dest,buf2);
2358
2359         if (NT_STATUS_IS_ERR(smbcli_unix_symlink(cli->tree, src, dest))) {
2360                 d_printf("%s symlinking files (%s -> %s)\n",
2361                         smbcli_errstr(cli->tree), src, dest);
2362                 return 1;
2363         } 
2364
2365         return 0;
2366 }
2367
2368 /****************************************************************************
2369  UNIX chmod.
2370 ****************************************************************************/
2371
2372 static int cmd_chmod(const char **cmd_ptr)
2373 {
2374         pstring src;
2375         mode_t mode;
2376         fstring buf, buf2;
2377   
2378         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2379                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2380                 return 1;
2381         }
2382
2383         pstrcpy(src,cur_dir);
2384         
2385         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2386             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2387                 d_printf("chmod mode file\n");
2388                 return 1;
2389         }
2390
2391         mode = (mode_t)strtol(buf, NULL, 8);
2392         pstrcat(src,buf2);
2393
2394         if (NT_STATUS_IS_ERR(smbcli_unix_chmod(cli->tree, src, mode))) {
2395                 d_printf("%s chmod file %s 0%o\n",
2396                         smbcli_errstr(cli->tree), src, (uint_t)mode);
2397                 return 1;
2398         } 
2399
2400         return 0;
2401 }
2402
2403 /****************************************************************************
2404  UNIX chown.
2405 ****************************************************************************/
2406
2407 static int cmd_chown(const char **cmd_ptr)
2408 {
2409         pstring src;
2410         uid_t uid;
2411         gid_t gid;
2412         fstring buf, buf2, buf3;
2413   
2414         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2415                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2416                 return 1;
2417         }
2418
2419         pstrcpy(src,cur_dir);
2420         
2421         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2422             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2)) ||
2423             !next_token(cmd_ptr,buf3,NULL, sizeof(buf3))) {
2424                 d_printf("chown uid gid file\n");
2425                 return 1;
2426         }
2427
2428         uid = (uid_t)atoi(buf);
2429         gid = (gid_t)atoi(buf2);
2430         pstrcat(src,buf3);
2431
2432         if (NT_STATUS_IS_ERR(smbcli_unix_chown(cli->tree, src, uid, gid))) {
2433                 d_printf("%s chown file %s uid=%d, gid=%d\n",
2434                         smbcli_errstr(cli->tree), src, (int)uid, (int)gid);
2435                 return 1;
2436         } 
2437
2438         return 0;
2439 }
2440
2441 /****************************************************************************
2442 rename some files
2443 ****************************************************************************/
2444 static int cmd_rename(const char **cmd_ptr)
2445 {
2446         pstring src,dest;
2447         fstring buf,buf2;
2448   
2449         pstrcpy(src,cur_dir);
2450         pstrcpy(dest,cur_dir);
2451         
2452         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2453             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2454                 d_printf("rename <src> <dest>\n");
2455                 return 1;
2456         }
2457
2458         pstrcat(src,buf);
2459         pstrcat(dest,buf2);
2460
2461         if (NT_STATUS_IS_ERR(smbcli_rename(cli->tree, src, dest))) {
2462                 d_printf("%s renaming files\n",smbcli_errstr(cli->tree));
2463                 return 1;
2464         }
2465         
2466         return 0;
2467 }
2468
2469
2470 /****************************************************************************
2471 toggle the prompt flag
2472 ****************************************************************************/
2473 static int cmd_prompt(const char **cmd_ptr)
2474 {
2475         prompt = !prompt;
2476         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
2477         
2478         return 1;
2479 }
2480
2481
2482 /****************************************************************************
2483 set the newer than time
2484 ****************************************************************************/
2485 static int cmd_newer(const char **cmd_ptr)
2486 {
2487         fstring buf;
2488         BOOL ok;
2489         struct stat sbuf;
2490
2491         ok = next_token(cmd_ptr,buf,NULL,sizeof(buf));
2492         if (ok && (stat(buf,&sbuf) == 0)) {
2493                 newer_than = sbuf.st_mtime;
2494                 DEBUG(1,("Getting files newer than %s",
2495                          asctime(localtime(&newer_than))));
2496         } else {
2497                 newer_than = 0;
2498         }
2499
2500         if (ok && newer_than == 0) {
2501                 d_printf("Error setting newer-than time\n");
2502                 return 1;
2503         }
2504
2505         return 0;
2506 }
2507
2508 /****************************************************************************
2509 set the archive level
2510 ****************************************************************************/
2511 static int cmd_archive(const char **cmd_ptr)
2512 {
2513         fstring buf;
2514
2515         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2516                 archive_level = atoi(buf);
2517         } else
2518                 d_printf("Archive level is %d\n",archive_level);
2519
2520         return 0;
2521 }
2522
2523 /****************************************************************************
2524 toggle the lowercaseflag
2525 ****************************************************************************/
2526 static int cmd_lowercase(const char **cmd_ptr)
2527 {
2528         lowercase = !lowercase;
2529         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
2530
2531         return 0;
2532 }
2533
2534
2535
2536
2537 /****************************************************************************
2538 toggle the recurse flag
2539 ****************************************************************************/
2540 static int cmd_recurse(const char **cmd_ptr)
2541 {
2542         recurse = !recurse;
2543         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
2544
2545         return 0;
2546 }
2547
2548 /****************************************************************************
2549 toggle the translate flag
2550 ****************************************************************************/
2551 static int cmd_translate(const char **cmd_ptr)
2552 {
2553         translation = !translation;
2554         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
2555                  translation?"on":"off"));
2556
2557         return 0;
2558 }
2559
2560
2561 /****************************************************************************
2562 do a printmode command
2563 ****************************************************************************/
2564 static int cmd_printmode(const char **cmd_ptr)
2565 {
2566         fstring buf;
2567         fstring mode;
2568
2569         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2570                 if (strequal(buf,"text")) {
2571                         printmode = 0;      
2572                 } else {
2573                         if (strequal(buf,"graphics"))
2574                                 printmode = 1;
2575                         else
2576                                 printmode = atoi(buf);
2577                 }
2578         }
2579
2580         switch(printmode)
2581                 {
2582                 case 0: 
2583                         fstrcpy(mode,"text");
2584                         break;
2585                 case 1: 
2586                         fstrcpy(mode,"graphics");
2587                         break;
2588                 default: 
2589                         slprintf(mode,sizeof(mode)-1,"%d",printmode);
2590                         break;
2591                 }
2592         
2593         DEBUG(2,("the printmode is now %s\n",mode));
2594
2595         return 0;
2596 }
2597
2598 /****************************************************************************
2599  do the lcd command
2600  ****************************************************************************/
2601 static int cmd_lcd(const char **cmd_ptr)
2602 {
2603         fstring buf;
2604         char d[PATH_MAX];
2605         
2606         if (next_token(cmd_ptr,buf,NULL,sizeof(buf)))
2607                 chdir(buf);
2608         DEBUG(2,("the local directory is now %s\n",getcwd(d, PATH_MAX)));
2609
2610         return 0;
2611 }
2612
2613 /****************************************************************************
2614 history
2615 ****************************************************************************/
2616 static int cmd_history(const char **cmd_ptr)
2617 {
2618 #if defined(HAVE_LIBREADLINE)
2619         HIST_ENTRY **hlist;
2620         int i;
2621
2622         hlist = history_list();
2623         
2624         for (i = 0; hlist && hlist[i]; i++) {
2625                 DEBUG(0, ("%d: %s\n", i, hlist[i]->line));
2626         }
2627 #else
2628         DEBUG(0,("no history without readline support\n"));
2629 #endif
2630
2631         return 0;
2632 }
2633
2634 /****************************************************************************
2635  get a file restarting at end of local file
2636  ****************************************************************************/
2637 static int cmd_reget(const char **cmd_ptr)
2638 {
2639         pstring local_name;
2640         pstring remote_name;
2641         char *p;
2642
2643         pstrcpy(remote_name, cur_dir);
2644         pstrcat(remote_name, "\\");
2645         
2646         p = remote_name + strlen(remote_name);
2647         
2648         if (!next_token(cmd_ptr, p, NULL, sizeof(remote_name) - strlen(remote_name))) {
2649                 d_printf("reget <filename>\n");
2650                 return 1;
2651         }
2652         pstrcpy(local_name, p);
2653         dos_clean_name(remote_name);
2654         
2655         next_token(cmd_ptr, local_name, NULL, sizeof(local_name));
2656         
2657         return do_get(remote_name, local_name, True);
2658 }
2659
2660 /****************************************************************************
2661  put a file restarting at end of local file
2662  ****************************************************************************/
2663 static int cmd_reput(const char **cmd_ptr)
2664 {
2665         pstring local_name;
2666         pstring remote_name;
2667         fstring buf;
2668         char *p = buf;
2669         
2670         pstrcpy(remote_name, cur_dir);
2671         pstrcat(remote_name, "\\");
2672   
2673         if (!next_token(cmd_ptr, p, NULL, sizeof(buf))) {
2674                 d_printf("reput <filename>\n");
2675                 return 1;
2676         }
2677         pstrcpy(local_name, p);
2678   
2679         if (!file_exist(local_name)) {
2680                 d_printf("%s does not exist\n", local_name);
2681                 return 1;
2682         }
2683
2684         if (next_token(cmd_ptr, p, NULL, sizeof(buf)))
2685                 pstrcat(remote_name, p);
2686         else
2687                 pstrcat(remote_name, local_name);
2688         
2689         dos_clean_name(remote_name);
2690
2691         return do_put(remote_name, local_name, True);
2692 }
2693
2694
2695 /*
2696   return a string representing a share type
2697 */
2698 static const char *share_type_str(uint32_t type)
2699 {
2700         switch (type & 0xF) {
2701         case STYPE_DISKTREE: 
2702                 return "Disk";
2703         case STYPE_PRINTQ: 
2704                 return "Printer";
2705         case STYPE_DEVICE: 
2706                 return "Device";
2707         case STYPE_IPC: 
2708                 return "IPC";
2709         default:
2710                 return "Unknown";
2711         }
2712 }
2713
2714
2715 /*
2716   display a list of shares from a level 1 share enum
2717 */
2718 static void display_share_result(struct srvsvc_NetShareCtr1 *ctr1)
2719 {
2720         int i;
2721
2722         for (i=0;i<ctr1->count;i++) {
2723                 struct srvsvc_NetShareInfo1 *info = ctr1->array+i;
2724
2725                 printf("\t%-15s %-10.10s %s\n", 
2726                        info->name, 
2727                        share_type_str(info->type), 
2728                        info->comment);
2729         }
2730 }
2731
2732
2733
2734 /****************************************************************************
2735 try and browse available shares on a host
2736 ****************************************************************************/
2737 static BOOL browse_host(const char *query_host)
2738 {
2739         struct dcerpc_pipe *p;
2740         char *binding;
2741         NTSTATUS status;
2742         struct srvsvc_NetShareEnumAll r;
2743         uint32_t resume_handle = 0;
2744         TALLOC_CTX *mem_ctx = talloc_init("browse_host");
2745         struct srvsvc_NetShareCtr1 ctr1;
2746
2747         binding = talloc_asprintf(mem_ctx, "ncacn_np:%s", query_host);
2748
2749         status = dcerpc_pipe_connect(mem_ctx, &p, binding, 
2750                                      DCERPC_SRVSVC_UUID, 
2751                                      DCERPC_SRVSVC_VERSION,
2752                                      cmdline_credentials, NULL);
2753         if (!NT_STATUS_IS_OK(status)) {
2754                 d_printf("Failed to connect to %s - %s\n", 
2755                          binding, nt_errstr(status));
2756                 talloc_free(mem_ctx);
2757                 return False;
2758         }
2759
2760         r.in.server_unc = talloc_asprintf(mem_ctx,"\\\\%s",dcerpc_server_name(p));
2761         r.in.level = 1;
2762         r.in.ctr.ctr1 = &ctr1;
2763         r.in.max_buffer = ~0;
2764         r.in.resume_handle = &resume_handle;
2765
2766         d_printf("\n\tSharename       Type       Comment\n");
2767         d_printf("\t---------       ----       -------\n");
2768
2769         do {
2770                 ZERO_STRUCT(ctr1);
2771                 status = dcerpc_srvsvc_NetShareEnumAll(p, mem_ctx, &r);
2772
2773                 if (NT_STATUS_IS_OK(status) && 
2774                     (W_ERROR_EQUAL(r.out.result, WERR_MORE_DATA) ||
2775                      W_ERROR_IS_OK(r.out.result)) &&
2776                     r.out.ctr.ctr1) {
2777                         display_share_result(r.out.ctr.ctr1);
2778                         resume_handle += r.out.ctr.ctr1->count;
2779                 }
2780         } while (NT_STATUS_IS_OK(status) && W_ERROR_EQUAL(r.out.result, WERR_MORE_DATA));
2781
2782         talloc_free(mem_ctx);
2783
2784         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(r.out.result)) {
2785                 d_printf("Failed NetShareEnumAll %s - %s/%s\n", 
2786                          binding, nt_errstr(status), win_errstr(r.out.result));
2787                 return False;
2788         }
2789
2790         return False;
2791 }
2792
2793 /****************************************************************************
2794 try and browse available connections on a host
2795 ****************************************************************************/
2796 static BOOL list_servers(const char *wk_grp)
2797 {
2798         d_printf("REWRITE: list servers not implemented\n");
2799         return False;
2800 }
2801
2802 /* Some constants for completing filename arguments */
2803
2804 #define COMPL_NONE        0          /* No completions */
2805 #define COMPL_REMOTE      1          /* Complete remote filename */
2806 #define COMPL_LOCAL       2          /* Complete local filename */
2807
2808 /* This defines the commands supported by this client.
2809  * NOTE: The "!" must be the last one in the list because it's fn pointer
2810  *       field is NULL, and NULL in that field is used in process_tok()
2811  *       (below) to indicate the end of the list.  crh
2812  */
2813 static struct
2814 {
2815   const char *name;
2816   int (*fn)(const char **cmd_ptr);
2817   const char *description;
2818   char compl_args[2];      /* Completion argument info */
2819 } commands[] = 
2820 {
2821   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2822   {"addprivileges",cmd_addprivileges,"<sid|name> <privilege...> add privileges for a user",{COMPL_NONE,COMPL_NONE}},
2823   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
2824   {"acl",cmd_acl,"<file> show file ACL",{COMPL_NONE,COMPL_NONE}},
2825   {"allinfo",cmd_allinfo,"<file> show all possible info about a file",{COMPL_NONE,COMPL_NONE}},
2826   {"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}},
2827   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
2828   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2829   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
2830   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
2831   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2832   {"delprivileges",cmd_delprivileges,"<sid|name> <privilege...> remove privileges for a user",{COMPL_NONE,COMPL_NONE}},
2833   {"deltree",cmd_deltree,"<dir> delete a whole directory tree",{COMPL_REMOTE,COMPL_NONE}},
2834   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2835   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2836   {"eainfo",cmd_eainfo,"<file> show EA contents for a file",{COMPL_NONE,COMPL_NONE}},
2837   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2838   {"fsinfo",cmd_fsinfo,"query file system info",{COMPL_NONE,COMPL_NONE}},
2839   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2840   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2841   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2842   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2843   {"link",cmd_link,"<src> <dest> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
2844   {"lookup",cmd_lookup,"<sid|name> show SID for name or name for SID",{COMPL_NONE,COMPL_NONE}},
2845   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2846   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2847   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
2848   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2849   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2850   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2851   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
2852   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2853   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2854   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
2855   {"privileges",cmd_privileges,"<user> show privileges for a user",{COMPL_NONE,COMPL_NONE}},
2856   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
2857   {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
2858   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2859   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2860   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2861   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2862   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
2863   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2864   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2865   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2866   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
2867   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2868   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
2869   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2870   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2871   {"symlink",cmd_symlink,"<src> <dest> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
2872   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2873   
2874   /* Yes, this must be here, see crh's comment above. */
2875   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2876   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2877 };
2878
2879
2880 /*******************************************************************
2881   lookup a command string in the list of commands, including 
2882   abbreviations
2883   ******************************************************************/
2884 static int process_tok(fstring tok)
2885 {
2886         int i = 0, matches = 0;
2887         int cmd=0;
2888         int tok_len = strlen(tok);
2889         
2890         while (commands[i].fn != NULL) {
2891                 if (strequal(commands[i].name,tok)) {
2892                         matches = 1;
2893                         cmd = i;
2894                         break;
2895                 } else if (strncasecmp(commands[i].name, tok, tok_len) == 0) {
2896                         matches++;
2897                         cmd = i;
2898                 }
2899                 i++;
2900         }
2901   
2902         if (matches == 0)
2903                 return(-1);
2904         else if (matches == 1)
2905                 return(cmd);
2906         else
2907                 return(-2);
2908 }
2909
2910 /****************************************************************************
2911 help
2912 ****************************************************************************/
2913 static int cmd_help(const char **cmd_ptr)
2914 {
2915         int i=0,j;
2916         fstring buf;
2917         
2918         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2919                 if ((i = process_tok(buf)) >= 0)
2920                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
2921         } else {
2922                 while (commands[i].description) {
2923                         for (j=0; commands[i].description && (j<5); j++) {
2924                                 d_printf("%-15s",commands[i].name);
2925                                 i++;
2926                         }
2927                         d_printf("\n");
2928                 }
2929         }
2930         return 0;
2931 }
2932
2933 /****************************************************************************
2934 process a -c command string
2935 ****************************************************************************/
2936 static int process_command_string(char *cmd)
2937 {
2938         pstring line;
2939         const char *ptr;
2940         int rc = 0;
2941
2942         /* establish the connection if not already */
2943         
2944         if (!cli) {
2945                 cli = do_connect(desthost, service, cmdline_credentials);
2946                 if (!cli)
2947                         return 0;
2948         }
2949         
2950         while (cmd[0] != '\0')    {
2951                 char *p;
2952                 fstring tok;
2953                 int i;
2954                 
2955                 if ((p = strchr_m(cmd, ';')) == 0) {
2956                         strncpy(line, cmd, 999);
2957                         line[1000] = '\0';
2958                         cmd += strlen(cmd);
2959                 } else {
2960                         if (p - cmd > 999) p = cmd + 999;
2961                         strncpy(line, cmd, p - cmd);
2962                         line[p - cmd] = '\0';
2963                         cmd = p + 1;
2964                 }
2965                 
2966                 /* and get the first part of the command */
2967                 ptr = line;
2968                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
2969                 
2970                 if ((i = process_tok(tok)) >= 0) {
2971                         rc = commands[i].fn(&ptr);
2972                 } else if (i == -2) {
2973                         d_printf("%s: command abbreviation ambiguous\n",tok);
2974                 } else {
2975                         d_printf("%s: command not found\n",tok);
2976                 }
2977         }
2978         
2979         return rc;
2980 }       
2981
2982 #define MAX_COMPLETIONS 100
2983
2984 typedef struct {
2985         pstring dirmask;
2986         char **matches;
2987         int count, samelen;
2988         const char *text;
2989         int len;
2990 } completion_remote_t;
2991
2992 static void completion_remote_filter(struct clilist_file_info *f, const char *mask, void *state)
2993 {
2994         completion_remote_t *info = (completion_remote_t *)state;
2995
2996         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
2997                 if ((info->dirmask[0] == 0) && !(f->attrib & FILE_ATTRIBUTE_DIRECTORY))
2998                         info->matches[info->count] = strdup(f->name);
2999                 else {
3000                         pstring tmp;
3001
3002                         if (info->dirmask[0] != 0)
3003                                 pstrcpy(tmp, info->dirmask);
3004                         else
3005                                 tmp[0] = 0;
3006                         pstrcat(tmp, f->name);
3007                         if (f->attrib & FILE_ATTRIBUTE_DIRECTORY)
3008                                 pstrcat(tmp, "/");
3009                         info->matches[info->count] = strdup(tmp);
3010                 }
3011                 if (info->matches[info->count] == NULL)
3012                         return;
3013                 if (f->attrib & FILE_ATTRIBUTE_DIRECTORY)
3014                         smb_readline_ca_char(0);
3015
3016                 if (info->count == 1)
3017                         info->samelen = strlen(info->matches[info->count]);
3018                 else
3019                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
3020                                 info->samelen--;
3021                 info->count++;
3022         }
3023 }
3024
3025 static char **remote_completion(const char *text, int len)
3026 {
3027         pstring dirmask;
3028         int i;
3029         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
3030
3031         info.samelen = len;
3032         info.text = text;
3033         info.len = len;
3034  
3035         if (len >= PATH_MAX)
3036                 return(NULL);
3037
3038         info.matches = malloc_array_p(char *, MAX_COMPLETIONS);
3039         if (!info.matches) return NULL;
3040         info.matches[0] = NULL;
3041
3042         for (i = len-1; i >= 0; i--)
3043                 if ((text[i] == '/') || (text[i] == '\\'))
3044                         break;
3045         info.text = text+i+1;
3046         info.samelen = info.len = len-i-1;
3047
3048         if (i > 0) {
3049                 strncpy(info.dirmask, text, i+1);
3050                 info.dirmask[i+1] = 0;
3051                 snprintf(dirmask, sizeof(dirmask), "%s%*s*", cur_dir, i-1, text);
3052         } else
3053                 snprintf(dirmask, sizeof(dirmask), "%s*", cur_dir);
3054
3055         if (smbcli_list(cli->tree, dirmask, 
3056                      FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN, 
3057                      completion_remote_filter, &info) < 0)
3058                 goto cleanup;
3059
3060         if (info.count == 2)
3061                 info.matches[0] = strdup(info.matches[1]);
3062         else {
3063                 info.matches[0] = malloc(info.samelen+1);
3064                 if (!info.matches[0])
3065                         goto cleanup;
3066                 strncpy(info.matches[0], info.matches[1], info.samelen);
3067                 info.matches[0][info.samelen] = 0;
3068         }
3069         info.matches[info.count] = NULL;
3070         return info.matches;
3071
3072 cleanup:
3073         for (i = 0; i < info.count; i++)
3074                 free(info.matches[i]);
3075         free(info.matches);
3076         return NULL;
3077 }
3078
3079 static char **completion_fn(const char *text, int start, int end)
3080 {
3081         smb_readline_ca_char(' ');
3082
3083         if (start) {
3084                 const char *buf, *sp;
3085                 int i;
3086                 char compl_type;
3087
3088                 buf = smb_readline_get_line_buffer();
3089                 if (buf == NULL)
3090                         return NULL;
3091                 
3092                 sp = strchr(buf, ' ');
3093                 if (sp == NULL)
3094                         return NULL;
3095                 
3096                 for (i = 0; commands[i].name; i++)
3097                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
3098                                 break;
3099                 if (commands[i].name == NULL)
3100                         return NULL;
3101
3102                 while (*sp == ' ')
3103                         sp++;
3104
3105                 if (sp == (buf + start))
3106                         compl_type = commands[i].compl_args[0];
3107                 else
3108                         compl_type = commands[i].compl_args[1];
3109
3110                 if (compl_type == COMPL_REMOTE)
3111                         return remote_completion(text, end - start);
3112                 else /* fall back to local filename completion */
3113                         return NULL;
3114         } else {
3115                 char **matches;
3116                 int i, len, samelen = 0, count=1;
3117
3118                 matches = malloc_array_p(char *, MAX_COMPLETIONS);
3119                 if (!matches) return NULL;
3120                 matches[0] = NULL;
3121
3122                 len = strlen(text);
3123                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
3124                         if (strncmp(text, commands[i].name, len) == 0) {
3125                                 matches[count] = strdup(commands[i].name);
3126                                 if (!matches[count])
3127                                         goto cleanup;
3128                                 if (count == 1)
3129                                         samelen = strlen(matches[count]);
3130                                 else
3131                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
3132                                                 samelen--;
3133                                 count++;
3134                         }
3135                 }
3136
3137                 switch (count) {
3138                 case 0: /* should never happen */
3139                 case 1:
3140                         goto cleanup;
3141                 case 2:
3142                         matches[0] = strdup(matches[1]);
3143                         break;
3144                 default:
3145                         matches[0] = malloc(samelen+1);
3146                         if (!matches[0])
3147                                 goto cleanup;
3148                         strncpy(matches[0], matches[1], samelen);
3149                         matches[0][samelen] = 0;
3150                 }
3151                 matches[count] = NULL;
3152                 return matches;
3153
3154 cleanup:
3155                 while (i >= 0) {
3156                         free(matches[i]);
3157                         i--;
3158                 }
3159<