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