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