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