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