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