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