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