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