Putting back the -p flag in smbclient.
[samba.git] / source3 / client / client.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    SMB client
5    Copyright (C) Andrew Tridgell 1994-1998
6    
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program; if not, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #define NO_SYSLOG
23
24 #include "includes.h"
25
26 #ifndef REGISTER
27 #define REGISTER 0
28 #endif
29
30 struct cli_state *cli;
31 extern BOOL in_client;
32 static int port = SMB_PORT;
33 pstring cur_dir = "\\";
34 pstring cd_path = "";
35 static pstring service;
36 static pstring desthost;
37 extern pstring global_myname;
38 extern pstring myhostname;
39 static pstring password;
40 static pstring username;
41 static pstring workgroup;
42 static char *cmdstr;
43 static BOOL got_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_ARRAY(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,uint16 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         uint16 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         uint16 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         uint16 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 = sys_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_qfileinfo(cli, fnum, 
510                            &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
511             !cli_getattrE(cli, fnum, 
512                           &attr, &size, NULL, NULL, NULL)) {
513                 DEBUG(0,("getattrib: %s\n",cli_errstr(cli)));
514                 return;
515         }
516
517         DEBUG(2,("getting file %s of size %.0f as %s ", 
518                  lname, (double)size, lname));
519
520         data = (char *)malloc(read_size);
521
522         while (1) {
523                 int n = cli_read(cli, fnum, data, nread, read_size);
524
525                 if (n <= 0) break;
526  
527                 if (writefile(handle,data, n) != n) {
528                         DEBUG(0,("Error writing local file\n"));
529                         break;
530                 }
531       
532                 nread += n;
533         }
534         
535         if (!cli_close(cli, fnum)) {
536                 DEBUG(0,("Error %s closing remote file\n",cli_errstr(cli)));
537         }
538
539         if (newhandle) {
540                 close(handle);
541         }
542
543         if (archive_level >= 2 && (attr & aARCH)) {
544                 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
545         }
546
547         {
548                 struct timeval tp_end;
549                 int this_time;
550                 
551                 GetTimeOfDay(&tp_end);
552                 this_time = 
553                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
554                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
555                 get_total_time_ms += this_time;
556                 get_total_size += nread;
557                 
558                 DEBUG(2,("(%g kb/s) (average %g kb/s)\n",
559                          nread / (1.024*this_time + 1.0e-4),
560                          get_total_size / (1.024*get_total_time_ms)));
561         }
562 }
563
564
565 /****************************************************************************
566   get a file
567   ****************************************************************************/
568 static void cmd_get(void)
569 {
570         pstring lname;
571         pstring rname;
572         char *p;
573
574         pstrcpy(rname,cur_dir);
575         pstrcat(rname,"\\");
576         
577         p = rname + strlen(rname);
578         
579         if (!next_token(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
580                 DEBUG(0,("get <filename>\n"));
581                 return;
582         }
583         pstrcpy(lname,p);
584         dos_clean_name(rname);
585         
586         next_token(NULL,lname,NULL,sizeof(lname));
587         
588         do_get(rname, lname);
589 }
590
591
592 /****************************************************************************
593   do a mget operation on one file
594   ****************************************************************************/
595 static void do_mget(file_info *finfo)
596 {
597         pstring rname;
598         pstring quest;
599         pstring saved_curdir;
600         pstring mget_mask;
601
602         if (strequal(finfo->name,".") || strequal(finfo->name,".."))
603                 return;
604
605         if (abort_mget) {
606                 DEBUG(0,("mget aborted\n"));
607                 return;
608         }
609
610         if (finfo->mode & aDIR)
611                 slprintf(quest,sizeof(pstring)-1,
612                          "Get directory %s? ",CNV_LANG(finfo->name));
613         else
614                 slprintf(quest,sizeof(pstring)-1,
615                          "Get file %s? ",CNV_LANG(finfo->name));
616
617         if (prompt && !yesno(quest)) return;
618
619         if (!(finfo->mode & aDIR)) {
620                 pstrcpy(rname,cur_dir);
621                 pstrcat(rname,finfo->name);
622                 do_get(rname,finfo->name);
623                 return;
624         }
625
626         /* handle directories */
627         pstrcpy(saved_curdir,cur_dir);
628
629         pstrcat(cur_dir,finfo->name);
630         pstrcat(cur_dir,"\\");
631
632         unix_format(finfo->name);
633         if (lowercase)
634                 strlower(finfo->name);
635         
636         if (!dos_directory_exist(finfo->name,NULL) && 
637             dos_mkdir(finfo->name,0777) != 0) {
638                 DEBUG(0,("failed to create directory %s\n",CNV_LANG(finfo->name)));
639                 pstrcpy(cur_dir,saved_curdir);
640                 return;
641         }
642         
643         if (dos_chdir(finfo->name) != 0) {
644                 DEBUG(0,("failed to chdir to directory %s\n",CNV_LANG(finfo->name)));
645                 pstrcpy(cur_dir,saved_curdir);
646                 return;
647         }
648
649         pstrcpy(mget_mask,cur_dir);
650         pstrcat(mget_mask,"*");
651         
652         do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,False, True);
653         chdir("..");
654         pstrcpy(cur_dir,saved_curdir);
655 }
656
657
658 /****************************************************************************
659 view the file using the pager
660 ****************************************************************************/
661 static void cmd_more(void)
662 {
663         fstring rname,lname,tmpname,pager_cmd;
664         char *pager;
665
666         fstrcpy(rname,cur_dir);
667         fstrcat(rname,"\\");
668         slprintf(tmpname,
669                  sizeof(fstring)-1,
670                  "%s/smbmore.%d",tmpdir(),(int)getpid());
671         fstrcpy(lname,tmpname);
672         
673         if (!next_token(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
674                 DEBUG(0,("more <filename>\n"));
675                 return;
676         }
677         dos_clean_name(rname);
678
679         do_get(rname,lname);
680
681         pager=getenv("PAGER");
682
683         slprintf(pager_cmd,sizeof(pager_cmd)-1,
684                  "%s %s",(pager? pager:PAGER), tmpname);
685         system(pager_cmd);
686         unlink(tmpname);
687 }
688
689
690
691 /****************************************************************************
692 do a mget command
693 ****************************************************************************/
694 static void cmd_mget(void)
695 {
696         uint16 attribute = aSYSTEM | aHIDDEN;
697         pstring mget_mask;
698         fstring buf;
699         char *p=buf;
700
701         *mget_mask = 0;
702
703         if (recurse)
704                 attribute |= aDIR;
705         
706         abort_mget = False;
707
708         while (next_token(NULL,p,NULL,sizeof(buf))) {
709                 pstrcpy(mget_mask,cur_dir);
710                 if(mget_mask[strlen(mget_mask)-1]!='\\')
711                         pstrcat(mget_mask,"\\");
712                 
713                 if (*p == '\\')
714                         pstrcpy(mget_mask,p);
715                 else
716                         pstrcat(mget_mask,p);
717                 do_list(mget_mask, attribute,do_mget,False,True);
718         }
719
720         if (!*mget_mask) {
721                 pstrcpy(mget_mask,cur_dir);
722                 if(mget_mask[strlen(mget_mask)-1]!='\\')
723                         pstrcat(mget_mask,"\\");
724                 pstrcat(mget_mask,"*");
725                 do_list(mget_mask, attribute,do_mget,False,True);
726         }
727 }
728
729
730 /****************************************************************************
731 make a directory of name "name"
732 ****************************************************************************/
733 static BOOL do_mkdir(char *name)
734 {
735         if (!cli_mkdir(cli, name)) {
736                 DEBUG(0,("%s making remote directory %s\n",
737                          cli_errstr(cli),CNV_LANG(name)));
738                 return(False);
739         }
740
741         return(True);
742 }
743
744
745 /****************************************************************************
746 make a directory of name "name"
747 ****************************************************************************/
748 static void cmd_quit(void)
749 {
750         cli_shutdown(cli);
751         exit(0);
752 }
753
754
755 /****************************************************************************
756   make a directory
757   ****************************************************************************/
758 static void cmd_mkdir(void)
759 {
760         pstring mask;
761         fstring buf;
762         char *p=buf;
763   
764         pstrcpy(mask,cur_dir);
765
766         if (!next_token(NULL,p,NULL,sizeof(buf))) {
767                 if (!recurse)
768                         DEBUG(0,("mkdir <dirname>\n"));
769                 return;
770         }
771         pstrcat(mask,p);
772
773         if (recurse) {
774                 pstring ddir;
775                 pstring ddir2;
776                 *ddir2 = 0;
777                 
778                 pstrcpy(ddir,mask);
779                 trim_string(ddir,".",NULL);
780                 p = strtok(ddir,"/\\");
781                 while (p) {
782                         pstrcat(ddir2,p);
783                         if (!cli_chkpath(cli, ddir2)) { 
784                                 do_mkdir(ddir2);
785                         }
786                         pstrcat(ddir2,"\\");
787                         p = strtok(NULL,"/\\");
788                 }        
789         } else {
790                 do_mkdir(mask);
791         }
792 }
793
794
795 /****************************************************************************
796   put a single file
797   ****************************************************************************/
798 static void do_put(char *rname,char *lname)
799 {
800         int fnum;
801         FILE *f;
802         int nread=0;
803         char *buf=NULL;
804         int maxwrite=65520;
805         
806         struct timeval tp_start;
807         GetTimeOfDay(&tp_start);
808
809         fnum = cli_open(cli, rname, O_WRONLY|O_CREAT|O_TRUNC, DENY_NONE);
810   
811         if (fnum == -1) {
812                 DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),CNV_LANG(rname)));
813                 return;
814         }
815
816         /* allow files to be piped into smbclient
817            jdblair 24.jun.98 */
818         if (!strcmp(lname, "-")) {
819                 f = stdin;
820                 /* size of file is not known */
821         } else {
822                 f = sys_fopen(lname,"r");
823         }
824
825         if (!f) {
826                 DEBUG(0,("Error opening local file %s\n",lname));
827                 return;
828         }
829
830   
831         DEBUG(1,("putting file %s as %s ",lname,
832                  CNV_LANG(rname)));
833   
834         buf = (char *)malloc(maxwrite);
835         while (!feof(f)) {
836                 int n = maxwrite;
837                 int ret;
838
839                 if ((n = readfile(buf,1,n,f)) < 1) {
840                         DEBUG(0,("Error reading local file\n"));
841                         break;
842                 }
843
844                 ret = cli_write(cli, fnum, 0, buf, nread, n);
845
846                 if (n != ret) {
847                         DEBUG(0,("Error writing file: %s\n", cli_errstr(cli)));
848                         break;
849                 } 
850
851                 nread += n;
852         }
853
854         if (!cli_close(cli, fnum)) {
855                 DEBUG(0,("%s closing remote file %s\n",cli_errstr(cli),CNV_LANG(rname)));
856                 fclose(f);
857                 if (buf) free(buf);
858                 return;
859         }
860
861         
862         fclose(f);
863         if (buf) free(buf);
864
865         {
866                 struct timeval tp_end;
867                 int this_time;
868                 
869                 GetTimeOfDay(&tp_end);
870                 this_time = 
871                         (tp_end.tv_sec - tp_start.tv_sec)*1000 +
872                         (tp_end.tv_usec - tp_start.tv_usec)/1000;
873                 put_total_time_ms += this_time;
874                 put_total_size += nread;
875                 
876                 DEBUG(1,("(%g kb/s) (average %g kb/s)\n",
877                          nread / (1.024*this_time + 1.0e-4),
878                          put_total_size / (1.024*put_total_time_ms)));
879         }
880
881         if (f == stdin) {
882                 cli_shutdown(cli);
883                 exit(0);
884         }
885 }
886
887  
888
889 /****************************************************************************
890   put a file
891   ****************************************************************************/
892 static void cmd_put(void)
893 {
894         pstring lname;
895         pstring rname;
896         fstring buf;
897         char *p=buf;
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         }
925
926         do_put(rname,lname);
927 }
928
929
930 /****************************************************************************
931   seek in a directory/file list until you get something that doesn't start with
932   the specified name
933   ****************************************************************************/
934 static BOOL seek_list(FILE *f,char *name)
935 {
936         pstring s;
937         while (!feof(f)) {
938                 if (fscanf(f,"%s",s) != 1) return(False);
939                 trim_string(s,"./",NULL);
940                 if (strncmp(s,name,strlen(name)) != 0) {
941                         pstrcpy(name,s);
942                         return(True);
943                 }
944         }
945       
946         return(False);
947 }
948
949
950 /****************************************************************************
951   set the file selection mask
952   ****************************************************************************/
953 static void cmd_select(void)
954 {
955         pstrcpy(fileselection,"");
956         next_token(NULL,fileselection,NULL,sizeof(fileselection));
957 }
958
959
960 /****************************************************************************
961   mput some files
962   ****************************************************************************/
963 static void cmd_mput(void)
964 {
965         pstring lname;
966         pstring rname;
967         fstring buf;
968         char *p=buf;
969         
970         while (next_token(NULL,p,NULL,sizeof(buf))) {
971                 SMB_STRUCT_STAT st;
972                 pstring cmd;
973                 pstring tmpname;
974                 FILE *f;
975                 
976                 slprintf(tmpname,sizeof(pstring)-1,
977                          "%s/ls.smb.%d",tmpdir(),(int)getpid());
978                 if (recurse)
979                         slprintf(cmd,sizeof(pstring)-1,
980                                  "find . -name \"%s\" -print > %s",p,tmpname);
981                 else
982                         slprintf(cmd,sizeof(pstring)-1,
983                                  "/bin/ls %s > %s",p,tmpname);
984                 system(cmd);
985
986                 f = sys_fopen(tmpname,"r");
987                 if (!f) continue;
988                 
989                 while (!feof(f)) {
990                         pstring quest;
991
992                         if (fscanf(f,"%s",lname) != 1) break;
993                         trim_string(lname,"./",NULL);
994                         
995                 again1:
996                         
997                         /* check if it's a directory */
998                         if (directory_exist(lname,&st)) {
999                                 if (!recurse) continue;
1000                                 slprintf(quest,sizeof(pstring)-1,
1001                                          "Put directory %s? ",lname);
1002                                 if (prompt && !yesno(quest)) {
1003                                         pstrcat(lname,"/");
1004                                         if (!seek_list(f,lname))
1005                                                 break;
1006                                         goto again1;                
1007                                 }
1008               
1009                                 pstrcpy(rname,cur_dir);
1010                                 pstrcat(rname,lname);
1011                                 if (!cli_chkpath(cli, rname) && !do_mkdir(rname)) {
1012                                         pstrcat(lname,"/");
1013                                         if (!seek_list(f,lname))
1014                                                 break;
1015                                         goto again1;
1016                                 }
1017                                 continue;
1018                         } else {
1019                                 slprintf(quest,sizeof(quest)-1,
1020                                          "Put file %s? ",lname);
1021                                 if (prompt && !yesno(quest)) continue;
1022                                 
1023                                 pstrcpy(rname,cur_dir);
1024                                 pstrcat(rname,lname);
1025                         }
1026
1027                         dos_format(rname);
1028
1029                         do_put(rname,lname);
1030                 }
1031                 fclose(f);
1032                 unlink(tmpname);
1033         }
1034 }
1035
1036
1037 /****************************************************************************
1038   cancel a print job
1039   ****************************************************************************/
1040 static void do_cancel(int job)
1041 {
1042         if (cli_printjob_del(cli, job)) {
1043                 printf("Job %d cancelled\n",job);
1044         } else {
1045                 printf("Error calcelling job %d : %s\n",job,cli_errstr(cli));
1046         }
1047 }
1048
1049
1050 /****************************************************************************
1051   cancel a print job
1052   ****************************************************************************/
1053 static void cmd_cancel(void)
1054 {
1055         fstring buf;
1056         int job; 
1057
1058         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1059                 printf("cancel <jobid> ...\n");
1060                 return;
1061         }
1062         do {
1063                 job = atoi(buf);
1064                 do_cancel(job);
1065         } while (next_token(NULL,buf,NULL,sizeof(buf)));
1066 }
1067
1068
1069 /****************************************************************************
1070   print a file
1071   ****************************************************************************/
1072 static void cmd_print(void)
1073 {
1074         pstring lname;
1075         pstring rname;
1076         char *p;
1077
1078         if (!next_token(NULL,lname,NULL, sizeof(lname))) {
1079                 DEBUG(0,("print <filename>\n"));
1080                 return;
1081         }
1082
1083         pstrcpy(rname,lname);
1084         p = strrchr(rname,'/');
1085         if (p) {
1086                 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)getpid());
1087         }
1088
1089         if (strequal(lname,"-")) {
1090                 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)getpid());
1091         }
1092
1093         do_put(rname, lname);
1094 }
1095
1096
1097 /****************************************************************************
1098  show a print queue entry
1099 ****************************************************************************/
1100 static void queue_fn(struct print_job_info *p)
1101 {
1102         DEBUG(0,("%-6d   %-9d    %s\n", (int)p->id, (int)p->size, p->name));
1103 }
1104
1105 /****************************************************************************
1106  show a print queue
1107 ****************************************************************************/
1108 static void cmd_queue(void)
1109 {
1110         cli_print_queue(cli, queue_fn);  
1111 }
1112
1113 /****************************************************************************
1114 delete some files
1115 ****************************************************************************/
1116 static void do_del(file_info *finfo)
1117 {
1118         pstring mask;
1119
1120         pstrcpy(mask,cur_dir);
1121         pstrcat(mask,finfo->name);
1122
1123         if (finfo->mode & aDIR) 
1124                 return;
1125
1126         if (!cli_unlink(cli, mask)) {
1127                 DEBUG(0,("%s deleting remote file %s\n",cli_errstr(cli),CNV_LANG(mask)));
1128         }
1129 }
1130
1131 /****************************************************************************
1132 delete some files
1133 ****************************************************************************/
1134 static void cmd_del(void)
1135 {
1136         pstring mask;
1137         fstring buf;
1138         uint16 attribute = aSYSTEM | aHIDDEN;
1139
1140         if (recurse)
1141                 attribute |= aDIR;
1142         
1143         pstrcpy(mask,cur_dir);
1144         
1145         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1146                 DEBUG(0,("del <filename>\n"));
1147                 return;
1148         }
1149         pstrcat(mask,buf);
1150
1151         do_list(mask, attribute,do_del,False,False);
1152 }
1153
1154
1155 /****************************************************************************
1156 remove a directory
1157 ****************************************************************************/
1158 static void cmd_rmdir(void)
1159 {
1160         pstring mask;
1161         fstring buf;
1162   
1163         pstrcpy(mask,cur_dir);
1164         
1165         if (!next_token(NULL,buf,NULL,sizeof(buf))) {
1166                 DEBUG(0,("rmdir <dirname>\n"));
1167                 return;
1168         }
1169         pstrcat(mask,buf);
1170
1171         if (!cli_rmdir(cli, mask)) {
1172                 DEBUG(0,("%s removing remote directory file %s\n",
1173                          cli_errstr(cli),CNV_LANG(mask)));
1174         }  
1175 }
1176
1177 /****************************************************************************
1178 rename some files
1179 ****************************************************************************/
1180 static void cmd_rename(void)
1181 {
1182         pstring src,dest;
1183         fstring buf,buf2;
1184   
1185         pstrcpy(src,cur_dir);
1186         pstrcpy(dest,cur_dir);
1187         
1188         if (!next_token(NULL,buf,NULL,sizeof(buf)) || 
1189             !next_token(NULL,buf2,NULL, sizeof(buf2))) {
1190                 DEBUG(0,("rename <src> <dest>\n"));
1191                 return;
1192         }
1193
1194         pstrcat(src,buf);
1195         pstrcat(dest,buf2);
1196
1197         if (!cli_rename(cli, src, dest)) {
1198                 DEBUG(0,("%s renaming files\n",cli_errstr(cli)));
1199                 return;
1200         }  
1201 }
1202
1203
1204 /****************************************************************************
1205 toggle the prompt flag
1206 ****************************************************************************/
1207 static void cmd_prompt(void)
1208 {
1209         prompt = !prompt;
1210         DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
1211 }
1212
1213
1214 /****************************************************************************
1215 set the newer than time
1216 ****************************************************************************/
1217 static void cmd_newer(void)
1218 {
1219         fstring buf;
1220         BOOL ok;
1221         SMB_STRUCT_STAT sbuf;
1222
1223         ok = next_token(NULL,buf,NULL,sizeof(buf));
1224         if (ok && (dos_stat(buf,&sbuf) == 0)) {
1225                 newer_than = sbuf.st_mtime;
1226                 DEBUG(1,("Getting files newer than %s",
1227                          asctime(LocalTime(&newer_than))));
1228         } else {
1229                 newer_than = 0;
1230         }
1231
1232         if (ok && newer_than == 0)
1233                 DEBUG(0,("Error setting newer-than time\n"));
1234 }
1235
1236 /****************************************************************************
1237 set the archive level
1238 ****************************************************************************/
1239 static void cmd_archive(void)
1240 {
1241         fstring buf;
1242
1243         if (next_token(NULL,buf,NULL,sizeof(buf))) {
1244                 archive_level = atoi(buf);
1245         } else
1246                 DEBUG(0,("Archive level is %d\n",archive_level));
1247 }
1248
1249 /****************************************************************************
1250 toggle the lowercaseflag
1251 ****************************************************************************/
1252 static void cmd_lowercase(void)
1253 {
1254         lowercase = !lowercase;
1255         DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
1256 }
1257
1258
1259
1260
1261 /****************************************************************************
1262 toggle the recurse flag
1263 ****************************************************************************/
1264 static void cmd_recurse(void)
1265 {
1266         recurse = !recurse;
1267         DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
1268 }
1269
1270 /****************************************************************************
1271 toggle the translate flag
1272 ****************************************************************************/
1273 static void cmd_translate(void)
1274 {
1275         translation = !translation;
1276         DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
1277                  translation?"on":"off"));
1278 }
1279
1280
1281 /****************************************************************************
1282 do a printmode command
1283 ****************************************************************************/
1284 static void cmd_printmode(void)
1285 {
1286         fstring buf;
1287         fstring mode;
1288
1289         if (next_token(NULL,buf,NULL,sizeof(buf))) {
1290                 if (strequal(buf,"text")) {
1291                         printmode = 0;      
1292                 } else {
1293                         if (strequal(buf,"graphics"))
1294                                 printmode = 1;
1295                         else
1296                                 printmode = atoi(buf);
1297                 }
1298         }
1299
1300         switch(printmode)
1301                 {
1302                 case 0: 
1303                         fstrcpy(mode,"text");
1304                         break;
1305                 case 1: 
1306                         fstrcpy(mode,"graphics");
1307                         break;
1308                 default: 
1309                         slprintf(mode,sizeof(mode)-1,"%d",printmode);
1310                         break;
1311                 }
1312         
1313         DEBUG(2,("the printmode is now %s\n",mode));
1314 }
1315
1316 /****************************************************************************
1317 do the lcd command
1318 ****************************************************************************/
1319 static void cmd_lcd(void)
1320 {
1321         fstring buf;
1322         pstring d;
1323         
1324         if (next_token(NULL,buf,NULL,sizeof(buf)))
1325                 chdir(buf);
1326         DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
1327 }
1328
1329 /****************************************************************************
1330 list a share name
1331 ****************************************************************************/
1332 static void browse_fn(const char *name, uint32 m, const char *comment)
1333 {
1334         fstring typestr;
1335         *typestr=0;
1336
1337         switch (m)
1338         {
1339           case STYPE_DISKTREE:
1340             fstrcpy(typestr,"Disk"); break;
1341           case STYPE_PRINTQ:
1342             fstrcpy(typestr,"Printer"); break;
1343           case STYPE_DEVICE:
1344             fstrcpy(typestr,"Device"); break;
1345           case STYPE_IPC:
1346             fstrcpy(typestr,"IPC"); break;
1347         }
1348
1349         printf("\t%-15.15s%-10.10s%s\n",
1350                name, typestr,comment);
1351 }
1352
1353
1354 /****************************************************************************
1355 try and browse available connections on a host
1356 ****************************************************************************/
1357 static BOOL browse_host(BOOL sort)
1358 {
1359         printf("\n\tSharename      Type      Comment\n");
1360         printf("\t---------      ----      -------\n");
1361
1362         return cli_RNetShareEnum(cli, browse_fn);
1363 }
1364
1365 /****************************************************************************
1366 list a server name
1367 ****************************************************************************/
1368 static void server_fn(const char *name, uint32 m, const char *comment)
1369 {
1370         printf("\t%-16.16s     %s\n", name, comment);
1371 }
1372
1373 /****************************************************************************
1374 try and browse available connections on a host
1375 ****************************************************************************/
1376 static BOOL list_servers(char *wk_grp)
1377 {
1378         printf("\n\tServer               Comment\n");
1379         printf("\t---------            -------\n");
1380
1381         cli_NetServerEnum(cli, workgroup, SV_TYPE_ALL, server_fn);
1382
1383         printf("\n\tWorkgroup            Master\n");
1384         printf("\t---------            -------\n");
1385
1386         cli_NetServerEnum(cli, workgroup, SV_TYPE_DOMAIN_ENUM, server_fn);
1387         return True;
1388 }
1389
1390
1391 /* Some constants for completing filename arguments */
1392
1393 #define COMPL_NONE        0          /* No completions */
1394 #define COMPL_REMOTE      1          /* Complete remote filename */
1395 #define COMPL_LOCAL       2          /* Complete local filename */
1396
1397 /* This defines the commands supported by this client */
1398 struct
1399 {
1400   char *name;
1401   void (*fn)(void);
1402   char *description;
1403   char compl_args[2];      /* Completion argument info */
1404 } commands[] = 
1405 {
1406   {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1407   {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1408   {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1409   {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
1410   {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
1411   {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
1412   {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
1413   {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
1414   {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
1415   {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
1416   {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
1417   {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},  
1418   {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
1419   {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
1420   {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
1421   {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
1422   {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
1423   {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
1424   {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
1425   {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},  
1426   {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},  
1427   {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},  
1428   {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},  
1429   {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
1430   {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
1431   {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
1432   {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
1433   {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1434   {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1435   {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1436   {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
1437   {"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}},
1438   {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
1439   {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
1440   {"tarmode",cmd_tarmode,
1441      "<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
1442   {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
1443   {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
1444   {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
1445   {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
1446   {"",NULL,NULL,{COMPL_NONE,COMPL_NONE}}
1447 };
1448
1449
1450 /*******************************************************************
1451   lookup a command string in the list of commands, including 
1452   abbreviations
1453   ******************************************************************/
1454 static int process_tok(fstring tok)
1455 {
1456         int i = 0, matches = 0;
1457         int cmd=0;
1458         int tok_len = strlen(tok);
1459         
1460         while (commands[i].fn != NULL) {
1461                 if (strequal(commands[i].name,tok)) {
1462                         matches = 1;
1463                         cmd = i;
1464                         break;
1465                 } else if (strnequal(commands[i].name, tok, tok_len)) {
1466                         matches++;
1467                         cmd = i;
1468                 }
1469                 i++;
1470         }
1471   
1472         if (matches == 0)
1473                 return(-1);
1474         else if (matches == 1)
1475                 return(cmd);
1476         else
1477                 return(-2);
1478 }
1479
1480 /****************************************************************************
1481 help
1482 ****************************************************************************/
1483 static void cmd_help(void)
1484 {
1485         int i=0,j;
1486         fstring buf;
1487         
1488         if (next_token(NULL,buf,NULL,sizeof(buf))) {
1489                 if ((i = process_tok(buf)) >= 0)
1490                         DEBUG(0,("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description));                   
1491         } else {
1492                 while (commands[i].description) {
1493                         for (j=0; commands[i].description && (j<5); j++) {
1494                                 DEBUG(0,("%-15s",commands[i].name));
1495                                 i++;
1496                         }
1497                         DEBUG(0,("\n"));
1498                 }
1499         }
1500 }
1501
1502 /****************************************************************************
1503 wait for keyboard activity, swallowing network packets
1504 ****************************************************************************/
1505 static void wait_keyboard(void)
1506 {
1507         fd_set fds;
1508         struct timeval timeout;
1509   
1510         while (1) {
1511                 FD_ZERO(&fds);
1512                 FD_SET(cli->fd,&fds);
1513                 FD_SET(fileno(stdin),&fds);
1514
1515                 timeout.tv_sec = 20;
1516                 timeout.tv_usec = 0;
1517                 sys_select(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
1518       
1519                 if (FD_ISSET(fileno(stdin),&fds))
1520                         return;
1521
1522                 /* We deliberately use receive_smb instead of
1523                    client_receive_smb as we want to receive
1524                    session keepalives and then drop them here.
1525                 */
1526                 if (FD_ISSET(cli->fd,&fds))
1527                         receive_smb(cli->fd,cli->inbuf,0);
1528       
1529                 cli_chkpath(cli, "\\");
1530         }  
1531 }
1532
1533 /****************************************************************************
1534 process a -c command string
1535 ****************************************************************************/
1536 static void process_command_string(char *cmd)
1537 {
1538         pstring line;
1539         char *ptr;
1540
1541         while (cmd[0] != '\0')    {
1542                 char *p;
1543                 fstring tok;
1544                 int i;
1545                 
1546                 if ((p = strchr(cmd, ';')) == 0) {
1547                         strncpy(line, cmd, 999);
1548                         line[1000] = '\0';
1549                         cmd += strlen(cmd);
1550                 } else {
1551                         if (p - cmd > 999) p = cmd + 999;
1552                         strncpy(line, cmd, p - cmd);
1553                         line[p - cmd] = '\0';
1554                         cmd = p + 1;
1555                 }
1556                 
1557                 /* input language code to internal one */
1558                 CNV_INPUT (line);
1559                 
1560                 /* and get the first part of the command */
1561                 ptr = line;
1562                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
1563                 
1564                 if ((i = process_tok(tok)) >= 0) {
1565                         commands[i].fn();
1566                 } else if (i == -2) {
1567                         DEBUG(0,("%s: command abbreviation ambiguous\n",CNV_LANG(tok)));
1568                 } else {
1569                         DEBUG(0,("%s: command not found\n",CNV_LANG(tok)));
1570                 }
1571         }
1572 }       
1573
1574 /****************************************************************************
1575 process commands on stdin
1576 ****************************************************************************/
1577 static void process_stdin(void)
1578 {
1579         pstring line;
1580         char *ptr;
1581
1582         while (!feof(stdin)) {
1583                 fstring tok;
1584                 int i;
1585
1586                 /* display a prompt */
1587                 DEBUG(0,("smb: %s> ", CNV_LANG(cur_dir)));
1588                 dbgflush( );
1589                 
1590                 wait_keyboard();
1591                 
1592                 /* and get a response */
1593                 if (!fgets(line,1000,stdin))
1594                         break;
1595
1596                 /* input language code to internal one */
1597                 CNV_INPUT (line);
1598                 
1599                 /* special case - first char is ! */
1600                 if (*line == '!') {
1601                         system(line + 1);
1602                         continue;
1603                 }
1604       
1605                 /* and get the first part of the command */
1606                 ptr = line;
1607                 if (!next_token(&ptr,tok,NULL,sizeof(tok))) continue;
1608
1609                 if ((i = process_tok(tok)) >= 0) {
1610                         commands[i].fn();
1611                 } else if (i == -2) {
1612                         DEBUG(0,("%s: command abbreviation ambiguous\n",CNV_LANG(tok)));
1613                 } else {
1614                         DEBUG(0,("%s: command not found\n",CNV_LANG(tok)));
1615                 }
1616         }
1617 }
1618
1619
1620 /***************************************************** 
1621 return a connection to a server
1622 *******************************************************/
1623 struct cli_state *do_connect(char *server, char *share)
1624 {
1625         struct cli_state *c;
1626         struct nmb_name called, calling;
1627         char *server_n;
1628         struct in_addr ip;
1629         extern struct in_addr ipzero;
1630
1631         if (*share == '\\') {
1632                 server = share+2;
1633                 share = strchr(server,'\\');
1634                 if (!share) return NULL;
1635                 *share = 0;
1636                 share++;
1637         }
1638
1639         server_n = server;
1640         
1641         ip = ipzero;
1642
1643         make_nmb_name(&calling, global_myname, 0x0, "");
1644         make_nmb_name(&called , server, name_type, "");
1645
1646         if (port == 0)
1647           port = 139;   /* If not set, set to 139, FIXME, NUMBERS BAD */
1648
1649  again:
1650         ip = ipzero;
1651         if (have_ip) ip = dest_ip;
1652
1653         /* have to open a new connection */
1654         if (!(c=cli_initialise(NULL)) || (cli_set_port(c, port) == 0) ||
1655             !cli_connect(c, server_n, &ip)) {
1656                 DEBUG(0,("Connection to %s failed\n", server_n));
1657                 return NULL;
1658         }
1659
1660         if (!cli_session_request(c, &calling, &called)) {
1661                 DEBUG(0,("session request to %s failed\n", called.name));
1662                 cli_shutdown(c);
1663                 if (strcmp(called.name, "*SMBSERVER")) {
1664                         make_nmb_name(&called , "*SMBSERVER", 0x20, "");
1665                         goto again;
1666                 }
1667                 return NULL;
1668         }
1669
1670         DEBUG(4,(" session request ok\n"));
1671
1672         if (!cli_negprot(c)) {
1673                 DEBUG(0,("protocol negotiation failed\n"));
1674                 cli_shutdown(c);
1675                 return NULL;
1676         }
1677
1678         if (!got_pass) {
1679                 char *pass = getpass("Password: ");
1680                 if (pass) {
1681                         pstrcpy(password, pass);
1682                 }
1683         }
1684
1685         if (!cli_session_setup(c, username, 
1686                                password, strlen(password),
1687                                password, strlen(password),
1688                                workgroup)) {
1689                 DEBUG(0,("session setup failed: %s\n", cli_errstr(c)));
1690                 return NULL;
1691         }
1692
1693         /*
1694          * These next two lines are needed to emulate
1695          * old client behaviour for people who have
1696          * scripts based on client output.
1697          * QUESTION ? Do we want to have a 'client compatibility
1698          * mode to turn these on/off ? JRA.
1699          */
1700
1701         if (*c->server_domain || *c->server_os || *c->server_type)
1702                 DEBUG(1,("Domain=[%s] OS=[%s] Server=[%s]\n",
1703                         c->server_domain,c->server_os,c->server_type));
1704         
1705         DEBUG(4,(" session setup ok\n"));
1706
1707         if (!cli_send_tconX(c, share, "?????",
1708                             password, strlen(password)+1)) {
1709                 DEBUG(0,("tree connect failed: %s\n", cli_errstr(c)));
1710                 cli_shutdown(c);
1711                 return NULL;
1712         }
1713
1714         DEBUG(4,(" tconx ok\n"));
1715
1716         return c;
1717 }
1718
1719
1720 /****************************************************************************
1721   process commands from the client
1722 ****************************************************************************/
1723 static BOOL process(char *base_directory)
1724 {
1725         cli = do_connect(desthost, service);
1726         if (!cli) {
1727                 return(False);
1728         }
1729
1730         if (*base_directory) do_cd(base_directory);
1731         
1732         if (cmdstr) {
1733                 process_command_string(cmdstr);
1734         } else {
1735                 process_stdin();
1736         }
1737   
1738         cli_shutdown(cli);
1739         return(True);
1740 }
1741
1742 /****************************************************************************
1743 usage on the program
1744 ****************************************************************************/
1745 static void usage(char *pname)
1746 {
1747   DEBUG(0,("Usage: %s service <password> ", pname));
1748
1749   DEBUG(0,("\nVersion %s\n",VERSION));
1750   DEBUG(0,("\t-s smb.conf           pathname to smb.conf file\n"));
1751   DEBUG(0,("\t-B IP addr            broadcast IP address to use\n"));
1752   DEBUG(0,("\t-O socket_options     socket options to use\n"));
1753   DEBUG(0,("\t-R name resolve order use these name resolution services only\n"));
1754   DEBUG(0,("\t-M host               send a winpopup message to the host\n"));
1755   DEBUG(0,("\t-i scope              use this NetBIOS scope\n"));
1756   DEBUG(0,("\t-N                    don't ask for a password\n"));
1757   DEBUG(0,("\t-n netbios name.      Use this name as my netbios name\n"));
1758   DEBUG(0,("\t-d debuglevel         set the debuglevel\n"));
1759   DEBUG(0,("\t-P                    connect to service as a printer\n"));
1760   DEBUG(0,("\t-p port               connect to the specified port\n"));
1761   DEBUG(0,("\t-l log basename.      Basename for log/debug files\n"));
1762   DEBUG(0,("\t-h                    Print this help message.\n"));
1763   DEBUG(0,("\t-I dest IP            use this IP to connect to\n"));
1764   DEBUG(0,("\t-E                    write messages to stderr instead of stdout\n"));
1765   DEBUG(0,("\t-U username           set the network username\n"));
1766   DEBUG(0,("\t-L host               get a list of shares available on a host\n"));
1767   DEBUG(0,("\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n"));
1768   DEBUG(0,("\t-m max protocol       set the max protocol level\n"));
1769   DEBUG(0,("\t-W workgroup          set the workgroup name\n"));
1770   DEBUG(0,("\t-T<c|x>IXFqgbNan      command line tar\n"));
1771   DEBUG(0,("\t-D directory          start from directory\n"));
1772   DEBUG(0,("\t-c command string     execute semicolon separated commands\n"));
1773   DEBUG(0,("\n"));
1774 }
1775
1776
1777 /****************************************************************************
1778 get a password from a a file or file descriptor
1779 exit on failure
1780 ****************************************************************************/
1781 static void get_password_file(void)
1782 {
1783         int fd = -1;
1784         char *p;
1785         BOOL close_it = False;
1786         pstring spec;
1787         char pass[128];
1788                 
1789         if ((p = getenv("PASSWD_FD")) != NULL) {
1790                 pstrcpy(spec, "descriptor ");
1791                 pstrcat(spec, p);
1792                 sscanf(p, "%d", &fd);
1793                 close_it = False;
1794         } else if ((p = getenv("PASSWD_FILE")) != NULL) {
1795                 fd = sys_open(p, O_RDONLY, 0);
1796                 pstrcpy(spec, p);
1797                 if (fd < 0) {
1798                         fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
1799                                 spec, strerror(errno));
1800                         exit(1);
1801                 }
1802                 close_it = True;
1803         }
1804
1805         for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
1806             p && p - pass < sizeof(pass);) {
1807                 switch (read(fd, p, 1)) {
1808                 case 1:
1809                         if (*p != '\n' && *p != '\0') {
1810                                 *++p = '\0'; /* advance p, and null-terminate pass */
1811                                 break;
1812                         }
1813                 case 0:
1814                         if (p - pass) {
1815                                 *p = '\0'; /* null-terminate it, just in case... */
1816                                 p = NULL; /* then force the loop condition to become false */
1817                                 break;
1818                         } else {
1819                                 fprintf(stderr, "Error reading password from file %s: %s\n",
1820                                         spec, "empty password\n");
1821                                 exit(1);
1822                         }
1823                         
1824                 default:
1825                         fprintf(stderr, "Error reading password from file %s: %s\n",
1826                                 spec, strerror(errno));
1827                         exit(1);
1828                 }
1829         }
1830         pstrcpy(password, pass);
1831         if (close_it)
1832                 close(fd);
1833 }       
1834
1835
1836
1837 /****************************************************************************
1838 handle a -L query
1839 ****************************************************************************/
1840 static int do_host_query(char *query_host, int port)
1841 {
1842         cli = do_connect(query_host, "IPC$");
1843         if (!cli)
1844                 return 1;
1845
1846         browse_host(True);
1847         list_servers(workgroup);
1848
1849         cli_shutdown(cli);
1850         
1851         return(0);
1852 }
1853
1854
1855 /****************************************************************************
1856 handle a tar operation
1857 ****************************************************************************/
1858 static int do_tar_op(int port, char *base_directory)
1859 {
1860         int ret;
1861         cli = do_connect(desthost, service);
1862         if (!cli)
1863                 return 1;
1864
1865         recurse=True;
1866
1867         if (*base_directory) do_cd(base_directory);
1868         
1869         ret=process_tar();
1870
1871         cli_shutdown(cli);
1872
1873         return(ret);
1874 }
1875
1876 /****************************************************************************
1877 handle a message operation
1878 ****************************************************************************/
1879 static int do_message_op(void)
1880 {
1881         struct in_addr ip;
1882         struct nmb_name called, calling;
1883
1884         ip = ipzero;
1885
1886         make_nmb_name(&calling, global_myname, 0x0, "");
1887         make_nmb_name(&called , desthost, name_type, "");
1888
1889         ip = ipzero;
1890         if (have_ip) ip = dest_ip;
1891
1892         if (!(cli=cli_initialise(NULL)) || !cli_connect(cli, desthost, &ip)) {
1893                 DEBUG(0,("Connection to %s failed\n", desthost));
1894                 return 1;
1895         }
1896
1897         if (!cli_session_request(cli, &calling, &called)) {
1898                 DEBUG(0,("session request failed\n"));
1899                 cli_shutdown(cli);
1900                 return 1;
1901         }
1902
1903         send_message();
1904         cli_shutdown(cli);
1905
1906         return 0;
1907 }
1908
1909
1910 /****************************************************************************
1911   main program
1912 ****************************************************************************/
1913  int main(int argc,char *argv[])
1914 {
1915         fstring base_directory;
1916         char *pname = argv[0];
1917         int opt;
1918         extern FILE *dbf;
1919         extern char *optarg;
1920         extern int optind;
1921         pstring query_host;
1922         BOOL message = False;
1923         BOOL explicit_user = False;
1924         extern char tar_type;
1925         static pstring servicesf = CONFIGFILE;
1926         pstring term_code;
1927         pstring new_name_resolve_order;
1928         char *p;
1929
1930 #ifdef KANJI
1931         pstrcpy(term_code, KANJI);
1932 #else /* KANJI */
1933         *term_code = 0;
1934 #endif /* KANJI */
1935
1936         *query_host = 0;
1937         *base_directory = 0;
1938
1939         *new_name_resolve_order = 0;
1940
1941         DEBUGLEVEL = 2;
1942
1943         setup_logging(pname,True);
1944
1945         TimeInit();
1946         charset_initialise();
1947
1948         if(!get_myname(myhostname,NULL)) {
1949                 DEBUG(0,("Failed to get my hostname.\n"));
1950         }
1951
1952         in_client = True;   /* Make sure that we tell lp_load we are */
1953
1954         if (!lp_load(servicesf,True,False,False)) {
1955                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
1956         }
1957         
1958         codepage_initialise(lp_client_code_page());
1959
1960         interpret_coding_system(term_code);
1961
1962 #ifdef WITH_SSL
1963         sslutil_init(0);
1964 #endif
1965
1966         pstrcpy(workgroup,lp_workgroup());
1967
1968         load_interfaces();
1969         myumask = umask(0);
1970         umask(myumask);
1971
1972         if (getenv("USER")) {
1973                 pstrcpy(username,getenv("USER"));
1974
1975                 /* modification to support userid%passwd syntax in the USER var
1976                    25.Aug.97, jdblair@uab.edu */
1977
1978                 if ((p=strchr(username,'%'))) {
1979                         *p = 0;
1980                         pstrcpy(password,p+1);
1981                         got_pass = True;
1982                         memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
1983                 }
1984                 strupper(username);
1985         }
1986
1987         /* modification to support PASSWD environmental var
1988            25.Aug.97, jdblair@uab.edu */
1989         if (getenv("PASSWD")) {
1990                 pstrcpy(password,getenv("PASSWD"));
1991                 got_pass = True;
1992         }
1993
1994         if (getenv("PASSWD_FD") || getenv("PASSWD_FILE")) {
1995                 get_password_file();
1996                 got_pass = True;
1997         }
1998
1999         if (*username == 0 && getenv("LOGNAME")) {
2000                 pstrcpy(username,getenv("LOGNAME"));
2001                 strupper(username);
2002         }
2003
2004         if (*username == 0) {
2005                 pstrcpy(username,"GUEST");
2006         }
2007
2008         if (argc < 2) {
2009                 usage(pname);
2010                 exit(1);
2011         }
2012   
2013         if (*argv[1] != '-') {
2014                 pstrcpy(service,argv[1]);  
2015                 /* Convert any '/' characters in the service name to '\' characters */
2016                 string_replace( service, '/','\\');
2017                 argc--;
2018                 argv++;
2019                 
2020                 if (count_chars(service,'\\') < 3) {
2021                         usage(pname);
2022                         printf("\n%s: Not enough '\\' characters in service\n",service);
2023                         exit(1);
2024                 }
2025
2026                 if (argc > 1 && (*argv[1] != '-')) {
2027                         got_pass = True;
2028                         pstrcpy(password,argv[1]);  
2029                         memset(argv[1],'X',strlen(argv[1]));
2030                         argc--;
2031                         argv++;
2032                 }
2033         }
2034
2035         while ((opt = 
2036                 getopt(argc, argv,"s:B:O:R:M:i:Nn:d:Pp:l:hI:EU:L:t:m:W:T:D:c:")) != EOF) {
2037                 switch (opt) {
2038                 case 's':
2039                         pstrcpy(servicesf, optarg);
2040                         break;
2041                 case 'B':
2042                         iface_set_default(NULL,optarg,NULL);
2043                         break;
2044                 case 'O':
2045                         pstrcpy(user_socket_options,optarg);
2046                         break;  
2047                 case 'R':
2048                         pstrcpy(new_name_resolve_order, optarg);
2049                         break;
2050                 case 'M':
2051                         name_type = 0x03; /* messages are sent to NetBIOS name type 0x3 */
2052                         pstrcpy(desthost,optarg);
2053                         message = True;
2054                         break;
2055                 case 'i':
2056                         pstrcpy(scope,optarg);
2057                         break;
2058                 case 'N':
2059                         got_pass = True;
2060                         break;
2061                 case 'n':
2062                         pstrcpy(global_myname,optarg);
2063                         break;
2064                 case 'd':
2065                         if (*optarg == 'A')
2066                                 DEBUGLEVEL = 10000;
2067                         else
2068                                 DEBUGLEVEL = atoi(optarg);
2069                         break;
2070                 case 'P':
2071                         /* not needed anymore */
2072                         break;
2073                 case 'p':
2074                         port = atoi(optarg);
2075                         break;
2076                 case 'l':
2077                         slprintf(debugf,sizeof(debugf)-1, "%s.client",optarg);
2078                         break;
2079                 case 'h':
2080                         usage(pname);
2081                         exit(0);
2082                         break;
2083                 case 'I':
2084                         {
2085                                 dest_ip = *interpret_addr2(optarg);
2086                                 if (zero_ip(dest_ip))
2087                                         exit(1);
2088                                 have_ip = True;
2089                         }
2090                         break;
2091                 case 'E':
2092                         dbf = stderr;
2093                         break;
2094                 case 'U':
2095                         {
2096                                 char *lp;
2097                                 explicit_user = True;
2098                                 pstrcpy(username,optarg);
2099                                 if ((lp=strchr(username,'%'))) {
2100                                         *lp = 0;
2101                                         pstrcpy(password,lp+1);
2102                                         got_pass = True;
2103                                         memset(strchr(optarg,'%')+1,'X',strlen(password));
2104                                 }
2105                         }
2106                         break;
2107                 case 'L':
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
2142         if(*new_name_resolve_order)
2143                 lp_set_name_resolve_order(new_name_resolve_order);
2144
2145         if (!tar_type && !*query_host && !*service && !message) {
2146                 usage(pname);
2147                 exit(1);
2148         }
2149
2150         DEBUG( 3, ( "Client started (version %s).\n", VERSION ) );
2151
2152         if (tar_type) {
2153                 return do_tar_op(port, base_directory);
2154         }
2155
2156         if ((p=strchr(query_host,'#'))) {
2157                 *p = 0;
2158                 p++;
2159                 sscanf(p, "%x", &name_type);
2160         }
2161   
2162         if (*query_host) {
2163                 return do_host_query(query_host, port);
2164         }
2165
2166         if (message) {
2167                 return do_message_op();
2168         }
2169
2170         if (!process(base_directory)) {
2171                 close_sockets();
2172                 return(1);
2173         }
2174         close_sockets();
2175
2176         return(0);
2177 }