082594dbf25e76eb5693256c84c6c925538c46db
[kai/samba.git] / source / client / client.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    SMB client
5    Copyright (C) Andrew Tridgell 1994-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #define NO_SYSLOG
23
24 #include "includes.h"
25
26 #ifndef REGISTER
27 #define REGISTER 0
28 #endif
29
30 struct cli_state *cli;
31 extern BOOL in_client;
32 static int port = SMB_PORT;
33 pstring cur_dir = "\\";
34 pstring cd_path = "";
35 static pstring service;
36 static pstring desthost;
37 extern pstring global_myname;
38 static pstring password;
39 static pstring username;
40 static pstring workgroup;
41 static char *cmdstr;
42 static BOOL got_pass;
43 static int io_bufsize = 64512;
44 extern struct in_addr ipzero;
45
46 static int name_type = 0x20;
47 static int max_protocol = PROTOCOL_NT1;
48 extern pstring user_socket_options;
49
50 static int process_tok(fstring tok);
51 static void cmd_help(void);
52
53 /* 30 second timeout on most commands */
54 #define CLIENT_TIMEOUT (30*1000)
55 #define SHORT_TIMEOUT (5*1000)
56
57 /* value for unused fid field in trans2 secondary request */
58 #define FID_UNUSED (0xFFFF)
59
60 time_t newer_than = 0;
61 int archive_level = 0;
62
63 extern pstring debugf;
64 extern int DEBUGLEVEL;
65
66 BOOL translation = False;
67
68 static BOOL have_ip;
69
70 /* clitar bits insert */
71 extern int blocksize;
72 extern BOOL tar_inc;
73 extern BOOL tar_reset;
74 /* clitar bits end */
75  
76
77 mode_t myumask = 0755;
78
79 BOOL prompt = True;
80
81 int printmode = 1;
82
83 static BOOL recurse = False;
84 BOOL lowercase = False;
85
86 struct in_addr dest_ip;
87
88 #define SEPARATORS " \t\n\r"
89
90 BOOL abort_mget = True;
91
92 pstring fileselection = "";
93
94 extern file_info def_finfo;
95
96 /* readline variables */
97 static pstring command_line;
98 static int readline_event;
99
100 /* timing globals */
101 int get_total_size = 0;
102 int get_total_time_ms = 0;
103 int put_total_size = 0;
104 int put_total_time_ms = 0;
105
106 /* totals globals */
107 static double dir_total;
108
109 #define USENMB
110
111 /****************************************************************************
112 write to a local file with CR/LF->LF translation if appropriate. return the 
113 number taken from the buffer. This may not equal the number written.
114 ****************************************************************************/
115 static int writefile(int f, char *b, int n)
116 {
117         int i;
118
119         if (!translation) {
120                 return write(f,b,n);
121         }
122
123         i = 0;
124         while (i < n) {
125                 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
126                         b++;i++;
127                 }
128                 if (write(f, b, 1) != 1) {
129                         break;
130                 }
131                 b++;
132                 i++;
133         }
134   
135         return(i);
136 }
137
138 /****************************************************************************
139   read from a file with LF->CR/LF translation if appropriate. return the 
140   number read. read approx n bytes.
141 ****************************************************************************/
142 static int readfile(char *b, int size, int n, FILE *f)
143 {
144         int i;
145         int c;
146
147         if (!translation || (size != 1))
148                 return(fread(b,size,n,f));
149   
150         i = 0;
151         while (i < (n - 1) && (i < BUFFER_SIZE)) {
152                 if ((c = getc(f)) == EOF) {
153                         break;
154                 }
155       
156                 if (c == '\n') { /* change all LFs to CR/LF */
157                         b[i++] = '\r';
158                 }
159       
160                 b[i++] = c;
161         }
162   
163         return(i);
164 }
165  
166
167 /****************************************************************************
168 send a message
169 ****************************************************************************/
170 static void send_message(void)
171 {
172         int total_len = 0;
173         int grp_id;
174
175         if (!cli_message_start(cli, desthost, username, &grp_id)) {
176                 DEBUG(0,("message start: %s\n", cli_errstr(cli)));
177                 return;
178         }
179
180
181         printf("Connected. Type your message, ending it with a Control-D\n");
182
183         while (!feof(stdin) && total_len < 1600) {
184                 int maxlen = MIN(1600 - total_len,127);
185                 pstring msg;
186                 int l=0;
187                 int c;
188
189                 ZERO_ARRAY(msg);
190
191                 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
192                         if (c == '\n')
193                                 msg[l++] = '\r';
194                         msg[l] = c;   
195                 }
196
197                 /*
198                  * The message is in UNIX codepage format. Convert to
199                  * DOS before sending.
200                  */
201
202                 unix_to_dos(msg, True);
203
204                 if (!cli_message_text(cli, msg, l, grp_id)) {
205                         printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
206                         return;
207                 }      
208                 
209                 total_len += l;
210         }
211
212         if (total_len >= 1600)
213                 printf("the message was truncated to 1600 bytes\n");
214         else
215                 printf("sent %d bytes\n",total_len);
216
217         if (!cli_message_end(cli, grp_id)) {
218                 printf("SMBsendend failed (%s)\n",cli_errstr(cli));
219                 return;
220         }      
221 }
222
223
224
225 /****************************************************************************
226 check the space on a device
227 ****************************************************************************/
228 static void do_dskattr(void)
229 {
230         int total, bsize, avail;
231
232         if (!cli_dskattr(cli, &bsize, &total, &avail)) {
233                 DEBUG(0,("Error in dskattr: %s\n",cli_errstr(cli))); 
234                 return;
235         }
236
237         DEBUG(0,("\n\t\t%d blocks of size %d. %d blocks available\n",
238                  total, bsize, avail));
239 }
240
241 /****************************************************************************
242 show cd/pwd
243 ****************************************************************************/
244 static void cmd_pwd(void)
245 {
246         DEBUG(0,("Current directory is %s",service));
247         DEBUG(0,("%s\n",cur_dir));
248 }
249
250
251 /****************************************************************************
252 change directory - inner section
253 ****************************************************************************/
254 static void do_cd(char *newdir)
255 {
256         char *p = newdir;
257         pstring saved_dir;
258         pstring dname;
259       
260         dos_format(newdir);
261
262         /* Save the current directory in case the
263            new directory is invalid */
264         pstrcpy(saved_dir, cur_dir);
265         if (*p == '\\')
266                 pstrcpy(cur_dir,p);
267         else
268                 pstrcat(cur_dir,p);
269         if (*(cur_dir+strlen(cur_dir)-1) != '\\') {
270                 pstrcat(cur_dir, "\\");
271         }
272         dos_clean_name(cur_dir);
273         pstrcpy(dname,cur_dir);
274         pstrcat(cur_dir,"\\");
275         dos_clean_name(cur_dir);
276         
277         if (!strequal(cur_dir,"\\")) {
278                 if (!cli_chkpath(cli, dname)) {
279                         DEBUG(0,("cd %s: %s\n", dname, cli_errstr(cli)));
280                         pstrcpy(cur_dir,saved_dir);
281                 }
282         }
283         
284         pstrcpy(cd_path,cur_dir);
285 }
286
287 /****************************************************************************
288 change directory
289 ****************************************************************************/
290 static void cmd_cd(void)
291 {
292         fstring buf;
293
294         if (next_token(NULL,buf,NULL,sizeof(buf)))
295                 do_cd(buf);
296         else
297                 DEBUG(0,("Current directory is %s\n",cur_dir));
298 }
299
300
301 /*******************************************************************
302   decide if a file should be operated on
303   ********************************************************************/
304 static BOOL do_this_one(file_info *finfo)
305 {
306         if (finfo->mode & aDIR) return(True);
307
308         if (*fileselection && 
309             !mask_match(finfo->name,fileselection,False)) {
310                 DEBUG(3,("match_match %s failed\n", finfo->name));
311                 return False;
312         }
313
314         if (newer_than && finfo->mtime < newer_than) {
315                 DEBUG(3,("newer_than %s failed\n", finfo->name));
316                 return(False);
317         }
318
319         if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
320                 DEBUG(3,("archive %s failed\n", finfo->name));
321                 return(False);
322         }
323         
324         return(True);
325 }
326
327 /****************************************************************************
328   display info about a file
329   ****************************************************************************/
330 static void display_finfo(file_info *finfo)
331 {
332         if (do_this_one(finfo)) {
333                 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
334                 DEBUG(0,("  %-30s%7.7s %8.0f  %s",
335                          finfo->name,
336                          attrib_string(finfo->mode),
337                          (double)finfo->size,
338                          asctime(LocalTime(&t))));
339                 dir_total += finfo->size;
340         }
341 }
342
343
344 /****************************************************************************
345    accumulate size of a file
346   ****************************************************************************/
347 static void do_du(file_info *finfo)
348 {
349         if (do_this_one(finfo)) {
350                 dir_total += finfo->size;
351         }
352 }
353
354 static BOOL do_list_recurse;
355 static BOOL do_list_dirs;
356 static char *do_list_queue = 0;
357 static long do_list_queue_size = 0;
358 static long do_list_queue_start = 0;
359 static long do_list_queue_end = 0;
360 static void (*do_list_fn)(file_info *);
361
362 /****************************************************************************
363 functions for do_list_queue
364   ****************************************************************************/
365
366 /*
367  * The do_list_queue is a NUL-separated list of strings stored in a
368  * char*.  Since this is a FIFO, we keep track of the beginning and
369  * ending locations of the data in the queue.  When we overflow, we
370  * double the size of the char*.  When the start of the data passes
371  * the midpoint, we move everything back.  This is logically more
372  * complex than a linked list, but easier from a memory management
373  * angle.  In any memory error condition, do_list_queue is reset.
374  * Functions check to ensure that do_list_queue is non-NULL before
375  * accessing it.
376  */
377 static void reset_do_list_queue(void)
378 {
379         if (do_list_queue)
380         {
381                 free(do_list_queue);
382         }
383         do_list_queue = 0;
384         do_list_queue_size = 0;
385         do_list_queue_start = 0;
386         do_list_queue_end = 0;
387 }
388
389 static void init_do_list_queue(void)
390 {
391         reset_do_list_queue();
392         do_list_queue_size = 1024;
393         do_list_queue = malloc(do_list_queue_size);
394         if (do_list_queue == 0) { 
395                 DEBUG(0,("malloc fail for size %d\n",
396                          (int)do_list_queue_size));
397                 reset_do_list_queue();
398         } else {
399                 memset(do_list_queue, 0, do_list_queue_size);
400         }
401 }
402
403 static void adjust_do_list_queue(void)
404 {
405         /*
406          * If the starting point of the queue is more than half way through,
407          * move everything toward the beginning.
408          */
409         if (do_list_queue && (do_list_queue_start == do_list_queue_end))
410         {
411                 DEBUG(4,("do_list_queue is empty\n"));
412                 do_list_queue_start = do_list_queue_end = 0;
413                 *do_list_queue = '\0';
414         }
415         else if (do_list_queue_start > (do_list_queue_size / 2))
416         {
417                 DEBUG(4,("sliding do_list_queue backward\n"));
418                 memmove(do_list_queue,
419                         do_list_queue + do_list_queue_start,
420                         do_list_queue_end - do_list_queue_start);
421                 do_list_queue_end -= do_list_queue_start;
422                 do_list_queue_start = 0;
423         }
424            
425 }
426
427 static void add_to_do_list_queue(const char* entry)
428 {
429         long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
430         while (new_end > do_list_queue_size)
431         {
432                 do_list_queue_size *= 2;
433                 DEBUG(4,("enlarging do_list_queue to %d\n",
434                          (int)do_list_queue_size));
435                 do_list_queue = Realloc(do_list_queue, do_list_queue_size);
436                 if (! do_list_queue) {
437                         DEBUG(0,("failure enlarging do_list_queue to %d bytes\n",
438                                  (int)do_list_queue_size));
439                         reset_do_list_queue();
440                 }
441                 else
442                 {
443                         memset(do_list_queue + do_list_queue_size / 2,
444                                0, do_list_queue_size / 2);
445                 }
446         }
447         if (do_list_queue)
448         {
449                 pstrcpy(do_list_queue + do_list_queue_end, entry);
450                 do_list_queue_end = new_end;
451                 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
452                          entry, (int)do_list_queue_start, (int)do_list_queue_end));
453         }
454 }
455
456 static char *do_list_queue_head(void)
457 {
458         return do_list_queue + do_list_queue_start;
459 }
460
461 static void remove_do_list_queue_head(void)
462 {
463         if (do_list_queue_end > do_list_queue_start)
464         {
465                 do_list_queue_start += strlen(do_list_queue_head()) + 1;
466                 adjust_do_list_queue();
467                 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
468                          (int)do_list_queue_start, (int)do_list_queue_end));
469         }
470 }
471
472 static int do_list_queue_empty(void)
473 {
474         return (! (do_list_queue && *do_list_queue));
475 }
476
477 /****************************************************************************
478 a helper for do_list
479   ****************************************************************************/
480 static void do_list_helper(file_info *f, const char *mask, void *state)
481 {
482         if (f->mode & aDIR) {
483                 if (do_list_dirs && do_this_one(f)) {
484                         do_list_fn(f);
485                 }
486                 if (do_list_recurse && 
487                     !strequal(f->name,".") && 
488                     !strequal(f->name,"..")) {
489                         pstring mask2;
490                         char *p;
491
492                         pstrcpy(mask2, mask);
493                         p = strrchr(mask2,'\\');
494                         if (!p) return;
495                         p[1] = 0;
496                         pstrcat(mask2, f->name);
497                         pstrcat(mask2,"\\*");
498                         add_to_do_list_queue(mask2);
499                 }
500                 return;
501         }
502
503         if (do_this_one(f)) {
504                 do_list_fn(f);
505         }
506 }
507
508
509 /****************************************************************************
510 a wrapper around cli_list that adds recursion
511   ****************************************************************************/
512 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
513 {
514         static int in_do_list = 0;
515
516         if (in_do_list && rec)
517         {
518                 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
519                 exit(1);
520         }
521
522         in_do_list = 1;
523
524         do_list_recurse = rec;
525         do_list_dirs = dirs;
526         do_list_fn = fn;
527
528         if (rec)
529         {
530                 init_do_list_queue();
531                 add_to_do_list_queue(mask);
532                 
533                 while (! do_list_queue_empty())
534                 {
535                         /*
536                          * Need to copy head so that it doesn't become
537                          * invalid inside the call to cli_list.  This
538                          * would happen if the list were expanded
539                          * during the call.
540                          * Fix from E. Jay Berkenbilt (ejb@ql.org)
541                          */
542                         pstring head;
543                         pstrcpy(head, do_list_queue_head());
544                         cli_list(cli, head, attribute, do_list_helper, NULL);
545                         remove_do_list_queue_head();
546                         if ((! do_list_queue_empty()) && (fn == display_finfo))
547                         {
548                                 char* next_file = do_list_queue_head();
549                                 char* save_ch = 0;
550                                 if ((strlen(next_file) >= 2) &&
551                                     (next_file[strlen(next_file) - 1] == '*') &&
552                                     (next_file[strlen(next_file) - 2] == '\\'))
553                                 {
554                                         save_ch = next_file +
555                                                 strlen(next_file) - 2;
556                                         *save_ch = '\0';
557                                 }
558                                 DEBUG(0,("\n%s\n",next_file));
559                                 if (save_ch)
560                                 {
561                                         *save_ch = '\\';
562                                 }
563                         }
564                 }
565         }
566         else
567         {
568                 if (cli_list(cli, mask, attribute, do_list_helper, NULL) == -1)
569                 {
570                         DEBUG(0, ("%s listing %s\n", cli_errstr(cli), mask));
571                 }
572         }
573
574         in_do_list = 0;
575         reset_do_list_queue();
576 }
577
578 /****************************************************************************
579   get a directory listing
580   ****************************************************************************/
581 static void cmd_dir(void)
582 {
583         uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
584         pstring mask;
585         fstring buf;
586         char *p=buf;
587         
588         dir_total = 0;
589         pstrcpy(mask,cur_dir);
590         if(mask[strlen(mask)-1]!='\\')
591                 pstrcat(mask,"\\");
592         
593         if (next_token(NULL,buf,NULL,sizeof(buf))) {
594                 dos_format(p);
595                 if (*p == '\\')
596                         pstrcpy(mask,p);
597                 else
598                         pstrcat(mask,p);
599         }
600         else {
601                 pstrcat(mask,"*");
602         }
603
604         do_list(mask, attribute, display_finfo, recurse, True);
605
606         do_dskattr();
607
608         DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
609 }
610
611
612 /****************************************************************************
613   get a directory listing
614   ****************************************************************************/
615 static void cmd_du(void)
616 {
617         uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
618         pstring mask;
619         fstring buf;
620         char *p=buf;
621         
622         dir_total = 0;
623         pstrcpy(mask,cur_dir);
624         if(mask[strlen(mask)-1]!='\\')
625                 pstrcat(mask,"\\");
626         
627         if (next_token(NULL,buf,NULL,sizeof(buf))) {
628                 dos_format(p);
629                 if (*p == '\\')
630                         pstrcpy(mask,p);
631                 else
632                         pstrcat(mask,p);
633         } else {
634                 pstrcat(mask,"*");
635         }
636
637         do_list(mask, attribute, do_du, recurse, True);
638
639         do_dskattr();
640
641         DEBUG(0, ("Total number of bytes: %.0f\n", dir_total));
642 }
643
644
645 /****************************************************************************
646   get a file from rname to lname
647   ****************************************************************************/
648 static void do_get(char *rname,char *lname)
649 {  
650         int handle=0,fnum;
651         BOOL newhandle = False;
652         char *data;
653         struct timeval tp_start;
654         int read_size = io_bufsize;
655         uint16 attr;
656         size_t size;
657         off_t nread = 0;
658
659         GetTimeOfDay(&tp_start);
660
661         if (lowercase) {
662                 strlower(lname);
663         }
664
665         fnum = cli_open(cli, rname, O_RDONLY, DENY_NONE);
666
667         if (fnum == -1) {
668                 DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),rname));
669                 return;
670         }
671
672         if(!strcmp(lname,"-")) {
673                 handle = fileno(stdout);
674         } else {
675                 handle = sys_open(lname,O_WRONLY|O_CREAT|O_TRUNC,0644);
676                 newhandle = True;
677         }
678         if (handle < 0) {
679                 DEBUG(0,("Error opening local file %s\n",lname));
680                 return;
681         }
682
683
684         if (!cli_qfileinfo(cli, fnum, 
685                            &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
686             !cli_getattrE(cli, fnum, 
687                           &attr, &size, NULL, NULL, NULL)) {
688                 DEBUG(0,("getattrib: %s\n",cli_errstr(cli)));
689                 return;
690         }
691
692         DEBUG(2,("getting file %s of size %.0f as %s ", 
693                  lname, (double)size, lname));
694
695         if(!(data = (char *)malloc(read_size))) { 
696                 DEBUG(0,("malloc fail for size %d\n", read_size));
697                 cli_close(cli, fnum);
698                 return;
699         }
700
701         while (1) {
702                 int n = cli_read(cli, fnum, data, nread, read_size);
703
704                 if (n <= 0) break;
705  
706                 if (writefile(handle,data, n) != n) {
707                         DEBUG(0,("Error writing local file\n"));
708                         break;
709                 }
710       
711                 nread += n;
712         }
713
714         if (nread < size) {
715                 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
716                rname, (long)nread));
717         }
718
719         free(data);
720         
721         if (!cli_close(cli, fnum)) {
722                 DEBUG(0,("Error %s closing remote file\n",cli_errstr(cli)));
723         }
724
725         if (newhandle) {
726                 close(handle);
727         }
728
729         if (archive_level >= 2 && (attr & aARCH)) {
730                 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
731         }
732
733         {
734                 struct timeval tp_end;
735                 int this_time;
736                 
737                 GetTimeOfDay(&tp_end);
738                 this_time = 
739                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
740                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
741                 get_total_time_ms += this_time;
742                 get_total_size += nread;
743                 
744                 DEBUG(2,("(%3.1f kb/s) (average %3.1f kb/s)\n",
745                          nread / (1.024*this_time + 1.0e-4),
746                          get_total_size / (1.024*get_total_time_ms)));
747         }
748 }
749
750
751 /****************************************************************************
752   get a file
753   ****************************************************************************/
754 static void cmd_get(void)
755 {
756         pstring lname;
757         pstring rname;
758         char *p;
759
760         pstrcpy(rname,cur_dir);
761         pstrcat(rname,"\\");
762         
763         p = rname + strlen(rname);
764         
765         if (!next_token(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
766                 DEBUG(0,("get <filename>\n"));
767                 return;
768         }
769         pstrcpy(lname,p);
770         dos_clean_name(rname);
771         
772         next_token(NULL,lname,NULL,sizeof(lname));
773         
774         do_get(rname, lname);
775 }
776
777
778 /****************************************************************************
779   do a mget operation on one file
780   ****************************************************************************/
781 static void do_mget(file_info *finfo)
782 {
783         pstring rname;
784         pstring quest;
785         pstring saved_curdir;
786         pstring mget_mask;
787
788         if (strequal(finfo->name,".") || strequal(finfo->name,".."))
789                 return;
790
791         if (abort_mget) {
792                 DEBUG(0,("mget aborted\n"));
793                 return;
794         }
795
796         if (finfo->mode & aDIR)
797                 slprintf(quest,sizeof(pstring)-1,
798                          "Get directory %s? ",finfo->name);
799         else
800                 slprintf(quest,sizeof(pstring)-1,
801                          "Get file %s? ",finfo->name);
802
803         if (prompt && !yesno(quest)) return;
804
805         if (!(finfo->mode & aDIR)) {
806                 pstrcpy(rname,cur_dir);
807                 pstrcat(rname,finfo->name);
808                 do_get(rname,finfo->name);
809                 return;
810         }
811
812         /* handle directories */
813         pstrcpy(saved_curdir,cur_dir);
814
815         pstrcat(cur_dir,finfo->name);
816         pstrcat(cur_dir,"\\");
817
818         unix_format(finfo->name);
819         if (lowercase)
820                 strlower(finfo->name);
821         
822         if (!directory_exist(finfo->name,NULL) && 
823             mkdir(finfo->name,0777) != 0) {
824                 DEBUG(0,("failed to create directory %s\n",finfo->name));
825                 pstrcpy(cur_dir,saved_curdir);
826                 return;
827         }
828         
829         if (chdir(finfo->name) != 0) {
830                 DEBUG(0,("failed to chdir to directory %s\n",finfo->name));
831                 pstrcpy(cur_dir,saved_curdir);
832                 return;
833         }
834
835         pstrcpy(mget_mask,cur_dir);
836         pstrcat(mget_mask,"*");
837         
838         do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,False, True);
839         chdir("..");
840         pstrcpy(cur_dir,saved_curdir);
841 }
842
843
844 /****************************************************************************
845 view the file using the pager
846 ****************************************************************************/
847 static void cmd_more(void)
848 {
849         fstring rname,lname,tmpname,pager_cmd;
850         char *pager;
851
852         fstrcpy(rname,cur_dir);
853         fstrcat(rname,"\\");
854         slprintf(tmpname,
855                  sizeof(fstring)-1,
856                  "%s/smbmore.%d",tmpdir(),(int)sys_getpid());
857         fstrcpy(lname,tmpname);
858         
859         if (!next_token(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
860                 DEBUG(0,("more <filename>\n"));
861                 return;
862         }
863         dos_clean_name(rname);
864
865         do_get(rname,lname);
866
867         pager=getenv("PAGER");
868
869         slprintf(pager_cmd,sizeof(pager_cmd)-1,
870                  "%s %s",(pager? pager:PAGER), tmpname);
871         system(pager_cmd);
872         unlink(tmpname);
873 }
874
875
876
877 /****************************************************************************
878 do a mget command
879 ****************************************************************************/
880 static void cmd_mget(void)
881 {
882         uint16 attribute = aSYSTEM | aHIDDEN;
883         pstring mget_mask;
884         fstring buf;
885         char *p=buf;
886
887         *mget_mask = 0;
888
889         if (recurse)
890                 attribute |= aDIR;
891         
892         abort_mget = False;
893
894         while (next_token(NULL,p,NULL,sizeof(buf))) {
895                 pstrcpy(mget_mask,cur_dir);
896                 if(mget_mask[strlen(mget_mask)-1]!='\\')
897                         pstrcat(mget_mask,"\\");
898                 
899                 if (*p == '\\')
900                         pstrcpy(mget_mask,p);
901                 else
902                         pstrcat(mget_mask,p);
903                 do_list(mget_mask, attribute,do_mget,False,True);
904         }
905
906         if (!*mget_mask) {
907                 pstrcpy(mget_mask,cur_dir);
908                 if(mget_mask[strlen(mget_mask)-1]!='\\')
909                         pstrcat(mget_mask,"\\");
910                 pstrcat(mget_mask,"*");
911                 do_list(mget_mask, attribute,do_mget,False,True);
912         }
913 }
914
915
916 /****************************************************************************
917 make a directory of name "name"
918 ****************************************************************************/
919 static BOOL do_mkdir(char *name)
920 {
921         if (!cli_mkdir(cli, name)) {
922                 DEBUG(0,("%s making remote directory %s\n",
923                          cli_errstr(cli),name));
924                 return(False);
925         }
926
927         return(True);
928 }
929
930
931 /****************************************************************************
932  Exit client.
933 ****************************************************************************/
934 static void cmd_quit(void)
935 {
936         smb_readline_remove_handler();
937         cli_shutdown(cli);
938         exit(0);
939 }
940
941
942 /****************************************************************************
943   make a directory
944   ****************************************************************************/
945 static void cmd_mkdir(void)
946 {
947         pstring mask;
948         fstring buf;
949         char *p=buf;
950   
951         pstrcpy(mask,cur_dir);
952
953         if (!next_token(NULL,p,NULL,sizeof(buf))) {
954                 if (!recurse)
955                         DEBUG(0,("mkdir <dirname>\n"));
956                 return;
957         }
958         pstrcat(mask,p);
959
960         if (recurse) {
961                 pstring ddir;
962                 pstring ddir2;
963                 *ddir2 = 0;
964                 
965                 pstrcpy(ddir,mask);
966                 trim_string(ddir,".",NULL);
967                 p = strtok(ddir,"/\\");
968                 while (p) {
969                         pstrcat(ddir2,p);
970                         if (!cli_chkpath(cli, ddir2)) { 
971                                 do_mkdir(ddir2);
972                         }
973                         pstrcat(ddir2,"\\");
974                         p = strtok(NULL,"/\\");
975                 }        
976         } else {
977                 do_mkdir(mask);
978         }
979 }
980
981
982 /****************************************************************************
983   put a single file
984   ****************************************************************************/
985 static void do_put(char *rname,char *lname)
986 {
987         int fnum;
988         FILE *f;
989         int nread=0;
990         char *buf=NULL;
991         int maxwrite=io_bufsize;
992         
993         struct timeval tp_start;
994         GetTimeOfDay(&tp_start);
995
996         fnum = cli_open(cli, rname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
997   
998         if (fnum == -1) {
999                 DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),rname));
1000                 return;
1001         }
1002
1003         /* allow files to be piped into smbclient
1004            jdblair 24.jun.98 */
1005         if (!strcmp(lname, "-")) {
1006                 f = stdin;
1007                 /* size of file is not known */
1008         } else {
1009                 f = sys_fopen(lname,"r");
1010         }
1011
1012         if (!f) {
1013                 DEBUG(0,("Error opening local file %s\n",lname));
1014                 return;
1015         }
1016
1017   
1018         DEBUG(1,("putting file %s as %s ",lname,
1019                  rname));
1020   
1021         buf = (char *)malloc(maxwrite);
1022         while (!feof(f)) {
1023                 int n = maxwrite;
1024                 int ret;
1025
1026                 if ((n = readfile(buf,1,n,f)) < 1) {
1027                         if((n == 0) && feof(f))
1028                                 break; /* Empty local file. */
1029
1030                         DEBUG(0,("Error reading local file: %s\n", strerror(errno) ));
1031                         break;
1032                 }
1033
1034                 ret = cli_write(cli, fnum, 0, buf, nread, n);
1035
1036                 if (n != ret) {
1037                         DEBUG(0,("Error writing file: %s\n", cli_errstr(cli)));
1038                         break;
1039                 } 
1040
1041                 nread += n;
1042         }
1043
1044         if (!cli_close(cli, fnum)) {
1045                 DEBUG(0,("%s closing remote file %s\n",cli_errstr(cli),rname));
1046                 fclose(f);
1047                 if (buf) free(buf);
1048                 return;
1049         }
1050
1051         
1052         fclose(f);
1053         if (buf) free(buf);
1054
1055         {
1056                 struct timeval tp_end;
1057                 int this_time;
1058                 
1059                 GetTimeOfDay(&tp_end);
1060                 this_time = 
1061                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1062                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
1063                 put_total_time_ms += this_time;
1064                 put_total_size += nread;
1065                 
1066                 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1067                          nread / (1.024*this_time + 1.0e-4),
1068                          put_total_size / (1.024*put_total_time_ms)));
1069         }
1070
1071         if (f == stdin) {
1072                 cli_shutdown(cli);
1073                 exit(0);
1074         }
1075 }
1076
1077  
1078
1079 /****************************************************************************
1080   put a file
1081   ****************************************************************************/
1082 static void cmd_put(void)
1083 {
1084         pstring lname;
1085         pstring rname;
1086         fstring buf;
1087         char *p=buf;
1088         
1089         pstrcpy(rname,cur_dir);
1090         pstrcat(rname,"\\");
1091   
1092         if (!next_token(NULL,p,NULL,sizeof(buf))) {
1093                 DEBUG(0,("put <filename>\n"));
1094                 return;
1095         }
1096         pstrcpy(lname,p);
1097   
1098         if (next_token(NULL,p,NULL,sizeof(buf)))
1099                 pstrcat(rname,p);      
1100         else
1101                 pstrcat(rname,lname);
1102         
1103         dos_clean_name(rname);
1104
1105         {
1106                 SMB_STRUCT_STAT st;
1107                 /* allow '-' to represent stdin
1108                    jdblair, 24.jun.98 */
1109                 if (!file_exist(lname,&st) &&
1110                     (strcmp(lname,"-"))) {
1111                         DEBUG(0,("%s does not exist\n",lname));
1112                         return;
1113                 }
1114         }
1115
1116         do_put(rname,lname);
1117 }
1118
1119
1120 /****************************************************************************
1121   seek in a directory/file list until you get something that doesn't start with
1122   the specified name
1123   ****************************************************************************/
1124 static BOOL seek_list(FILE *f,char *name)
1125 {
1126         pstring s;
1127         while (!feof(f)) {
1128                 if (!fgets(s,sizeof(s),f)) return(False);
1129                 trim_string(s,"./","\n");
1130                 if (strncmp(s,name,strlen(name)) != 0) {
1131                         pstrcpy(name,s);
1132                         return(True);
1133                 }
1134         }
1135       
1136         return(False);
1137 }
1138
1139
1140 /****************************************************************************
1141   set the file selection mask
1142   ****************************************************************************/
1143 static void cmd_select(void)
1144 {
1145         pstrcpy(fileselection,"");
1146         next_token(NULL,fileselection,NULL,sizeof(fileselection));
1147 }
1148
1149
1150 /****************************************************************************
1151   mput some files
1152   ****************************************************************************/
1153 static void cmd_mput(void)
1154 {
1155         pstring lname;
1156         pstring rname;
1157         fstring buf;
1158         char *p=buf;
1159         
1160         while (next_token(NULL,p,NULL,sizeof(buf))) {
1161                 SMB_STRUCT_STAT st;
1162                 pstring cmd;
1163                 pstring tmpname;
1164                 FILE *f;
1165                 
1166                 slprintf(tmpname,sizeof(pstring)-1,
1167                          "%s/ls.smb.%d",tmpdir(),(int)sys_getpid());
1168                 if (recurse)
1169                         slprintf(cmd,sizeof(pstring)-1,
1170                                 "find . -name \"%s\" -print > %s",p,tmpname);
1171                 else
1172                         slprintf(cmd,sizeof(pstring)-1,
1173                                 "find . -maxdepth 1 -name \"%s\" -print > %s",p,tmpname);
1174                 system(cmd);
1175
1176                 f = sys_fopen(tmpname,"r");
1177                 if (!f) continue;
1178                 
1179                 while (!feof(f)) {
1180                         pstring quest;
1181
1182                         if (!fgets(lname,sizeof(lname),f)) break;
1183                         trim_string(lname,"./","\n");
1184                         
1185                 again1:
1186                         
1187                         /* check if it's a directory */
1188                         if (directory_exist(lname,&st)) {
1189                                 if (!recurse) continue;
1190                                 slprintf(quest,sizeof(pstring)-1,
1191                                          "Put directory %s? ",lname);
1192                                 if (prompt && !yesno(quest)) {
1193                                         pstrcat(lname,"/");
1194                                         if (!seek_list(f,lname))
1195                                                 break;
1196                                         goto again1;                
1197                                 }
1198               
1199                                 pstrcpy(rname,cur_dir);
1200                                 pstrcat(rname,lname);
1201                                 dos_format(rname);
1202                                 if (!cli_chkpath(cli, rname) && !do_mkdir(rname)) {
1203                                         pstrcat(lname,"/");
1204                                         if (!seek_list(f,lname))
1205                                                 break;
1206                                         goto again1;
1207                                 }
1208                                 continue;
1209                         } else {
1210                                 slprintf(quest,sizeof(quest)-1,
1211                                          "Put file %s? ",lname);
1212                                 if (prompt && !yesno(quest)) continue;
1213                                 
1214                                 pstrcpy(rname,cur_dir);
1215                                 pstrcat(rname,lname);
1216                         }
1217
1218                         dos_format(rname);
1219
1220                         do_put(rname,lname);
1221                 }
1222                 fclose(f);
1223                 unlink(tmpname);
1224         }
1225 }
1226
1227
1228 /****************************************************************************
1229   cancel a print job
1230   ****************************************************************************/
1231 static void do_cancel(int job)
1232 {
1233         if (cli_printjob_del(cli, job)) {
1234                 printf("Job %d cancelled\n",job);
1235         } else {
1236                 printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1237         }
1238 }
1239
1240
1241 /****************************************************************************
1242   cancel a print job
1243   ****************************************************************************/
1244 static void cmd_cancel(void)
1245 {
1246         fstring buf;
1247         int job; 
1248
1249         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1250                 printf("cancel <jobid> ...\n");
1251                 return;
1252         }
1253         do {
1254                 job = atoi(buf);
1255                 do_cancel(job);
1256         } while (next_token(NULL,buf,NULL,sizeof(buf)));
1257 }
1258
1259
1260 /****************************************************************************
1261   print a file
1262   ****************************************************************************/
1263 static void cmd_print(void)
1264 {
1265         pstring lname;
1266         pstring rname;
1267         char *p;
1268
1269         if (!next_token(NULL,lname,NULL, sizeof(lname))) {
1270                 DEBUG(0,("print <filename>\n"));
1271                 return;
1272         }
1273
1274         pstrcpy(rname,lname);
1275         p = strrchr(rname,'/');
1276         if (p) {
1277                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)sys_getpid());
1278         }
1279
1280         if (strequal(lname,"-")) {
1281                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)sys_getpid());
1282         }
1283
1284         do_put(rname, lname);
1285 }
1286
1287
1288 /****************************************************************************
1289  show a print queue entry
1290 ****************************************************************************/
1291 static void queue_fn(struct print_job_info *p)
1292 {
1293         DEBUG(0,("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name));
1294 }
1295
1296 /****************************************************************************
1297  show a print queue
1298 ****************************************************************************/
1299 static void cmd_queue(void)
1300 {
1301         cli_print_queue(cli, queue_fn);  
1302 }
1303
1304 /****************************************************************************
1305 delete some files
1306 ****************************************************************************/
1307 static void do_del(file_info *finfo)
1308 {
1309         pstring mask;
1310
1311         pstrcpy(mask,cur_dir);
1312         pstrcat(mask,finfo->name);
1313
1314         if (finfo->mode & aDIR) 
1315                 return;
1316
1317         if (!cli_unlink(cli, mask)) {
1318                 DEBUG(0,("%s deleting remote file %s\n",cli_errstr(cli),mask));
1319         }
1320 }
1321
1322 /****************************************************************************
1323 delete some files
1324 ****************************************************************************/
1325 static void cmd_del(void)
1326 {
1327         pstring mask;
1328         fstring buf;
1329         uint16 attribute = aSYSTEM | aHIDDEN;
1330
1331         if (recurse)
1332                 attribute |= aDIR;
1333         
1334         pstrcpy(mask,cur_dir);
1335         
1336         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1337                 DEBUG(0,("del <filename>\n"));
1338                 return;
1339         }
1340         pstrcat(mask,buf);
1341
1342         do_list(mask, attribute,do_del,False,False);
1343 }
1344
1345 /****************************************************************************
1346 ****************************************************************************/
1347 static void cmd_open(void)
1348 {
1349         pstring mask;
1350         fstring buf;
1351         
1352         pstrcpy(mask,cur_dir);
1353         
1354         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1355                 DEBUG(0,("del <filename>\n"));
1356                 return;
1357         }
1358         pstrcat(mask,buf);
1359
1360         cli_open(cli, mask, O_RDWR, DENY_ALL);
1361 }
1362
1363
1364 /****************************************************************************
1365 remove a directory
1366 ****************************************************************************/
1367 static void cmd_rmdir(void)
1368 {
1369         pstring mask;
1370         fstring buf;
1371   
1372         pstrcpy(mask,cur_dir);
1373         
1374         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1375                 DEBUG(0,("rmdir <dirname>\n"));
1376                 return;
1377         }
1378         pstrcat(mask,buf);
1379
1380         if (!cli_rmdir(cli, mask)) {
1381                 DEBUG(0,("%s removing remote directory file %s\n",
1382                          cli_errstr(cli),mask));
1383         }  
1384 }
1385
1386 /****************************************************************************
1387 rename some files
1388 ****************************************************************************/
1389 static void cmd_rename(void)
1390 {
1391         pstring src,dest;
1392         fstring buf,buf2;
1393   
1394         pstrcpy(src,cur_dir);
1395         pstrcpy(dest,cur_dir);
1396         
1397         if (!next_token(NULL,buf,NULL,sizeof(buf)) || 
1398             !next_token(NULL,buf2,NULL, sizeof(buf2))) {
1399                 DEBUG(0,("rename <src> <dest>\n"));
1400                 return;
1401         }
1402
1403         pstrcat(src,buf);
1404         pstrcat(dest,buf2);
1405
1406         if (!cli_rename(cli, src, dest)) {
1407                 DEBUG(0,("%s renaming files\n",cli_errstr(cli)));
1408                 return;
1409         }  
1410 }
1411
1412
1413 /****************************************************************************
1414 toggle the prompt flag
1415 ****************************************************************************/
1416 static void cmd_prompt(void)
1417 {
1418         prompt = !prompt;
1419         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
1420 }
1421
1422
1423 /****************************************************************************
1424 set the newer than time
1425 ****************************************************************************/
1426 static void cmd_newer(void)
1427 {
1428         fstring buf;
1429         BOOL ok;
1430         SMB_STRUCT_STAT sbuf;
1431
1432         ok = next_token(NULL,buf,NULL,sizeof(buf));
1433         if (ok && (sys_stat(buf,&sbuf) == 0)) {
1434                 newer_than = sbuf.st_mtime;
1435                 DEBUG(1,("Getting files newer than %s",
1436                          asctime(LocalTime(&newer_than))));
1437         } else {
1438                 newer_than = 0;
1439         }
1440
1441         if (ok && newer_than == 0)
1442                 DEBUG(0,("Error setting newer-than time\n"));
1443 }
1444
1445 /****************************************************************************
1446 set the archive level
1447 ****************************************************************************/
1448 static void cmd_archive(void)
1449 {
1450         fstring buf;
1451
1452         if (next_token(NULL,buf,NULL,sizeof(buf))) {
1453                 archive_level = atoi(buf);
1454         } else
1455                 DEBUG(0,("Archive level is %d\n",archive_level));
1456 }
1457
1458 /****************************************************************************
1459 toggle the lowercaseflag
1460 ****************************************************************************/
1461 static void cmd_lowercase(void)
1462 {
1463         lowercase = !lowercase;
1464         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
1465 }
1466
1467
1468
1469
1470 /****************************************************************************
1471 toggle the recurse flag
1472 ****************************************************************************/
1473 static void cmd_recurse(void)
1474 {
1475         recurse = !recurse;
1476         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
1477 }
1478
1479 /****************************************************************************
1480 toggle the translate flag
1481 ****************************************************************************/
1482 static void cmd_translate(void)
1483 {
1484         translation = !translation;
1485         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
1486                  translation?"on":"off"));
1487 }
1488
1489
1490 /****************************************************************************
1491 do a printmode command
1492 ****************************************************************************/
1493 static void cmd_printmode(void)
1494 {
1495         fstring buf;
1496         fstring mode;
1497
1498         if (next_token(NULL,buf,NULL,sizeof(buf))) {
1499                 if (strequal(buf,"text")) {
1500                         printmode = 0;      
1501                 } else {
1502                         if (strequal(buf,"graphics"))
1503                                 printmode = 1;
1504                         else
1505                                 printmode = atoi(buf);
1506                 }
1507         }
1508
1509         switch(printmode)
1510                 {
1511                 case 0: 
1512                         fstrcpy(mode,"text");
1513                         break;
1514                 case 1: 
1515                         fstrcpy(mode,"graphics");
1516                         break;
1517                 default: 
1518                         slprintf(mode,sizeof(mode)-1,"%d",printmode);
1519                         break;
1520                 }
1521         
1522         DEBUG(2,("the printmode is now %s\n",mode));
1523 }
1524
1525 /****************************************************************************
1526 do the lcd command
1527 ****************************************************************************/
1528 static void cmd_lcd(void)
1529 {
1530         fstring buf;
1531         pstring d;
1532         
1533         if (next_token(NULL,buf,NULL,sizeof(buf)))
1534                 chdir(buf);
1535         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
1536 }
1537
1538 /****************************************************************************
1539 list a share name
1540 ****************************************************************************/
1541 static void browse_fn(const char *name, uint32 m, 
1542                       const char *comment, void *state)
1543 {
1544         fstring typestr;
1545
1546         *typestr=0;
1547
1548         switch (m)
1549         {
1550           case STYPE_DISKTREE:
1551             fstrcpy(typestr,"Disk"); break;
1552           case STYPE_PRINTQ:
1553             fstrcpy(typestr,"Printer"); break;
1554           case STYPE_DEVICE:
1555             fstrcpy(typestr,"Device"); break;
1556           case STYPE_IPC:
1557             fstrcpy(typestr,"IPC"); break;
1558         }
1559
1560         printf("\t%-15.15s%-10.10s%s\n",
1561                name, typestr,comment);
1562 }
1563
1564
1565 /****************************************************************************
1566 try and browse available connections on a host
1567 ****************************************************************************/
1568 static BOOL browse_host(BOOL sort)
1569 {
1570         int ret;
1571
1572         printf("\n\tSharename      Type      Comment\n");
1573         printf("\t---------      ----      -------\n");
1574
1575         if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
1576                 printf("Error returning browse list: %s\n", cli_errstr(cli));
1577
1578         return (ret != -1);
1579 }
1580
1581 /****************************************************************************
1582 list a server name
1583 ****************************************************************************/
1584 static void server_fn(const char *name, uint32 m, 
1585                       const char *comment, void *state)
1586 {
1587         printf("\t%-16.16s     %s\n", name, comment);
1588 }
1589
1590 /****************************************************************************
1591 try and browse available connections on a host
1592 ****************************************************************************/
1593 static BOOL list_servers(char *wk_grp)
1594 {
1595         if (!cli->server_domain) return False;
1596
1597         printf("\n\tServer               Comment\n");
1598         printf("\t---------            -------\n");
1599
1600         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn, NULL);
1601
1602         printf("\n\tWorkgroup            Master\n");
1603         printf("\t---------            -------\n");
1604
1605         cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM, server_fn, NULL);
1606         return True;
1607 }
1608
1609 /* Some constants for completing filename arguments */
1610
1611 #define COMPL_NONE        0          /* No completions */
1612 #define COMPL_REMOTE      1          /* Complete remote filename */
1613 #define COMPL_LOCAL       2          /* Complete local filename */
1614
1615 /* This defines the commands supported by this client */
1616 struct
1617 {
1618   char *name;
1619   void (*fn)(void);
1620   char *description;
1621   char compl_args[2];      /* Completion argument info */
1622 } commands[] = 
1623 {
1624   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1625   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1626   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1627   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
1628   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
1629   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
1630   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
1631   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
1632   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
1633   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
1634   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
1635   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
1636   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
1637   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
1638   {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
1639   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
1640   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
1641   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
1642   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
1643   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
1644   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
1645   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
1646   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},  
1647   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
1648   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
1649   {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
1650   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
1651   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
1652   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1653   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1654   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1655   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
1656   {"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}},
1657   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
1658   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
1659   {"tarmode",cmd_tarmode,
1660      "<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
1661   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
1662   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
1663   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
1664   {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
1665   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
1666   {"",NULL,NULL,{COMPL_NONE,COMPL_NONE}}
1667 };
1668
1669
1670 /*******************************************************************
1671   lookup a command string in the list of commands, including 
1672   abbreviations
1673   ******************************************************************/
1674 static int process_tok(fstring tok)
1675 {
1676         int i = 0, matches = 0;
1677         int cmd=0;
1678         int tok_len = strlen(tok);
1679         
1680         while (commands[i].fn != NULL) {
1681                 if (strequal(commands[i].name,tok)) {
1682                         matches = 1;
1683                         cmd = i;
1684                         break;
1685                 } else if (strnequal(commands[i].name, tok, tok_len)) {
1686                         matches++;
1687                         cmd = i;
1688                 }
1689                 i++;
1690         }
1691   
1692         if (matches == 0)
1693                 return(-1);
1694         else if (matches == 1)
1695                 return(cmd);
1696         else
1697                 return(-2);
1698 }
1699
1700 /****************************************************************************
1701 help
1702 ****************************************************************************/
1703 static void cmd_help(void)
1704 {
1705         int i=0,j;
1706         fstring buf;
1707         
1708         if (next_token(NULL,buf,NULL,sizeof(buf))) {
1709                 if ((i = process_tok(buf)) >= 0)
1710                         DEBUG(0,("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description));                   
1711         } else {
1712                 while (commands[i].description) {
1713                         for (j=0; commands[i].description && (j<5); j++) {
1714                                 DEBUG(0,("%-15s",commands[i].name));
1715                                 i++;
1716                         }
1717                         DEBUG(0,("\n"));
1718                 }
1719         }
1720 }
1721
1722 /****************************************************************************
1723 wait for keyboard activity, swallowing network packets
1724 ****************************************************************************/
1725 static void wait_keyboard(void)
1726 {
1727         fd_set fds;
1728         struct timeval timeout;
1729   
1730         while (1) {
1731                 FD_ZERO(&fds);
1732                 FD_SET(cli->fd,&fds);
1733                 FD_SET(fileno(stdin),&fds);
1734
1735                 timeout.tv_sec = 20;
1736                 timeout.tv_usec = 0;
1737                 sys_select_intr(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
1738                 
1739                 if (FD_ISSET(fileno(stdin),&fds))
1740                 {
1741                         smb_rl_read_char();
1742                         if (readline_event != RL_NO_EVENTS) return;
1743                 }
1744
1745                 /* We deliberately use receive_smb instead of
1746                    client_receive_smb as we want to receive
1747                    session keepalives and then drop them here.
1748                 */
1749                 if (FD_ISSET(cli->fd,&fds))
1750                         receive_smb(cli->fd,cli->inbuf,0);
1751       
1752                 cli_chkpath(cli, "\\");
1753         }  
1754 }
1755
1756 /****************************************************************************
1757 process a -c command string
1758 ****************************************************************************/
1759 static void process_command_string(char *cmd)
1760 {
1761         pstring line;
1762         char *ptr;
1763
1764         while (cmd[0] != '\0')    {
1765                 char *p;
1766                 fstring tok;
1767                 int i;
1768                 
1769                 if ((p = strchr(cmd, ';')) == 0) {
1770                         strncpy(line, cmd, 999);
1771                         line[1000] = '\0';
1772                         cmd += strlen(cmd);
1773                 } else {
1774                         if (p - cmd > 999) p = cmd + 999;
1775                         strncpy(line, cmd, p - cmd);
1776                         line[p - cmd] = '\0';
1777                         cmd = p + 1;
1778                 }
1779                 
1780                 /* and get the first part of the command */
1781                 ptr = line;
1782                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
1783                 
1784                 if ((i = process_tok(tok)) >= 0) {
1785                         commands[i].fn();
1786                 } else if (i == -2) {
1787                         DEBUG(0,("%s: command abbreviation ambiguous\n",tok));
1788                 } else {
1789                         DEBUG(0,("%s: command not found\n",tok));
1790                 }
1791         }
1792 }       
1793
1794
1795 /****************************************************************************
1796 process commands on stdin
1797 ****************************************************************************/
1798 static void process_stdin(void)
1799 {
1800         char *ptr;
1801
1802         init_smb_readline("smbclient", command_line, &readline_event);
1803         
1804         while (!feof(stdin)) {
1805                 fstring tok;
1806                 fstring prompt;
1807                 int i;
1808                 
1809                 /* display a prompt */
1810                 slprintf(prompt, sizeof(prompt), "smb: %s> ", cur_dir);
1811                 smb_readline_prompt(prompt);
1812
1813                 wait_keyboard();
1814
1815                 if (readline_event == RL_GOT_EOF) /* got an eof */
1816                         break;
1817
1818                 /* special case - first char is ! */
1819                 if (*command_line == '!') {
1820                         system(command_line + 1);
1821                         continue;
1822                 }
1823       
1824                 /* and get the first part of the command */
1825                 ptr = command_line;
1826                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
1827
1828                 if ((i = process_tok(tok)) >= 0) {
1829                         commands[i].fn();
1830                 } else if (i == -2) {
1831                         DEBUG(0,("%s: command abbreviation ambiguous\n",tok));
1832                 } else {
1833                         DEBUG(0,("%s: command not found\n",tok));
1834                 }
1835         }
1836         smb_readline_remove_handler ();
1837 }
1838
1839
1840 /***************************************************** 
1841 return a connection to a server
1842 *******************************************************/
1843 struct cli_state *do_connect(char *server, char *share)
1844 {
1845         struct cli_state *c;
1846         struct nmb_name called, calling;
1847         char *server_n;
1848         struct in_addr ip;
1849         extern struct in_addr ipzero;
1850         fstring servicename;
1851         char *sharename;
1852         
1853         /* make a copy so we don't modify the global string 'service' */
1854         safe_strcpy(servicename, share, sizeof(servicename)-1);
1855         sharename = servicename;
1856         if (*sharename == '\\') {
1857                 server = sharename+2;
1858                 sharename = strchr(server,'\\');
1859                 if (!sharename) return NULL;
1860                 *sharename = 0;
1861                 sharename++;
1862         }
1863
1864         server_n = server;
1865         
1866         ip = ipzero;
1867
1868         make_nmb_name(&calling, global_myname, 0x0);
1869         make_nmb_name(&called , server, name_type);
1870
1871  again:
1872         ip = ipzero;
1873         if (have_ip) ip = dest_ip;
1874
1875         /* have to open a new connection */
1876         if (!(c=cli_initialise(NULL)) || (cli_set_port(c, port) == 0) ||
1877             !cli_connect(c, server_n, &ip)) {
1878                 DEBUG(0,("Connection to %s failed\n", server_n));
1879                 return NULL;
1880         }
1881
1882         c->protocol = max_protocol;
1883
1884         if (!cli_session_request(c, &calling, &called)) {
1885                 char *p;
1886                 DEBUG(0,("session request to %s failed (%s)\n", 
1887                          called.name, cli_errstr(c)));
1888                 cli_shutdown(c);
1889                 free(c);
1890                 if ((p=strchr(called.name, '.'))) {
1891                         *p = 0;
1892                         goto again;
1893                 }
1894                 if (strcmp(called.name, "*SMBSERVER")) {
1895                         make_nmb_name(&called , "*SMBSERVER", 0x20);
1896                         goto again;
1897                 }
1898                 return NULL;
1899         }
1900
1901         DEBUG(4,(" session request ok\n"));
1902
1903         if (!cli_negprot(c)) {
1904                 DEBUG(0,("protocol negotiation failed\n"));
1905                 cli_shutdown(c);
1906                 free(c);
1907                 return NULL;
1908         }
1909
1910         if (!got_pass) {
1911                 char *pass = getpass("Password: ");
1912                 if (pass) {
1913                         pstrcpy(password, pass);
1914                 }
1915         }
1916
1917         if (!cli_session_setup(c, username, 
1918                                password, strlen(password),
1919                                password, strlen(password),
1920                                workgroup)) {
1921                 /* if a password was not supplied then try again with a null username */
1922                 if (password[0] || !username[0] || 
1923                     !cli_session_setup(c, "", "", 0, "", 0, workgroup)) { 
1924                         DEBUG(0,("session setup failed: %s\n", cli_errstr(c)));
1925                         cli_shutdown(c);
1926                         free(c);
1927                         return NULL;
1928                 }
1929                 DEBUG(0,("Anonymous login successful\n"));
1930         }
1931
1932         /*
1933          * These next two lines are needed to emulate
1934          * old client behaviour for people who have
1935          * scripts based on client output.
1936          * QUESTION ? Do we want to have a 'client compatibility
1937          * mode to turn these on/off ? JRA.
1938          */
1939
1940         if (*c->server_domain || *c->server_os || *c->server_type)
1941                 DEBUG(1,("Domain=[%s] OS=[%s] Server=[%s]\n",
1942                         c->server_domain,c->server_os,c->server_type));
1943         
1944         DEBUG(4,(" session setup ok\n"));
1945
1946         if (!cli_send_tconX(c, sharename, "?????",
1947                             password, strlen(password)+1)) {
1948                 DEBUG(0,("tree connect failed: %s\n", cli_errstr(c)));
1949                 cli_shutdown(c);
1950                 free(c);
1951                 return NULL;
1952         }
1953
1954         DEBUG(4,(" tconx ok\n"));
1955
1956         return c;
1957 }
1958
1959
1960 /****************************************************************************
1961   process commands from the client
1962 ****************************************************************************/
1963 static BOOL process(char *base_directory)
1964 {
1965         cli = do_connect(desthost, service);
1966         if (!cli) {
1967                 return(False);
1968         }
1969
1970         if (*base_directory) do_cd(base_directory);
1971         
1972         if (cmdstr) {
1973                 process_command_string(cmdstr);
1974         } else {
1975                 process_stdin();
1976         }
1977   
1978         cli_shutdown(cli);
1979         return(True);
1980 }
1981
1982 /****************************************************************************
1983 usage on the program
1984 ****************************************************************************/
1985 static void usage(char *pname)
1986 {
1987   DEBUG(0,("Usage: %s service <password> [options]", pname));
1988
1989   DEBUG(0,("\nVersion %s\n",VERSION));
1990   DEBUG(0,("\t-s smb.conf           pathname to smb.conf file\n"));
1991   DEBUG(0,("\t-O socket_options     socket options to use\n"));
1992   DEBUG(0,("\t-R name resolve order use these name resolution services only\n"));
1993   DEBUG(0,("\t-M host               send a winpopup message to the host\n"));
1994   DEBUG(0,("\t-i scope              use this NetBIOS scope\n"));
1995   DEBUG(0,("\t-N                    don't ask for a password\n"));
1996   DEBUG(0,("\t-n netbios name.      Use this name as my netbios name\n"));
1997   DEBUG(0,("\t-d debuglevel         set the debuglevel\n"));
1998   DEBUG(0,("\t-P                    connect to service as a printer\n"));
1999   DEBUG(0,("\t-p port               connect to the specified port\n"));
2000   DEBUG(0,("\t-l log basename.      Basename for log/debug files\n"));
2001   DEBUG(0,("\t-h                    Print this help message.\n"));
2002   DEBUG(0,("\t-I dest IP            use this IP to connect to\n"));
2003   DEBUG(0,("\t-E                    write messages to stderr instead of stdout\n"));
2004   DEBUG(0,("\t-U username           set the network username\n"));
2005   DEBUG(0,("\t-L host               get a list of shares available on a host\n"));
2006   DEBUG(0,("\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n"));
2007   DEBUG(0,("\t-m max protocol       set the max protocol level\n"));
2008   DEBUG(0,("\t-A filename           get the credentials from a file\n"));
2009   DEBUG(0,("\t-W workgroup          set the workgroup name\n"));
2010   DEBUG(0,("\t-T<c|x>IXFqgbNan      command line tar\n"));
2011   DEBUG(0,("\t-D directory          start from directory\n"));
2012   DEBUG(0,("\t-c command string     execute semicolon separated commands\n"));
2013   DEBUG(0,("\t-b xmit/send buffer   changes the transmit/send buffer (default: 65520)\n"));
2014   DEBUG(0,("\n"));
2015 }
2016
2017
2018 /****************************************************************************
2019 get a password from a a file or file descriptor
2020 exit on failure
2021 ****************************************************************************/
2022 static void get_password_file(void)
2023 {
2024         int fd = -1;
2025         char *p;
2026         BOOL close_it = False;
2027         pstring spec;
2028         char pass[128];
2029                 
2030         if ((p = getenv("PASSWD_FD")) != NULL) {
2031                 pstrcpy(spec, "descriptor ");
2032                 pstrcat(spec, p);
2033                 sscanf(p, "%d", &fd);
2034                 close_it = False;
2035         } else if ((p = getenv("PASSWD_FILE")) != NULL) {
2036                 fd = sys_open(p, O_RDONLY, 0);
2037                 pstrcpy(spec, p);
2038                 if (fd < 0) {
2039                         fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
2040                                 spec, strerror(errno));
2041                         exit(1);
2042                 }
2043                 close_it = True;
2044         }
2045
2046         for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
2047             p && p - pass < sizeof(pass);) {
2048                 switch (read(fd, p, 1)) {
2049                 case 1:
2050                         if (*p != '\n' && *p != '\0') {
2051                                 *++p = '\0'; /* advance p, and null-terminate pass */
2052                                 break;
2053                         }
2054                 case 0:
2055                         if (p - pass) {
2056                                 *p = '\0'; /* null-terminate it, just in case... */
2057                                 p = NULL; /* then force the loop condition to become false */
2058                                 break;
2059                         } else {
2060                                 fprintf(stderr, "Error reading password from file %s: %s\n",
2061                                         spec, "empty password\n");
2062                                 exit(1);
2063                         }
2064                         
2065                 default:
2066                         fprintf(stderr, "Error reading password from file %s: %s\n",
2067                                 spec, strerror(errno));
2068                         exit(1);
2069                 }
2070         }
2071         pstrcpy(password, pass);
2072         if (close_it)
2073                 close(fd);
2074 }       
2075
2076
2077
2078 /****************************************************************************
2079 handle a -L query
2080 ****************************************************************************/
2081 static int do_host_query(char *query_host)
2082 {
2083         cli = do_connect(query_host, "IPC$");
2084         if (!cli)
2085                 return 1;
2086
2087         browse_host(True);
2088         list_servers(workgroup);
2089
2090         cli_shutdown(cli);
2091         
2092         return(0);
2093 }
2094
2095
2096 /****************************************************************************
2097 handle a tar operation
2098 ****************************************************************************/
2099 static int do_tar_op(char *base_directory)
2100 {
2101         int ret;
2102         cli = do_connect(desthost, service);
2103         if (!cli)
2104                 return 1;
2105
2106         recurse=True;
2107
2108         if (*base_directory) do_cd(base_directory);
2109         
2110         ret=process_tar();
2111
2112         cli_shutdown(cli);
2113
2114         return(ret);
2115 }
2116
2117 /****************************************************************************
2118 handle a message operation
2119 ****************************************************************************/
2120 static int do_message_op(void)
2121 {
2122         struct in_addr ip;
2123         struct nmb_name called, calling;
2124
2125         ip = ipzero;
2126
2127         make_nmb_name(&calling, global_myname, 0x0);
2128         make_nmb_name(&called , desthost, name_type);
2129
2130         ip = ipzero;
2131         if (have_ip) ip = dest_ip;
2132
2133         if (!(cli=cli_initialise(NULL)) || !cli_connect(cli, desthost, &ip)) {
2134                 DEBUG(0,("Connection to %s failed\n", desthost));
2135                 return 1;
2136         }
2137
2138         if (!cli_session_request(cli, &calling, &called)) {
2139                 DEBUG(0,("session request failed\n"));
2140                 cli_shutdown(cli);
2141                 return 1;
2142         }
2143
2144         send_message();
2145         cli_shutdown(cli);
2146
2147         return 0;
2148 }
2149
2150
2151 /****************************************************************************
2152   main program
2153 ****************************************************************************/
2154  int main(int argc,char *argv[])
2155 {
2156         fstring base_directory;
2157         char *pname = argv[0];
2158         int opt;
2159         extern FILE *dbf;
2160         extern char *optarg;
2161         extern int optind;
2162         pstring query_host;
2163         BOOL message = False;
2164         extern char tar_type;
2165         static pstring servicesf = CONFIGFILE;
2166         pstring term_code;
2167         pstring new_name_resolve_order;
2168         char *p;
2169
2170 #ifdef KANJI
2171         pstrcpy(term_code, KANJI);
2172 #else /* KANJI */
2173         *term_code = 0;
2174 #endif /* KANJI */
2175
2176         *query_host = 0;
2177         *base_directory = 0;
2178
2179         *new_name_resolve_order = 0;
2180
2181         DEBUGLEVEL = 2;
2182  
2183         setup_logging(pname,True);
2184
2185         /*
2186          * If the -E option is given, be careful not to clobber stdout
2187          * before processing the options.  28.Feb.99, richard@hacom.nl.
2188          * Also pre-parse the -s option to get the service file name.
2189          */
2190
2191         for (opt = 1; opt < argc; opt++) {
2192                 if (strcmp(argv[opt], "-E") == 0)
2193                         dbf = stderr;
2194                 else if(strncmp(argv[opt], "-s", 2) == 0) {
2195                         if(argv[opt][2] != '\0')
2196                                 pstrcpy(servicesf, &argv[opt][2]);
2197                         else if(argv[opt+1] != NULL) {
2198                                 /*
2199                                  * At least one more arg left.
2200                                  */
2201                                 pstrcpy(servicesf, argv[opt+1]);
2202                         } else {
2203                                 usage(pname);
2204                                 exit(1);
2205                         }
2206                 }
2207         }
2208
2209         TimeInit();
2210         charset_initialise();
2211
2212         in_client = True;   /* Make sure that we tell lp_load we are */
2213
2214         if (!lp_load(servicesf,True,False,False)) {
2215                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
2216         }
2217         
2218         codepage_initialise(lp_client_code_page());
2219
2220 #ifdef WITH_SSL
2221         sslutil_init(0);
2222 #endif
2223
2224         pstrcpy(workgroup,lp_workgroup());
2225
2226         load_interfaces();
2227         myumask = umask(0);
2228         umask(myumask);
2229
2230         if (getenv("USER")) {
2231                 pstrcpy(username,getenv("USER"));
2232
2233                 /* modification to support userid%passwd syntax in the USER var
2234                    25.Aug.97, jdblair@uab.edu */
2235
2236                 if ((p=strchr(username,'%'))) {
2237                         *p = 0;
2238                         pstrcpy(password,p+1);
2239                         got_pass = True;
2240                         memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
2241                 }
2242                 strupper(username);
2243         }
2244
2245         /* modification to support PASSWD environmental var
2246            25.Aug.97, jdblair@uab.edu */
2247         if (getenv("PASSWD")) {
2248                 pstrcpy(password,getenv("PASSWD"));
2249                 got_pass = True;
2250         }
2251
2252         if (getenv("PASSWD_FD") || getenv("PASSWD_FILE")) {
2253                 get_password_file();
2254                 got_pass = True;
2255         }
2256
2257         if (*username == 0 && getenv("LOGNAME")) {
2258                 pstrcpy(username,getenv("LOGNAME"));
2259                 strupper(username);
2260         }
2261
2262         if (*username == 0) {
2263                 pstrcpy(username,"GUEST");
2264         }
2265
2266         if (argc < 2) {
2267                 usage(pname);
2268                 exit(1);
2269         }
2270   
2271         if (*argv[1] != '-') {
2272                 pstrcpy(service,argv[1]);  
2273                 /* Convert any '/' characters in the service name to '\' characters */
2274                 string_replace( service, '/','\\');
2275                 argc--;
2276                 argv++;
2277                 
2278                 if (count_chars(service,'\\') < 3) {
2279                         usage(pname);
2280                         printf("\n%s: Not enough '\\' characters in service\n",service);
2281                         exit(1);
2282                 }
2283
2284                 if (argc > 1 && (*argv[1] != '-')) {
2285                         got_pass = True;
2286                         pstrcpy(password,argv[1]);  
2287                         memset(argv[1],'X',strlen(argv[1]));
2288                         argc--;
2289                         argv++;
2290                 }
2291         }
2292
2293         while ((opt = 
2294                 getopt(argc, argv,"s:O:R:M:i:Nn:d:Pp:l:hI:EU:L:t:m:W:T:D:c:b:A:")) != EOF) {
2295                 switch (opt) {
2296                 case 's':
2297                         pstrcpy(servicesf, optarg);
2298                         break;
2299                 case 'O':
2300                         pstrcpy(user_socket_options,optarg);
2301                         break;  
2302                 case 'R':
2303                         pstrcpy(new_name_resolve_order, optarg);
2304                         break;
2305                 case 'M':
2306                         name_type = 0x03; /* messages are sent to NetBIOS name type 0x3 */
2307                         pstrcpy(desthost,optarg);
2308                         message = True;
2309                         break;
2310                 case 'i':
2311                         {
2312                                 extern pstring global_scope;
2313                                 pstrcpy(global_scope,optarg);
2314                                 strupper(global_scope);
2315                         }
2316                         break;
2317                 case 'N':
2318                         got_pass = True;
2319                         break;
2320                 case 'n':
2321                         pstrcpy(global_myname,optarg);
2322                         break;
2323                 case 'd':
2324                         if (*optarg == 'A')
2325                                 DEBUGLEVEL = 10000;
2326                         else
2327                                 DEBUGLEVEL = atoi(optarg);
2328                         break;
2329                 case 'P':
2330                         /* not needed anymore */
2331                         break;
2332                 case 'p':
2333                         port = atoi(optarg);
2334                         break;
2335                 case 'l':
2336                         slprintf(debugf,sizeof(debugf)-1, "%s.client",optarg);
2337                         break;
2338                 case 'h':
2339                         usage(pname);
2340                         exit(0);
2341                         break;
2342                 case 'I':
2343                         {
2344                                 dest_ip = *interpret_addr2(optarg);
2345                                 if (zero_ip(dest_ip))
2346                                         exit(1);
2347                                 have_ip = True;
2348                         }
2349                         break;
2350                 case 'E':
2351                         dbf = stderr;
2352                         break;
2353                 case 'U':
2354                         {
2355                                 char *lp;
2356                                 pstrcpy(username,optarg);
2357                                 if ((lp=strchr(username,'%'))) {
2358                                         *lp = 0;
2359                                         pstrcpy(password,lp+1);
2360                                         got_pass = True;
2361                                         memset(strchr(optarg,'%')+1,'X',strlen(password));
2362                                 }
2363                         }
2364                         break;
2365
2366                 case 'A':
2367                         {
2368                                 FILE *auth;
2369                                 fstring buf;
2370                                 uint16 len = 0;
2371                                 char *ptr, *val, *param;
2372                                
2373                                 if ((auth=sys_fopen(optarg, "r")) == NULL)
2374                                 {
2375                                         /* fail if we can't open the credentials file */
2376                                         DEBUG(0,("ERROR: Unable to open credentials file!\n"));
2377                                         exit (-1);
2378                                 }
2379                                 
2380                                 while (!feof(auth))
2381                                 {  
2382                                         /* get a line from the file */
2383                                         if (!fgets (buf, sizeof(buf), auth))
2384                                                 continue;
2385                                         len = strlen(buf);
2386                                         
2387                                         if ((len) && (buf[len-1]=='\n'))
2388                                         {
2389                                                 buf[len-1] = '\0';
2390                                                 len--;
2391                                         }       
2392                                         if (len == 0)
2393                                                 continue;
2394                                         
2395                                         /* break up the line into parameter & value.
2396                                            will need to eat a little whitespace possibly */
2397                                         param = buf;
2398                                         if (!(ptr = strchr (buf, '=')))
2399                                                 continue;
2400                                         val = ptr+1;
2401                                         *ptr = '\0';
2402                                         
2403                                         /* eat leading white space */
2404                                         while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
2405                                                 val++;
2406                                         
2407                                         if (strwicmp("password", param) == 0)
2408                                         {
2409                                                 pstrcpy(password, val);
2410                                                 got_pass = True;
2411                                         }
2412                                         else if (strwicmp("username", param) == 0)
2413                                                 pstrcpy(username, val);
2414                                                 
2415                                         memset(buf, 0, sizeof(buf));
2416                                 }
2417                                 fclose(auth);
2418                         }
2419                         break;
2420
2421                 case 'L':
2422                         p = optarg;
2423                         while(*p == '\\' || *p == '/')
2424                                 p++;
2425                         pstrcpy(query_host,p);
2426                         break;
2427                 case 't':
2428                         pstrcpy(term_code, optarg);
2429                         break;
2430                 case 'm':
2431                         max_protocol = interpret_protocol(optarg, max_protocol);
2432                         break;
2433                 case 'W':
2434                         pstrcpy(workgroup,optarg);
2435                         break;
2436                 case 'T':
2437                         if (!tar_parseargs(argc, argv, optarg, optind)) {
2438                                 usage(pname);
2439                                 exit(1);
2440                         }
2441                         break;
2442                 case 'D':
2443                         pstrcpy(base_directory,optarg);
2444                         break;
2445                 case 'c':
2446                         cmdstr = optarg;
2447                         got_pass = True;
2448                         break;
2449                 case 'b':
2450                         io_bufsize = MAX(1, atoi(optarg));
2451                         break;
2452                 default:
2453                         usage(pname);
2454                         exit(1);
2455                 }
2456         }
2457
2458         get_myname((*global_myname)?NULL:global_myname);  
2459
2460         if(*new_name_resolve_order)
2461                 lp_set_name_resolve_order(new_name_resolve_order);
2462
2463         if (*term_code)
2464                 interpret_coding_system(term_code);
2465
2466         if (!tar_type && !*query_host && !*service && !message) {
2467                 usage(pname);
2468                 exit(1);
2469         }
2470
2471         DEBUG( 3, ( "Client started (version %s).\n", VERSION ) );
2472
2473         if (tar_type) {
2474                 if (cmdstr)
2475                         process_command_string(cmdstr);
2476                 return do_tar_op(base_directory);
2477         }
2478
2479         if ((p=strchr(query_host,'#'))) {
2480                 *p = 0;
2481                 p++;
2482                 sscanf(p, "%x", &name_type);
2483         }
2484   
2485         if (*query_host) {
2486                 return do_host_query(query_host);
2487         }
2488
2489         if (message) {
2490                 return do_message_op();
2491         }
2492         
2493         if (!process(base_directory)) {
2494                 return(1);
2495         }
2496
2497         return(0);
2498 }