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