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