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