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