0ebebf747e2f6373c85d31a4545c901fe95bcb52
[samba.git] / source / 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_STRUCT(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) && 
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         /* allow '-' to represent stdin
1305            jdblair, 24.jun.98 */
1306         if (!file_exist(lname) && (strcmp(lname,"-"))) {
1307                 d_printf("%s does not exist\n",lname);
1308                 return 1;
1309         }
1310
1311         return do_put(rname, lname, False);
1312 }
1313
1314 /*************************************
1315   File list structure
1316 *************************************/
1317
1318 static struct file_list {
1319         struct file_list *prev, *next;
1320         char *file_path;
1321         BOOL isdir;
1322 } *file_list;
1323
1324 /****************************************************************************
1325   Free a file_list structure
1326 ****************************************************************************/
1327
1328 static void free_file_list (struct file_list * list)
1329 {
1330         struct file_list *tmp;
1331         
1332         while (list)
1333         {
1334                 tmp = list;
1335                 DLIST_REMOVE(list, list);
1336                 SAFE_FREE(tmp->file_path);
1337                 SAFE_FREE(tmp);
1338         }
1339 }
1340
1341 /****************************************************************************
1342   seek in a directory/file list until you get something that doesn't start with
1343   the specified name
1344   ****************************************************************************/
1345 static BOOL seek_list(struct file_list *list, char *name)
1346 {
1347         while (list) {
1348                 trim_string(list->file_path,"./","\n");
1349                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1350                         return(True);
1351                 }
1352                 list = list->next;
1353         }
1354       
1355         return(False);
1356 }
1357
1358 /****************************************************************************
1359   set the file selection mask
1360   ****************************************************************************/
1361 static int cmd_select(const char **cmd_ptr)
1362 {
1363         pstrcpy(fileselection,"");
1364         next_token(cmd_ptr,fileselection,NULL,sizeof(fileselection));
1365
1366         return 0;
1367 }
1368
1369 /*******************************************************************
1370   A readdir wrapper which just returns the file name.
1371  ********************************************************************/
1372 static const char *readdirname(DIR *p)
1373 {
1374         struct dirent *ptr;
1375         char *dname;
1376
1377         if (!p)
1378                 return(NULL);
1379   
1380         ptr = (struct dirent *)readdir(p);
1381         if (!ptr)
1382                 return(NULL);
1383
1384         dname = ptr->d_name;
1385
1386 #ifdef NEXT2
1387         if (telldir(p) < 0)
1388                 return(NULL);
1389 #endif
1390
1391 #ifdef HAVE_BROKEN_READDIR
1392         /* using /usr/ucb/cc is BAD */
1393         dname = dname - 2;
1394 #endif
1395
1396         {
1397                 static pstring buf;
1398                 int len = NAMLEN(ptr);
1399                 memcpy(buf, dname, len);
1400                 buf[len] = 0;
1401                 dname = buf;
1402         }
1403
1404         return(dname);
1405 }
1406
1407 /****************************************************************************
1408   Recursive file matching function act as find
1409   match must be always set to True when calling this function
1410 ****************************************************************************/
1411 static int file_find(struct file_list **list, const char *directory, 
1412                       const char *expression, BOOL match)
1413 {
1414         DIR *dir;
1415         struct file_list *entry;
1416         struct stat statbuf;
1417         int ret;
1418         char *path;
1419         BOOL isdir;
1420         const char *dname;
1421
1422         dir = opendir(directory);
1423         if (!dir) return -1;
1424         
1425         while ((dname = readdirname(dir))) {
1426                 if (!strcmp("..", dname)) continue;
1427                 if (!strcmp(".", dname)) continue;
1428                 
1429                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1430                         continue;
1431                 }
1432
1433                 isdir = False;
1434                 if (!match || !gen_fnmatch(expression, dname)) {
1435                         if (recurse) {
1436                                 ret = stat(path, &statbuf);
1437                                 if (ret == 0) {
1438                                         if (S_ISDIR(statbuf.st_mode)) {
1439                                                 isdir = True;
1440                                                 ret = file_find(list, path, expression, False);
1441                                         }
1442                                 } else {
1443                                         d_printf("file_find: cannot stat file %s\n", path);
1444                                 }
1445                                 
1446                                 if (ret == -1) {
1447                                         SAFE_FREE(path);
1448                                         closedir(dir);
1449                                         return -1;
1450                                 }
1451                         }
1452                         entry = malloc_p(struct file_list);
1453                         if (!entry) {
1454                                 d_printf("Out of memory in file_find\n");
1455                                 closedir(dir);
1456                                 return -1;
1457                         }
1458                         entry->file_path = path;
1459                         entry->isdir = isdir;
1460                         DLIST_ADD(*list, entry);
1461                 } else {
1462                         SAFE_FREE(path);
1463                 }
1464         }
1465
1466         closedir(dir);
1467         return 0;
1468 }
1469
1470 /****************************************************************************
1471   mput some files
1472   ****************************************************************************/
1473 static int cmd_mput(const char **cmd_ptr)
1474 {
1475         fstring buf;
1476         char *p=buf;
1477         
1478         while (next_token(cmd_ptr,p,NULL,sizeof(buf))) {
1479                 int ret;
1480                 struct file_list *temp_list;
1481                 char *quest, *lname, *rname;
1482         
1483                 file_list = NULL;
1484
1485                 ret = file_find(&file_list, ".", p, True);
1486                 if (ret) {
1487                         free_file_list(file_list);
1488                         continue;
1489                 }
1490                 
1491                 quest = NULL;
1492                 lname = NULL;
1493                 rname = NULL;
1494                                 
1495                 for (temp_list = file_list; temp_list; 
1496                      temp_list = temp_list->next) {
1497
1498                         SAFE_FREE(lname);
1499                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1500                                 continue;
1501                         trim_string(lname, "./", "/");
1502                         
1503                         /* check if it's a directory */
1504                         if (temp_list->isdir) {
1505                                 /* if (!recurse) continue; */
1506                                 
1507                                 SAFE_FREE(quest);
1508                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) break;
1509                                 if (prompt && !yesno(quest)) { /* No */
1510                                         /* Skip the directory */
1511                                         lname[strlen(lname)-1] = '/';
1512                                         if (!seek_list(temp_list, lname))
1513                                                 break;              
1514                                 } else { /* Yes */
1515                                         SAFE_FREE(rname);
1516                                         if(asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1517                                         dos_format(rname);
1518                                         if (NT_STATUS_IS_ERR(smbcli_chkpath(cli->tree, rname)) && 
1519                                             NT_STATUS_IS_ERR(do_mkdir(rname))) {
1520                                                 DEBUG (0, ("Unable to make dir, skipping..."));
1521                                                 /* Skip the directory */
1522                                                 lname[strlen(lname)-1] = '/';
1523                                                 if (!seek_list(temp_list, lname))
1524                                                         break;
1525                                         }
1526                                 }
1527                                 continue;
1528                         } else {
1529                                 SAFE_FREE(quest);
1530                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) break;
1531                                 if (prompt && !yesno(quest)) /* No */
1532                                         continue;
1533                                 
1534                                 /* Yes */
1535                                 SAFE_FREE(rname);
1536                                 if (asprintf(&rname, "%s%s", cur_dir, lname) < 0) break;
1537                         }
1538
1539                         dos_format(rname);
1540
1541                         do_put(rname, lname, False);
1542                 }
1543                 free_file_list(file_list);
1544                 SAFE_FREE(quest);
1545                 SAFE_FREE(lname);
1546                 SAFE_FREE(rname);
1547         }
1548
1549         return 0;
1550 }
1551
1552
1553 /****************************************************************************
1554   cancel a print job
1555   ****************************************************************************/
1556 static int do_cancel(int job)
1557 {
1558         d_printf("REWRITE: print job cancel not implemented\n");
1559         return 1;
1560 }
1561
1562
1563 /****************************************************************************
1564   cancel a print job
1565   ****************************************************************************/
1566 static int cmd_cancel(const char **cmd_ptr)
1567 {
1568         fstring buf;
1569         int job; 
1570
1571         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1572                 d_printf("cancel <jobid> ...\n");
1573                 return 1;
1574         }
1575         do {
1576                 job = atoi(buf);
1577                 do_cancel(job);
1578         } while (next_token(cmd_ptr,buf,NULL,sizeof(buf)));
1579         
1580         return 0;
1581 }
1582
1583
1584 /****************************************************************************
1585   print a file
1586   ****************************************************************************/
1587 static int cmd_print(const char **cmd_ptr)
1588 {
1589         pstring lname;
1590         pstring rname;
1591         char *p;
1592
1593         if (!next_token(cmd_ptr,lname,NULL, sizeof(lname))) {
1594                 d_printf("print <filename>\n");
1595                 return 1;
1596         }
1597
1598         pstrcpy(rname,lname);
1599         p = strrchr_m(rname,'/');
1600         if (p) {
1601                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)getpid());
1602         }
1603
1604         if (strequal(lname,"-")) {
1605                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)getpid());
1606         }
1607
1608         return do_put(rname, lname, False);
1609 }
1610
1611
1612 /****************************************************************************
1613  show a print queue
1614 ****************************************************************************/
1615 static int cmd_queue(const char **cmd_ptr)
1616 {
1617         d_printf("REWRITE: print job queue not implemented\n");
1618         
1619         return 0;
1620 }
1621
1622 /****************************************************************************
1623 delete some files
1624 ****************************************************************************/
1625 static int cmd_del(const char **cmd_ptr)
1626 {
1627         pstring mask;
1628         fstring buf;
1629         uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
1630
1631         if (recurse)
1632                 attribute |= FILE_ATTRIBUTE_DIRECTORY;
1633         
1634         pstrcpy(mask,cur_dir);
1635         
1636         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1637                 d_printf("del <filename>\n");
1638                 return 1;
1639         }
1640         pstrcat(mask,buf);
1641
1642         if (NT_STATUS_IS_ERR(smbcli_unlink(cli->tree, mask))) {
1643                 d_printf("%s deleting remote file %s\n",smbcli_errstr(cli->tree),mask);
1644         }
1645         
1646         return 0;
1647 }
1648
1649
1650 /****************************************************************************
1651 delete a whole directory tree
1652 ****************************************************************************/
1653 static int cmd_deltree(const char **cmd_ptr)
1654 {
1655         pstring dname;
1656         fstring buf;
1657         int ret;
1658
1659         pstrcpy(dname,cur_dir);
1660         
1661         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1662                 d_printf("deltree <dirname>\n");
1663                 return 1;
1664         }
1665         pstrcat(dname,buf);
1666
1667         ret = smbcli_deltree(cli->tree, dname);
1668
1669         if (ret == -1) {
1670                 printf("Failed to delete tree %s - %s\n", dname, smbcli_errstr(cli->tree));
1671                 return -1;
1672         }
1673
1674         printf("Deleted %d files in %s\n", ret, dname);
1675         
1676         return 0;
1677 }
1678
1679
1680 /****************************************************************************
1681 show as much information as possible about a file
1682 ****************************************************************************/
1683 static int cmd_allinfo(const char **cmd_ptr)
1684 {
1685         pstring fname;
1686         fstring buf;
1687         int ret = 0;
1688         TALLOC_CTX *mem_ctx;
1689         union smb_fileinfo finfo;
1690         NTSTATUS status;
1691
1692         pstrcpy(fname,cur_dir);
1693         
1694         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1695                 d_printf("allinfo <filename>\n");
1696                 return 1;
1697         }
1698         pstrcat(fname,buf);
1699
1700         mem_ctx = talloc_init("%s", fname);
1701
1702         /* first a ALL_INFO QPATHINFO */
1703         finfo.generic.level = RAW_FILEINFO_ALL_INFO;
1704         finfo.generic.in.fname = fname;
1705         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1706         if (!NT_STATUS_IS_OK(status)) {
1707                 d_printf("%s - %s\n", fname, nt_errstr(status));
1708                 ret = 1;
1709                 goto done;
1710         }
1711
1712         d_printf("\tcreate_time:    %s\n", nt_time_string(mem_ctx, finfo.all_info.out.create_time));
1713         d_printf("\taccess_time:    %s\n", nt_time_string(mem_ctx, finfo.all_info.out.access_time));
1714         d_printf("\twrite_time:     %s\n", nt_time_string(mem_ctx, finfo.all_info.out.write_time));
1715         d_printf("\tchange_time:    %s\n", nt_time_string(mem_ctx, finfo.all_info.out.change_time));
1716         d_printf("\tattrib:         0x%x\n", finfo.all_info.out.attrib);
1717         d_printf("\talloc_size:     %lu\n", (unsigned long)finfo.all_info.out.alloc_size);
1718         d_printf("\tsize:           %lu\n", (unsigned long)finfo.all_info.out.size);
1719         d_printf("\tnlink:          %u\n", finfo.all_info.out.nlink);
1720         d_printf("\tdelete_pending: %u\n", finfo.all_info.out.delete_pending);
1721         d_printf("\tdirectory:      %u\n", finfo.all_info.out.directory);
1722         d_printf("\tea_size:        %u\n", finfo.all_info.out.ea_size);
1723         d_printf("\tfname:          '%s'\n", finfo.all_info.out.fname.s);
1724
1725         /* 8.3 name if any */
1726         finfo.generic.level = RAW_FILEINFO_ALT_NAME_INFO;
1727         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1728         if (NT_STATUS_IS_OK(status)) {
1729                 d_printf("\talt_name:       %s\n", finfo.alt_name_info.out.fname.s);
1730         }
1731
1732         /* file_id if available */
1733         finfo.generic.level = RAW_FILEINFO_INTERNAL_INFORMATION;
1734         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1735         if (NT_STATUS_IS_OK(status)) {
1736                 d_printf("\tfile_id         %.0f\n", 
1737                          (double)finfo.internal_information.out.file_id);
1738         }
1739
1740         /* the EAs, if any */
1741         finfo.generic.level = RAW_FILEINFO_ALL_EAS;
1742         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1743         if (NT_STATUS_IS_OK(status)) {
1744                 int i;
1745                 for (i=0;i<finfo.all_eas.out.num_eas;i++) {
1746                         d_printf("\tEA[%d] flags=%d len=%d '%s'\n", i,
1747                                  finfo.all_eas.out.eas[i].flags,
1748                                  finfo.all_eas.out.eas[i].value.length,
1749                                  finfo.all_eas.out.eas[i].name.s);
1750                 }
1751         }
1752
1753         /* streams, if available */
1754         finfo.generic.level = RAW_FILEINFO_STREAM_INFO;
1755         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1756         if (NT_STATUS_IS_OK(status)) {
1757                 int i;
1758                 for (i=0;i<finfo.stream_info.out.num_streams;i++) {
1759                         d_printf("\tstream %d:\n", i);
1760                         d_printf("\t\tsize       %ld\n", 
1761                                  (long)finfo.stream_info.out.streams[i].size);
1762                         d_printf("\t\talloc size %ld\n", 
1763                                  (long)finfo.stream_info.out.streams[i].alloc_size);
1764                         d_printf("\t\tname       %s\n", finfo.stream_info.out.streams[i].stream_name.s);
1765                 }
1766         }       
1767
1768         /* dev/inode if available */
1769         finfo.generic.level = RAW_FILEINFO_COMPRESSION_INFORMATION;
1770         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1771         if (NT_STATUS_IS_OK(status)) {
1772                 d_printf("\tcompressed size %ld\n", (long)finfo.compression_info.out.compressed_size);
1773                 d_printf("\tformat          %ld\n", (long)finfo.compression_info.out.format);
1774                 d_printf("\tunit_shift      %ld\n", (long)finfo.compression_info.out.unit_shift);
1775                 d_printf("\tchunk_shift     %ld\n", (long)finfo.compression_info.out.chunk_shift);
1776                 d_printf("\tcluster_shift   %ld\n", (long)finfo.compression_info.out.cluster_shift);
1777         }
1778
1779         talloc_free(mem_ctx);
1780
1781 done:
1782         return ret;
1783 }
1784
1785
1786 /****************************************************************************
1787 shows EA contents
1788 ****************************************************************************/
1789 static int cmd_eainfo(const char **cmd_ptr)
1790 {
1791         pstring fname;
1792         fstring buf;
1793         int ret = 0;
1794         TALLOC_CTX *mem_ctx;
1795         union smb_fileinfo finfo;
1796         NTSTATUS status;
1797         int i;
1798
1799         pstrcpy(fname,cur_dir);
1800         
1801         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1802                 d_printf("eainfo <filename>\n");
1803                 return 1;
1804         }
1805         pstrcat(fname,buf);
1806
1807         mem_ctx = talloc_init("%s", fname);
1808
1809         finfo.generic.in.fname = fname;
1810         finfo.generic.level = RAW_FILEINFO_ALL_EAS;
1811         status = smb_raw_pathinfo(cli->tree, mem_ctx, &finfo);
1812         
1813         if (!NT_STATUS_IS_OK(status)) {
1814                 d_printf("RAW_FILEINFO_ALL_EAS - %s\n", nt_errstr(status));
1815                 talloc_free(mem_ctx);
1816                 return 1;
1817         }
1818
1819         d_printf("%s has %d EAs\n", fname, finfo.all_eas.out.num_eas);
1820
1821         for (i=0;i<finfo.all_eas.out.num_eas;i++) {
1822                 d_printf("\tEA[%d] flags=%d len=%d '%s'\n", i,
1823                          finfo.all_eas.out.eas[i].flags,
1824                          finfo.all_eas.out.eas[i].value.length,
1825                          finfo.all_eas.out.eas[i].name.s);
1826                 fflush(stdout);
1827                 dump_data(0, 
1828                           finfo.all_eas.out.eas[i].value.data,
1829                           finfo.all_eas.out.eas[i].value.length);
1830         }
1831
1832         talloc_free(mem_ctx);
1833
1834         return ret;
1835 }
1836
1837
1838 /****************************************************************************
1839 show any ACL on a file
1840 ****************************************************************************/
1841 static int cmd_acl(const char **cmd_ptr)
1842 {
1843         pstring fname;
1844         fstring buf;
1845         int ret = 0;
1846         TALLOC_CTX *mem_ctx;
1847         union smb_fileinfo query;
1848         NTSTATUS status;
1849         int fnum;
1850
1851         pstrcpy(fname,cur_dir);
1852         
1853         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1854                 d_printf("acl <filename>\n");
1855                 return 1;
1856         }
1857         pstrcat(fname,buf);
1858
1859         fnum = smbcli_nt_create_full(cli->tree, fname, 0, 
1860                                      SEC_STD_READ_CONTROL,
1861                                      0,
1862                                      NTCREATEX_SHARE_ACCESS_DELETE|
1863                                      NTCREATEX_SHARE_ACCESS_READ|
1864                                      NTCREATEX_SHARE_ACCESS_WRITE, 
1865                                      NTCREATEX_DISP_OPEN,
1866                                      0, 0);
1867         if (fnum == -1) {
1868                 d_printf("%s - %s\n", fname, smbcli_errstr(cli->tree));
1869                 return -1;
1870         }
1871
1872         mem_ctx = talloc_init("%s", fname);
1873
1874         query.query_secdesc.level = RAW_FILEINFO_SEC_DESC;
1875         query.query_secdesc.in.fnum = fnum;
1876         query.query_secdesc.in.secinfo_flags = 0x7;
1877
1878         status = smb_raw_fileinfo(cli->tree, mem_ctx, &query);
1879         if (!NT_STATUS_IS_OK(status)) {
1880                 d_printf("%s - %s\n", fname, nt_errstr(status));
1881                 ret = 1;
1882                 goto done;
1883         }
1884
1885         NDR_PRINT_DEBUG(security_descriptor, query.query_secdesc.out.sd);
1886
1887         talloc_free(mem_ctx);
1888
1889 done:
1890         return ret;
1891 }
1892
1893 /****************************************************************************
1894 lookup a name or sid
1895 ****************************************************************************/
1896 static int cmd_lookup(const char **cmd_ptr)
1897 {
1898         fstring buf;
1899         TALLOC_CTX *mem_ctx = talloc_new(NULL);
1900         NTSTATUS status;
1901         struct dom_sid *sid;
1902
1903         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1904                 d_printf("lookup <sid|name>\n");
1905                 talloc_free(mem_ctx);
1906                 return 1;
1907         }
1908
1909         sid = dom_sid_parse_talloc(mem_ctx, buf);
1910         if (sid == NULL) {
1911                 const char *sidstr;
1912                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sidstr);
1913                 if (!NT_STATUS_IS_OK(status)) {
1914                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
1915                         talloc_free(mem_ctx);
1916                         return 1;
1917                 }
1918
1919                 d_printf("%s\n", sidstr);
1920         } else {
1921                 const char *name;
1922                 status = smblsa_lookup_sid(cli, buf, mem_ctx, &name);
1923                 if (!NT_STATUS_IS_OK(status)) {
1924                         d_printf("lsa_LookupSids - %s\n", nt_errstr(status));
1925                         talloc_free(mem_ctx);
1926                         return 1;
1927                 }
1928
1929                 d_printf("%s\n", name);
1930         }
1931
1932         talloc_free(mem_ctx);
1933
1934         return 0;
1935 }
1936
1937 /****************************************************************************
1938 show privileges for a user
1939 ****************************************************************************/
1940 static int cmd_privileges(const char **cmd_ptr)
1941 {
1942         fstring buf;
1943         TALLOC_CTX *mem_ctx = talloc_new(NULL);
1944         NTSTATUS status;
1945         struct dom_sid *sid;
1946         struct lsa_RightSet rights;
1947         unsigned i;
1948
1949         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1950                 d_printf("privileges <sid|name>\n");
1951                 talloc_free(mem_ctx);
1952                 return 1;
1953         }
1954
1955         sid = dom_sid_parse_talloc(mem_ctx, buf);
1956         if (sid == NULL) {
1957                 const char *sid_str;
1958                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sid_str);
1959                 if (!NT_STATUS_IS_OK(status)) {
1960                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
1961                         talloc_free(mem_ctx);
1962                         return 1;
1963                 }
1964                 sid = dom_sid_parse_talloc(mem_ctx, sid_str);
1965         }
1966
1967         status = smblsa_sid_privileges(cli, sid, mem_ctx, &rights);
1968         if (!NT_STATUS_IS_OK(status)) {
1969                 d_printf("lsa_EnumAccountRights - %s\n", nt_errstr(status));
1970                 talloc_free(mem_ctx);
1971                 return 1;
1972         }
1973
1974         for (i=0;i<rights.count;i++) {
1975                 d_printf("\t%s\n", rights.names[i].string);
1976         }
1977
1978         talloc_free(mem_ctx);
1979
1980         return 0;
1981 }
1982
1983
1984 /****************************************************************************
1985 add privileges for a user
1986 ****************************************************************************/
1987 static int cmd_addprivileges(const char **cmd_ptr)
1988 {
1989         fstring buf;
1990         TALLOC_CTX *mem_ctx = talloc_new(NULL);
1991         NTSTATUS status;
1992         struct dom_sid *sid;
1993         struct lsa_RightSet rights;
1994
1995         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
1996                 d_printf("addprivileges <sid|name> <privilege...>\n");
1997                 talloc_free(mem_ctx);
1998                 return 1;
1999         }
2000
2001         sid = dom_sid_parse_talloc(mem_ctx, buf);
2002         if (sid == NULL) {
2003                 const char *sid_str;
2004                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sid_str);
2005                 if (!NT_STATUS_IS_OK(status)) {
2006                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
2007                         talloc_free(mem_ctx);
2008                         return 1;
2009                 }
2010                 sid = dom_sid_parse_talloc(mem_ctx, sid_str);
2011         }
2012
2013         ZERO_STRUCT(rights);
2014         while (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2015                 rights.names = talloc_realloc(mem_ctx, rights.names, 
2016                                                 struct lsa_String, rights.count+1);
2017                 rights.names[rights.count].string = talloc_strdup(mem_ctx, buf);
2018                 rights.count++;
2019         }
2020
2021
2022         status = smblsa_sid_add_privileges(cli, sid, mem_ctx, &rights);
2023         if (!NT_STATUS_IS_OK(status)) {
2024                 d_printf("lsa_AddAccountRights - %s\n", nt_errstr(status));
2025                 talloc_free(mem_ctx);
2026                 return 1;
2027         }
2028
2029         talloc_free(mem_ctx);
2030
2031         return 0;
2032 }
2033
2034 /****************************************************************************
2035 delete privileges for a user
2036 ****************************************************************************/
2037 static int cmd_delprivileges(const char **cmd_ptr)
2038 {
2039         fstring buf;
2040         TALLOC_CTX *mem_ctx = talloc_new(NULL);
2041         NTSTATUS status;
2042         struct dom_sid *sid;
2043         struct lsa_RightSet rights;
2044
2045         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2046                 d_printf("delprivileges <sid|name> <privilege...>\n");
2047                 talloc_free(mem_ctx);
2048                 return 1;
2049         }
2050
2051         sid = dom_sid_parse_talloc(mem_ctx, buf);
2052         if (sid == NULL) {
2053                 const char *sid_str;
2054                 status = smblsa_lookup_name(cli, buf, mem_ctx, &sid_str);
2055                 if (!NT_STATUS_IS_OK(status)) {
2056                         d_printf("lsa_LookupNames - %s\n", nt_errstr(status));
2057                         talloc_free(mem_ctx);
2058                         return 1;
2059                 }
2060                 sid = dom_sid_parse_talloc(mem_ctx, sid_str);
2061         }
2062
2063         ZERO_STRUCT(rights);
2064         while (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2065                 rights.names = talloc_realloc(mem_ctx, rights.names, 
2066                                                 struct lsa_String, rights.count+1);
2067                 rights.names[rights.count].string = talloc_strdup(mem_ctx, buf);
2068                 rights.count++;
2069         }
2070
2071
2072         status = smblsa_sid_del_privileges(cli, sid, mem_ctx, &rights);
2073         if (!NT_STATUS_IS_OK(status)) {
2074                 d_printf("lsa_RemoveAccountRights - %s\n", nt_errstr(status));
2075                 talloc_free(mem_ctx);
2076                 return 1;
2077         }
2078
2079         talloc_free(mem_ctx);
2080
2081         return 0;
2082 }
2083
2084
2085 /****************************************************************************
2086 ****************************************************************************/
2087 static int cmd_open(const char **cmd_ptr)
2088 {
2089         pstring mask;
2090         fstring buf;
2091         
2092         pstrcpy(mask,cur_dir);
2093         
2094         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2095                 d_printf("open <filename>\n");
2096                 return 1;
2097         }
2098         pstrcat(mask,buf);
2099
2100         smbcli_open(cli->tree, mask, O_RDWR, DENY_ALL);
2101
2102         return 0;
2103 }
2104
2105
2106 /****************************************************************************
2107 remove a directory
2108 ****************************************************************************/
2109 static int cmd_rmdir(const char **cmd_ptr)
2110 {
2111         pstring mask;
2112         fstring buf;
2113   
2114         pstrcpy(mask,cur_dir);
2115         
2116         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2117                 d_printf("rmdir <dirname>\n");
2118                 return 1;
2119         }
2120         pstrcat(mask,buf);
2121
2122         if (NT_STATUS_IS_ERR(smbcli_rmdir(cli->tree, mask))) {
2123                 d_printf("%s removing remote directory file %s\n",
2124                          smbcli_errstr(cli->tree),mask);
2125         }
2126         
2127         return 0;
2128 }
2129
2130 /****************************************************************************
2131  UNIX hardlink.
2132 ****************************************************************************/
2133 static int cmd_link(const char **cmd_ptr)
2134 {
2135         pstring src,dest;
2136         fstring buf,buf2;
2137   
2138         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2139                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2140                 return 1;
2141         }
2142
2143         pstrcpy(src,cur_dir);
2144         pstrcpy(dest,cur_dir);
2145   
2146         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2147             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2148                 d_printf("link <src> <dest>\n");
2149                 return 1;
2150         }
2151
2152         pstrcat(src,buf);
2153         pstrcat(dest,buf2);
2154
2155         if (NT_STATUS_IS_ERR(smbcli_unix_hardlink(cli->tree, src, dest))) {
2156                 d_printf("%s linking files (%s -> %s)\n", smbcli_errstr(cli->tree), src, dest);
2157                 return 1;
2158         }  
2159
2160         return 0;
2161 }
2162
2163 /****************************************************************************
2164  UNIX symlink.
2165 ****************************************************************************/
2166
2167 static int cmd_symlink(const char **cmd_ptr)
2168 {
2169         pstring src,dest;
2170         fstring buf,buf2;
2171   
2172         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2173                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2174                 return 1;
2175         }
2176
2177         pstrcpy(src,cur_dir);
2178         pstrcpy(dest,cur_dir);
2179         
2180         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2181             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2182                 d_printf("symlink <src> <dest>\n");
2183                 return 1;
2184         }
2185
2186         pstrcat(src,buf);
2187         pstrcat(dest,buf2);
2188
2189         if (NT_STATUS_IS_ERR(smbcli_unix_symlink(cli->tree, src, dest))) {
2190                 d_printf("%s symlinking files (%s -> %s)\n",
2191                         smbcli_errstr(cli->tree), src, dest);
2192                 return 1;
2193         } 
2194
2195         return 0;
2196 }
2197
2198 /****************************************************************************
2199  UNIX chmod.
2200 ****************************************************************************/
2201
2202 static int cmd_chmod(const char **cmd_ptr)
2203 {
2204         pstring src;
2205         mode_t mode;
2206         fstring buf, buf2;
2207   
2208         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2209                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2210                 return 1;
2211         }
2212
2213         pstrcpy(src,cur_dir);
2214         
2215         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2216             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2217                 d_printf("chmod mode file\n");
2218                 return 1;
2219         }
2220
2221         mode = (mode_t)strtol(buf, NULL, 8);
2222         pstrcat(src,buf2);
2223
2224         if (NT_STATUS_IS_ERR(smbcli_unix_chmod(cli->tree, src, mode))) {
2225                 d_printf("%s chmod file %s 0%o\n",
2226                         smbcli_errstr(cli->tree), src, (uint_t)mode);
2227                 return 1;
2228         } 
2229
2230         return 0;
2231 }
2232
2233 /****************************************************************************
2234  UNIX chown.
2235 ****************************************************************************/
2236
2237 static int cmd_chown(const char **cmd_ptr)
2238 {
2239         pstring src;
2240         uid_t uid;
2241         gid_t gid;
2242         fstring buf, buf2, buf3;
2243   
2244         if (!(cli->transport->negotiate.capabilities & CAP_UNIX)) {
2245                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2246                 return 1;
2247         }
2248
2249         pstrcpy(src,cur_dir);
2250         
2251         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2252             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2)) ||
2253             !next_token(cmd_ptr,buf3,NULL, sizeof(buf3))) {
2254                 d_printf("chown uid gid file\n");
2255                 return 1;
2256         }
2257
2258         uid = (uid_t)atoi(buf);
2259         gid = (gid_t)atoi(buf2);
2260         pstrcat(src,buf3);
2261
2262         if (NT_STATUS_IS_ERR(smbcli_unix_chown(cli->tree, src, uid, gid))) {
2263                 d_printf("%s chown file %s uid=%d, gid=%d\n",
2264                         smbcli_errstr(cli->tree), src, (int)uid, (int)gid);
2265                 return 1;
2266         } 
2267
2268         return 0;
2269 }
2270
2271 /****************************************************************************
2272 rename some files
2273 ****************************************************************************/
2274 static int cmd_rename(const char **cmd_ptr)
2275 {
2276         pstring src,dest;
2277         fstring buf,buf2;
2278   
2279         pstrcpy(src,cur_dir);
2280         pstrcpy(dest,cur_dir);
2281         
2282         if (!next_token(cmd_ptr,buf,NULL,sizeof(buf)) || 
2283             !next_token(cmd_ptr,buf2,NULL, sizeof(buf2))) {
2284                 d_printf("rename <src> <dest>\n");
2285                 return 1;
2286         }
2287
2288         pstrcat(src,buf);
2289         pstrcat(dest,buf2);
2290
2291         if (NT_STATUS_IS_ERR(smbcli_rename(cli->tree, src, dest))) {
2292                 d_printf("%s renaming files\n",smbcli_errstr(cli->tree));
2293                 return 1;
2294         }
2295         
2296         return 0;
2297 }
2298
2299
2300 /****************************************************************************
2301 toggle the prompt flag
2302 ****************************************************************************/
2303 static int cmd_prompt(const char **cmd_ptr)
2304 {
2305         prompt = !prompt;
2306         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
2307         
2308         return 1;
2309 }
2310
2311
2312 /****************************************************************************
2313 set the newer than time
2314 ****************************************************************************/
2315 static int cmd_newer(const char **cmd_ptr)
2316 {
2317         fstring buf;
2318         BOOL ok;
2319         struct stat sbuf;
2320
2321         ok = next_token(cmd_ptr,buf,NULL,sizeof(buf));
2322         if (ok && (stat(buf,&sbuf) == 0)) {
2323                 newer_than = sbuf.st_mtime;
2324                 DEBUG(1,("Getting files newer than %s",
2325                          asctime(localtime(&newer_than))));
2326         } else {
2327                 newer_than = 0;
2328         }
2329
2330         if (ok && newer_than == 0) {
2331                 d_printf("Error setting newer-than time\n");
2332                 return 1;
2333         }
2334
2335         return 0;
2336 }
2337
2338 /****************************************************************************
2339 set the archive level
2340 ****************************************************************************/
2341 static int cmd_archive(const char **cmd_ptr)
2342 {
2343         fstring buf;
2344
2345         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2346                 archive_level = atoi(buf);
2347         } else
2348                 d_printf("Archive level is %d\n",archive_level);
2349
2350         return 0;
2351 }
2352
2353 /****************************************************************************
2354 toggle the lowercaseflag
2355 ****************************************************************************/
2356 static int cmd_lowercase(const char **cmd_ptr)
2357 {
2358         lowercase = !lowercase;
2359         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
2360
2361         return 0;
2362 }
2363
2364
2365
2366
2367 /****************************************************************************
2368 toggle the recurse flag
2369 ****************************************************************************/
2370 static int cmd_recurse(const char **cmd_ptr)
2371 {
2372         recurse = !recurse;
2373         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
2374
2375         return 0;
2376 }
2377
2378 /****************************************************************************
2379 toggle the translate flag
2380 ****************************************************************************/
2381 static int cmd_translate(const char **cmd_ptr)
2382 {
2383         translation = !translation;
2384         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
2385                  translation?"on":"off"));
2386
2387         return 0;
2388 }
2389
2390
2391 /****************************************************************************
2392 do a printmode command
2393 ****************************************************************************/
2394 static int cmd_printmode(const char **cmd_ptr)
2395 {
2396         fstring buf;
2397         fstring mode;
2398
2399         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2400                 if (strequal(buf,"text")) {
2401                         printmode = 0;      
2402                 } else {
2403                         if (strequal(buf,"graphics"))
2404                                 printmode = 1;
2405                         else
2406                                 printmode = atoi(buf);
2407                 }
2408         }
2409
2410         switch(printmode)
2411                 {
2412                 case 0: 
2413                         fstrcpy(mode,"text");
2414                         break;
2415                 case 1: 
2416                         fstrcpy(mode,"graphics");
2417                         break;
2418                 default: 
2419                         slprintf(mode,sizeof(mode)-1,"%d",printmode);
2420                         break;
2421                 }
2422         
2423         DEBUG(2,("the printmode is now %s\n",mode));
2424
2425         return 0;
2426 }
2427
2428 /****************************************************************************
2429  do the lcd command
2430  ****************************************************************************/
2431 static int cmd_lcd(const char **cmd_ptr)
2432 {
2433         fstring buf;
2434         pstring d;
2435         
2436         if (next_token(cmd_ptr,buf,NULL,sizeof(buf)))
2437                 chdir(buf);
2438         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
2439
2440         return 0;
2441 }
2442
2443 /****************************************************************************
2444  get a file restarting at end of local file
2445  ****************************************************************************/
2446 static int cmd_reget(const char **cmd_ptr)
2447 {
2448         pstring local_name;
2449         pstring remote_name;
2450         char *p;
2451
2452         pstrcpy(remote_name, cur_dir);
2453         pstrcat(remote_name, "\\");
2454         
2455         p = remote_name + strlen(remote_name);
2456         
2457         if (!next_token(cmd_ptr, p, NULL, sizeof(remote_name) - strlen(remote_name))) {
2458                 d_printf("reget <filename>\n");
2459                 return 1;
2460         }
2461         pstrcpy(local_name, p);
2462         dos_clean_name(remote_name);
2463         
2464         next_token(cmd_ptr, local_name, NULL, sizeof(local_name));
2465         
2466         return do_get(remote_name, local_name, True);
2467 }
2468
2469 /****************************************************************************
2470  put a file restarting at end of local file
2471  ****************************************************************************/
2472 static int cmd_reput(const char **cmd_ptr)
2473 {
2474         pstring local_name;
2475         pstring remote_name;
2476         fstring buf;
2477         char *p = buf;
2478         
2479         pstrcpy(remote_name, cur_dir);
2480         pstrcat(remote_name, "\\");
2481   
2482         if (!next_token(cmd_ptr, p, NULL, sizeof(buf))) {
2483                 d_printf("reput <filename>\n");
2484                 return 1;
2485         }
2486         pstrcpy(local_name, p);
2487   
2488         if (!file_exist(local_name)) {
2489                 d_printf("%s does not exist\n", local_name);
2490                 return 1;
2491         }
2492
2493         if (next_token(cmd_ptr, p, NULL, sizeof(buf)))
2494                 pstrcat(remote_name, p);
2495         else
2496                 pstrcat(remote_name, local_name);
2497         
2498         dos_clean_name(remote_name);
2499
2500         return do_put(remote_name, local_name, True);
2501 }
2502
2503
2504 /*
2505   return a string representing a share type
2506 */
2507 static const char *share_type_str(uint32_t type)
2508 {
2509         switch (type & 0xF) {
2510         case STYPE_DISKTREE: 
2511                 return "Disk";
2512         case STYPE_PRINTQ: 
2513                 return "Printer";
2514         case STYPE_DEVICE: 
2515                 return "Device";
2516         case STYPE_IPC: 
2517                 return "IPC";
2518         default:
2519                 return "Unknown";
2520         }
2521 }
2522
2523
2524 /*
2525   display a list of shares from a level 1 share enum
2526 */
2527 static void display_share_result(struct srvsvc_NetShareCtr1 *ctr1)
2528 {
2529         int i;
2530
2531         for (i=0;i<ctr1->count;i++) {
2532                 struct srvsvc_NetShareInfo1 *info = ctr1->array+i;
2533
2534                 printf("\t%-15s %-10.10s %s\n", 
2535                        info->name, 
2536                        share_type_str(info->type), 
2537                        info->comment);
2538         }
2539 }
2540
2541
2542
2543 /****************************************************************************
2544 try and browse available shares on a host
2545 ****************************************************************************/
2546 static BOOL browse_host(const char *query_host)
2547 {
2548         struct dcerpc_pipe *p;
2549         char *binding;
2550         NTSTATUS status;
2551         struct srvsvc_NetShareEnumAll r;
2552         uint32_t resume_handle = 0;
2553         TALLOC_CTX *mem_ctx = talloc_init("browse_host");
2554         struct srvsvc_NetShareCtr1 ctr1;
2555
2556         binding = talloc_asprintf(mem_ctx, "ncacn_np:%s", query_host);
2557
2558         status = dcerpc_pipe_connect(&p, binding, 
2559                                      DCERPC_SRVSVC_UUID, 
2560                                      DCERPC_SRVSVC_VERSION,
2561                                      lp_netbios_name(),
2562                                      domain, 
2563                                      username, password);
2564         if (!NT_STATUS_IS_OK(status)) {
2565                 d_printf("Failed to connect to %s - %s\n", 
2566                          binding, nt_errstr(status));
2567                 talloc_free(mem_ctx);
2568                 return False;
2569         }
2570         talloc_steal(mem_ctx, p);
2571
2572         r.in.server_unc = talloc_asprintf(mem_ctx,"\\\\%s",dcerpc_server_name(p));
2573         r.in.level = 1;
2574         r.in.ctr.ctr1 = &ctr1;
2575         r.in.max_buffer = ~0;
2576         r.in.resume_handle = &resume_handle;
2577
2578         d_printf("\n\tSharename       Type       Comment\n");
2579         d_printf("\t---------       ----       -------\n");
2580
2581         do {
2582                 ZERO_STRUCT(ctr1);
2583                 status = dcerpc_srvsvc_NetShareEnumAll(p, mem_ctx, &r);
2584
2585                 if (NT_STATUS_IS_OK(status) && 
2586                     (W_ERROR_EQUAL(r.out.result, WERR_MORE_DATA) ||
2587                      W_ERROR_IS_OK(r.out.result)) &&
2588                     r.out.ctr.ctr1) {
2589                         display_share_result(r.out.ctr.ctr1);
2590                         resume_handle += r.out.ctr.ctr1->count;
2591                 }
2592         } while (NT_STATUS_IS_OK(status) && W_ERROR_EQUAL(r.out.result, WERR_MORE_DATA));
2593
2594         talloc_free(mem_ctx);
2595
2596         if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(r.out.result)) {
2597                 d_printf("Failed NetShareEnumAll %s - %s/%s\n", 
2598                          binding, nt_errstr(status), win_errstr(r.out.result));
2599                 return False;
2600         }
2601
2602         return False;
2603 }
2604
2605 /****************************************************************************
2606 try and browse available connections on a host
2607 ****************************************************************************/
2608 static BOOL list_servers(const char *wk_grp)
2609 {
2610         d_printf("REWRITE: list servers not implemented\n");
2611         return False;
2612 }
2613
2614 /* Some constants for completing filename arguments */
2615
2616 #define COMPL_NONE        0          /* No completions */
2617 #define COMPL_REMOTE      1          /* Complete remote filename */
2618 #define COMPL_LOCAL       2          /* Complete local filename */
2619
2620 /* This defines the commands supported by this client.
2621  * NOTE: The "!" must be the last one in the list because it's fn pointer
2622  *       field is NULL, and NULL in that field is used in process_tok()
2623  *       (below) to indicate the end of the list.  crh
2624  */
2625 static struct
2626 {
2627   const char *name;
2628   int (*fn)(const char **cmd_ptr);
2629   const char *description;
2630   char compl_args[2];      /* Completion argument info */
2631 } commands[] = 
2632 {
2633   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2634   {"addprivileges",cmd_addprivileges,"<sid|name> <privilege...> add privileges for a user",{COMPL_NONE,COMPL_NONE}},
2635   {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
2636   {"acl",cmd_acl,"<file> show file ACL",{COMPL_NONE,COMPL_NONE}},
2637   {"allinfo",cmd_allinfo,"<file> show all possible info about a file",{COMPL_NONE,COMPL_NONE}},
2638   {"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}},
2639   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
2640   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2641   {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
2642   {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
2643   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2644   {"delprivileges",cmd_delprivileges,"<sid|name> <privilege...> remove privileges for a user",{COMPL_NONE,COMPL_NONE}},
2645   {"deltree",cmd_deltree,"<dir> delete a whole directory tree",{COMPL_REMOTE,COMPL_NONE}},
2646   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2647   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2648   {"eainfo",cmd_eainfo,"<file> show EA contents for a file",{COMPL_NONE,COMPL_NONE}},
2649   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2650   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2651   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2652   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2653   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2654   {"link",cmd_link,"<src> <dest> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
2655   {"lookup",cmd_lookup,"<sid|name> show SID for name or name for SID",{COMPL_NONE,COMPL_NONE}},
2656   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2657   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2658   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
2659   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2660   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2661   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2662   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
2663   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2664   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2665   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
2666   {"privileges",cmd_privileges,"<user> show privileges for a user",{COMPL_NONE,COMPL_NONE}},
2667   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
2668   {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
2669   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2670   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2671   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2672   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2673   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
2674   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2675   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2676   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
2677   {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
2678   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2679   {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
2680   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
2681   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2682   {"symlink",cmd_symlink,"<src> <dest> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
2683   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2684   
2685   /* Yes, this must be here, see crh's comment above. */
2686   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2687   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2688 };
2689
2690
2691 /*******************************************************************
2692   lookup a command string in the list of commands, including 
2693   abbreviations
2694   ******************************************************************/
2695 static int process_tok(fstring tok)
2696 {
2697         int i = 0, matches = 0;
2698         int cmd=0;
2699         int tok_len = strlen(tok);
2700         
2701         while (commands[i].fn != NULL) {
2702                 if (strequal(commands[i].name,tok)) {
2703                         matches = 1;
2704                         cmd = i;
2705                         break;
2706                 } else if (strncasecmp(commands[i].name, tok, tok_len) == 0) {
2707                         matches++;
2708                         cmd = i;
2709                 }
2710                 i++;
2711         }
2712   
2713         if (matches == 0)
2714                 return(-1);
2715         else if (matches == 1)
2716                 return(cmd);
2717         else
2718                 return(-2);
2719 }
2720
2721 /****************************************************************************
2722 help
2723 ****************************************************************************/
2724 static int cmd_help(const char **cmd_ptr)
2725 {
2726         int i=0,j;
2727         fstring buf;
2728         
2729         if (next_token(cmd_ptr,buf,NULL,sizeof(buf))) {
2730                 if ((i = process_tok(buf)) >= 0)
2731                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
2732         } else {
2733                 while (commands[i].description) {
2734                         for (j=0; commands[i].description && (j<5); j++) {
2735                                 d_printf("%-15s",commands[i].name);
2736                                 i++;
2737                         }
2738                         d_printf("\n");
2739                 }
2740         }
2741         return 0;
2742 }
2743
2744 /****************************************************************************
2745 process a -c command string
2746 ****************************************************************************/
2747 static int process_command_string(char *cmd)
2748 {
2749         pstring line;
2750         const char *ptr;
2751         int rc = 0;
2752
2753         /* establish the connection if not already */
2754         
2755         if (!cli) {
2756                 cli = do_connect(desthost, service);
2757                 if (!cli)
2758                         return 0;
2759         }
2760         
2761         while (cmd[0] != '\0')    {
2762                 char *p;
2763                 fstring tok;
2764                 int i;
2765                 
2766                 if ((p = strchr_m(cmd, ';')) == 0) {
2767                         strncpy(line, cmd, 999);
2768                         line[1000] = '\0';
2769                         cmd += strlen(cmd);
2770                 } else {
2771                         if (p - cmd > 999) p = cmd + 999;
2772                         strncpy(line, cmd, p - cmd);
2773                         line[p - cmd] = '\0';
2774                         cmd = p + 1;
2775                 }
2776                 
2777                 /* and get the first part of the command */
2778                 ptr = line;
2779                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
2780                 
2781                 if ((i = process_tok(tok)) >= 0) {
2782                         rc = commands[i].fn(&ptr);
2783                 } else if (i == -2) {
2784                         d_printf("%s: command abbreviation ambiguous\n",tok);
2785                 } else {
2786                         d_printf("%s: command not found\n",tok);
2787                 }
2788         }
2789         
2790         return rc;
2791 }       
2792
2793 #define MAX_COMPLETIONS 100
2794
2795 typedef struct {
2796         pstring dirmask;
2797         char **matches;
2798         int count, samelen;
2799         const char *text;
2800         int len;
2801 } completion_remote_t;
2802
2803 static void completion_remote_filter(struct clilist_file_info *f, const char *mask, void *state)
2804 {
2805         completion_remote_t *info = (completion_remote_t *)state;
2806
2807         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
2808                 if ((info->dirmask[0] == 0) && !(f->attrib & FILE_ATTRIBUTE_DIRECTORY))
2809                         info->matches[info->count] = strdup(f->name);
2810                 else {
2811                         pstring tmp;
2812
2813                         if (info->dirmask[0] != 0)
2814                                 pstrcpy(tmp, info->dirmask);
2815                         else
2816                                 tmp[0] = 0;
2817                         pstrcat(tmp, f->name);
2818                         if (f->attrib & FILE_ATTRIBUTE_DIRECTORY)
2819                                 pstrcat(tmp, "/");
2820                         info->matches[info->count] = strdup(tmp);
2821                 }
2822                 if (info->matches[info->count] == NULL)
2823                         return;
2824                 if (f->attrib & FILE_ATTRIBUTE_DIRECTORY)
2825                         smb_readline_ca_char(0);
2826
2827                 if (info->count == 1)
2828                         info->samelen = strlen(info->matches[info->count]);
2829                 else
2830                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
2831                                 info->samelen--;
2832                 info->count++;
2833         }
2834 }
2835
2836 static char **remote_completion(const char *text, int len)
2837 {
2838         pstring dirmask;
2839         int i;
2840         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
2841
2842         info.samelen = len;
2843         info.text = text;
2844         info.len = len;
2845  
2846         if (len >= PATH_MAX)
2847                 return(NULL);
2848
2849         info.matches = malloc_array_p(char *, MAX_COMPLETIONS);
2850         if (!info.matches) return NULL;
2851         info.matches[0] = NULL;
2852
2853         for (i = len-1; i >= 0; i--)
2854                 if ((text[i] == '/') || (text[i] == '\\'))
2855                         break;
2856         info.text = text+i+1;
2857         info.samelen = info.len = len-i-1;
2858
2859         if (i > 0) {
2860                 strncpy(info.dirmask, text, i+1);
2861                 info.dirmask[i+1] = 0;
2862                 snprintf(dirmask, sizeof(dirmask), "%s%*s*", cur_dir, i-1, text);
2863         } else
2864                 snprintf(dirmask, sizeof(dirmask), "%s*", cur_dir);
2865
2866         if (smbcli_list(cli->tree, dirmask, 
2867                      FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN, 
2868                      completion_remote_filter, &info) < 0)
2869                 goto cleanup;
2870
2871         if (info.count == 2)
2872                 info.matches[0] = strdup(info.matches[1]);
2873         else {
2874                 info.matches[0] = malloc(info.samelen+1);
2875                 if (!info.matches[0])
2876                         goto cleanup;
2877                 strncpy(info.matches[0], info.matches[1], info.samelen);
2878                 info.matches[0][info.samelen] = 0;
2879         }
2880         info.matches[info.count] = NULL;
2881         return info.matches;
2882
2883 cleanup:
2884         for (i = 0; i < info.count; i++)
2885                 free(info.matches[i]);
2886         free(info.matches);
2887         return NULL;
2888 }
2889
2890 static char **completion_fn(const char *text, int start, int end)
2891 {
2892         smb_readline_ca_char(' ');
2893
2894         if (start) {
2895                 const char *buf, *sp;
2896                 int i;
2897                 char compl_type;
2898
2899                 buf = smb_readline_get_line_buffer();
2900                 if (buf == NULL)
2901                         return NULL;
2902                 
2903                 sp = strchr(buf, ' ');
2904                 if (sp == NULL)
2905                         return NULL;
2906                 
2907                 for (i = 0; commands[i].name; i++)
2908                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
2909                                 break;
2910                 if (commands[i].name == NULL)
2911                         return NULL;
2912
2913                 while (*sp == ' ')
2914                         sp++;
2915
2916                 if (sp == (buf + start))
2917                         compl_type = commands[i].compl_args[0];
2918                 else
2919                         compl_type = commands[i].compl_args[1];
2920
2921                 if (compl_type == COMPL_REMOTE)
2922                         return remote_completion(text, end - start);
2923                 else /* fall back to local filename completion */
2924                         return NULL;
2925         } else {
2926                 char **matches;
2927                 int i, len, samelen = 0, count=1;
2928
2929                 matches = malloc_array_p(char *, MAX_COMPLETIONS);
2930                 if (!matches) return NULL;
2931                 matches[0] = NULL;
2932
2933                 len = strlen(text);
2934                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
2935                         if (strncmp(text, commands[i].name, len) == 0) {
2936                                 matches[count] = strdup(commands[i].name);
2937                                 if (!matches[count])
2938                                         goto cleanup;
2939                                 if (count == 1)
2940                                         samelen = strlen(matches[count]);
2941                                 else
2942                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
2943                                                 samelen--;
2944                                 count++;
2945                         }
2946                 }
2947
2948                 switch (count) {
2949                 case 0: /* should never happen */
2950                 case 1:
2951                         goto cleanup;
2952                 case 2:
2953                         matches[0] = strdup(matches[1]);
2954                         break;
2955                 default:
2956                         matches[0] = malloc(samelen+1);
2957                         if (!matches[0])
2958                                 goto cleanup;
2959                         strncpy(matches[0], matches[1], samelen);
2960                         matches[0][samelen] = 0;
2961                 }
2962                 matches[count] = NULL;
2963                 return matches;
2964
2965 cleanup:
2966                 while (i >= 0) {
2967                         free(matches[i]);
2968                         i--;
2969                 }
2970                 free(matches);
2971                 return NULL;
2972         }
2973 }
2974
2975 /****************************************************************************
2976 make sure we swallow keepalives during idle time
2977 ****************************************************************************/
2978 static void readline_callback(void)
2979 {
2980         static time_t last_t;
2981         time_t t;
2982
2983         t = time(NULL);
2984
2985         if (t - last_t < 5) return;
2986
2987         last_t = t;
2988
2989         smbcli_transport_process(cli->transport);
2990
2991         if (cli->tree) {
2992                 smbcli_chkpath(cli->tree, "\\");
2993         }
2994 }
2995
2996
2997 /****************************************************************************
2998 process commands on stdin
2999 ****************************************************************************/
3000 static void process_stdin(void)
3001 {
3002         while (1) {
3003                 fstring tok;
3004                 fstring the_prompt;
3005                 char *cline;
3006                 pstring line;
3007                 const char *ptr;
3008                 int i;
3009                 
3010                 /* display a prompt */
3011                 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);
3012                 cline = smb_readline(the_prompt, readline_callback, completion_fn);
3013                         
3014                 if (!cline) break;
3015                 
3016                 pstrcpy(line, cline);
3017
3018                 /* special case - first char is ! */
3019                 if (*line == '!') {
3020                         system(line + 1);
3021                         continue;
3022                 }
3023       
3024                 /* and get the first part of the command */
3025                 ptr = line;
3026                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
3027
3028                 if ((i = process_tok(tok)) >= 0) {
3029                         commands[i].fn(&ptr);
3030                 } else if (i == -2) {
3031                         d_printf("%s: command abbreviation ambiguous\n",tok);
3032                 } else {
3033                         d_printf("%s: command not found\n",tok);
3034                 }
3035         }
3036 }
3037
3038
3039 /***************************************************** 
3040 return a connection to a server
3041 *******************************************************/
3042 static struct smbcli_state *do_connect(const char *server, const char *share)
3043 {
3044         struct smbcli_state *c;
3045         NTSTATUS status;
3046
3047         if (strncmp(share, "\\\\", 2) == 0 ||
3048             strncmp(share, "//", 2) == 0) {
3049                 smbcli_parse_unc(share, NULL, &server, &share);
3050         }
3051         
3052         status = smbcli_full_connection(NULL, &c, lp_netbios_name(), server,
3053                                         share, NULL, username, domain, password);
3054         if (!NT_STATUS_IS_OK(status)) {
3055                 d_printf("Connection to \\\\%s\\%s failed - %s\n", 
3056                          server, share, nt_errstr(status));
3057                 return NULL;
3058         }
3059
3060         return c;
3061 }
3062
3063
3064 /****************************************************************************
3065   process commands from the client
3066 ****************************************************************************/
3067 static int process(char *base_directory)
3068 {
3069         int rc = 0;
3070
3071         cli = do_connect(desthost, service);
3072         if (!cli) {
3073                 return 1;
3074         }
3075
3076         if (*base_directory) do_cd(base_directory);
3077         
3078         if (cmdstr) {
3079                 rc = process_command_string(cmdstr);
3080         } else {
3081                 process_stdin();
3082         }
3083   
3084         smbcli_shutdown(cli);
3085         return rc;
3086 }
3087
3088 /****************************************************************************
3089 handle a -L query
3090 ****************************************************************************/
3091 static int do_host_query(char *query_host)
3092 {
3093         browse_host(query_host);
3094         list_servers(lp_workgroup());
3095         return(0);
3096 }
3097
3098
3099 /****************************************************************************
3100 handle a message operation
3101 ****************************************************************************/
3102 static int do_message_op(void)
3103 {
3104         struct nbt_name called, calling;
3105         const char *server_name;
3106
3107         calling.name = lp_netbios_name();
3108         calling.type = NBT_NAME_CLIENT;
3109         calling.scope = NULL;
3110
3111         nbt_choose_called_name(NULL, &called, desthost, name_type);
3112
3113         server_name = dest_ip ? dest_ip : desthost;
3114
3115         if (!(cli=smbcli_state_init(NULL)) || !smbcli_socket_connect(cli, server_name)) {
3116                 d_printf("Connection to %s failed\n", server_name);
3117                 return 1;
3118         }
3119
3120         if (!smbcli_transport_establish(cli, &calling, &called)) {
3121                 d_printf("session request failed\n");
3122                 smbcli_shutdown(cli);
3123                 return 1;
3124         }
3125
3126         send_message();
3127         smbcli_shutdown(cli);
3128
3129         return 0;
3130 }
3131
3132
3133 /**
3134  * Process "-L hostname" option.
3135  *
3136  * We don't actually do anything yet -- we just stash the name in a
3137  * global variable and do the query when all options have been read.
3138  **/
3139 static void remember_query_host(const char *arg,
3140                                 pstring query_host)
3141 {
3142         char *slash;
3143         
3144         while (*arg == '\\' || *arg == '/')
3145                 arg++;
3146         pstrcpy(query_host, arg);
3147         if ((slash = strchr(query_host, '/'))
3148             || (slash = strchr(query_host, '\\'))) {
3149                 *slash = 0;
3150         }
3151 }
3152
3153
3154 /****************************************************************************
3155   main program
3156 ****************************************************************************/
3157  int main(int argc,char *argv[])
3158 {
3159         fstring base_directory;
3160         int opt;
3161         pstring query_host;
3162         BOOL message = False;
3163         pstring term_code;
3164         poptContext pc;
3165         char *p;
3166         int rc = 0;
3167         TALLOC_CTX *mem_ctx;
3168         struct poptOption long_options[] = {
3169                 POPT_AUTOHELP
3170
3171                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
3172                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
3173                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
3174                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
3175                 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
3176                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
3177                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
3178                 { "send-buffer", 'b', POPT_ARG_INT, NULL, 'b', "Changes the transmit/send buffer", "BYTES" },
3179                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
3180                 POPT_COMMON_SAMBA
3181                 POPT_COMMON_CONNECTION
3182                 POPT_COMMON_CREDENTIALS
3183                 POPT_COMMON_VERSION
3184                 POPT_TABLEEND
3185         };
3186         
3187 #ifdef KANJI
3188         pstrcpy(term_code, KANJI);
3189 #else /* KANJI */
3190         *term_code = 0;
3191 #endif /* KANJI */
3192
3193         *query_host = 0;
3194         *base_directory = 0;
3195
3196         setup_logging(argv[0],DEBUG_STDOUT);
3197         mem_ctx = talloc_init("client.c/main");
3198         if (!mem_ctx) {
3199                 d_printf("\nclient.c: Not enough memory\n");
3200                 exit(1);
3201         }
3202
3203         if (!lp_load(dyn_CONFIGFILE,True,False,False)) {
3204                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
3205                         argv[0], dyn_CONFIGFILE);
3206         }
3207         
3208         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 0);
3209         poptSetOtherOptionHelp(pc, "[OPTIONS] service <password>");
3210
3211         in_client = True;   /* Make sure that we tell lp_load we are */
3212
3213         while ((opt = poptGetNextOpt(pc)) != -1) {
3214                 switch (opt) {
3215                 case 'M':
3216                         /* Messages are sent to NetBIOS name type 0x3
3217                          * (Messenger Service).  Make sure we default
3218                          * to port 139 instead of port 445. srl,crh
3219                          */
3220                         name_type = 0x03; 
3221                         pstrcpy(desthost,poptGetOptArg(pc));
3222                         if( 0 == port ) port = 139;
3223                         message = True;
3224                         break;
3225                 case 'I':
3226                         dest_ip = poptGetOptArg(pc);
3227                         break;
3228                 case 'E':
3229                         setup_logging("client", DEBUG_STDERR);
3230                         break;
3231
3232                 case 'L':
3233                         remember_query_host(poptGetOptArg(pc), query_host);
3234                         break;
3235                 case 't':
3236                         pstrcpy(term_code, poptGetOptArg(pc));
3237                         break;
3238                 case 'D':
3239                         fstrcpy(base_directory,poptGetOptArg(pc));
3240                         break;
3241                 case 'b':
3242                         io_bufsize = MAX(1, atoi(poptGetOptArg(pc)));
3243                         break;
3244                 }
3245         }
3246
3247         load_interfaces();
3248
3249         smbclient_init_subsystems;
3250
3251         if(poptPeekArg(pc)) {
3252                 pstrcpy(service,poptGetArg(pc));  
3253                 /* Convert any '/' characters in the service name to '\' characters */
3254                 string_replace(service, '/','\\');
3255
3256                 if (count_chars(service,'\\') < 3) {
3257                         d_printf("\n%s: Not enough '\\' characters in service\n",service);
3258                         poptPrintUsage(pc, stderr, 0);
3259                         exit(1);
3260                 }
3261         }
3262
3263         if (poptPeekArg(pc)) { 
3264                 cmdline_set_userpassword(poptGetArg(pc));
3265         }
3266
3267         /*init_names(); */
3268
3269         if (!*query_host && !*service && !message) {
3270                 poptPrintUsage(pc, stderr, 0);
3271                 exit(1);
3272         }
3273
3274         poptFreeContext(pc);
3275
3276         pstrcpy(username, cmdline_get_username());
3277         pstrcpy(domain, cmdline_get_userdomain());
3278         pstrcpy(password, cmdline_get_userpassword());
3279
3280         DEBUG( 3, ( "Client started (version %s).\n", SAMBA_VERSION_STRING ) );
3281
3282         talloc_free(mem_ctx);
3283
3284         if ((p=strchr_m(query_host,'#'))) {
3285                 *p = 0;
3286                 p++;
3287                 sscanf(p, "%x", &name_type);
3288         }
3289   
3290         if (*query_host) {
3291                 return do_host_query(query_host);
3292         }
3293
3294         if (message) {
3295                 return do_message_op();
3296         }
3297         
3298         if (process(base_directory)) {
3299                 return 1;
3300         }
3301
3302         return rc;
3303 }