r13212: r12414@cabra: derrell | 2006-01-28 17:52:17 -0500
[tprouty/samba.git] / source / client / smbctool.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
7    Copyright (C) Gerald (Jerry) Carter          2004
8    Copyright (C) Kalim Moghul                   2005
9    
10    This program is free software; you can redistribute it and/or modify
11    it under the terms of the GNU General Public License as published by
12    the Free Software Foundation; either version 2 of the License, or
13    (at your option) any later version.
14    
15    This program is distributed in the hope that it will be useful,
16    but WITHOUT ANY WARRANTY; without even the implied warranty of
17    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18    GNU General Public License for more details.
19    
20    You should have received a copy of the GNU General Public License
21    along with this program; if not, write to the Free Software
22    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25 #define NO_SYSLOG
26
27 #include "includes.h"
28 #include "libsmbclient.h"
29 #include "client/client_proto.h"
30 #ifndef REGISTER
31 #define REGISTER 0
32 #endif
33
34 extern BOOL AllowDebugChange;
35 extern BOOL override_logfile;
36 extern char tar_type;
37 extern BOOL in_client;
38 static int port = 0;
39 pstring cur_dir = "/";
40 static pstring service;
41 static pstring desthost;
42 static pstring username;
43 static pstring workgroup;
44 static pstring calling_name;
45 static BOOL grepable=False;
46 static char *cmdstr = NULL;
47
48 static int io_bufsize = 64512;
49
50 static int name_type = 0x20;
51 extern int max_protocol;
52
53 static int process_tok(pstring tok);
54 static int cmd_help(void);
55
56 /* 30 second timeout on most commands */
57 #define CLIENT_TIMEOUT (30*1000)
58 #define SHORT_TIMEOUT (5*1000)
59
60 /* value for unused fid field in trans2 secondary request */
61 #define FID_UNUSED (0xFFFF)
62
63 time_t newer_than = 0;
64 static int archive_level = 0;
65
66 static BOOL translation = False;
67 static BOOL have_ip;
68
69 /* clitar bits insert */
70 extern int blocksize;
71 extern BOOL tar_inc;
72 extern BOOL tar_reset;
73 /* clitar bits end */
74  
75
76 static BOOL prompt = True;
77
78 static BOOL recurse = False;
79 BOOL lowercase = False;
80
81 static struct in_addr dest_ip;
82
83 #define SEPARATORS " \t\n\r"
84
85 static BOOL abort_mget = True;
86
87 static pstring fileselection = "";
88
89 extern file_info def_finfo;
90
91 /* timing globals */
92 SMB_BIG_UINT get_total_size = 0;
93 unsigned int get_total_time_ms = 0;
94 static SMB_BIG_UINT put_total_size = 0;
95 static unsigned int put_total_time_ms = 0;
96
97 /* totals globals */
98 static double dir_total;
99
100 /* root cli_state connection */
101
102 struct cli_state *cli;
103
104
105 /****************************************************************************
106  Authentication callback function for libsmbclient 
107 ****************************************************************************/
108
109 static void
110 get_auth_data_fn(const char * pServer, const char * pShare,
111         char * pWorkgroup, int maxLenWorkgroup,
112         char * pUsername, int maxLenUsername,
113         char * pPassword, int maxLenPassword)
114 {
115         char temp[sizeof(fstring)];
116         
117         static char authUsername[sizeof(fstring)];
118         static char authWorkgroup[sizeof(fstring)];
119         static char authPassword[sizeof(fstring)];
120         static char authSet = 0;
121
122         
123         if (authSet)
124         {
125                 strncpy(pWorkgroup, authWorkgroup, maxLenWorkgroup - 1);
126                 strncpy(pUsername, authUsername, maxLenUsername - 1);
127                 strncpy(pPassword, authPassword, maxLenPassword - 1);
128         }
129         else
130         {
131                 d_printf("Workgroup: %s\n", workgroup);
132                 strncpy(pWorkgroup, workgroup, maxLenWorkgroup - 1);
133                 strncpy(authWorkgroup, workgroup, maxLenWorkgroup - 1);
134                 
135                 d_printf("Username: %s\n", username);
136                 strncpy(pUsername, username, maxLenUsername - 1);
137                 strncpy(authUsername, username, maxLenUsername - 1);
138                 
139                 if (cmdline_auth_info.got_pass)
140                 {
141                         strncpy(pPassword, cmdline_auth_info.password, maxLenPassword - 1);
142                         strncpy(authPassword, cmdline_auth_info.password, maxLenPassword - 1);
143                 }
144                 else
145                 {
146                         char *pass = getpass("Password: ");
147                         if (pass)
148                                 fstrcpy(temp, pass);
149                         if (temp[strlen(temp) - 1] == '\n') /* A new line? */
150                         {
151                                 temp[strlen(temp) - 1] = '\0';
152                         }                
153                         if (temp[0] != '\0')
154                         {
155                                 strncpy(pPassword, temp, maxLenPassword - 1);
156                                 strncpy(authPassword, pPassword, maxLenPassword - 1);
157                         }
158                 }
159                 pstrcpy(cmdline_auth_info.username, authUsername);
160                 pstrcpy(cmdline_auth_info.password, authPassword);
161                 cmdline_auth_info.got_pass = True;
162                 set_global_myworkgroup(authWorkgroup);
163                 cli_cm_set_credentials(&cmdline_auth_info);
164                 authSet = 1;
165         }
166 }
167
168 /*******************************************************************
169  Return a string representing an attribute for a file.
170 ********************************************************************/
171
172 fstring *mode_t_string(mode_t mode)
173 {
174         static fstring attrstr;
175
176         attrstr[0] = 0;
177         
178         S_ISDIR(mode) ? fstrcat(attrstr, "d") : fstrcat(attrstr, "-");
179         (mode & S_IRUSR) ? fstrcat(attrstr, "r") : fstrcat(attrstr, "-");
180         (mode & S_IWUSR) ? fstrcat(attrstr, "w") : fstrcat(attrstr, "-");
181         (mode & S_IXUSR) ? fstrcat(attrstr, "x") : fstrcat(attrstr, "-");
182         
183         (mode & S_IRGRP) ? fstrcat(attrstr, "r") : fstrcat(attrstr, "-");
184         (mode & S_IWGRP) ? fstrcat(attrstr, "w") : fstrcat(attrstr, "-");
185         (mode & S_IXGRP) ? fstrcat(attrstr, "x") : fstrcat(attrstr, "-");
186         
187         (mode & S_IROTH) ? fstrcat(attrstr, "r") : fstrcat(attrstr, "-");
188         (mode & S_IWOTH) ? fstrcat(attrstr, "w") : fstrcat(attrstr, "-");
189         (mode & S_IXOTH) ? fstrcat(attrstr, "x") : fstrcat(attrstr, "-");
190         
191
192         return(&attrstr);
193 }
194
195 /****************************************************************************
196  Write to a local file with CR/LF->LF translation if appropriate. Return the 
197  number taken from the buffer. This may not equal the number written.
198 ****************************************************************************/
199
200 static int writefile(int f, char *b, int n)
201 {
202         int i;
203
204         if (!translation) {
205                 return write(f,b,n);
206         }
207
208         i = 0;
209         while (i < n) {
210                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
211                         b++;i++;
212                 }
213                 if (write(f, b, 1) != 1) {
214                         break;
215                 }
216                 b++;
217                 i++;
218         }
219   
220         return(i);
221 }
222
223 /****************************************************************************
224  Read from a file with LF->CR/LF translation if appropriate. Return the 
225  number read. read approx n bytes.
226 ****************************************************************************/
227
228 static int readfile(char *b, int n, XFILE *f)
229 {
230         int i;
231         int c;
232
233         if (!translation)
234                 return x_fread(b,1,n,f);
235   
236         i = 0;
237         while (i < (n - 1) && (i < BUFFER_SIZE)) {
238                 if ((c = x_getc(f)) == EOF) {
239                         break;
240                 }
241           
242                 if (c == '\n') { /* change all LFs to CR/LF */
243                         b[i++] = '\r';
244                 }
245           
246                 b[i++] = c;
247         }
248   
249         return(i);
250 }
251  
252 /****************************************************************************
253  Send a message.
254 ****************************************************************************/
255
256 static void send_message(void)
257 {
258         int total_len = 0;
259         int grp_id;
260
261         if (!cli_message_start(cli, desthost, username, &grp_id)) {
262                 d_printf("message start: %s\n", cli_errstr(cli));
263                 return;
264         }
265
266
267         d_printf("Connected. Type your message, ending it with a Control-D\n");
268
269         while (!feof(stdin) && total_len < 1600) {
270                 int maxlen = MIN(1600 - total_len,127);
271                 pstring msg;
272                 int l=0;
273                 int c;
274
275                 ZERO_ARRAY(msg);
276
277                 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
278                         if (c == '\n')
279                                 msg[l++] = '\r';
280                         msg[l] = c;       
281                 }
282
283                 if (!cli_message_text(cli, msg, l, grp_id)) {
284                         d_printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
285                         return;
286                 }          
287                 
288                 total_len += l;
289         }
290
291         if (total_len >= 1600)
292                 d_printf("the message was truncated to 1600 bytes\n");
293         else
294                 d_printf("sent %d bytes\n",total_len);
295
296         if (!cli_message_end(cli, grp_id)) {
297                 d_printf("SMBsendend failed (%s)\n",cli_errstr(cli));
298                 return;
299         }          
300 }
301
302 /****************************************************************************
303  Check the space on a device.
304 ****************************************************************************/
305
306 static int do_dskattr(void)
307 {
308         int total, bsize, avail;
309         struct cli_state *targetcli;
310         pstring targetpath;
311
312         if ( !cli_resolve_path( "", cli, cur_dir, &targetcli, targetpath ) ) {
313                 d_printf("Error in dskattr: %s\n", cli_errstr(cli));
314                 return 1;
315         }
316
317         if (!cli_dskattr(targetcli, &bsize, &total, &avail)) {
318                 d_printf("Error in dskattr: %s\n",cli_errstr(targetcli)); 
319                 return 1;
320         }
321
322         d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
323                  total, bsize, avail);
324
325         return 0;
326 }
327
328 /****************************************************************************
329  Show cd/pwd.
330 ****************************************************************************/
331
332 static int cmd_pwd(void)
333 {
334         d_printf("Current directory is %s",service);
335         d_printf("%s\n",cur_dir);
336         return 0;
337 }
338
339 /****************************************************************************
340  Change directory - inner section.
341 ****************************************************************************/
342
343 static int do_cd(char *newdir)
344 {
345         char *p = newdir;
346         pstring saved_dir;
347         pstring dname;
348         pstring targetpath;
349         struct cli_state *targetcli;
350         SMB_STRUCT_STAT sbuf;
351         uint32 attributes;
352         int dh;
353         
354         unix_format(newdir);
355
356         /* Save the current directory in case the new directory is invalid */
357         pstrcpy(saved_dir, cur_dir);
358
359         pstrcpy(dname, p);                      /* first save the argument */
360         
361         if (*p == '/')
362                 pstrcpy(cur_dir,dname);
363         else
364                 pstrcat(cur_dir,dname);
365
366         if (*(cur_dir+strlen(cur_dir)-1) != '/') {
367                 pstrcat(cur_dir, "/");
368         }
369         
370         all_string_sub(cur_dir, "/./", "/", 0);
371         
372         /* Format the directory in a libmsmbclient friendly way */
373         unix_clean_name(cur_dir);
374         all_string_sub(cur_dir, "/./", "/", 0);
375         pstrcpy(targetpath, "smb:");
376         pstrcat(targetpath, service);
377         pstrcat(targetpath, cur_dir);
378         unix_format(targetpath);
379
380         dh = smbc_opendir(targetpath);
381         
382         if (dh < 0)
383         {
384                 d_printf("%s changing to directory %s\n", strerror(errno), cur_dir);
385                 pstrcpy(cur_dir, saved_dir);
386                 return 1;
387         }
388         smbc_closedir(dh);
389
390         return 0;
391 }
392
393 /****************************************************************************
394  Change directory.
395 ****************************************************************************/
396
397 static int cmd_cd(void)
398 {
399         pstring buf;
400         int rc = 0;
401                 
402         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
403                 rc = do_cd(buf);
404         else
405                 d_printf("Current directory is %s\n",cur_dir);
406
407         return rc;
408 }
409
410 /*******************************************************************
411  Decide if a file should be operated on.
412 ********************************************************************/
413
414 static BOOL do_this_one(file_info *finfo)
415 {
416         if (finfo->mode & aDIR)
417                 return(True);
418
419         if (*fileselection && 
420                 !mask_match(finfo->name,fileselection,False)) {
421                 DEBUG(3,("mask_match %s failed\n", finfo->name));
422                 return False;
423         }
424
425         if (newer_than && finfo->mtime < newer_than) {
426                 DEBUG(3,("newer_than %s failed\n", finfo->name));
427                 return(False);
428         }
429
430         if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
431                 DEBUG(3,("archive %s failed\n", finfo->name));
432                 return(False);
433         }
434         
435         return(True);
436 }
437
438 /****************************************************************************
439  Display info about a file.
440 ****************************************************************************/
441
442 static void display_finfo(file_info *finfo)
443 {
444         if (do_this_one(finfo)) {
445                 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
446                 d_printf("  %-30s%7.7s %8.0f  %s",
447                          finfo->name,
448                          attrib_string(finfo->mode),
449                          (double)finfo->size,
450                          asctime(localtime(&t)));
451                 dir_total += finfo->size;
452         }
453 }
454
455 /****************************************************************************
456  Display info about a file.
457 ****************************************************************************/
458
459 static void display_stat(char *name, struct stat *st)
460 {
461         time_t t = st->st_mtime;
462         pstring time_str;
463         pstrcpy(time_str, asctime(localtime(&t)));
464         time_str[strlen(time_str)-1] = 0;
465         d_printf("> %-30s", name);
466         d_printf("%10.10s %8.0f  %s\n", *mode_t_string(st->st_mode), (double)st->st_size, time_str);
467 }
468
469 /****************************************************************************
470  Accumulate size of a file.
471 ****************************************************************************/
472
473 static void do_du(file_info *finfo)
474 {
475         if (do_this_one(finfo)) {
476                 dir_total += finfo->size;
477         }
478 }
479
480 static BOOL do_list_recurse;
481 static BOOL do_list_dirs;
482 static char *do_list_queue = 0;
483 static long do_list_queue_size = 0;
484 static long do_list_queue_start = 0;
485 static long do_list_queue_end = 0;
486 static void (*do_list_fn)(file_info *);
487 static void (*tool_list_fn)(char *, struct stat *);
488
489 /****************************************************************************
490  Functions for do_list_queue.
491 ****************************************************************************/
492
493 /*
494  * The do_list_queue is a NUL-separated list of strings stored in a
495  * char*.  Since this is a FIFO, we keep track of the beginning and
496  * ending locations of the data in the queue.  When we overflow, we
497  * double the size of the char*.  When the start of the data passes
498  * the midpoint, we move everything back.  This is logically more
499  * complex than a linked list, but easier from a memory management
500  * angle.  In any memory error condition, do_list_queue is reset.
501  * Functions check to ensure that do_list_queue is non-NULL before
502  * accessing it.
503  */
504
505 static void reset_do_list_queue(void)
506 {
507         SAFE_FREE(do_list_queue);
508         do_list_queue_size = 0;
509         do_list_queue_start = 0;
510         do_list_queue_end = 0;
511 }
512
513 static void init_do_list_queue(void)
514 {
515         reset_do_list_queue();
516         do_list_queue_size = 1024;
517         do_list_queue = SMB_MALLOC(do_list_queue_size);
518         if (do_list_queue == 0) { 
519                 d_printf("malloc fail for size %d\n",
520                          (int)do_list_queue_size);
521                 reset_do_list_queue();
522         } else {
523                 memset(do_list_queue, 0, do_list_queue_size);
524         }
525 }
526
527 static void adjust_do_list_queue(void)
528 {
529         /*
530          * If the starting point of the queue is more than half way through,
531          * move everything toward the beginning.
532          */
533         if (do_list_queue && (do_list_queue_start == do_list_queue_end)) {
534                 DEBUG(4,("do_list_queue is empty\n"));
535                 do_list_queue_start = do_list_queue_end = 0;
536                 *do_list_queue = '\0';
537         } else if (do_list_queue_start > (do_list_queue_size / 2)) {
538                 DEBUG(4,("sliding do_list_queue backward\n"));
539                 memmove(do_list_queue,
540                         do_list_queue + do_list_queue_start,
541                         do_list_queue_end - do_list_queue_start);
542                 do_list_queue_end -= do_list_queue_start;
543                 do_list_queue_start = 0;
544         }
545 }
546
547 static void add_to_do_list_queue(const char* entry)
548 {
549         char *dlq;
550         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
551         while (new_end > do_list_queue_size) {
552                 do_list_queue_size *= 2;
553                 DEBUG(4,("enlarging do_list_queue to %d\n",
554                          (int)do_list_queue_size));
555                 dlq = SMB_REALLOC(do_list_queue, do_list_queue_size);
556                 if (! dlq) {
557                         d_printf("failure enlarging do_list_queue to %d bytes\n",
558                                  (int)do_list_queue_size);
559                         reset_do_list_queue();
560                 } else {
561                         do_list_queue = dlq;
562                         memset(do_list_queue + do_list_queue_size / 2,
563                                    0, do_list_queue_size / 2);
564                 }
565         }
566         if (do_list_queue) {
567                 safe_strcpy_base(do_list_queue + do_list_queue_end, 
568                                  entry, do_list_queue, do_list_queue_size);
569                 do_list_queue_end = new_end;
570                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
571                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
572         }
573 }
574
575 static char *do_list_queue_head(void)
576 {
577         return do_list_queue + do_list_queue_start;
578 }
579
580 static void remove_do_list_queue_head(void)
581 {
582         if (do_list_queue_end > do_list_queue_start) {
583                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
584                 adjust_do_list_queue();
585                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
586                          (int)do_list_queue_start, (int)do_list_queue_end));
587         }
588 }
589
590 static int do_list_queue_empty(void)
591 {
592         return (! (do_list_queue && *do_list_queue));
593 }
594
595 /****************************************************************************
596  A helper for tool_list.
597 ****************************************************************************/
598
599 static void tool_list_helper(const char *mntpoint, struct stat *f, const char *mask, void *state)
600 {
601         /*if (f is a directory)
602         {
603                 if (we want to do directories and we want to do this f)
604                 {
605                         execute the callback on f
606                 }
607                 if (recursion is set and f isn't . and it isn't ..)
608                 {
609                         make sure the name is valid
610                         construct a full path out of the name
611                         add the full path to the list
612                 }
613                 return;
614         }
615         if (we want to do this f)
616         {
617                 execute the callback on f
618         }*/
619 }
620
621 /****************************************************************************
622  A cli_list-like function that executes fn on each directory entry.
623  fn operates on the returned entry name and struct stat.
624 ****************************************************************************/
625
626 int tool_list(  char *mask,
627                                 mode_t mode,
628                                 void (*fn)(char *, struct stat *),
629                                 BOOL rec,
630                                 BOOL dirs)
631 {
632         int dh;
633         pstring dentname;
634         pstring res;
635         struct stat stat;
636         struct smbc_dirent* dent;
637         
638         pstrcpy(res, "smb:");
639         pstrcat(res, service);
640         pstrcat(res, cur_dir);
641         
642         if ((dh = smbc_opendir(res)) < 1)
643         {
644                 d_printf("Error: %s opening %s\n", strerror(errno), res);
645                 return 1;
646         }
647         
648         while (dent = smbc_readdir(dh))
649         {
650                 switch(dent->smbc_type)
651                 {
652                 case SMBC_WORKGROUP:
653                 case SMBC_SERVER:
654                 case SMBC_FILE_SHARE:
655                 case SMBC_PRINTER_SHARE:
656                 case SMBC_COMMS_SHARE:
657                 case SMBC_IPC_SHARE:
658                         break;
659                 case SMBC_DIR:
660                         if (!dirs)
661                                 break;
662                 case SMBC_FILE:
663                         pstrcpy(dentname, res);
664                         pstrcat(dentname, dent->name);
665                         /*if (mask_match(dent->name, mask, False))*/
666                         if (mask_match(dentname, mask, False))
667                         {
668                                 if (smbc_stat(dentname, &stat) < 0)
669                                 {
670                                         d_printf("> %s - stat error: %s\n", dent->name, strerror(errno));
671                                 }
672                                 else
673                                 {
674                                         fn(dent->name, &stat);
675                                 }
676                         }
677                         break;
678                 case SMBC_LINK:
679                         break;
680                 }
681         }
682         smbc_closedir(dh);
683 }
684
685 /****************************************************************************
686  A helper for do_list.
687 ****************************************************************************/
688
689 static void do_list_helper(const char *mntpoint, file_info *f, const char *mask, void *state)
690 {
691         if (f->mode & aDIR) {
692                 if (do_list_dirs && do_this_one(f)) {
693                         do_list_fn(f);
694                 }
695                 if (do_list_recurse && 
696                         !strequal(f->name,".") && 
697                         !strequal(f->name,"..")) {
698                         pstring mask2;
699                         char *p;
700
701                         if (!f->name[0]) {
702                                 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
703                                 return;
704                         }
705
706                         pstrcpy(mask2, mntpoint);
707                         pstrcat(mask2, mask);
708                         p = strrchr_m(mask2,'/');
709                         if (!p)
710                                 return;
711                         p[1] = 0;
712                         pstrcat(mask2, f->name);
713                         pstrcat(mask2,"/*");
714                         add_to_do_list_queue(mask2);
715                 }
716                 return;
717         }
718
719         if (do_this_one(f)) {
720                 do_list_fn(f);
721         }
722 }
723
724 /****************************************************************************
725  A wrapper around cli_list that adds recursion.
726 ****************************************************************************/
727
728 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
729 {
730         static int in_do_list = 0;
731         struct cli_state *targetcli;
732         pstring targetpath;
733
734         if (in_do_list && rec) {
735                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
736                 exit(1);
737         }
738
739         in_do_list = 1;
740
741         do_list_recurse = rec;
742         do_list_dirs = dirs;
743         do_list_fn = fn;
744
745         if (rec) {
746                 init_do_list_queue();
747                 add_to_do_list_queue(mask);
748                 
749                 while (! do_list_queue_empty()) {
750                         /*
751                          * Need to copy head so that it doesn't become
752                          * invalid inside the call to cli_list.  This
753                          * would happen if the list were expanded
754                          * during the call.
755                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
756                          */
757                         pstring head;
758                         pstrcpy(head, do_list_queue_head());
759                         
760                         /* check for dfs */
761                         
762                         if ( !cli_resolve_path( "", cli, head, &targetcli, targetpath ) ) {
763                                 d_printf("do_list: [%s] %s\n", head, cli_errstr(cli));
764                                 remove_do_list_queue_head();
765                                 continue;
766                         }
767                         
768                         cli_list(targetcli, targetpath, attribute, do_list_helper, NULL);
769                         remove_do_list_queue_head();
770                         if ((! do_list_queue_empty()) && (fn == display_finfo)) {
771                                 char* next_file = do_list_queue_head();
772                                 char* save_ch = 0;
773                                 if ((strlen(next_file) >= 2) &&
774                                         (next_file[strlen(next_file) - 1] == '*') &&
775                                         (next_file[strlen(next_file) - 2] == '/')) {
776                                         save_ch = next_file +
777                                                 strlen(next_file) - 2;
778                                         *save_ch = '\0';
779                                 }
780                                 d_printf("\n%s\n",next_file);
781                                 if (save_ch) {
782                                         *save_ch = '/';
783                                 }
784                         }
785                 }
786         } else {
787                 /* check for dfs */
788                         
789                 if ( cli_resolve_path( "", cli, mask, &targetcli, targetpath ) ) {
790                         if (cli_list(targetcli, targetpath, attribute, do_list_helper, NULL) == -1) 
791                                 d_printf("%s listing %s\n", cli_errstr(targetcli), targetpath);
792                 }
793                 else
794                         d_printf("do_list: [%s] %s\n", mask, cli_errstr(cli));
795                 
796         }
797
798         in_do_list = 0;
799         reset_do_list_queue();
800 }
801
802 /****************************************************************************
803  Get a directory listing.
804 ****************************************************************************/
805
806 static int cmd_dir(void)
807 {
808         mode_t mode = S_IFDIR | S_IRWXU | S_IRWXG | S_IRWXO;
809         pstring mask;
810         pstring buf;
811         char *p=buf;
812         
813         pstrcpy(mask, "smb:");
814         pstrcat(mask, service);
815         pstrcat(mask, cur_dir);
816         
817         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
818                 pstrcat(mask,buf);
819         else
820                 pstrcat(mask,"*");
821         
822         tool_list(mask, mode, display_stat, recurse, True);
823         return 0;
824 }
825
826 /****************************************************************************
827  Get a directory listing.
828 ****************************************************************************/
829
830 static int cmd_du(void)
831 {
832         uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
833         pstring mask;
834         pstring buf;
835         char *p=buf;
836         int rc;
837         
838         dir_total = 0;
839         pstrcpy(mask,cur_dir);
840         if(mask[strlen(mask)-1]!='/')
841                 pstrcat(mask,"/");
842         
843         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
844                 dos_format(p);
845                 if (*p == '/')
846                         pstrcpy(mask,p);
847                 else
848                         pstrcat(mask,p);
849         } else {
850                 pstrcat(mask,"*");
851         }
852
853         do_list(mask, attribute, do_du, recurse, True);
854
855         rc = do_dskattr();
856
857         d_printf("Total number of bytes: %.0f\n", dir_total);
858
859         return rc;
860 }
861
862 /****************************************************************************
863  Get a file from rname to lname
864 ****************************************************************************/
865
866 static int do_get(char *rname, char *lname, BOOL reget)
867 {  
868         int handle = 0, fnum;
869         BOOL newhandle = False;
870         char *data;
871         struct timeval tp_start;
872         int read_size = io_bufsize;
873         /*uint16 attr;*/
874         struct stat stat;
875         off_t start = 0;
876         off_t nread = 0;
877         int rc = 0;
878
879         if (lowercase) {
880                 strlower_m(lname);
881         }
882
883         GetTimeOfDay(&tp_start);
884         
885         fnum = smbc_open(rname, O_RDONLY, 0666);
886         if (fnum < 0)
887         {
888                 d_printf("%s opening remote file %s\n", strerror(errno), rname);
889                 return 1;
890         }
891
892         if(!strcmp(lname,"-")) {
893                 handle = fileno(stdout);
894         } else {
895                 if (reget) {
896                         handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
897                         if (handle >= 0) {
898                                 start = sys_lseek(handle, 0, SEEK_END);
899                                 if (start == -1) {
900                                         smbc_close(fnum);
901                                         d_printf("Error seeking local file\n");
902                                         return 1;
903                                 }
904                         }
905                 } else {
906                         handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
907                 }
908                 newhandle = True;
909         }
910         if (handle < 0) {
911                 d_printf("Error opening local file %s\n",lname);
912                 smbc_close(fnum);
913                 return 1;
914         }
915
916         if (smbc_fstat(fnum, &stat) < 0)
917         {
918                 d_printf("%s trying to stat remote file %s\n", strerror(errno), rname);
919                 if (newhandle)
920                         close(handle);
921                 smbc_close(fnum);
922                 return 1;
923         }
924
925         DEBUG(1,("getting file %s of size %.0f as %s ", 
926                  rname, (double)stat.st_size, lname));
927
928         if(!(data = (char *)SMB_MALLOC(read_size))) { 
929                 d_printf("malloc fail for size %d\n", read_size);
930                 if (newhandle)
931                         close(handle);
932                 smbc_close(fnum);
933                 return 1;
934         }
935
936         if (smbc_lseek(fnum, start, SEEK_SET) < 0)
937         {
938                 d_printf("%s trying to lseek remote file %s\n", strerror(errno), rname);
939                 if (newhandle)
940                         close(handle);
941                 smbc_close(fnum);
942                 SAFE_FREE(data);
943                 return 1;
944         }
945         while (1) {
946                 int n = smbc_read(fnum, data, read_size);
947
948                 if (n < 0)
949                 {
950                         d_printf("%s while reading remote file %s\n", strerror(errno), rname);
951                         if (newhandle)
952                                 close(handle);
953                         smbc_close(fnum);
954                         SAFE_FREE(data);
955                         return 1;
956                 }
957                 if (n == 0)
958                         break;
959  
960                 if (writefile(handle,data, n) != n) {
961                         d_printf("Error writing local file\n");
962                         rc = 1;
963                         break;
964                 }
965           
966                 nread += n;
967         }
968
969         if (nread + start < stat.st_size) {
970                 DEBUG (1, ("Short read when getting file %s. Only got %ld bytes.\n", rname, (long)nread));
971                 rc = 1;
972         }
973
974         SAFE_FREE(data);
975         
976         if (smbc_close(fnum) < 0)
977         {
978                 d_printf("%s closing remote file %s\n", strerror(errno), rname);
979                 rc = 1;
980         }
981
982         if (newhandle) {
983                 close(handle);
984         }
985
986         /*if (archive_level >= 2 && (attr & aARCH)) {
987                 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
988         }*/
989
990         {
991                 struct timeval tp_end;
992                 int this_time;
993                 
994                 GetTimeOfDay(&tp_end);
995                 this_time = 
996                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
997                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
998                 get_total_time_ms += this_time;
999                 get_total_size += nread;
1000                 
1001                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1002                          nread / (1.024*this_time + 1.0e-4),
1003                          get_total_size / (1.024*get_total_time_ms)));
1004         }
1005         
1006         return rc;
1007 }
1008
1009 /****************************************************************************
1010  Get a file.
1011 ****************************************************************************/
1012
1013 static int cmd_get(void)
1014 {
1015         pstring lname;
1016         pstring rname;
1017         char *p;
1018
1019         pstrcpy(rname, "smb:");
1020         pstrcat(rname, service);
1021         pstrcat(rname, cur_dir);
1022         
1023         p = rname + strlen(rname);
1024         
1025         if (!next_token_nr(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
1026                 d_printf("get <filename>\n");
1027                 return 1;
1028         }
1029         pstrcpy(lname,p);
1030         
1031         next_token_nr(NULL,lname,NULL,sizeof(lname));
1032         /*d_printf("lname: %s, rname: %s\n", lname, rname);*/
1033         return do_get(rname, lname, False);
1034 }
1035
1036 /****************************************************************************
1037  Do an mget operation on one file.
1038 ****************************************************************************/
1039
1040 static void do_mget(char *name, struct stat *st)
1041 {
1042         pstring rname;
1043         pstring quest;
1044         pstring saved_curdir;
1045         pstring mget_mask;
1046         mode_t mode;
1047
1048         if (strequal(name,".") || strequal(name,".."))
1049                 return;
1050
1051         if (S_ISDIR(st->st_mode))
1052                 slprintf(quest,sizeof(pstring)-1, "Get directory %s%s? ", cur_dir, name);
1053         else
1054                 slprintf(quest,sizeof(pstring)-1, "Get file %s%s? ", cur_dir, name);
1055
1056         if (prompt && !yesno(quest))
1057                 return;
1058
1059         if (!S_ISDIR(st->st_mode)) {
1060                 pstrcpy(rname,"smb:");
1061                 pstrcat(rname,service);
1062                 pstrcat(rname,cur_dir);
1063                 pstrcat(rname,name);
1064                 do_get(rname,name, False);
1065                 return;
1066         }
1067
1068         /* handle directories */
1069         /* TODO: clean this code up for recursive calls */
1070         pstrcpy(saved_curdir,cur_dir);
1071
1072         pstrcat(cur_dir,name);
1073         pstrcat(cur_dir,"/");
1074
1075         unix_format(name);
1076         if (lowercase)
1077                 strlower_m(name);
1078         
1079         if (!directory_exist(name,NULL) && 
1080                 mkdir(name,0777) != 0) {
1081                 d_printf("failed to create directory %s\n",name);
1082                 pstrcpy(cur_dir,saved_curdir);
1083                 return;
1084         }
1085         
1086         if (chdir(name) != 0) {
1087                 d_printf("failed to chdir to directory %s\n",name);
1088                 pstrcpy(cur_dir,saved_curdir);
1089                 return;
1090         }
1091
1092         pstrcpy(mget_mask,"smb:");
1093         pstrcat(mget_mask,service);
1094         pstrcat(mget_mask,cur_dir);
1095         pstrcat(mget_mask,"*");
1096         
1097         /*d_printf("Calling with mask: %s\n", mget_mask);*/
1098         tool_list(mget_mask, mode, do_mget, recurse, recurse);
1099         chdir("..");
1100         pstrcpy(cur_dir,saved_curdir);
1101 }
1102
1103 /****************************************************************************
1104  View the file using the pager.
1105 ****************************************************************************/
1106
1107 static int cmd_more(void)
1108 {
1109         pstring rname,lname,pager_cmd;
1110         char *pager;
1111         int fd;
1112         int rc = 0;
1113
1114         pstrcpy(rname,cur_dir);
1115         pstrcat(rname,"/");
1116         
1117         slprintf(lname,sizeof(lname)-1, "%s/smbmore.XXXXXX",tmpdir());
1118         fd = smb_mkstemp(lname);
1119         if (fd == -1) {
1120                 d_printf("failed to create temporary file for more\n");
1121                 return 1;
1122         }
1123         close(fd);
1124
1125         if (!next_token_nr(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
1126                 d_printf("more <filename>\n");
1127                 unlink(lname);
1128                 return 1;
1129         }
1130         dos_clean_name(rname);
1131
1132         rc = do_get(rname, lname, False);
1133
1134         pager=getenv("PAGER");
1135
1136         slprintf(pager_cmd,sizeof(pager_cmd)-1,
1137                  "%s %s",(pager? pager:PAGER), lname);
1138         system(pager_cmd);
1139         unlink(lname);
1140         
1141         return rc;
1142 }
1143
1144 /****************************************************************************
1145  Do a mget command.
1146 ****************************************************************************/
1147
1148 static int cmd_mget(void)
1149 {
1150         mode_t mode;
1151         pstring mget_mask;
1152         pstring buf;
1153         char *p=buf;
1154
1155         *mget_mask = 0;
1156
1157         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1158                 pstrcpy(mget_mask, "smb:");
1159                 pstrcat(mget_mask, service);
1160                 pstrcat(mget_mask,cur_dir);
1161                 if(mget_mask[strlen(mget_mask)-1]!='/')
1162                         pstrcat(mget_mask,"/");
1163                 
1164                 if (*p == '/')
1165                 {
1166                         pstrcpy(mget_mask, "smb:");
1167                         pstrcat(mget_mask, service);
1168                         pstrcat(mget_mask,p);
1169                 }
1170                 else
1171                         pstrcat(mget_mask,p);
1172                 /* TODO: enable directories on calls to tool_list
1173                    once recursion is worked out */
1174                 tool_list(mget_mask, mode, do_mget, recurse, recurse);
1175         }
1176
1177         if (!*mget_mask) {
1178                 pstrcpy(mget_mask, "smb:");
1179                 pstrcat(mget_mask, service);
1180                 pstrcat(mget_mask,cur_dir);
1181                 if(mget_mask[strlen(mget_mask)-1]!='/')
1182                         pstrcat(mget_mask,"/");
1183                 pstrcat(mget_mask,"*");
1184                 tool_list(mget_mask, mode, do_mget, recurse, recurse);
1185         }
1186         
1187         return 0;
1188 }
1189
1190 /****************************************************************************
1191  Make a directory of name "name".
1192 ****************************************************************************/
1193
1194 static BOOL do_mkdir(char *name)
1195 {
1196         if (smbc_mkdir(name, 755) < 0)
1197         {
1198                 d_printf("Error: %s making remote directory %s\n", strerror(errno), name);
1199                 return False;
1200         }
1201         
1202         return True;
1203 }
1204
1205 /****************************************************************************
1206  Show 8.3 name of a file.
1207 ****************************************************************************/
1208
1209 static BOOL do_altname(char *name)
1210 {
1211         pstring altname;
1212         if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
1213                 d_printf("%s getting alt name for %s\n",
1214                          cli_errstr(cli),name);
1215                 return(False);
1216         }
1217         d_printf("%s\n", altname);
1218
1219         return(True);
1220 }
1221
1222 /****************************************************************************
1223  Exit client.
1224 ****************************************************************************/
1225
1226 static int cmd_quit(void)
1227 {
1228         cli_cm_shutdown();
1229         exit(0);
1230         /* NOTREACHED */
1231         return 0;
1232 }
1233
1234 /****************************************************************************
1235  Make a directory.
1236 ****************************************************************************/
1237
1238 static int cmd_mkdir(void)
1239 {
1240         int dh;
1241         pstring mask;
1242         pstring buf;
1243         pstring targetname;
1244         char *p=buf;
1245   
1246         pstrcpy(mask,cur_dir);
1247
1248         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1249                 if (!recurse)
1250                         d_printf("mkdir <dirname>\n");
1251                 return 1;
1252         }
1253         pstrcat(mask,p);
1254         
1255         if (recurse) {
1256                 pstring ddir;
1257                 pstring ddir2;
1258                 *ddir2 = 0;
1259                 
1260                 pstrcpy(ddir,mask);
1261                 trim_char(ddir,'.','\0');
1262                 p = strtok(ddir,"/\\");
1263                 while (p) {
1264                         pstrcat(ddir2,p);
1265                         
1266                         pstrcpy(targetname, "smb:");
1267                         pstrcat(targetname, service);
1268                         pstrcat(targetname, "/");
1269                         pstrcat(targetname, ddir2);
1270                         DEBUG(3, ("Recursively making directory %s\n", targetname));
1271                         if ((dh = smbc_opendir(targetname)) < 0) {
1272                                 if (!do_mkdir(targetname))
1273                                         return 1;
1274                         }
1275                         else
1276                                 smbc_closedir(dh);
1277                         
1278                         pstrcat(ddir2,"/");
1279                         p = strtok(NULL,"/\\");
1280                 }
1281         }
1282         else {
1283                 pstrcpy(targetname, "smb:");
1284                 pstrcat(targetname, service);
1285                 pstrcat(targetname, mask);
1286                 
1287                 if (!do_mkdir(targetname))
1288                         return 1;
1289         }
1290         
1291         return 0;
1292 }
1293
1294 /****************************************************************************
1295  Show alt name.
1296 ****************************************************************************/
1297
1298 static int cmd_altname(void)
1299 {
1300         pstring name;
1301         pstring buf;
1302         char *p=buf;
1303   
1304         pstrcpy(name,cur_dir);
1305
1306         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1307                 d_printf("altname <file>\n");
1308                 return 1;
1309         }
1310         pstrcat(name,p);
1311
1312         do_altname(name);
1313
1314         return 0;
1315 }
1316
1317 /****************************************************************************
1318  Put a single file.
1319 ****************************************************************************/
1320
1321 static int do_put(char *rname, char *lname, BOOL reput)
1322 {
1323         int fnum;
1324         XFILE *f;
1325         SMB_OFF_T start = 0;
1326         off_t nread = 0;
1327         char *buf = NULL;
1328         int maxwrite = io_bufsize;
1329         int rc = 0;
1330         struct timeval tp_start;
1331         struct stat stat;
1332         
1333         GetTimeOfDay(&tp_start);
1334
1335         if (reput) {
1336                 fnum = smbc_open(rname, O_RDWR|O_CREAT, 0644);
1337                 if (fnum < 0)
1338                 {
1339                         d_printf("%s opening remote file %s\n", strerror(errno), rname);
1340                         return 1;
1341                 }
1342                 if (smbc_fstat(fnum, &stat) < 0)
1343                 {
1344                         d_printf("%s trying to stat remote file %s\n", strerror(errno), rname);
1345                         smbc_close(fnum);
1346                         return 1;
1347                 }
1348                 start = stat.st_size;
1349         } else {
1350                 fnum = smbc_creat(rname, 0644);
1351                 if (fnum < 0)
1352                 {
1353                         d_printf("%s trying to create remote file %s\n", strerror(errno), rname);
1354                         return 1;
1355                 }
1356         }
1357
1358         /* allow files to be piped into smbclient
1359            jdblair 24.jun.98
1360
1361            Note that in this case this function will exit(0) rather
1362            than returning. */
1363         if (!strcmp(lname, "-")) {
1364                 f = x_stdin;
1365                 /* size of file is not known */
1366         } else {
1367                 f = x_fopen(lname,O_RDONLY, 0);
1368                 if (f && reput) {
1369                         if (x_tseek(f, start, SEEK_SET) == -1) {
1370                                 d_printf("Error seeking local file\n");
1371                                 smbc_close(fnum);
1372                                 x_fclose(f);
1373                                 return 1;
1374                         }
1375                 }
1376         }
1377
1378         if (!f) {
1379                 d_printf("Error opening local file %s\n",lname);
1380                 smbc_close(fnum);
1381                 return 1;
1382         }
1383   
1384         DEBUG(1,("putting file %s as %s ",lname,rname));
1385   
1386         buf = (char *)SMB_MALLOC(maxwrite);
1387         if (!buf) {
1388                 d_printf("ERROR: Not enough memory!\n");
1389                 smbc_close(fnum);
1390                 if (f != x_stdin)
1391                         x_fclose(f);
1392                 return 1;
1393         }
1394         
1395         if (smbc_lseek(fnum, start, SEEK_SET) < 0)
1396         {
1397                 d_printf("%s trying to lseek remote file %s\n", strerror(errno), rname);
1398                 if (f != x_stdin)
1399                         x_fclose(f);
1400                 smbc_close(fnum);
1401                 SAFE_FREE(buf);
1402                 return 1;
1403         }
1404         while (!x_feof(f)) {
1405                 int n = maxwrite;
1406                 int ret;
1407
1408                 if ((n = readfile(buf,n,f)) < 1) {
1409                         if((n == 0) && x_feof(f))
1410                                 break; /* Empty local file. */
1411
1412                         d_printf("Error reading local file: %s\n", strerror(errno));
1413                         rc = 1;
1414                         break;
1415                 }
1416
1417                 ret = smbc_write(fnum, buf, n);
1418
1419                 if (n != ret) {
1420                         d_printf("Error writing file: %s\n", strerror(errno));
1421                         rc = 1;
1422                         break;
1423                 } 
1424
1425                 nread += n;
1426         }
1427
1428         if (smbc_close(fnum) < 0) {
1429                 d_printf("%s closing remote file %s\n",strerror(errno),rname);
1430                 if (f != x_stdin)
1431                         x_fclose(f);
1432                 SAFE_FREE(buf);
1433                 return 1;
1434         }
1435
1436         
1437         if (f != x_stdin) {
1438                 x_fclose(f);
1439         }
1440
1441         SAFE_FREE(buf);
1442
1443         {
1444                 struct timeval tp_end;
1445                 int this_time;
1446                 
1447                 GetTimeOfDay(&tp_end);
1448                 this_time = 
1449                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1450                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
1451                 put_total_time_ms += this_time;
1452                 put_total_size += nread;
1453                 
1454                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1455                          nread / (1.024*this_time + 1.0e-4),
1456                          put_total_size / (1.024*put_total_time_ms)));
1457         }
1458
1459         if (f == x_stdin) {
1460                 cli_cm_shutdown();
1461                 exit(0);
1462         }
1463         
1464         return rc;
1465 }
1466
1467 /****************************************************************************
1468  Put a file.
1469 ****************************************************************************/
1470
1471 static int cmd_put(void)
1472 {
1473         pstring lname;
1474         pstring rname;
1475         pstring buf;
1476         char *p=buf;
1477         
1478         pstrcpy(rname, "smb:");
1479         pstrcat(rname, service);
1480         pstrcat(rname, cur_dir);
1481   
1482         if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1483                 d_printf("put <filename>\n");
1484                 return 1;
1485         }
1486         pstrcpy(lname,p);
1487   
1488         if (next_token_nr(NULL,p,NULL,sizeof(buf)))
1489                 pstrcat(rname,p);          
1490         else
1491                 pstrcat(rname,lname);
1492         
1493         {
1494                 SMB_STRUCT_STAT st;
1495                 /* allow '-' to represent stdin
1496                    jdblair, 24.jun.98 */
1497                 if (!file_exist(lname,&st) &&
1498                         (strcmp(lname,"-"))) {
1499                         d_printf("%s does not exist\n",lname);
1500                         return 1;
1501                 }
1502         }
1503
1504         /*d_printf("lname: %s, rname: %s\n", lname, rname);*/
1505         return do_put(rname, lname, False);
1506 }
1507
1508 /*************************************
1509  File list structure.
1510 *************************************/
1511
1512 static struct file_list {
1513         struct file_list *prev, *next;
1514         char *file_path;
1515         BOOL isdir;
1516 } *file_list;
1517
1518 /****************************************************************************
1519  Free a file_list structure.
1520 ****************************************************************************/
1521
1522 static void free_file_list (struct file_list * list)
1523 {
1524         struct file_list *tmp;
1525         
1526         while (list) {
1527                 tmp = list;
1528                 DLIST_REMOVE(list, list);
1529                 SAFE_FREE(tmp->file_path);
1530                 SAFE_FREE(tmp);
1531         }
1532 }
1533
1534 /****************************************************************************
1535  Seek in a directory/file list until you get something that doesn't start with
1536  the specified name.
1537 ****************************************************************************/
1538
1539 static BOOL seek_list(struct file_list *list, char *name)
1540 {
1541         while (list) {
1542                 trim_string(list->file_path,"./","\n");
1543                 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1544                         return(True);
1545                 }
1546                 list = list->next;
1547         }
1548           
1549         return(False);
1550 }
1551
1552 /****************************************************************************
1553  Set the file selection mask.
1554 ****************************************************************************/
1555
1556 static int cmd_select(void)
1557 {
1558         pstrcpy(fileselection,"");
1559         next_token_nr(NULL,fileselection,NULL,sizeof(fileselection));
1560
1561         return 0;
1562 }
1563
1564 /****************************************************************************
1565   Recursive file matching function act as find
1566   match must be always set to True when calling this function
1567 ****************************************************************************/
1568
1569 static int file_find(struct file_list **list, const char *directory, 
1570                           const char *expression, BOOL match)
1571 {
1572         DIR *dir;
1573         struct file_list *entry;
1574                 struct stat statbuf;
1575                 int ret;
1576                 char *path;
1577         BOOL isdir;
1578         const char *dname;
1579
1580                 dir = opendir(directory);
1581         if (!dir)
1582                 return -1;
1583         
1584                 while ((dname = readdirname(dir))) {
1585                 if (!strcmp("..", dname))
1586                         continue;
1587                 if (!strcmp(".", dname))
1588                         continue;
1589                 
1590                 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1591                         continue;
1592                 }
1593
1594                 isdir = False;
1595                 if (!match || !gen_fnmatch(expression, dname)) {
1596                         if (recurse) {
1597                                 ret = stat(path, &statbuf);
1598                                 if (ret == 0) {
1599                                         if (S_ISDIR(statbuf.st_mode)) {
1600                                                 isdir = True;
1601                                                 ret = file_find(list, path, expression, False);
1602                                         }
1603                                 } else {
1604                                         d_printf("file_find: cannot stat file %s\n", path);
1605                                 }
1606                                 
1607                                 if (ret == -1) {
1608                                         SAFE_FREE(path);
1609                                         closedir(dir);
1610                                         return -1;
1611                                 }
1612                         }
1613                         entry = SMB_MALLOC_P(struct file_list);
1614                         if (!entry) {
1615                                 d_printf("Out of memory in file_find\n");
1616                                 closedir(dir);
1617                                 return -1;
1618                         }
1619                         entry->file_path = path;
1620                         entry->isdir = isdir;
1621                                                 DLIST_ADD(*list, entry);
1622                 } else {
1623                         SAFE_FREE(path);
1624                 }
1625                 }
1626
1627         closedir(dir);
1628         return 0;
1629 }
1630
1631 /****************************************************************************
1632  mput some files.
1633 ****************************************************************************/
1634
1635 static int cmd_mput(void)
1636 {
1637         pstring buf;
1638         char *p=buf;
1639         
1640         while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1641                 int ret;
1642                 struct file_list *temp_list;
1643                 char *quest, *lname, *rname;
1644         
1645                 file_list = NULL;
1646
1647                 ret = file_find(&file_list, ".", p, True);
1648                 if (ret) {
1649                         free_file_list(file_list);
1650                         continue;
1651                 }
1652                 
1653                 quest = NULL;
1654                 lname = NULL;
1655                 rname = NULL;
1656                                 
1657                 for (temp_list = file_list; temp_list; 
1658                          temp_list = temp_list->next) {
1659
1660                         SAFE_FREE(lname);
1661                         if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1662                                 continue;
1663                         trim_string(lname, "./", "/");
1664                         
1665                         /* check if it's a directory */
1666                         if (temp_list->isdir) {
1667                                 /* if (!recurse) continue; */
1668                                 
1669                                 SAFE_FREE(quest);
1670                                 if (asprintf(&quest, "Put directory %s? ", lname) < 0) break;
1671                                 if (prompt && !yesno(quest)) { /* No */
1672                                         /* Skip the directory */
1673                                         lname[strlen(lname)-1] = '/';
1674                                         if (!seek_list(temp_list, lname))
1675                                                 break;                  
1676                                 } else { /* Yes */
1677                                         SAFE_FREE(rname);
1678                                         if(asprintf(&rname, "smb:%s%s%s", service, cur_dir, lname) < 0) break;
1679                                         /*dos_format(rname);*/
1680                                         
1681                                         /* test if the directory exists by opening it */
1682                                         /*if (!((dh=smbc_opendir(rname)) < 0)) {
1683                                                 smbc_closedir(dh);
1684                                                 continue;
1685                                         }*/
1686                                         /* test if the directory exists by making it */
1687                                         ret = smbc_mkdir(rname, 755);
1688                                         if ((ret != 0) && (errno != EEXIST))
1689                                         {
1690                                                 d_printf("Error: %s. Unable to open or create dir %s, skipping...\n", strerror(errno), rname);
1691                                                 /* Skip the directory */
1692                                                 lname[strlen(lname)-1] = '/';
1693                                                 if (!seek_list(temp_list, lname))
1694                                                         break;
1695                                         }
1696                                 }
1697                                 continue;
1698                         } else {
1699                                 SAFE_FREE(quest);
1700                                 if (asprintf(&quest,"Put file %s? ", lname) < 0) break;
1701                                 if (prompt && !yesno(quest)) /* No */
1702                                         continue;
1703                                 
1704                                 /* Yes */
1705                                 SAFE_FREE(rname);
1706                                 if (asprintf(&rname, "smb:%s%s%s", service, cur_dir, lname) < 0) break;
1707                         }
1708
1709                         /*d_printf("PUT: rname: %s, lname: %s\n", rname, lname);*/
1710                         do_put(rname, lname, False);
1711                 }
1712                 free_file_list(file_list);
1713                 SAFE_FREE(quest);
1714                 SAFE_FREE(lname);
1715                 SAFE_FREE(rname);
1716         }
1717
1718         return 0;
1719 }
1720
1721 /****************************************************************************
1722  Cancel a print job.
1723 ****************************************************************************/
1724
1725 static int do_cancel(int job)
1726 {
1727         if (cli_printjob_del(cli, job)) {
1728                 d_printf("Job %d cancelled\n",job);
1729                 return 0;
1730         } else {
1731                 d_printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1732                 return 1;
1733         }
1734 }
1735
1736 /****************************************************************************
1737  Cancel a print job.
1738 ****************************************************************************/
1739
1740 static int cmd_cancel(void)
1741 {
1742         pstring buf;
1743         int job; 
1744
1745         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1746                 d_printf("cancel <jobid> ...\n");
1747                 return 1;
1748         }
1749         do {
1750                 job = atoi(buf);
1751                 do_cancel(job);
1752         } while (next_token_nr(NULL,buf,NULL,sizeof(buf)));
1753         
1754         return 0;
1755 }
1756
1757 /****************************************************************************
1758  Print a file.
1759 ****************************************************************************/
1760
1761 static int cmd_print(void)
1762 {
1763         pstring lname;
1764         pstring rname;
1765         char *p;
1766
1767         if (!next_token_nr(NULL,lname,NULL, sizeof(lname))) {
1768                 d_printf("print <filename>\n");
1769                 return 1;
1770         }
1771
1772         pstrcpy(rname,lname);
1773         p = strrchr_m(rname,'/');
1774         if (p) {
1775                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)sys_getpid());
1776         }
1777
1778         if (strequal(lname,"-")) {
1779                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)sys_getpid());
1780         }
1781
1782         return do_put(rname, lname, False);
1783 }
1784
1785 /****************************************************************************
1786  Show a print queue entry.
1787 ****************************************************************************/
1788
1789 static void queue_fn(struct print_job_info *p)
1790 {
1791         d_printf("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name);
1792 }
1793
1794 /****************************************************************************
1795  Show a print queue.
1796 ****************************************************************************/
1797
1798 static int cmd_queue(void)
1799 {
1800         cli_print_queue(cli, queue_fn);
1801         
1802         return 0;
1803 }
1804
1805 /****************************************************************************
1806  Delete some files.
1807 ****************************************************************************/
1808
1809 static void do_del(file_info *finfo)
1810 {
1811         pstring mask;
1812
1813         pstrcpy(mask,cur_dir);
1814         pstrcat(mask,finfo->name);
1815
1816         if (finfo->mode & aDIR) 
1817                 return;
1818
1819         if (!cli_unlink(cli, mask)) {
1820                 d_printf("%s deleting remote file %s\n",cli_errstr(cli),mask);
1821         }
1822 }
1823
1824 /****************************************************************************
1825  Delete some files.
1826 ****************************************************************************/
1827
1828 static int cmd_del(void)
1829 {
1830         pstring mask;
1831         pstring buf;
1832         uint16 attribute = aSYSTEM | aHIDDEN;
1833
1834         if (recurse)
1835                 attribute |= aDIR;
1836         
1837         pstrcpy(mask,cur_dir);
1838         
1839         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1840                 d_printf("del <filename>\n");
1841                 return 1;
1842         }
1843         pstrcat(mask,buf);
1844
1845         do_list(mask, attribute,do_del,False,False);
1846         
1847         return 0;
1848 }
1849
1850 /****************************************************************************
1851 ****************************************************************************/
1852
1853 static int cmd_open(void)
1854 {
1855         pstring mask;
1856         pstring buf;
1857         struct cli_state *targetcli;
1858         pstring targetname;
1859         
1860         pstrcpy(mask,cur_dir);
1861         
1862         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1863                 d_printf("open <filename>\n");
1864                 return 1;
1865         }
1866         pstrcat(mask,buf);
1867
1868         if ( !cli_resolve_path( "", cli, mask, &targetcli, targetname ) ) {
1869                 d_printf("open %s: %s\n", mask, cli_errstr(cli));
1870                 return 1;
1871         }
1872         
1873         cli_nt_create(targetcli, targetname, FILE_READ_DATA);
1874
1875         return 0;
1876 }
1877
1878
1879 /****************************************************************************
1880  Remove a directory.
1881 ****************************************************************************/
1882
1883 static int cmd_rmdir(void)
1884 {
1885         pstring mask;
1886         pstring buf;
1887         struct cli_state *targetcli;
1888         pstring targetname;
1889         
1890         pstrcpy(mask, "smb:");
1891         pstrcat(mask, service);
1892         pstrcat(mask,cur_dir);
1893         
1894         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1895                 d_printf("rmdir <dirname>\n");
1896                 return 1;
1897         }
1898         pstrcat(mask,buf);
1899
1900         /*if ( !cli_resolve_path( "", cli, mask, &targetcli, targetname ) ) {
1901                 d_printf("rmdir %s: %s\n", mask, cli_errstr(cli));
1902                 return 1;
1903         }
1904         
1905         if (!cli_rmdir(targetcli, targetname)) {
1906                 d_printf("%s removing remote directory file %s\n",
1907                          cli_errstr(targetcli),mask);
1908         }*/
1909         
1910         if (smbc_rmdir(mask) < 0)
1911                 d_printf("Error: %s removing remote directory file %s\n", strerror(errno), mask);
1912         
1913         return 0;
1914 }
1915
1916 /****************************************************************************
1917  UNIX hardlink.
1918 ****************************************************************************/
1919
1920 static int cmd_link(void)
1921 {
1922         pstring oldname,newname;
1923         pstring buf,buf2;
1924         struct cli_state *targetcli;
1925         pstring targetname;
1926   
1927         pstrcpy(oldname,cur_dir);
1928         pstrcpy(newname,cur_dir);
1929   
1930         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1931                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1932                 d_printf("link <oldname> <newname>\n");
1933                 return 1;
1934         }
1935
1936         pstrcat(oldname,buf);
1937         pstrcat(newname,buf2);
1938
1939         if ( !cli_resolve_path( "", cli, oldname, &targetcli, targetname ) ) {
1940                 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
1941                 return 1;
1942         }
1943         
1944         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
1945                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1946                 return 1;
1947         }
1948         
1949         if (!cli_unix_hardlink(targetcli, targetname, newname)) {
1950                 d_printf("%s linking files (%s -> %s)\n", cli_errstr(targetcli), newname, oldname);
1951                 return 1;
1952         }  
1953
1954         return 0;
1955 }
1956
1957 /****************************************************************************
1958  UNIX symlink.
1959 ****************************************************************************/
1960
1961 static int cmd_symlink(void)
1962 {
1963         pstring oldname,newname;
1964         pstring buf,buf2;
1965   
1966         if (!SERVER_HAS_UNIX_CIFS(cli)) {
1967                 d_printf("Server doesn't support UNIX CIFS calls.\n");
1968                 return 1;
1969         }
1970
1971         pstrcpy(newname,cur_dir);
1972         
1973         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
1974                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1975                 d_printf("symlink <oldname> <newname>\n");
1976                 return 1;
1977         }
1978
1979         pstrcpy(oldname,buf);
1980         pstrcat(newname,buf2);
1981
1982         if (!cli_unix_symlink(cli, oldname, newname)) {
1983                 d_printf("%s symlinking files (%s -> %s)\n",
1984                         cli_errstr(cli), newname, oldname);
1985                 return 1;
1986         } 
1987
1988         return 0;
1989 }
1990
1991 /****************************************************************************
1992  UNIX chmod.
1993 ****************************************************************************/
1994
1995 static int cmd_chmod(void)
1996 {
1997         pstring src;
1998         mode_t mode;
1999         pstring buf, buf2;
2000         struct cli_state *targetcli;
2001         pstring targetname;
2002   
2003         pstrcpy(src,cur_dir);
2004         
2005         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2006                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
2007                 d_printf("chmod mode file\n");
2008                 return 1;
2009         }
2010
2011         mode = (mode_t)strtol(buf, NULL, 8);
2012         pstrcat(src,buf2);
2013
2014         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2015                 d_printf("chmod %s: %s\n", src, cli_errstr(cli));
2016                 return 1;
2017         }
2018         
2019         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2020                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2021                 return 1;
2022         }
2023         
2024         if (!cli_unix_chmod(targetcli, targetname, mode)) {
2025                 d_printf("%s chmod file %s 0%o\n",
2026                         cli_errstr(targetcli), src, (unsigned int)mode);
2027                 return 1;
2028         } 
2029
2030         return 0;
2031 }
2032
2033 static const char *filetype_to_str(mode_t mode)
2034 {
2035         if (S_ISREG(mode)) {
2036                 return "regular file";
2037         } else if (S_ISDIR(mode)) {
2038                 return "directory";
2039         } else 
2040 #ifdef S_ISCHR
2041         if (S_ISCHR(mode)) {
2042                 return "character device";
2043         } else
2044 #endif
2045 #ifdef S_ISBLK
2046         if (S_ISBLK(mode)) {
2047                 return "block device";
2048         } else
2049 #endif
2050 #ifdef S_ISFIFO
2051         if (S_ISFIFO(mode)) {
2052                 return "fifo";
2053         } else
2054 #endif
2055 #ifdef S_ISLNK
2056         if (S_ISLNK(mode)) {
2057                 return "symbolic link";
2058         } else
2059 #endif
2060 #ifdef S_ISSOCK
2061         if (S_ISSOCK(mode)) {
2062                 return "socket";
2063         } else
2064 #endif
2065         return "";
2066 }
2067
2068 static char rwx_to_str(mode_t m, mode_t bt, char ret)
2069 {
2070         if (m & bt) {
2071                 return ret;
2072         } else {
2073                 return '-';
2074         }
2075 }
2076
2077 static char *unix_mode_to_str(char *s, mode_t m)
2078 {
2079         char *p = s;
2080         const char *str = filetype_to_str(m);
2081
2082         switch(str[0]) {
2083                 case 'd':
2084                         *p++ = 'd';
2085                         break;
2086                 case 'c':
2087                         *p++ = 'c';
2088                         break;
2089                 case 'b':
2090                         *p++ = 'b';
2091                         break;
2092                 case 'f':
2093                         *p++ = 'p';
2094                         break;
2095                 case 's':
2096                         *p++ = str[1] == 'y' ? 'l' : 's';
2097                         break;
2098                 case 'r':
2099                 default:
2100                         *p++ = '-';
2101                         break;
2102         }
2103         *p++ = rwx_to_str(m, S_IRUSR, 'r');
2104         *p++ = rwx_to_str(m, S_IWUSR, 'w');
2105         *p++ = rwx_to_str(m, S_IXUSR, 'x');
2106         *p++ = rwx_to_str(m, S_IRGRP, 'r');
2107         *p++ = rwx_to_str(m, S_IWGRP, 'w');
2108         *p++ = rwx_to_str(m, S_IXGRP, 'x');
2109         *p++ = rwx_to_str(m, S_IROTH, 'r');
2110         *p++ = rwx_to_str(m, S_IWOTH, 'w');
2111         *p++ = rwx_to_str(m, S_IXOTH, 'x');
2112         *p++ = '\0';
2113         return s;
2114 }
2115
2116 /****************************************************************************
2117  Utility function for UNIX getfacl.
2118 ****************************************************************************/
2119
2120 static char *perms_to_string(fstring permstr, unsigned char perms)
2121 {
2122         fstrcpy(permstr, "---");
2123         if (perms & SMB_POSIX_ACL_READ) {
2124                 permstr[0] = 'r';
2125         }
2126         if (perms & SMB_POSIX_ACL_WRITE) {
2127                 permstr[1] = 'w';
2128         }
2129         if (perms & SMB_POSIX_ACL_EXECUTE) {
2130                 permstr[2] = 'x';
2131         }
2132         return permstr;
2133 }
2134
2135 /****************************************************************************
2136  UNIX getfacl.
2137 ****************************************************************************/
2138
2139 static int cmd_getfacl(void)
2140 {
2141         pstring src, name;
2142         uint16 major, minor;
2143         uint32 caplow, caphigh;
2144         char *retbuf = NULL;
2145         size_t rb_size = 0;
2146         SMB_STRUCT_STAT sbuf;
2147         uint16 num_file_acls = 0;
2148         uint16 num_dir_acls = 0;
2149         uint16 i;
2150         struct cli_state *targetcli;
2151         pstring targetname;
2152  
2153         pstrcpy(src,cur_dir);
2154         
2155         if (!next_token_nr(NULL,name,NULL,sizeof(name))) {
2156                 d_printf("stat file\n");
2157                 return 1;
2158         }
2159
2160         pstrcat(src,name);
2161         
2162         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2163                 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2164                 return 1;
2165         }
2166         
2167         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2168                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2169                 return 1;
2170         }
2171         
2172         if (!cli_unix_extensions_version(targetcli, &major, &minor, &caplow, &caphigh)) {
2173                 d_printf("Can't get UNIX CIFS version from server.\n");
2174                 return 1;
2175         }
2176
2177         if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
2178                 d_printf("This server supports UNIX extensions but doesn't support POSIX ACLs.\n");
2179                 return 1;
2180         }
2181
2182
2183         if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2184                 d_printf("%s getfacl doing a stat on file %s\n",
2185                         cli_errstr(targetcli), src);
2186                 return 1;
2187         } 
2188
2189         if (!cli_unix_getfacl(targetcli, targetname, &rb_size, &retbuf)) {
2190                 d_printf("%s getfacl file %s\n",
2191                         cli_errstr(targetcli), src);
2192                 return 1;
2193         } 
2194
2195         /* ToDo : Print out the ACL values. */
2196         if (SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION || rb_size < 6) {
2197                 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
2198                         src, (unsigned int)CVAL(retbuf,0) );
2199                 SAFE_FREE(retbuf);
2200                 return 1;
2201         }
2202
2203         num_file_acls = SVAL(retbuf,2);
2204         num_dir_acls = SVAL(retbuf,4);
2205         if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
2206                 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
2207                         src,
2208                         (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
2209                         (unsigned int)rb_size);
2210
2211                 SAFE_FREE(retbuf);
2212                 return 1;
2213         }
2214
2215         d_printf("# file: %s\n", src);
2216         d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_uid, (unsigned int)sbuf.st_gid);
2217
2218         if (num_file_acls == 0 && num_dir_acls == 0) {
2219                 d_printf("No acls found.\n");
2220         }
2221
2222         for (i = 0; i < num_file_acls; i++) {
2223                 uint32 uorg;
2224                 fstring permstring;
2225                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
2226                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2227
2228                 switch(tagtype) {
2229                         case SMB_POSIX_ACL_USER_OBJ:
2230                                 d_printf("user::");
2231                                 break;
2232                         case SMB_POSIX_ACL_USER:
2233                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2234                                 d_printf("user:%u:", uorg);
2235                                 break;
2236                         case SMB_POSIX_ACL_GROUP_OBJ:
2237                                 d_printf("group::");
2238                                 break;
2239                         case SMB_POSIX_ACL_GROUP:
2240                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2241                                 d_printf("group:%u", uorg);
2242                                 break;
2243                         case SMB_POSIX_ACL_MASK:
2244                                 d_printf("mask::");
2245                                 break;
2246                         case SMB_POSIX_ACL_OTHER:
2247                                 d_printf("other::");
2248                                 break;
2249                         default:
2250                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2251                                         src, (unsigned int)tagtype );
2252                                 SAFE_FREE(retbuf);
2253                                 return 1;
2254                 }
2255
2256                 d_printf("%s\n", perms_to_string(permstring, perms));
2257         }
2258
2259         for (i = 0; i < num_dir_acls; i++) {
2260                 uint32 uorg;
2261                 fstring permstring;
2262                 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
2263                 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2264
2265                 switch(tagtype) {
2266                         case SMB_POSIX_ACL_USER_OBJ:
2267                                 d_printf("default:user::");
2268                                 break;
2269                         case SMB_POSIX_ACL_USER:
2270                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2271                                 d_printf("default:user:%u:", uorg);
2272                                 break;
2273                         case SMB_POSIX_ACL_GROUP_OBJ:
2274                                 d_printf("default:group::");
2275                                 break;
2276                         case SMB_POSIX_ACL_GROUP:
2277                                 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2278                                 d_printf("default:group:%u", uorg);
2279                                 break;
2280                         case SMB_POSIX_ACL_MASK:
2281                                 d_printf("default:mask::");
2282                                 break;
2283                         case SMB_POSIX_ACL_OTHER:
2284                                 d_printf("default:other::");
2285                                 break;
2286                         default:
2287                                 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2288                                         src, (unsigned int)tagtype );
2289                                 SAFE_FREE(retbuf);
2290                                 return 1;
2291                 }
2292
2293                 d_printf("%s\n", perms_to_string(permstring, perms));
2294         }
2295
2296         SAFE_FREE(retbuf);
2297         return 0;
2298 }
2299
2300 /****************************************************************************
2301  UNIX stat.
2302 ****************************************************************************/
2303
2304 static int cmd_stat(void)
2305 {
2306         pstring src, name;
2307         fstring mode_str;
2308         SMB_STRUCT_STAT sbuf;
2309         struct cli_state *targetcli;
2310         pstring targetname;
2311  
2312         if (!SERVER_HAS_UNIX_CIFS(cli)) {
2313                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2314                 return 1;
2315         }
2316
2317         pstrcpy(src,cur_dir);
2318         
2319         if (!next_token_nr(NULL,name,NULL,sizeof(name))) {
2320                 d_printf("stat file\n");
2321                 return 1;
2322         }
2323
2324         pstrcat(src,name);
2325
2326         
2327         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2328                 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2329                 return 1;
2330         }
2331         
2332         if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2333                 d_printf("%s stat file %s\n",
2334                         cli_errstr(targetcli), src);
2335                 return 1;
2336         } 
2337
2338         /* Print out the stat values. */
2339         d_printf("File: %s\n", src);
2340         d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
2341                 (double)sbuf.st_size,
2342                 (unsigned int)sbuf.st_blocks,
2343                 filetype_to_str(sbuf.st_mode));
2344
2345 #if defined(S_ISCHR) && defined(S_ISBLK)
2346         if (S_ISCHR(sbuf.st_mode) || S_ISBLK(sbuf.st_mode)) {
2347                 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
2348                         (double)sbuf.st_ino,
2349                         (unsigned int)sbuf.st_nlink,
2350                         unix_dev_major(sbuf.st_rdev),
2351                         unix_dev_minor(sbuf.st_rdev));
2352         } else 
2353 #endif
2354                 d_printf("Inode: %.0f\tLinks: %u\n",
2355                         (double)sbuf.st_ino,
2356                         (unsigned int)sbuf.st_nlink);
2357
2358         d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
2359                 ((int)sbuf.st_mode & 0777),
2360                 unix_mode_to_str(mode_str, sbuf.st_mode),
2361                 (unsigned int)sbuf.st_uid, 
2362                 (unsigned int)sbuf.st_gid);
2363
2364         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_atime));
2365         d_printf("Access: %s\n", mode_str);
2366
2367         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_mtime));
2368         d_printf("Modify: %s\n", mode_str);
2369
2370         strftime(mode_str, sizeof(mode_str), "%F %T %z", localtime(&sbuf.st_ctime));
2371         d_printf("Change: %s\n", mode_str);
2372         
2373         return 0;
2374 }
2375
2376
2377 /****************************************************************************
2378  UNIX chown.
2379 ****************************************************************************/
2380
2381 static int cmd_chown(void)
2382 {
2383         pstring src;
2384         uid_t uid;
2385         gid_t gid;
2386         pstring buf, buf2, buf3;
2387         struct cli_state *targetcli;
2388         pstring targetname;
2389   
2390         pstrcpy(src,cur_dir);
2391         
2392         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2393                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2)) ||
2394                 !next_token_nr(NULL,buf3,NULL, sizeof(buf3))) {
2395                 d_printf("chown uid gid file\n");
2396                 return 1;
2397         }
2398
2399         uid = (uid_t)atoi(buf);
2400         gid = (gid_t)atoi(buf2);
2401         pstrcat(src,buf3);
2402
2403         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2404                 d_printf("chown %s: %s\n", src, cli_errstr(cli));
2405                 return 1;
2406         }
2407
2408
2409         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2410                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2411                 return 1;
2412         }
2413         
2414         if (!cli_unix_chown(targetcli, targetname, uid, gid)) {
2415                 d_printf("%s chown file %s uid=%d, gid=%d\n",
2416                         cli_errstr(targetcli), src, (int)uid, (int)gid);
2417                 return 1;
2418         } 
2419
2420         return 0;
2421 }
2422
2423 /****************************************************************************
2424  Rename some file.
2425 ****************************************************************************/
2426
2427 static int cmd_rename(void)
2428 {
2429         int err;
2430         pstring src, dest;
2431         pstring oname, nname;
2432   
2433         pstrcpy(src, "smb:");
2434         pstrcat(src, service);
2435         pstrcat(src, cur_dir);
2436         pstrcpy(dest, src);
2437         
2438         if (!next_token_nr(NULL,oname,NULL,sizeof(oname)) || 
2439                 !next_token_nr(NULL,nname,NULL, sizeof(nname))) {
2440                 d_printf("rename <src> <dest>\n");
2441                 return 1;
2442         }
2443
2444         pstrcat(src, oname);
2445         pstrcat(dest, nname);
2446         
2447         DEBUG(4, ("O: %s\nN: %s\n", src, dest));
2448
2449         err = smbc_rename(src, dest);
2450         if (err < 0)
2451         {
2452                 d_printf("%s renaming files\n", strerror(errno));
2453                 return 1;
2454         }
2455         
2456         return 0;
2457 }
2458
2459 /****************************************************************************
2460  Print the volume name.
2461 ****************************************************************************/
2462
2463 static int cmd_volume(void)
2464 {
2465         fstring volname;
2466         uint32 serial_num;
2467         time_t create_date;
2468   
2469         if (!cli_get_fs_volume_info(cli, volname, &serial_num, &create_date)) {
2470                 d_printf("Errr %s getting volume info\n",cli_errstr(cli));
2471                 return 1;
2472         }
2473         
2474         d_printf("Volume: |%s| serial number 0x%x\n", volname, (unsigned int)serial_num);
2475         return 0;
2476 }
2477
2478 /****************************************************************************
2479  Hard link files using the NT call.
2480 ****************************************************************************/
2481
2482 static int cmd_hardlink(void)
2483 {
2484         pstring src,dest;
2485         pstring buf,buf2;
2486         struct cli_state *targetcli;
2487         pstring targetname;
2488   
2489         pstrcpy(src,cur_dir);
2490         pstrcpy(dest,cur_dir);
2491         
2492         if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) || 
2493                 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
2494                 d_printf("hardlink <src> <dest>\n");
2495                 return 1;
2496         }
2497
2498         pstrcat(src,buf);
2499         pstrcat(dest,buf2);
2500
2501         if ( !cli_resolve_path( "", cli, src, &targetcli, targetname ) ) {
2502                 d_printf("hardlink %s: %s\n", src, cli_errstr(cli));
2503                 return 1;
2504         }
2505         
2506         if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2507                 d_printf("Server doesn't support UNIX CIFS calls.\n");
2508                 return 1;
2509         }
2510         
2511         if (!cli_nt_hardlink(targetcli, targetname, dest)) {
2512                 d_printf("%s doing an NT hard link of files\n",cli_errstr(targetcli));
2513                 return 1;
2514         }
2515         
2516         return 0;
2517 }
2518
2519 /****************************************************************************
2520  Toggle the prompt flag.
2521 ****************************************************************************/
2522
2523 static int cmd_prompt(void)
2524 {
2525         prompt = !prompt;
2526         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
2527         
2528         return 1;
2529 }
2530
2531 /****************************************************************************
2532  Set the newer than time.
2533 ****************************************************************************/
2534
2535 static int cmd_newer(void)
2536 {
2537         pstring buf;
2538         BOOL ok;
2539         SMB_STRUCT_STAT sbuf;
2540
2541         ok = next_token_nr(NULL,buf,NULL,sizeof(buf));
2542         if (ok && (sys_stat(buf,&sbuf) == 0)) {
2543                 newer_than = sbuf.st_mtime;
2544                 DEBUG(1,("Getting files newer than %s",
2545                          asctime(localtime(&newer_than))));
2546         } else {
2547                 newer_than = 0;
2548         }
2549
2550         if (ok && newer_than == 0) {
2551                 d_printf("Error setting newer-than time\n");
2552                 return 1;
2553         }
2554
2555         return 0;
2556 }
2557
2558 /****************************************************************************
2559  Set the archive level.
2560 ****************************************************************************/
2561
2562 static int cmd_archive(void)
2563 {
2564         pstring buf;
2565
2566         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2567                 archive_level = atoi(buf);
2568         } else
2569                 d_printf("Archive level is %d\n",archive_level);
2570
2571         return 0;
2572 }
2573
2574 /****************************************************************************
2575  Toggle the lowercaseflag.
2576 ****************************************************************************/
2577
2578 static int cmd_lowercase(void)
2579 {
2580         lowercase = !lowercase;
2581         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
2582
2583         return 0;
2584 }
2585
2586 /****************************************************************************
2587  Toggle the case sensitive flag.
2588 ****************************************************************************/
2589
2590 static int cmd_setcase(void)
2591 {
2592         BOOL orig_case_sensitive = cli_set_case_sensitive(cli, False);
2593
2594         cli_set_case_sensitive(cli, !orig_case_sensitive);
2595         DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
2596                 "on":"off"));
2597
2598         return 0;
2599 }
2600
2601 /****************************************************************************
2602  Toggle the recurse flag.
2603 ****************************************************************************/
2604
2605 static int cmd_recurse(void)
2606 {
2607         recurse = !recurse;
2608         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
2609
2610         return 0;
2611 }
2612
2613 /****************************************************************************
2614  Toggle the translate flag.
2615 ****************************************************************************/
2616
2617 static int cmd_translate(void)
2618 {
2619         translation = !translation;
2620         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
2621                  translation?"on":"off"));
2622
2623         return 0;
2624 }
2625
2626 /****************************************************************************
2627  Do the lcd command.
2628  ****************************************************************************/
2629
2630 static int cmd_lcd(void)
2631 {
2632         pstring buf;
2633         pstring d;
2634         
2635         if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
2636                 chdir(buf);
2637         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
2638
2639         return 0;
2640 }
2641
2642 /****************************************************************************
2643  Get a file restarting at end of local file.
2644  ****************************************************************************/
2645
2646 static int cmd_reget(void)
2647 {
2648         pstring local_name;
2649         pstring remote_name;
2650         char *p;
2651
2652         pstrcpy(remote_name, cur_dir);
2653         pstrcat(remote_name, "/");
2654         
2655         p = remote_name + strlen(remote_name);
2656         
2657         if (!next_token_nr(NULL, p, NULL, sizeof(remote_name) - strlen(remote_name))) {
2658                 d_printf("reget <filename>\n");
2659                 return 1;
2660         }
2661         pstrcpy(local_name, p);
2662         dos_clean_name(remote_name);
2663         
2664         next_token_nr(NULL, local_name, NULL, sizeof(local_name));
2665         
2666         return do_get(remote_name, local_name, True);
2667 }
2668
2669 /****************************************************************************
2670  Put a file restarting at end of local file.
2671  ****************************************************************************/
2672
2673 static int cmd_reput(void)
2674 {
2675         pstring local_name;
2676         pstring remote_name;
2677         pstring buf;
2678         char *p = buf;
2679         SMB_STRUCT_STAT st;
2680         
2681         pstrcpy(remote_name, cur_dir);
2682         pstrcat(remote_name, "/");
2683   
2684         if (!next_token_nr(NULL, p, NULL, sizeof(buf))) {
2685                 d_printf("reput <filename>\n");
2686                 return 1;
2687         }
2688         pstrcpy(local_name, p);
2689   
2690         if (!file_exist(local_name, &st)) {
2691                 d_printf("%s does not exist\n", local_name);
2692                 return 1;
2693         }
2694
2695         if (next_token_nr(NULL, p, NULL, sizeof(buf)))
2696                 pstrcat(remote_name, p);
2697         else
2698                 pstrcat(remote_name, local_name);
2699         
2700         dos_clean_name(remote_name);
2701
2702         return do_put(remote_name, local_name, True);
2703 }
2704
2705 /****************************************************************************
2706  List a share name.
2707  ****************************************************************************/
2708
2709 static void browse_fn(const char *name, uint32 m, 
2710                       const char *comment, void *state)
2711 {
2712         fstring typestr;
2713
2714         *typestr=0;
2715
2716         switch (m)
2717         {
2718           case STYPE_DISKTREE:
2719             fstrcpy(typestr,"Disk"); break;
2720           case STYPE_PRINTQ:
2721             fstrcpy(typestr,"Printer"); break;
2722           case STYPE_DEVICE:
2723             fstrcpy(typestr,"Device"); break;
2724           case STYPE_IPC:
2725             fstrcpy(typestr,"IPC"); break;
2726         }
2727         /* FIXME: If the remote machine returns non-ascii characters
2728            in any of these fields, they can corrupt the output.  We
2729            should remove them. */
2730         if (!grepable) {
2731                 d_printf("\t%-15s %-10.10s%s\n",
2732                         name,typestr,comment);
2733         } else {
2734                 d_printf ("%s|%s|%s\n",typestr,name,comment);
2735         }
2736 }
2737
2738 /****************************************************************************
2739  Try and browse available connections on a host.
2740 ****************************************************************************/
2741
2742 static BOOL browse_host(BOOL sort)
2743 {
2744         int ret;
2745         if (!grepable) {
2746                 d_printf("\n\tSharename       Type      Comment\n");
2747                 d_printf("\t---------       ----      -------\n");
2748         }
2749
2750         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
2751                 d_printf("Error returning browse list: %s\n", cli_errstr(cli));
2752
2753         return (ret != -1);
2754 }
2755
2756 /****************************************************************************
2757  List a server name.
2758 ****************************************************************************/
2759
2760 static void server_fn(const char *name, uint32 m, 
2761                       const char *comment, void *state)
2762 {
2763         
2764         if (!grepable){
2765                 d_printf("\t%-16s     %s\n", name, comment);
2766         } else {
2767                 d_printf("%s|%s|%s\n",(char *)state, name, comment);
2768         }
2769 }
2770
2771 /****************************************************************************
2772  Try and browse available connections on a host.
2773 ****************************************************************************/
2774
2775 static BOOL list_servers(const char *wk_grp)
2776 {
2777         fstring state;
2778
2779         if (!cli->server_domain)
2780                 return False;
2781
2782         if (!grepable) {
2783                 d_printf("\n\tServer               Comment\n");
2784                 d_printf("\t---------            -------\n");
2785         };
2786         fstrcpy( state, "Server" );
2787         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
2788                           state);
2789
2790         if (!grepable) {
2791                 d_printf("\n\tWorkgroup            Master\n");
2792                 d_printf("\t---------            -------\n");
2793         }; 
2794
2795         fstrcpy( state, "Workgroup" );
2796         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
2797                           server_fn, state);
2798         return True;
2799 }
2800
2801 /****************************************************************************
2802  Print or set current VUID
2803 ****************************************************************************/
2804
2805 static int cmd_vuid(void)
2806 {
2807         fstring buf;
2808         
2809         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2810                 d_printf("Current VUID is %d\n", cli->vuid);
2811                 return 0;
2812         }
2813
2814         cli->vuid = atoi(buf);
2815         return 0;
2816 }
2817
2818 /****************************************************************************
2819  Setup a new VUID, by issuing a session setup
2820 ****************************************************************************/
2821
2822 static int cmd_logon(void)
2823 {
2824         pstring l_username, l_password;
2825         pstring buf,buf2;
2826   
2827         if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
2828                 d_printf("logon <username> [<password>]\n");
2829                 return 0;
2830         }
2831
2832         pstrcpy(l_username, buf);
2833
2834         if (!next_token_nr(NULL,buf2,NULL,sizeof(buf))) 
2835         {
2836                 char *pass = getpass("Password: ");
2837                 if (pass) 
2838                         pstrcpy(l_password, pass);
2839         } 
2840         else
2841                 pstrcpy(l_password, buf2);
2842
2843         if (!cli_session_setup(cli, l_username, 
2844                                    l_password, strlen(l_password),
2845                                    l_password, strlen(l_password),
2846                                    lp_workgroup())) {
2847                 d_printf("session setup failed: %s\n", cli_errstr(cli));
2848                 return -1;
2849         }
2850
2851         d_printf("Current VUID is %d\n", cli->vuid);
2852         return 0;
2853 }
2854
2855
2856 /****************************************************************************
2857  list active connections
2858 ****************************************************************************/
2859
2860 static int cmd_list_connect(void)
2861 {
2862         cli_cm_display();
2863
2864         return 0;
2865 }
2866
2867 /****************************************************************************
2868  display the current active client connection
2869 ****************************************************************************/
2870
2871 static int cmd_show_connect( void )
2872 {
2873         struct cli_state *targetcli;
2874         pstring targetpath;
2875         
2876         if ( !cli_resolve_path( "", cli, cur_dir, &targetcli, targetpath ) ) {
2877                 d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
2878                 return 1;
2879         }
2880         
2881         d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
2882         return 0;
2883 }
2884
2885 /* Some constants for completing filename arguments */
2886
2887 #define COMPL_NONE                0                      /* No completions */
2888 #define COMPL_REMOTE      1                      /* Complete remote filename */
2889 #define COMPL_LOCAL               2                      /* Complete local filename */
2890
2891 /* This defines the commands supported by this client.
2892  * NOTE: The "!" must be the last one in the list because it's fn pointer
2893  *               field is NULL, and NULL in that field is used in process_tok()
2894  *               (below) to indicate the end of the list.  crh
2895  */
2896 static struct
2897 {
2898   const char *name;
2899   int (*fn)(void);
2900   const char *description;
2901   char compl_args[2];      /* Completion argument info */
2902 } commands[] = {
2903   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2904 /*       {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}}, */
2905   {"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}},
2906   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
2907 /*       {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}}, */
2908 /*       {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}}, */
2909   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
2910 /*       {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}}, */
2911 /*       {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}}, */
2912 /*       {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}}, */
2913   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2914 /*       {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}}, */
2915   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2916   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
2917 /*       {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}}, */
2918 /*       {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}}, */
2919   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
2920   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
2921   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
2922 /*       {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}}, */
2923 /*       {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}}, */
2924 /*       {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}}, */
2925   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
2926   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
2927 /*       {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}}, */
2928   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2929   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
2930   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
2931 /*       {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}}, */      
2932   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
2933   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
2934 /*       {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}}, */
2935 /*       {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}}, */
2936   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},      
2937   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
2938   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
2939   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2940 /*       {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}}, */
2941   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
2942   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2943   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
2944 /*      {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},*/
2945   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
2946 /*      {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},*/
2947 /*      {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},*/
2948   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
2949 /*      {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},*/
2950 /*      {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},*/
2951 /*      {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},*/
2952 /*      {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},*/
2953   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
2954   {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
2955   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
2956 /*      {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}}, */
2957 /*      {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}}, */
2958   
2959   /* Yes, this must be here, see crh's comment above. */
2960   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
2961   {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
2962 };
2963
2964 /*******************************************************************
2965  Lookup a command string in the list of commands, including 
2966  abbreviations.
2967 ******************************************************************/
2968
2969 static int process_tok(pstring tok)
2970 {
2971         int i = 0, matches = 0;
2972         int cmd=0;
2973         int tok_len = strlen(tok);
2974         
2975         while ((commands[i].fn != NULL) || (strequal(commands[i].name, "!"))) {
2976                 if (strequal(commands[i].name,tok)) {
2977                         matches = 1;
2978                         cmd = i;
2979                         break;
2980                 } else if (strnequal(commands[i].name, tok, tok_len)) {
2981                         matches++;
2982                         cmd = i;
2983                 }
2984                 i++;
2985         }
2986   
2987         if (matches == 0)
2988                 return(-1);
2989         else if (matches == 1)
2990                 return(cmd);
2991         else
2992                 return(-2);
2993 }
2994
2995 /****************************************************************************
2996  Help.
2997 ****************************************************************************/
2998
2999 static int cmd_help(void)
3000 {
3001         int i=0,j;
3002         pstring buf;
3003         
3004         if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
3005                 if ((i = process_tok(buf)) >= 0)
3006                         d_printf("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);
3007         } else {
3008                 while (commands[i].description) {
3009                         for (j=0; commands[i].description && (j<5); j++) {
3010                                 d_printf("%-15s",commands[i].name);
3011                                 i++;
3012                         }
3013                         d_printf("\n");
3014                 }
3015         }
3016         return 0;
3017 }
3018
3019 /****************************************************************************
3020  Process a -c command string.
3021 ****************************************************************************/
3022
3023 static int process_command_string(char *cmd)
3024 {
3025         pstring line;
3026         const char *ptr;
3027         int rc = 0;
3028
3029         /* establish the connection if not already */
3030         
3031         if (!cli) {
3032                 cli = cli_cm_open(desthost, service, True);
3033                 if (!cli)
3034                         return 0;
3035         }
3036         
3037         while (cmd[0] != '\0')    {
3038                 char *p;
3039                 pstring tok;
3040                 int i;
3041                 
3042                 if ((p = strchr_m(cmd, ';')) == 0) {
3043                         strncpy(line, cmd, 999);
3044                         line[1000] = '\0';
3045                         cmd += strlen(cmd);
3046                 } else {
3047                         if (p - cmd > 999)
3048                                 p = cmd + 999;
3049                         strncpy(line, cmd, p - cmd);
3050                         line[p - cmd] = '\0';
3051                         cmd = p + 1;
3052                 }
3053                 
3054                 /* and get the first part of the command */
3055                 ptr = line;
3056                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
3057                 
3058                 if ((i = process_tok(tok)) >= 0) {
3059                         rc = commands[i].fn();
3060                 } else if (i == -2) {
3061                         d_printf("%s: command abbreviation ambiguous\n",tok);
3062                 } else {
3063                         d_printf("%s: command not found\n",tok);
3064                 }
3065         }
3066         
3067         return rc;
3068 }       
3069
3070 #define MAX_COMPLETIONS 100
3071
3072 typedef struct {
3073         pstring dirmask;
3074         char **matches;
3075         int count, samelen;
3076         const char *text;
3077         int len;
3078 } completion_remote_t;
3079
3080 static void completion_remote_filter(const char *mnt, file_info *f, const char *mask, void *state)
3081 {
3082         completion_remote_t *info = (completion_remote_t *)state;
3083
3084         if ((info->count < MAX_COMPLETIONS - 1) && (strncmp(info->text, f->name, info->len) == 0) && (strcmp(f->name, ".") != 0) && (strcmp(f->name, "..") != 0)) {
3085                 if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
3086                         info->matches[info->count] = SMB_STRDUP(f->name);
3087                 else {
3088                         pstring tmp;
3089
3090                         if (info->dirmask[0] != 0)
3091                                 pstrcpy(tmp, info->dirmask);
3092                         else
3093                                 tmp[0] = 0;
3094                         pstrcat(tmp, f->name);
3095                         if (f->mode & aDIR)
3096                                 pstrcat(tmp, "/");
3097                         info->matches[info->count] = SMB_STRDUP(tmp);
3098                 }
3099                 if (info->matches[info->count] == NULL)
3100                         return;
3101                 if (f->mode & aDIR)
3102                         smb_readline_ca_char(0);
3103
3104                 if (info->count == 1)
3105                         info->samelen = strlen(info->matches[info->count]);
3106                 else
3107                         while (strncmp(info->matches[info->count], info->matches[info->count-1], info->samelen) != 0)
3108                                 info->samelen--;
3109                 info->count++;
3110         }
3111 }
3112
3113 static char **remote_completion(const char *text, int len)
3114 {
3115         pstring dirmask;
3116         int i;
3117         completion_remote_t info = { "", NULL, 1, 0, NULL, 0 };
3118
3119         /* can't have non-static intialisation on Sun CC, so do it
3120            at run time here */
3121         info.samelen = len;
3122         info.text = text;
3123         info.len = len;
3124                 
3125         if (len >= PATH_MAX)
3126                 return(NULL);
3127
3128         info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
3129         if (!info.matches) return NULL;
3130         info.matches[0] = NULL;
3131
3132         for (i = len-1; i >= 0; i--)
3133                 if ((text[i] == '/') || (text[i] == '\\'))
3134                         break;
3135         info.text = text+i+1;
3136         info.samelen = info.len = len-i-1;
3137
3138         if (i > 0) {
3139                 strncpy(info.dirmask, text, i+1);
3140                 info.dirmask[i+1] = 0;
3141                 pstr_sprintf(dirmask, "%s%*s*", cur_dir, i-1, text);
3142         } else
3143                 pstr_sprintf(dirmask, "%s*", cur_dir);
3144
3145         if (cli_list(cli, dirmask, aDIR | aSYSTEM | aHIDDEN, completion_remote_filter, &info) < 0)
3146                 goto cleanup;
3147
3148         if (info.count == 2)
3149                 info.matches[0] = SMB_STRDUP(info.matches[1]);
3150         else {
3151                 info.matches[0] = SMB_MALLOC(info.samelen+1);
3152                 if (!info.matches[0])
3153                         goto cleanup;
3154                 strncpy(info.matches[0], info.matches[1], info.samelen);
3155                 info.matches[0][info.samelen] = 0;
3156         }
3157         info.matches[info.count] = NULL;
3158         return info.matches;
3159
3160 cleanup:
3161         for (i = 0; i < info.count; i++)
3162                 free(info.matches[i]);
3163         free(info.matches);
3164         return NULL;
3165 }
3166
3167 static char **completion_fn(const char *text, int start, int end)
3168 {
3169         smb_readline_ca_char(' ');
3170
3171         if (start) {
3172                 const char *buf, *sp;
3173                 int i;
3174                 char compl_type;
3175
3176                 buf = smb_readline_get_line_buffer();
3177                 if (buf == NULL)
3178                         return NULL;
3179                 
3180                 sp = strchr(buf, ' ');
3181                 if (sp == NULL)
3182                         return NULL;
3183                 
3184                 for (i = 0; commands[i].name; i++)
3185                         if ((strncmp(commands[i].name, text, sp - buf) == 0) && (commands[i].name[sp - buf] == 0))
3186                                 break;
3187                 if (commands[i].name == NULL)
3188                         return NULL;
3189
3190                 while (*sp == ' ')
3191                         sp++;
3192
3193                 if (sp == (buf + start))
3194                         compl_type = commands[i].compl_args[0];
3195                 else
3196                         compl_type = commands[i].compl_args[1];
3197
3198                 if (compl_type == COMPL_REMOTE)
3199                         return remote_completion(text, end - start);
3200                 else /* fall back to local filename completion */
3201                         return NULL;
3202         } else {
3203                 char **matches;
3204                 int i, len, samelen = 0, count=1;
3205
3206                 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
3207                 if (!matches) {
3208                         return NULL;
3209                 }
3210                 matches[0] = NULL;
3211
3212                 len = strlen(text);
3213                 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
3214                         if (strncmp(text, commands[i].name, len) == 0) {
3215                                 matches[count] = SMB_STRDUP(commands[i].name);
3216                                 if (!matches[count])
3217                                         goto cleanup;
3218                                 if (count == 1)
3219                                         samelen = strlen(matches[count]);
3220                                 else
3221                                         while (strncmp(matches[count], matches[count-1], samelen) != 0)
3222                                                 samelen--;
3223                                 count++;
3224                         }
3225                 }
3226
3227                 switch (count) {
3228                 case 0: /* should never happen */
3229                 case 1:
3230                         goto cleanup;
3231                 case 2:
3232                         matches[0] = SMB_STRDUP(matches[1]);
3233                         break;
3234                 default:
3235                         matches[0] = SMB_MALLOC(samelen+1);
3236                         if (!matches[0])
3237                                 goto cleanup;
3238                         strncpy(matches[0], matches[1], samelen);
3239                         matches[0][samelen] = 0;
3240                 }
3241                 matches[count] = NULL;
3242                 return matches;
3243
3244 cleanup:
3245                 for (i = 0; i < count; i++)
3246                         free(matches[i]);
3247
3248                 free(matches);
3249                 return NULL;
3250         }
3251 }
3252
3253 /****************************************************************************
3254  Make sure we swallow keepalives during idle time.
3255 ****************************************************************************/
3256
3257 static void readline_callback(void)
3258 {
3259         fd_set fds;
3260         struct timeval timeout;
3261         static time_t last_t;
3262         time_t t;
3263
3264         t = time(NULL);
3265
3266         if (t - last_t < 5)
3267                 return;
3268
3269         last_t = t;
3270
3271  again:
3272
3273         if (cli->fd == -1)
3274                 return;
3275
3276         FD_ZERO(&fds);
3277         FD_SET(cli->fd,&fds);
3278
3279         timeout.tv_sec = 0;
3280         timeout.tv_usec = 0;
3281         sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
3282                         
3283         /* We deliberately use receive_smb instead of
3284            client_receive_smb as we want to receive
3285            session keepalives and then drop them here.
3286         */
3287         if (FD_ISSET(cli->fd,&fds)) {
3288                 receive_smb(cli->fd,cli->inbuf,0);
3289                 goto again;
3290         }
3291           
3292         cli_chkpath(cli, "/");
3293 }
3294
3295 /****************************************************************************
3296  Process commands on stdin.
3297 ****************************************************************************/
3298
3299 static int process_stdin(void)
3300 {
3301         const char *ptr;
3302         int rc = 0;
3303
3304         while (1) {
3305                 pstring tok;
3306                 pstring the_prompt;
3307                 char *cline;
3308                 pstring line;
3309                 int i;
3310                 
3311                 /* display a prompt */
3312                 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);                
3313                 /* Removed callback since we don't need to swallow keepalives with libsmbclient */
3314                 /*cline = smb_readline(the_prompt, readline_callback, completion_fn);*/
3315                 cline = smb_readline(the_prompt, NULL, completion_fn);
3316                 
3317                 if (!cline) break;
3318                 
3319                 pstrcpy(line, cline);
3320
3321                 /* special case - first char is ! */
3322                 if (*line == '!') {
3323                         system(line + 1);
3324                         continue;
3325                 }
3326                 
3327                 /* and get the first part of the command */
3328                 ptr = line;
3329                 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
3330
3331                 if ((i = process_tok(tok)) >= 0) {
3332                         rc = commands[i].fn();
3333                 } else if (i == -2) {
3334                         d_printf("%s: command abbreviation ambiguous\n",tok);
3335                 } else {
3336                         d_printf("%s: command not found\n",tok);
3337                 }
3338         }
3339         return rc;
3340 }
3341
3342 /****************************************************************************
3343  Process commands from the client.
3344 ****************************************************************************/
3345
3346 static int process(char *base_directory)
3347 {
3348         int rc = 0;
3349
3350         /*cli = cli_cm_open(desthost, service, True);
3351         if (!cli) {
3352                 return 1;
3353         }*/
3354         rc = smbc_init(get_auth_data_fn, 0);   /* Initialize libsmbclient */
3355         if (rc < 0)
3356         {
3357                 d_printf("Error initializing libsmbclient: %s\n", strerror(errno));
3358                 return 1;
3359         }
3360         
3361         if (*base_directory) {
3362                 rc = do_cd(base_directory);
3363                 if (rc) {
3364                         cli_cm_shutdown();
3365                         return rc;
3366                 }
3367         }
3368         else    /* start the auth fn*/
3369         {
3370                 rc = do_cd("/");
3371                 if (rc)
3372                         return rc;
3373         }
3374         
3375         if (cmdstr) {
3376                 rc = process_command_string(cmdstr);
3377         } else {
3378                 process_stdin();
3379         }
3380   
3381         cli_cm_shutdown();
3382         return rc;
3383 }
3384
3385 /****************************************************************************
3386  Handle a -L query.
3387 ****************************************************************************/
3388
3389 static int do_host_query(char *query_host)
3390 {
3391         cli = cli_cm_open(query_host, "IPC$", True);
3392         if (!cli)
3393                 return 1;
3394
3395         browse_host(True);
3396
3397         if (port != 139) {
3398
3399                 /* Workgroups simply don't make sense over anything
3400                    else but port 139... */
3401
3402                 cli_cm_shutdown();
3403                 cli_cm_set_port( 139 );
3404                 cli = cli_cm_open(query_host, "IPC$", True);
3405         }
3406
3407         if (cli == NULL) {
3408                 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
3409                 return 1;
3410         }
3411
3412         list_servers(lp_workgroup());
3413
3414         cli_cm_shutdown();
3415         
3416         return(0);
3417 }
3418
3419 /****************************************************************************
3420  Handle a tar operation.
3421 ****************************************************************************/
3422
3423 static int do_tar_op(char *base_directory)
3424 {
3425         int ret;
3426
3427         /* do we already have a connection? */
3428         if (!cli) {
3429                 cli = cli_cm_open(desthost, service, True);
3430                 if (!cli)
3431                         return 1;
3432         }
3433
3434         recurse=True;
3435
3436         if (*base_directory)  {
3437                 ret = do_cd(base_directory);
3438                 if (ret) {
3439                         cli_cm_shutdown();
3440                         return ret;
3441                 }
3442         }
3443         
3444         ret=process_tar();
3445
3446         cli_cm_shutdown();
3447
3448         return(ret);
3449 }
3450
3451 /****************************************************************************
3452  Handle a message operation.
3453 ****************************************************************************/
3454
3455 static int do_message_op(void)
3456 {
3457         struct in_addr ip;
3458         struct nmb_name called, calling;
3459         fstring server_name;
3460         char name_type_hex[10];
3461         int msg_port;
3462
3463         make_nmb_name(&calling, calling_name, 0x0);
3464         make_nmb_name(&called , desthost, name_type);
3465
3466         fstrcpy(server_name, desthost);
3467         snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
3468         fstrcat(server_name, name_type_hex);
3469
3470                 zero_ip(&ip);
3471         if (have_ip) 
3472                 ip = dest_ip;
3473
3474         /* we can only do messages over port 139 (to windows clients at least) */
3475
3476         msg_port = port ? port : 139;
3477
3478         if (!(cli=cli_initialise(NULL)) || (cli_set_port(cli, msg_port) != msg_port) ||
3479                 !cli_connect(cli, server_name, &ip)) {
3480                 d_printf("Connection to %s failed\n", desthost);
3481                 return 1;
3482         }
3483
3484         if (!cli_session_request(cli, &calling, &called)) {
3485                 d_printf("session request failed\n");
3486                 cli_cm_shutdown();
3487                 return 1;
3488         }
3489
3490         send_message();
3491         cli_cm_shutdown();
3492
3493         return 0;
3494 }
3495
3496
3497 /****************************************************************************
3498   main program
3499 ****************************************************************************/
3500
3501  int main(int argc,char *argv[])
3502 {
3503         pstring base_directory;
3504         int opt;
3505         pstring query_host;
3506         BOOL message = False;
3507         pstring term_code;
3508         static const char *new_name_resolve_order = NULL;
3509         poptContext pc;
3510         char *p;
3511         int rc = 0;
3512         fstring new_workgroup;
3513         struct poptOption long_options[] = {
3514                 POPT_AUTOHELP
3515
3516                 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
3517                 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
3518                 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
3519                 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
3520                 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
3521                 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
3522                 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
3523                 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
3524                 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
3525                 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" }, 
3526                 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
3527                 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
3528                 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
3529                 POPT_COMMON_SAMBA
3530                 POPT_COMMON_CONNECTION
3531                 POPT_COMMON_CREDENTIALS
3532                 POPT_TABLEEND
3533         };
3534         
3535
3536 #ifdef KANJI
3537         pstrcpy(term_code, KANJI);
3538 #else /* KANJI */
3539         *term_code = 0;
3540 #endif /* KANJI */
3541
3542         *query_host = 0;
3543         *base_directory = 0;
3544         
3545         /* initialize the workgroup name so we can determine whether or 
3546            not it was set by a command line option */
3547            
3548         set_global_myworkgroup( "" );
3549         set_global_myname( "" );
3550
3551                 /* set default debug level to 0 regardless of what smb.conf sets */
3552         setup_logging( "smbclient", True );
3553         DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
3554         dbf = x_stderr;
3555         x_setbuf( x_stderr, NULL );
3556
3557         pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 
3558                                 POPT_CONTEXT_KEEP_FIRST);
3559         poptSetOtherOptionHelp(pc, "service <password>");
3560
3561         in_client = True;       /* Make sure that we tell lp_load we are */
3562
3563         while ((opt = poptGetNextOpt(pc)) != -1) {
3564                 switch (opt) {
3565                 case 'M':
3566                         /* Messages are sent to NetBIOS name type 0x3
3567                          * (Messenger Service).  Make sure we default
3568                          * to port 139 instead of port 445. srl,crh
3569                          */
3570                         name_type = 0x03; 
3571                         cli_cm_set_dest_name_type( name_type );
3572                         pstrcpy(desthost,poptGetOptArg(pc));
3573                         if( !port )
3574                                 cli_cm_set_port( 139 );
3575                         message = True;
3576                         break;
3577                 case 'I':
3578                         {
3579                                 dest_ip = *interpret_addr2(poptGetOptArg(pc));
3580                                 if (is_zero_ip(dest_ip))
3581                                         exit(1);
3582                                 have_ip = True;
3583
3584                                 cli_cm_set_dest_ip( dest_ip );
3585                         }
3586                         break;
3587                 case 'E':
3588                         dbf = x_stderr;
3589                         display_set_stderr();
3590                         break;
3591
3592                 case 'L':
3593                         pstrcpy(query_host, poptGetOptArg(pc));
3594                         break;
3595                 case 't':
3596                         pstrcpy(term_code, poptGetOptArg(pc));
3597                         break;
3598                 case 'm':
3599                         max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
3600                         break;
3601                 case 'T':
3602                         /* We must use old option processing for this. Find the
3603                          * position of the -T option in the raw argv[]. */
3604                         {
3605                                 int i, optnum;
3606                                 for (i = 1; i < argc; i++) {
3607                                         if (strncmp("-T", argv[i],2)==0)
3608                                                 break;
3609                                 }
3610                                 i++;
3611                                 if (!(optnum = tar_parseargs(argc, argv, poptGetOptArg(pc), i))) {
3612                                         poptPrintUsage(pc, stderr, 0);
3613                                         exit(1);
3614                                 }
3615                                 /* Now we must eat (optnum - i) options - they have
3616                                  * been processed by tar_parseargs().
3617                                  */
3618                                 optnum -= i;
3619                                 for (i = 0; i < optnum; i++)
3620                                         poptGetOptArg(pc);
3621                         }
3622                         break;
3623                 case 'D':
3624                         pstrcpy(base_directory,poptGetOptArg(pc));
3625                         break;
3626                 case 'g':
3627                         grepable=True;
3628                         break;
3629                 }
3630         }
3631
3632         poptGetArg(pc);
3633
3634         /* check for the -P option */
3635
3636         if ( port != 0 )
3637                 cli_cm_set_port( port );
3638
3639         /*
3640          * Don't load debug level from smb.conf. It should be
3641          * set by cmdline arg or remain default (0)
3642          */
3643         AllowDebugChange = False;
3644         
3645         /* save the workgroup...
3646         
3647            FIXME!! do we need to do this for other options as well 
3648            (or maybe a generic way to keep lp_load() from overwriting 
3649            everything)?  */
3650         
3651         fstrcpy( new_workgroup, lp_workgroup() );
3652         pstrcpy( calling_name, global_myname() );
3653         
3654         if ( override_logfile )
3655                 setup_logging( lp_logfile(), False );
3656         
3657         if (!lp_load(dyn_CONFIGFILE,True,False,False,True)) {
3658                 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
3659                         argv[0], dyn_CONFIGFILE);
3660         }
3661         
3662         load_interfaces();
3663         
3664         if ( strlen(new_workgroup) != 0 )
3665                 set_global_myworkgroup( new_workgroup );
3666         pstrcpy(workgroup, lp_workgroup());
3667
3668         if ( strlen(calling_name) != 0 )
3669                 set_global_myname( calling_name );
3670         else
3671                 pstrcpy( calling_name, global_myname() );
3672
3673         if(poptPeekArg(pc)) {
3674                 pstrcpy(service,poptGetArg(pc));  
3675                 /* Convert any '\' characters in the service name to '/' characters */
3676                 string_replace(service, '\\','/');
3677
3678                 if (count_chars(service,'/') < 3) {
3679                         d_printf("\n%s: Not enough '/' characters in service\n",service);
3680                         poptPrintUsage(pc, stderr, 0);
3681                         exit(1);
3682                 }
3683         }
3684
3685         if (poptPeekArg(pc) && !cmdline_auth_info.got_pass) { 
3686                 cmdline_auth_info.got_pass = True;
3687                 pstrcpy(cmdline_auth_info.password,poptGetArg(pc));      
3688         }
3689
3690         init_names();
3691
3692         if(new_name_resolve_order)
3693                 lp_set_name_resolve_order(new_name_resolve_order);
3694
3695         if (!tar_type && !*query_host && !*service && !message) {
3696                 poptPrintUsage(pc, stderr, 0);
3697                 exit(1);
3698         }
3699
3700         poptFreeContext(pc);
3701
3702         /* store the username an password for dfs support */
3703
3704         cli_cm_set_credentials( &cmdline_auth_info );
3705         pstrcpy(username, cmdline_auth_info.username);
3706
3707         DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
3708
3709         if (tar_type) {
3710                 if (cmdstr)
3711                         process_command_string(cmdstr);
3712                 return do_tar_op(base_directory);
3713         }
3714
3715         if (*query_host) {
3716                 char *qhost = query_host;
3717                 char *slash;
3718
3719                 while (*qhost == '\\' || *qhost == '/')
3720                         qhost++;
3721
3722                 if ((slash = strchr_m(qhost, '/'))
3723                         || (slash = strchr_m(qhost, '\\'))) {
3724                         *slash = 0;
3725                 }
3726
3727                 if ((p=strchr_m(qhost, '#'))) {
3728                         *p = 0;
3729                         p++;
3730                         sscanf(p, "%x", &name_type);
3731                         cli_cm_set_dest_name_type( name_type );
3732                 }
3733
3734                 return do_host_query(qhost);
3735         }
3736
3737         if (message) {
3738                 return do_message_op();
3739         }
3740         
3741         if (process(base_directory)) {
3742                 return 1;
3743         }
3744
3745         return rc;
3746 }