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