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