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