me stupid.
[Samba.git] / source / client / client.c
blob479c4f764f99b0862bb54f7e710e6cd13c3a2fd8
1 /*
2 Unix SMB/Netbios implementation.
3 Version 1.9.
4 SMB client
5 Copyright (C) Andrew Tridgell 1994-1998
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.
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.
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.
22 #define NO_SYSLOG
24 #include "includes.h"
26 #ifndef REGISTER
27 #define REGISTER 0
28 #endif
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 static pstring password;
39 static pstring username;
40 static pstring workgroup;
41 static char *cmdstr;
42 static BOOL got_pass;
43 static int io_bufsize = 64512;
44 extern struct in_addr ipzero;
46 static int name_type = 0x20;
47 static int max_protocol = PROTOCOL_NT1;
48 extern pstring user_socket_options;
50 static int process_tok(fstring tok);
51 static void cmd_help(void);
53 /* 30 second timeout on most commands */
54 #define CLIENT_TIMEOUT (30*1000)
55 #define SHORT_TIMEOUT (5*1000)
57 /* value for unused fid field in trans2 secondary request */
58 #define FID_UNUSED (0xFFFF)
60 time_t newer_than = 0;
61 int archive_level = 0;
63 extern pstring debugf;
64 extern int DEBUGLEVEL;
66 BOOL translation = False;
68 static BOOL have_ip;
70 /* clitar bits insert */
71 extern int blocksize;
72 extern BOOL tar_inc;
73 extern BOOL tar_reset;
74 /* clitar bits end */
77 mode_t myumask = 0755;
79 BOOL prompt = True;
81 int printmode = 1;
83 static BOOL recurse = False;
84 BOOL lowercase = False;
86 struct in_addr dest_ip;
88 #define SEPARATORS " \t\n\r"
90 BOOL abort_mget = True;
92 pstring fileselection = "";
94 extern file_info def_finfo;
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;
102 /* totals globals */
103 static double dir_total;
105 #define USENMB
107 /****************************************************************************
108 write to a local file with CR/LF->LF translation if appropriate. return the
109 number taken from the buffer. This may not equal the number written.
110 ****************************************************************************/
111 static int writefile(int f, char *b, int n)
113 int i;
115 if (!translation) {
116 return write(f,b,n);
119 i = 0;
120 while (i < n) {
121 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
122 b++;i++;
124 if (write(f, b, 1) != 1) {
125 break;
127 b++;
128 i++;
131 return(i);
134 /****************************************************************************
135 read from a file with LF->CR/LF translation if appropriate. return the
136 number read. read approx n bytes.
137 ****************************************************************************/
138 static int readfile(char *b, int size, int n, FILE *f)
140 int i;
141 int c;
143 if (!translation || (size != 1))
144 return(fread(b,size,n,f));
146 i = 0;
147 while (i < (n - 1) && (i < BUFFER_SIZE)) {
148 if ((c = getc(f)) == EOF) {
149 break;
152 if (c == '\n') { /* change all LFs to CR/LF */
153 b[i++] = '\r';
156 b[i++] = c;
159 return(i);
163 /****************************************************************************
164 send a message
165 ****************************************************************************/
166 static void send_message(void)
168 int total_len = 0;
169 int grp_id;
171 if (!cli_message_start(cli, desthost, username, &grp_id)) {
172 DEBUG(0,("message start: %s\n", cli_errstr(cli)));
173 return;
177 printf("Connected. Type your message, ending it with a Control-D\n");
179 while (!feof(stdin) && total_len < 1600) {
180 int maxlen = MIN(1600 - total_len,127);
181 pstring msg;
182 int l=0;
183 int c;
185 ZERO_ARRAY(msg);
187 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
188 if (c == '\n')
189 msg[l++] = '\r';
190 msg[l] = c;
193 if (!cli_message_text(cli, msg, l, grp_id)) {
194 printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
195 return;
198 total_len += l;
201 if (total_len >= 1600)
202 printf("the message was truncated to 1600 bytes\n");
203 else
204 printf("sent %d bytes\n",total_len);
206 if (!cli_message_end(cli, grp_id)) {
207 printf("SMBsendend failed (%s)\n",cli_errstr(cli));
208 return;
214 /****************************************************************************
215 check the space on a device
216 ****************************************************************************/
217 static void do_dskattr(void)
219 int total, bsize, avail;
221 if (!cli_dskattr(cli, &bsize, &total, &avail)) {
222 DEBUG(0,("Error in dskattr: %s\n",cli_errstr(cli)));
223 return;
226 DEBUG(0,("\n\t\t%d blocks of size %d. %d blocks available\n",
227 total, bsize, avail));
230 /****************************************************************************
231 show cd/pwd
232 ****************************************************************************/
233 static void cmd_pwd(void)
235 DEBUG(0,("Current directory is %s",service));
236 DEBUG(0,("%s\n",cur_dir));
240 /****************************************************************************
241 change directory - inner section
242 ****************************************************************************/
243 static void do_cd(char *newdir)
245 char *p = newdir;
246 pstring saved_dir;
247 pstring dname;
249 dos_format(newdir);
251 /* Save the current directory in case the
252 new directory is invalid */
253 pstrcpy(saved_dir, cur_dir);
254 if (*p == '\\')
255 pstrcpy(cur_dir,p);
256 else
257 pstrcat(cur_dir,p);
258 if (*(cur_dir+strlen(cur_dir)-1) != '\\') {
259 pstrcat(cur_dir, "\\");
261 dos_clean_name(cur_dir);
262 pstrcpy(dname,cur_dir);
263 pstrcat(cur_dir,"\\");
264 dos_clean_name(cur_dir);
266 if (!strequal(cur_dir,"\\")) {
267 if (!cli_chkpath(cli, dname)) {
268 DEBUG(0,("cd %s: %s\n", dname, cli_errstr(cli)));
269 pstrcpy(cur_dir,saved_dir);
273 pstrcpy(cd_path,cur_dir);
276 /****************************************************************************
277 change directory
278 ****************************************************************************/
279 static void cmd_cd(void)
281 fstring buf;
283 if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
284 do_cd(buf);
285 else
286 DEBUG(0,("Current directory is %s\n",cur_dir));
290 /*******************************************************************
291 decide if a file should be operated on
292 ********************************************************************/
293 static BOOL do_this_one(file_info *finfo)
295 if (finfo->mode & aDIR) return(True);
297 if (*fileselection &&
298 !mask_match(finfo->name,fileselection,False)) {
299 DEBUG(3,("match_match %s failed\n", finfo->name));
300 return False;
303 if (newer_than && finfo->mtime < newer_than) {
304 DEBUG(3,("newer_than %s failed\n", finfo->name));
305 return(False);
308 if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
309 DEBUG(3,("archive %s failed\n", finfo->name));
310 return(False);
313 return(True);
316 /****************************************************************************
317 display info about a file
318 ****************************************************************************/
319 static void display_finfo(file_info *finfo)
321 if (do_this_one(finfo)) {
322 time_t t = finfo->mtime; /* the time is assumed to be passed as GMT */
323 DEBUG(0,(" %-30s%7.7s %8.0f %s",
324 finfo->name,
325 attrib_string(finfo->mode),
326 (double)finfo->size,
327 asctime(LocalTime(&t))));
328 dir_total += finfo->size;
333 /****************************************************************************
334 accumulate size of a file
335 ****************************************************************************/
336 static void do_du(file_info *finfo)
338 if (do_this_one(finfo)) {
339 dir_total += finfo->size;
343 static BOOL do_list_recurse;
344 static BOOL do_list_dirs;
345 static char *do_list_queue = 0;
346 static long do_list_queue_size = 0;
347 static long do_list_queue_start = 0;
348 static long do_list_queue_end = 0;
349 static void (*do_list_fn)(file_info *);
351 /****************************************************************************
352 functions for do_list_queue
353 ****************************************************************************/
356 * The do_list_queue is a NUL-separated list of strings stored in a
357 * char*. Since this is a FIFO, we keep track of the beginning and
358 * ending locations of the data in the queue. When we overflow, we
359 * double the size of the char*. When the start of the data passes
360 * the midpoint, we move everything back. This is logically more
361 * complex than a linked list, but easier from a memory management
362 * angle. In any memory error condition, do_list_queue is reset.
363 * Functions check to ensure that do_list_queue is non-NULL before
364 * accessing it.
366 static void reset_do_list_queue(void)
368 if (do_list_queue)
370 free(do_list_queue);
372 do_list_queue = 0;
373 do_list_queue_size = 0;
374 do_list_queue_start = 0;
375 do_list_queue_end = 0;
378 static void init_do_list_queue(void)
380 reset_do_list_queue();
381 do_list_queue_size = 1024;
382 do_list_queue = malloc(do_list_queue_size);
383 if (do_list_queue == 0) {
384 DEBUG(0,("malloc fail for size %d\n",
385 (int)do_list_queue_size));
386 reset_do_list_queue();
387 } else {
388 memset(do_list_queue, 0, do_list_queue_size);
392 static void adjust_do_list_queue(void)
395 * If the starting point of the queue is more than half way through,
396 * move everything toward the beginning.
398 if (do_list_queue && (do_list_queue_start == do_list_queue_end))
400 DEBUG(4,("do_list_queue is empty\n"));
401 do_list_queue_start = do_list_queue_end = 0;
402 *do_list_queue = '\0';
404 else if (do_list_queue_start > (do_list_queue_size / 2))
406 DEBUG(4,("sliding do_list_queue backward\n"));
407 memmove(do_list_queue,
408 do_list_queue + do_list_queue_start,
409 do_list_queue_end - do_list_queue_start);
410 do_list_queue_end -= do_list_queue_start;
411 do_list_queue_start = 0;
416 static void add_to_do_list_queue(const char* entry)
418 long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
419 while (new_end > do_list_queue_size)
421 do_list_queue_size *= 2;
422 DEBUG(4,("enlarging do_list_queue to %d\n",
423 (int)do_list_queue_size));
424 do_list_queue = Realloc(do_list_queue, do_list_queue_size);
425 if (! do_list_queue) {
426 DEBUG(0,("failure enlarging do_list_queue to %d bytes\n",
427 (int)do_list_queue_size));
428 reset_do_list_queue();
430 else
432 memset(do_list_queue + do_list_queue_size / 2,
433 0, do_list_queue_size / 2);
436 if (do_list_queue)
438 pstrcpy(do_list_queue + do_list_queue_end, entry);
439 do_list_queue_end = new_end;
440 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
441 entry, (int)do_list_queue_start, (int)do_list_queue_end));
445 static char *do_list_queue_head(void)
447 return do_list_queue + do_list_queue_start;
450 static void remove_do_list_queue_head(void)
452 if (do_list_queue_end > do_list_queue_start)
454 do_list_queue_start += strlen(do_list_queue_head()) + 1;
455 adjust_do_list_queue();
456 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
457 (int)do_list_queue_start, (int)do_list_queue_end));
461 static int do_list_queue_empty(void)
463 return (! (do_list_queue && *do_list_queue));
466 /****************************************************************************
467 a helper for do_list
468 ****************************************************************************/
469 static void do_list_helper(file_info *f, const char *mask, void *state)
471 if (f->mode & aDIR) {
472 if (do_list_dirs && do_this_one(f)) {
473 do_list_fn(f);
475 if (do_list_recurse &&
476 !strequal(f->name,".") &&
477 !strequal(f->name,"..")) {
478 pstring mask2;
479 char *p;
481 pstrcpy(mask2, mask);
482 p = strrchr_m(mask2,'\\');
483 if (!p) return;
484 p[1] = 0;
485 pstrcat(mask2, f->name);
486 pstrcat(mask2,"\\*");
487 add_to_do_list_queue(mask2);
489 return;
492 if (do_this_one(f)) {
493 do_list_fn(f);
498 /****************************************************************************
499 a wrapper around cli_list that adds recursion
500 ****************************************************************************/
501 void do_list(const char *mask,uint16 attribute,void (*fn)(file_info *),BOOL rec, BOOL dirs)
503 static int in_do_list = 0;
505 if (in_do_list && rec)
507 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
508 exit(1);
511 in_do_list = 1;
513 do_list_recurse = rec;
514 do_list_dirs = dirs;
515 do_list_fn = fn;
517 if (rec)
519 init_do_list_queue();
520 add_to_do_list_queue(mask);
522 while (! do_list_queue_empty())
525 * Need to copy head so that it doesn't become
526 * invalid inside the call to cli_list. This
527 * would happen if the list were expanded
528 * during the call.
529 * Fix from E. Jay Berkenbilt (ejb@ql.org)
531 pstring head;
532 pstrcpy(head, do_list_queue_head());
533 cli_list(cli, head, attribute, do_list_helper, NULL);
534 remove_do_list_queue_head();
535 if ((! do_list_queue_empty()) && (fn == display_finfo))
537 char* next_file = do_list_queue_head();
538 char* save_ch = 0;
539 if ((strlen(next_file) >= 2) &&
540 (next_file[strlen(next_file) - 1] == '*') &&
541 (next_file[strlen(next_file) - 2] == '\\'))
543 save_ch = next_file +
544 strlen(next_file) - 2;
545 *save_ch = '\0';
547 DEBUG(0,("\n%s\n",next_file));
548 if (save_ch)
550 *save_ch = '\\';
555 else
557 if (cli_list(cli, mask, attribute, do_list_helper, NULL) == -1)
559 DEBUG(0, ("%s listing %s\n", cli_errstr(cli), mask));
563 in_do_list = 0;
564 reset_do_list_queue();
567 /****************************************************************************
568 get a directory listing
569 ****************************************************************************/
570 static void cmd_dir(void)
572 uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
573 pstring mask;
574 fstring buf;
575 char *p=buf;
577 dir_total = 0;
578 pstrcpy(mask,cur_dir);
579 if(mask[strlen(mask)-1]!='\\')
580 pstrcat(mask,"\\");
582 if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
583 dos_format(p);
584 if (*p == '\\')
585 pstrcpy(mask,p);
586 else
587 pstrcat(mask,p);
589 else {
590 pstrcat(mask,"*");
593 do_list(mask, attribute, display_finfo, recurse, True);
595 do_dskattr();
597 DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
601 /****************************************************************************
602 get a directory listing
603 ****************************************************************************/
604 static void cmd_du(void)
606 uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
607 pstring mask;
608 fstring buf;
609 char *p=buf;
611 dir_total = 0;
612 pstrcpy(mask,cur_dir);
613 if(mask[strlen(mask)-1]!='\\')
614 pstrcat(mask,"\\");
616 if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
617 dos_format(p);
618 if (*p == '\\')
619 pstrcpy(mask,p);
620 else
621 pstrcat(mask,p);
622 } else {
623 pstrcat(mask,"*");
626 do_list(mask, attribute, do_du, recurse, True);
628 do_dskattr();
630 DEBUG(0, ("Total number of bytes: %.0f\n", dir_total));
634 /****************************************************************************
635 get a file from rname to lname
636 ****************************************************************************/
637 static void do_get(char *rname,char *lname)
639 int handle=0,fnum;
640 BOOL newhandle = False;
641 char *data;
642 struct timeval tp_start;
643 int read_size = io_bufsize;
644 uint16 attr;
645 size_t size;
646 off_t nread = 0;
648 GetTimeOfDay(&tp_start);
650 if (lowercase) {
651 strlower(lname);
654 fnum = cli_open(cli, rname, O_RDONLY, DENY_NONE);
656 if (fnum == -1) {
657 DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),rname));
658 return;
661 if(!strcmp(lname,"-")) {
662 handle = fileno(stdout);
663 } else {
664 handle = sys_open(lname,O_WRONLY|O_CREAT|O_TRUNC,0644);
665 newhandle = True;
667 if (handle < 0) {
668 DEBUG(0,("Error opening local file %s\n",lname));
669 return;
673 if (!cli_qfileinfo(cli, fnum,
674 &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
675 !cli_getattrE(cli, fnum,
676 &attr, &size, NULL, NULL, NULL)) {
677 DEBUG(0,("getattrib: %s\n",cli_errstr(cli)));
678 return;
681 DEBUG(2,("getting file %s of size %.0f as %s ",
682 lname, (double)size, lname));
684 if(!(data = (char *)malloc(read_size))) {
685 DEBUG(0,("malloc fail for size %d\n", read_size));
686 cli_close(cli, fnum);
687 return;
690 while (1) {
691 int n = cli_read(cli, fnum, data, nread, read_size);
693 if (n <= 0) break;
695 if (writefile(handle,data, n) != n) {
696 DEBUG(0,("Error writing local file\n"));
697 break;
700 nread += n;
703 if (nread < size) {
704 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
705 rname, (long)nread));
708 free(data);
710 if (!cli_close(cli, fnum)) {
711 DEBUG(0,("Error %s closing remote file\n",cli_errstr(cli)));
714 if (newhandle) {
715 close(handle);
718 if (archive_level >= 2 && (attr & aARCH)) {
719 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
723 struct timeval tp_end;
724 int this_time;
726 GetTimeOfDay(&tp_end);
727 this_time =
728 (tp_end.tv_sec - tp_start.tv_sec)*1000 +
729 (tp_end.tv_usec - tp_start.tv_usec)/1000;
730 get_total_time_ms += this_time;
731 get_total_size += nread;
733 DEBUG(2,("(%3.1f kb/s) (average %3.1f kb/s)\n",
734 nread / (1.024*this_time + 1.0e-4),
735 get_total_size / (1.024*get_total_time_ms)));
740 /****************************************************************************
741 get a file
742 ****************************************************************************/
743 static void cmd_get(void)
745 pstring lname;
746 pstring rname;
747 char *p;
749 pstrcpy(rname,cur_dir);
750 pstrcat(rname,"\\");
752 p = rname + strlen(rname);
754 if (!next_token_nr(NULL,p,NULL,sizeof(rname)-strlen(rname))) {
755 DEBUG(0,("get <filename>\n"));
756 return;
758 pstrcpy(lname,p);
759 dos_clean_name(rname);
761 next_token_nr(NULL,lname,NULL,sizeof(lname));
763 do_get(rname, lname);
767 /****************************************************************************
768 do a mget operation on one file
769 ****************************************************************************/
770 static void do_mget(file_info *finfo)
772 pstring rname;
773 pstring quest;
774 pstring saved_curdir;
775 pstring mget_mask;
777 if (strequal(finfo->name,".") || strequal(finfo->name,".."))
778 return;
780 if (abort_mget) {
781 DEBUG(0,("mget aborted\n"));
782 return;
785 if (finfo->mode & aDIR)
786 slprintf(quest,sizeof(pstring)-1,
787 "Get directory %s? ",finfo->name);
788 else
789 slprintf(quest,sizeof(pstring)-1,
790 "Get file %s? ",finfo->name);
792 if (prompt && !yesno(quest)) return;
794 if (!(finfo->mode & aDIR)) {
795 pstrcpy(rname,cur_dir);
796 pstrcat(rname,finfo->name);
797 do_get(rname,finfo->name);
798 return;
801 /* handle directories */
802 pstrcpy(saved_curdir,cur_dir);
804 pstrcat(cur_dir,finfo->name);
805 pstrcat(cur_dir,"\\");
807 unix_format(finfo->name);
808 if (lowercase)
809 strlower(finfo->name);
811 if (!directory_exist(finfo->name,NULL) &&
812 mkdir(finfo->name,0777) != 0) {
813 DEBUG(0,("failed to create directory %s\n",finfo->name));
814 pstrcpy(cur_dir,saved_curdir);
815 return;
818 if (chdir(finfo->name) != 0) {
819 DEBUG(0,("failed to chdir to directory %s\n",finfo->name));
820 pstrcpy(cur_dir,saved_curdir);
821 return;
824 pstrcpy(mget_mask,cur_dir);
825 pstrcat(mget_mask,"*");
827 do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,False, True);
828 chdir("..");
829 pstrcpy(cur_dir,saved_curdir);
833 /****************************************************************************
834 view the file using the pager
835 ****************************************************************************/
836 static void cmd_more(void)
838 fstring rname,lname,pager_cmd;
839 char *pager;
840 int fd;
842 fstrcpy(rname,cur_dir);
843 fstrcat(rname,"\\");
845 slprintf(lname,sizeof(lname)-1, "%s/smbmore.XXXXXX",tmpdir());
846 fd = smb_mkstemp(lname);
847 if (fd == -1) {
848 DEBUG(0,("failed to create temporary file for more\n"));
849 return;
851 close(fd);
853 if (!next_token_nr(NULL,rname+strlen(rname),NULL,sizeof(rname)-strlen(rname))) {
854 DEBUG(0,("more <filename>\n"));
855 unlink(lname);
856 return;
858 dos_clean_name(rname);
860 do_get(rname,lname);
862 pager=getenv("PAGER");
864 slprintf(pager_cmd,sizeof(pager_cmd)-1,
865 "%s %s",(pager? pager:PAGER), lname);
866 system(pager_cmd);
867 unlink(lname);
872 /****************************************************************************
873 do a mget command
874 ****************************************************************************/
875 static void cmd_mget(void)
877 uint16 attribute = aSYSTEM | aHIDDEN;
878 pstring mget_mask;
879 fstring buf;
880 char *p=buf;
882 *mget_mask = 0;
884 if (recurse)
885 attribute |= aDIR;
887 abort_mget = False;
889 while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
890 pstrcpy(mget_mask,cur_dir);
891 if(mget_mask[strlen(mget_mask)-1]!='\\')
892 pstrcat(mget_mask,"\\");
894 if (*p == '\\')
895 pstrcpy(mget_mask,p);
896 else
897 pstrcat(mget_mask,p);
898 do_list(mget_mask, attribute,do_mget,False,True);
901 if (!*mget_mask) {
902 pstrcpy(mget_mask,cur_dir);
903 if(mget_mask[strlen(mget_mask)-1]!='\\')
904 pstrcat(mget_mask,"\\");
905 pstrcat(mget_mask,"*");
906 do_list(mget_mask, attribute,do_mget,False,True);
911 /****************************************************************************
912 make a directory of name "name"
913 ****************************************************************************/
914 static BOOL do_mkdir(char *name)
916 if (!cli_mkdir(cli, name)) {
917 DEBUG(0,("%s making remote directory %s\n",
918 cli_errstr(cli),name));
919 return(False);
922 return(True);
926 /****************************************************************************
927 Exit client.
928 ****************************************************************************/
929 static void cmd_quit(void)
931 cli_shutdown(cli);
932 exit(0);
936 /****************************************************************************
937 make a directory
938 ****************************************************************************/
939 static void cmd_mkdir(void)
941 pstring mask;
942 fstring buf;
943 char *p=buf;
945 pstrcpy(mask,cur_dir);
947 if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
948 if (!recurse)
949 DEBUG(0,("mkdir <dirname>\n"));
950 return;
952 pstrcat(mask,p);
954 if (recurse) {
955 pstring ddir;
956 pstring ddir2;
957 *ddir2 = 0;
959 pstrcpy(ddir,mask);
960 trim_string(ddir,".",NULL);
961 p = strtok(ddir,"/\\");
962 while (p) {
963 pstrcat(ddir2,p);
964 if (!cli_chkpath(cli, ddir2)) {
965 do_mkdir(ddir2);
967 pstrcat(ddir2,"\\");
968 p = strtok(NULL,"/\\");
970 } else {
971 do_mkdir(mask);
976 /****************************************************************************
977 put a single file
978 ****************************************************************************/
979 static void do_put(char *rname,char *lname)
981 int fnum;
982 FILE *f;
983 int nread=0;
984 char *buf=NULL;
985 int maxwrite=io_bufsize;
987 struct timeval tp_start;
988 GetTimeOfDay(&tp_start);
990 fnum = cli_open(cli, rname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
992 if (fnum == -1) {
993 DEBUG(0,("%s opening remote file %s\n",cli_errstr(cli),rname));
994 return;
997 /* allow files to be piped into smbclient
998 jdblair 24.jun.98 */
999 if (!strcmp(lname, "-")) {
1000 f = stdin;
1001 /* size of file is not known */
1002 } else {
1003 f = sys_fopen(lname,"r");
1006 if (!f) {
1007 DEBUG(0,("Error opening local file %s\n",lname));
1008 return;
1012 DEBUG(1,("putting file %s as %s ",lname,
1013 rname));
1015 buf = (char *)malloc(maxwrite);
1016 while (!feof(f)) {
1017 int n = maxwrite;
1018 int ret;
1020 if ((n = readfile(buf,1,n,f)) < 1) {
1021 if((n == 0) && feof(f))
1022 break; /* Empty local file. */
1024 DEBUG(0,("Error reading local file: %s\n", strerror(errno) ));
1025 break;
1028 ret = cli_write(cli, fnum, 0, buf, nread, n);
1030 if (n != ret) {
1031 DEBUG(0,("Error writing file: %s\n", cli_errstr(cli)));
1032 break;
1035 nread += n;
1038 if (!cli_close(cli, fnum)) {
1039 DEBUG(0,("%s closing remote file %s\n",cli_errstr(cli),rname));
1040 fclose(f);
1041 if (buf) free(buf);
1042 return;
1046 fclose(f);
1047 if (buf) free(buf);
1050 struct timeval tp_end;
1051 int this_time;
1053 GetTimeOfDay(&tp_end);
1054 this_time =
1055 (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1056 (tp_end.tv_usec - tp_start.tv_usec)/1000;
1057 put_total_time_ms += this_time;
1058 put_total_size += nread;
1060 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1061 nread / (1.024*this_time + 1.0e-4),
1062 put_total_size / (1.024*put_total_time_ms)));
1065 if (f == stdin) {
1066 cli_shutdown(cli);
1067 exit(0);
1073 /****************************************************************************
1074 put a file
1075 ****************************************************************************/
1076 static void cmd_put(void)
1078 pstring lname;
1079 pstring rname;
1080 fstring buf;
1081 char *p=buf;
1083 pstrcpy(rname,cur_dir);
1084 pstrcat(rname,"\\");
1086 if (!next_token_nr(NULL,p,NULL,sizeof(buf))) {
1087 DEBUG(0,("put <filename>\n"));
1088 return;
1090 pstrcpy(lname,p);
1092 if (next_token_nr(NULL,p,NULL,sizeof(buf)))
1093 pstrcat(rname,p);
1094 else
1095 pstrcat(rname,lname);
1097 dos_clean_name(rname);
1100 SMB_STRUCT_STAT st;
1101 /* allow '-' to represent stdin
1102 jdblair, 24.jun.98 */
1103 if (!file_exist(lname,&st) &&
1104 (strcmp(lname,"-"))) {
1105 DEBUG(0,("%s does not exist\n",lname));
1106 return;
1110 do_put(rname,lname);
1113 /*************************************
1114 File list structure
1115 *************************************/
1117 static struct file_list {
1118 struct file_list *prev, *next;
1119 char *file_path;
1120 BOOL isdir;
1121 } *file_list;
1123 /****************************************************************************
1124 Free a file_list structure
1125 ****************************************************************************/
1127 static void free_file_list (struct file_list * list)
1129 struct file_list *tmp;
1131 while (list)
1133 tmp = list;
1134 DLIST_REMOVE(list, list);
1135 if (tmp->file_path) free(tmp->file_path);
1136 free(tmp);
1140 /****************************************************************************
1141 seek in a directory/file list until you get something that doesn't start with
1142 the specified name
1143 ****************************************************************************/
1144 static BOOL seek_list(struct file_list *list, char *name)
1146 while (list) {
1147 trim_string(list->file_path,"./","\n");
1148 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1149 return(True);
1151 list = list->next;
1154 return(False);
1157 /****************************************************************************
1158 set the file selection mask
1159 ****************************************************************************/
1160 static void cmd_select(void)
1162 pstrcpy(fileselection,"");
1163 next_token_nr(NULL,fileselection,NULL,sizeof(fileselection));
1166 /****************************************************************************
1167 Recursive file matching function act as find
1168 match must be always set to True when calling this function
1169 ****************************************************************************/
1170 static int file_find(struct file_list **list, const char *directory,
1171 const char *expression, BOOL match)
1173 DIR *dir;
1174 struct file_list *entry;
1175 struct stat statbuf;
1176 int ret;
1177 char *path;
1178 BOOL isdir;
1179 char *dname;
1181 dir = opendir(directory);
1182 if (!dir) return -1;
1184 while ((dname = readdirname(dir))) {
1185 if (!strcmp("..", dname)) continue;
1186 if (!strcmp(".", dname)) continue;
1188 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1189 continue;
1192 isdir = False;
1193 if (!match || !ms_fnmatch(expression, dname)) {
1194 if (recurse) {
1195 ret = stat(path, &statbuf);
1196 if (ret == 0) {
1197 if (S_ISDIR(statbuf.st_mode)) {
1198 isdir = True;
1199 ret = file_find(list, path, expression, False);
1201 } else {
1202 DEBUG(0,("file_find: cannot stat file %s\n", path));
1205 if (ret == -1) {
1206 free(path);
1207 closedir(dir);
1208 return -1;
1211 entry = (struct file_list *) malloc(sizeof (struct file_list));
1212 if (!entry) {
1213 DEBUG(0,("Out of memory in file_find\n"));
1214 closedir(dir);
1215 return -1;
1217 entry->file_path = path;
1218 entry->isdir = isdir;
1219 DLIST_ADD(*list, entry);
1220 } else {
1221 free(path);
1225 closedir(dir);
1226 return 0;
1229 /****************************************************************************
1230 mput some files
1231 ****************************************************************************/
1232 static void cmd_mput(void)
1234 fstring buf;
1235 char *p=buf;
1237 while (next_token_nr(NULL,p,NULL,sizeof(buf))) {
1238 int ret;
1239 struct file_list *temp_list;
1240 char *quest, *lname, *rname;
1242 file_list = NULL;
1244 ret = file_find(&file_list, ".", p, True);
1245 if (ret) {
1246 free_file_list(file_list);
1247 continue;
1250 quest = NULL;
1251 lname = NULL;
1252 rname = NULL;
1254 for (temp_list = file_list; temp_list;
1255 temp_list = temp_list->next) {
1257 if (lname) free(lname);
1258 if (asprintf(&lname, "%s/", temp_list->file_path) <= 0)
1259 continue;
1260 trim_string(lname, "./", "/");
1262 /* check if it's a directory */
1263 if (temp_list->isdir) {
1264 /* if (!recurse) continue; */
1266 if (quest) free(quest);
1267 asprintf(&quest, "Put directory %s? ", lname);
1268 if (prompt && !yesno(quest)) { /* No */
1269 /* Skip the directory */
1270 lname[strlen(lname)-1] = '/';
1271 if (!seek_list(temp_list, lname))
1272 break;
1273 } else { /* Yes */
1274 if (rname) free(rname);
1275 asprintf(&rname, "%s%s", cur_dir, lname);
1276 dos_format(rname);
1277 if (!cli_chkpath(cli, rname) &&
1278 !do_mkdir(rname)) {
1279 DEBUG (0, ("Unable to make dir, skipping..."));
1280 /* Skip the directory */
1281 lname[strlen(lname)-1] = '/';
1282 if (!seek_list(temp_list, lname))
1283 break;
1286 continue;
1287 } else {
1288 if (quest) free(quest);
1289 asprintf(&quest,"Put file %s? ", lname);
1290 if (prompt && !yesno(quest)) /* No */
1291 continue;
1293 /* Yes */
1294 if (rname) free(rname);
1295 asprintf(&rname, "%s%s", cur_dir, lname);
1298 dos_format(rname);
1300 do_put(rname, lname);
1302 free_file_list(file_list);
1303 if (quest) free(quest);
1304 if (lname) free(lname);
1305 if (rname) free(rname);
1310 /****************************************************************************
1311 cancel a print job
1312 ****************************************************************************/
1313 static void do_cancel(int job)
1315 if (cli_printjob_del(cli, job)) {
1316 printf("Job %d cancelled\n",job);
1317 } else {
1318 printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1323 /****************************************************************************
1324 cancel a print job
1325 ****************************************************************************/
1326 static void cmd_cancel(void)
1328 fstring buf;
1329 int job;
1331 if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1332 printf("cancel <jobid> ...\n");
1333 return;
1335 do {
1336 job = atoi(buf);
1337 do_cancel(job);
1338 } while (next_token_nr(NULL,buf,NULL,sizeof(buf)));
1342 /****************************************************************************
1343 print a file
1344 ****************************************************************************/
1345 static void cmd_print(void)
1347 pstring lname;
1348 pstring rname;
1349 char *p;
1351 if (!next_token_nr(NULL,lname,NULL, sizeof(lname))) {
1352 DEBUG(0,("print <filename>\n"));
1353 return;
1356 pstrcpy(rname,lname);
1357 p = strrchr_m(rname,'/');
1358 if (p) {
1359 slprintf(rname, sizeof(rname)-1, "%s-%d", p+1, (int)sys_getpid());
1362 if (strequal(lname,"-")) {
1363 slprintf(rname, sizeof(rname)-1, "stdin-%d", (int)sys_getpid());
1366 do_put(rname, lname);
1370 /****************************************************************************
1371 show a print queue entry
1372 ****************************************************************************/
1373 static void queue_fn(struct print_job_info *p)
1375 DEBUG(0,("%-6d %-9d %s\n", (int)p->id, (int)p->size, p->name));
1378 /****************************************************************************
1379 show a print queue
1380 ****************************************************************************/
1381 static void cmd_queue(void)
1383 cli_print_queue(cli, queue_fn);
1386 /****************************************************************************
1387 delete some files
1388 ****************************************************************************/
1389 static void do_del(file_info *finfo)
1391 pstring mask;
1393 pstrcpy(mask,cur_dir);
1394 pstrcat(mask,finfo->name);
1396 if (finfo->mode & aDIR)
1397 return;
1399 if (!cli_unlink(cli, mask)) {
1400 DEBUG(0,("%s deleting remote file %s\n",cli_errstr(cli),mask));
1404 /****************************************************************************
1405 delete some files
1406 ****************************************************************************/
1407 static void cmd_del(void)
1409 pstring mask;
1410 fstring buf;
1411 uint16 attribute = aSYSTEM | aHIDDEN;
1413 if (recurse)
1414 attribute |= aDIR;
1416 pstrcpy(mask,cur_dir);
1418 if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1419 DEBUG(0,("del <filename>\n"));
1420 return;
1422 pstrcat(mask,buf);
1424 do_list(mask, attribute,do_del,False,False);
1427 /****************************************************************************
1428 ****************************************************************************/
1429 static void cmd_open(void)
1431 pstring mask;
1432 fstring buf;
1434 pstrcpy(mask,cur_dir);
1436 if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1437 DEBUG(0,("del <filename>\n"));
1438 return;
1440 pstrcat(mask,buf);
1442 cli_open(cli, mask, O_RDWR, DENY_ALL);
1446 /****************************************************************************
1447 remove a directory
1448 ****************************************************************************/
1449 static void cmd_rmdir(void)
1451 pstring mask;
1452 fstring buf;
1454 pstrcpy(mask,cur_dir);
1456 if (!next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1457 DEBUG(0,("rmdir <dirname>\n"));
1458 return;
1460 pstrcat(mask,buf);
1462 if (!cli_rmdir(cli, mask)) {
1463 DEBUG(0,("%s removing remote directory file %s\n",
1464 cli_errstr(cli),mask));
1468 /****************************************************************************
1469 rename some files
1470 ****************************************************************************/
1471 static void cmd_rename(void)
1473 pstring src,dest;
1474 fstring buf,buf2;
1476 pstrcpy(src,cur_dir);
1477 pstrcpy(dest,cur_dir);
1479 if (!next_token_nr(NULL,buf,NULL,sizeof(buf)) ||
1480 !next_token_nr(NULL,buf2,NULL, sizeof(buf2))) {
1481 DEBUG(0,("rename <src> <dest>\n"));
1482 return;
1485 pstrcat(src,buf);
1486 pstrcat(dest,buf2);
1488 if (!cli_rename(cli, src, dest)) {
1489 DEBUG(0,("%s renaming files\n",cli_errstr(cli)));
1490 return;
1495 /****************************************************************************
1496 toggle the prompt flag
1497 ****************************************************************************/
1498 static void cmd_prompt(void)
1500 prompt = !prompt;
1501 DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
1505 /****************************************************************************
1506 set the newer than time
1507 ****************************************************************************/
1508 static void cmd_newer(void)
1510 fstring buf;
1511 BOOL ok;
1512 SMB_STRUCT_STAT sbuf;
1514 ok = next_token_nr(NULL,buf,NULL,sizeof(buf));
1515 if (ok && (sys_stat(buf,&sbuf) == 0)) {
1516 newer_than = sbuf.st_mtime;
1517 DEBUG(1,("Getting files newer than %s",
1518 asctime(LocalTime(&newer_than))));
1519 } else {
1520 newer_than = 0;
1523 if (ok && newer_than == 0)
1524 DEBUG(0,("Error setting newer-than time\n"));
1527 /****************************************************************************
1528 set the archive level
1529 ****************************************************************************/
1530 static void cmd_archive(void)
1532 fstring buf;
1534 if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1535 archive_level = atoi(buf);
1536 } else
1537 DEBUG(0,("Archive level is %d\n",archive_level));
1540 /****************************************************************************
1541 toggle the lowercaseflag
1542 ****************************************************************************/
1543 static void cmd_lowercase(void)
1545 lowercase = !lowercase;
1546 DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
1552 /****************************************************************************
1553 toggle the recurse flag
1554 ****************************************************************************/
1555 static void cmd_recurse(void)
1557 recurse = !recurse;
1558 DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
1561 /****************************************************************************
1562 toggle the translate flag
1563 ****************************************************************************/
1564 static void cmd_translate(void)
1566 translation = !translation;
1567 DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
1568 translation?"on":"off"));
1572 /****************************************************************************
1573 do a printmode command
1574 ****************************************************************************/
1575 static void cmd_printmode(void)
1577 fstring buf;
1578 fstring mode;
1580 if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1581 if (strequal(buf,"text")) {
1582 printmode = 0;
1583 } else {
1584 if (strequal(buf,"graphics"))
1585 printmode = 1;
1586 else
1587 printmode = atoi(buf);
1591 switch(printmode)
1593 case 0:
1594 fstrcpy(mode,"text");
1595 break;
1596 case 1:
1597 fstrcpy(mode,"graphics");
1598 break;
1599 default:
1600 slprintf(mode,sizeof(mode)-1,"%d",printmode);
1601 break;
1604 DEBUG(2,("the printmode is now %s\n",mode));
1607 /****************************************************************************
1608 do the lcd command
1609 ****************************************************************************/
1610 static void cmd_lcd(void)
1612 fstring buf;
1613 pstring d;
1615 if (next_token_nr(NULL,buf,NULL,sizeof(buf)))
1616 chdir(buf);
1617 DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
1620 /****************************************************************************
1621 list a share name
1622 ****************************************************************************/
1623 static void browse_fn(const char *name, uint32 m,
1624 const char *comment, void *state)
1626 fstring typestr;
1628 *typestr=0;
1630 switch (m)
1632 case STYPE_DISKTREE:
1633 fstrcpy(typestr,"Disk"); break;
1634 case STYPE_PRINTQ:
1635 fstrcpy(typestr,"Printer"); break;
1636 case STYPE_DEVICE:
1637 fstrcpy(typestr,"Device"); break;
1638 case STYPE_IPC:
1639 fstrcpy(typestr,"IPC"); break;
1641 printf("\t%-15.15s%-10.10s%s\n",
1642 name,typestr,comment);
1646 /****************************************************************************
1647 try and browse available connections on a host
1648 ****************************************************************************/
1649 static BOOL browse_host(BOOL sort)
1651 int ret;
1653 printf("\n\tSharename Type Comment\n");
1654 printf("\t--------- ---- -------\n");
1656 if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
1657 printf("Error returning browse list: %s\n", cli_errstr(cli));
1659 return (ret != -1);
1662 /****************************************************************************
1663 list a server name
1664 ****************************************************************************/
1665 static void server_fn(const char *name, uint32 m,
1666 const char *comment, void *state)
1668 printf("\t%-16.16s %s\n", name, comment);
1671 /****************************************************************************
1672 try and browse available connections on a host
1673 ****************************************************************************/
1674 static BOOL list_servers(char *wk_grp)
1676 if (!cli->server_domain) return False;
1678 printf("\n\tServer Comment\n");
1679 printf("\t--------- -------\n");
1681 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn, NULL);
1683 printf("\n\tWorkgroup Master\n");
1684 printf("\t--------- -------\n");
1686 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM, server_fn, NULL);
1687 return True;
1690 /* Some constants for completing filename arguments */
1692 #define COMPL_NONE 0 /* No completions */
1693 #define COMPL_REMOTE 1 /* Complete remote filename */
1694 #define COMPL_LOCAL 2 /* Complete local filename */
1696 /* This defines the commands supported by this client */
1697 struct
1699 char *name;
1700 void (*fn)(void);
1701 char *description;
1702 char compl_args[2]; /* Completion argument info */
1703 } commands[] =
1705 {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1706 {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1707 {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
1708 {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
1709 {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
1710 {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
1711 {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
1712 {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
1713 {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
1714 {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
1715 {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
1716 {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
1717 {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
1718 {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
1719 {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
1720 {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
1721 {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
1722 {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
1723 {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
1724 {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
1725 {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
1726 {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
1727 {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
1728 {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
1729 {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
1730 {"printmode",cmd_printmode,"<graphics or text> set the print mode",{COMPL_NONE,COMPL_NONE}},
1731 {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
1732 {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
1733 {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1734 {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1735 {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
1736 {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
1737 {"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}},
1738 {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
1739 {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
1740 {"tarmode",cmd_tarmode,
1741 "<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
1742 {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
1743 {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
1744 {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
1745 {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
1746 {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
1747 {"",NULL,NULL,{COMPL_NONE,COMPL_NONE}}
1751 /*******************************************************************
1752 lookup a command string in the list of commands, including
1753 abbreviations
1754 ******************************************************************/
1755 static int process_tok(fstring tok)
1757 int i = 0, matches = 0;
1758 int cmd=0;
1759 int tok_len = strlen(tok);
1761 while (commands[i].fn != NULL) {
1762 if (strequal(commands[i].name,tok)) {
1763 matches = 1;
1764 cmd = i;
1765 break;
1766 } else if (strnequal(commands[i].name, tok, tok_len)) {
1767 matches++;
1768 cmd = i;
1770 i++;
1773 if (matches == 0)
1774 return(-1);
1775 else if (matches == 1)
1776 return(cmd);
1777 else
1778 return(-2);
1781 /****************************************************************************
1782 help
1783 ****************************************************************************/
1784 static void cmd_help(void)
1786 int i=0,j;
1787 fstring buf;
1789 if (next_token_nr(NULL,buf,NULL,sizeof(buf))) {
1790 if ((i = process_tok(buf)) >= 0)
1791 DEBUG(0,("HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description));
1792 } else {
1793 while (commands[i].description) {
1794 for (j=0; commands[i].description && (j<5); j++) {
1795 DEBUG(0,("%-15s",commands[i].name));
1796 i++;
1798 DEBUG(0,("\n"));
1803 /****************************************************************************
1804 process a -c command string
1805 ****************************************************************************/
1806 static void process_command_string(char *cmd)
1808 pstring line;
1809 char *ptr;
1811 while (cmd[0] != '\0') {
1812 char *p;
1813 fstring tok;
1814 int i;
1816 if ((p = strchr_m(cmd, ';')) == 0) {
1817 strncpy(line, cmd, 999);
1818 line[1000] = '\0';
1819 cmd += strlen(cmd);
1820 } else {
1821 if (p - cmd > 999) p = cmd + 999;
1822 strncpy(line, cmd, p - cmd);
1823 line[p - cmd] = '\0';
1824 cmd = p + 1;
1827 /* and get the first part of the command */
1828 ptr = line;
1829 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
1831 if ((i = process_tok(tok)) >= 0) {
1832 commands[i].fn();
1833 } else if (i == -2) {
1834 DEBUG(0,("%s: command abbreviation ambiguous\n",tok));
1835 } else {
1836 DEBUG(0,("%s: command not found\n",tok));
1841 /****************************************************************************
1842 handle completion of commands for readline
1843 ****************************************************************************/
1844 static char **completion_fn(char *text, int start, int end)
1846 #define MAX_COMPLETIONS 100
1847 char **matches;
1848 int i, count=0;
1850 /* for words not at the start of the line fallback to filename completion */
1851 if (start) return NULL;
1853 matches = (char **)malloc(sizeof(matches[0])*MAX_COMPLETIONS);
1854 if (!matches) return NULL;
1856 matches[count++] = strdup(text);
1857 if (!matches[0]) return NULL;
1859 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
1860 if (strncmp(text, commands[i].name, strlen(text)) == 0) {
1861 matches[count] = strdup(commands[i].name);
1862 if (!matches[count]) return NULL;
1863 count++;
1867 if (count == 2) {
1868 free(matches[0]);
1869 matches[0] = strdup(matches[1]);
1871 matches[count] = NULL;
1872 return matches;
1876 /****************************************************************************
1877 make sure we swallow keepalives during idle time
1878 ****************************************************************************/
1879 static void readline_callback(void)
1881 fd_set fds;
1882 struct timeval timeout;
1883 static time_t last_t;
1884 time_t t;
1886 t = time(NULL);
1888 if (t - last_t < 5) return;
1890 last_t = t;
1892 again:
1893 FD_ZERO(&fds);
1894 FD_SET(cli->fd,&fds);
1896 timeout.tv_sec = 0;
1897 timeout.tv_usec = 0;
1898 sys_select_intr(cli->fd+1,&fds,&timeout);
1900 /* We deliberately use receive_smb instead of
1901 client_receive_smb as we want to receive
1902 session keepalives and then drop them here.
1904 if (FD_ISSET(cli->fd,&fds)) {
1905 receive_smb(cli->fd,cli->inbuf,0);
1906 goto again;
1909 cli_chkpath(cli, "\\");
1913 /****************************************************************************
1914 process commands on stdin
1915 ****************************************************************************/
1916 static void process_stdin(void)
1918 char *ptr;
1920 while (1) {
1921 fstring tok;
1922 fstring the_prompt;
1923 char *cline;
1924 pstring line;
1925 int i;
1927 /* display a prompt */
1928 slprintf(the_prompt, sizeof(the_prompt)-1, "smb: %s> ", cur_dir);
1929 cline = smb_readline(the_prompt, readline_callback, completion_fn);
1931 if (!cline) break;
1933 pstrcpy(line, cline);
1935 /* special case - first char is ! */
1936 if (*line == '!') {
1937 system(line + 1);
1938 continue;
1941 /* and get the first part of the command */
1942 ptr = line;
1943 if (!next_token_nr(&ptr,tok,NULL,sizeof(tok))) continue;
1945 if ((i = process_tok(tok)) >= 0) {
1946 commands[i].fn();
1947 } else if (i == -2) {
1948 DEBUG(0,("%s: command abbreviation ambiguous\n",tok));
1949 } else {
1950 DEBUG(0,("%s: command not found\n",tok));
1956 /*****************************************************
1957 return a connection to a server
1958 *******************************************************/
1959 struct cli_state *do_connect(const char *server, const char *share)
1961 struct cli_state *c;
1962 struct nmb_name called, calling;
1963 const char *server_n;
1964 struct in_addr ip;
1965 extern struct in_addr ipzero;
1966 fstring servicename;
1967 char *sharename;
1969 /* make a copy so we don't modify the global string 'service' */
1970 safe_strcpy(servicename, share, sizeof(servicename)-1);
1971 sharename = servicename;
1972 if (*sharename == '\\') {
1973 server = sharename+2;
1974 sharename = strchr_m(server,'\\');
1975 if (!sharename) return NULL;
1976 *sharename = 0;
1977 sharename++;
1980 server_n = server;
1982 ip = ipzero;
1984 make_nmb_name(&calling, global_myname, 0x0);
1985 make_nmb_name(&called , server, name_type);
1987 again:
1988 ip = ipzero;
1989 if (have_ip) ip = dest_ip;
1991 /* have to open a new connection */
1992 if (!(c=cli_initialise(NULL)) || (cli_set_port(c, port) == 0) ||
1993 !cli_connect(c, server_n, &ip)) {
1994 DEBUG(0,("Connection to %s failed\n", server_n));
1995 return NULL;
1998 c->protocol = max_protocol;
2000 if (!cli_session_request(c, &calling, &called)) {
2001 char *p;
2002 DEBUG(0,("session request to %s failed (%s)\n",
2003 called.name, cli_errstr(c)));
2004 cli_shutdown(c);
2005 free(c);
2006 if ((p=strchr_m(called.name, '.'))) {
2007 *p = 0;
2008 goto again;
2010 if (strcmp(called.name, "*SMBSERVER")) {
2011 make_nmb_name(&called , "*SMBSERVER", 0x20);
2012 goto again;
2014 return NULL;
2017 DEBUG(4,(" session request ok\n"));
2019 if (!cli_negprot(c)) {
2020 DEBUG(0,("protocol negotiation failed\n"));
2021 cli_shutdown(c);
2022 free(c);
2023 return NULL;
2026 if (!got_pass) {
2027 char *pass = getpass("Password: ");
2028 if (pass) {
2029 pstrcpy(password, pass);
2033 if (!cli_session_setup(c, username,
2034 password, strlen(password),
2035 password, strlen(password),
2036 workgroup)) {
2037 /* if a password was not supplied then try again with a null username */
2038 if (password[0] || !username[0] ||
2039 !cli_session_setup(c, "", "", 0, "", 0, workgroup)) {
2040 DEBUG(0,("session setup failed: %s\n", cli_errstr(c)));
2041 cli_shutdown(c);
2042 free(c);
2043 return NULL;
2045 DEBUG(0,("Anonymous login successful\n"));
2049 * These next two lines are needed to emulate
2050 * old client behaviour for people who have
2051 * scripts based on client output.
2052 * QUESTION ? Do we want to have a 'client compatibility
2053 * mode to turn these on/off ? JRA.
2056 if (*c->server_domain || *c->server_os || *c->server_type){
2057 DEBUG(1,("Domain=[%s] OS=[%s] Server=[%s]\n",
2058 c->server_domain,c->server_os,c->server_type));
2061 DEBUG(4,(" session setup ok\n"));
2063 if (!cli_send_tconX(c, sharename, "?????",
2064 password, strlen(password)+1)) {
2065 DEBUG(0,("tree connect failed: %s\n", cli_errstr(c)));
2066 cli_shutdown(c);
2067 free(c);
2068 return NULL;
2071 DEBUG(4,(" tconx ok\n"));
2073 return c;
2077 /****************************************************************************
2078 process commands from the client
2079 ****************************************************************************/
2080 static BOOL process(char *base_directory)
2082 cli = do_connect(desthost, service);
2083 if (!cli) {
2084 return(False);
2087 if (*base_directory) do_cd(base_directory);
2089 if (cmdstr) {
2090 process_command_string(cmdstr);
2091 } else {
2092 process_stdin();
2095 cli_shutdown(cli);
2096 return(True);
2099 /****************************************************************************
2100 usage on the program
2101 ****************************************************************************/
2102 static void usage(char *pname)
2104 DEBUG(0,("Usage: %s service <password> [options]", pname));
2106 DEBUG(0,("\nVersion %s\n",VERSION));
2107 DEBUG(0,("\t-s smb.conf pathname to smb.conf file\n"));
2108 DEBUG(0,("\t-O socket_options socket options to use\n"));
2109 DEBUG(0,("\t-R name resolve order use these name resolution services only\n"));
2110 DEBUG(0,("\t-M host send a winpopup message to the host\n"));
2111 DEBUG(0,("\t-i scope use this NetBIOS scope\n"));
2112 DEBUG(0,("\t-N don't ask for a password\n"));
2113 DEBUG(0,("\t-n netbios name. Use this name as my netbios name\n"));
2114 DEBUG(0,("\t-d debuglevel set the debuglevel\n"));
2115 DEBUG(0,("\t-P connect to service as a printer\n"));
2116 DEBUG(0,("\t-p port connect to the specified port\n"));
2117 DEBUG(0,("\t-l log basename. Basename for log/debug files\n"));
2118 DEBUG(0,("\t-h Print this help message.\n"));
2119 DEBUG(0,("\t-I dest IP use this IP to connect to\n"));
2120 DEBUG(0,("\t-E write messages to stderr instead of stdout\n"));
2121 DEBUG(0,("\t-U username set the network username\n"));
2122 DEBUG(0,("\t-L host get a list of shares available on a host\n"));
2123 DEBUG(0,("\t-t terminal code terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n"));
2124 DEBUG(0,("\t-m max protocol set the max protocol level\n"));
2125 DEBUG(0,("\t-A filename get the credentials from a file\n"));
2126 DEBUG(0,("\t-W workgroup set the workgroup name\n"));
2127 DEBUG(0,("\t-T<c|x>IXFqgbNan command line tar\n"));
2128 DEBUG(0,("\t-D directory start from directory\n"));
2129 DEBUG(0,("\t-c command string execute semicolon separated commands\n"));
2130 DEBUG(0,("\t-b xmit/send buffer changes the transmit/send buffer (default: 65520)\n"));
2131 DEBUG(0,("\n"));
2135 /****************************************************************************
2136 get a password from a a file or file descriptor
2137 exit on failure
2138 ****************************************************************************/
2139 static void get_password_file(void)
2141 int fd = -1;
2142 char *p;
2143 BOOL close_it = False;
2144 pstring spec;
2145 char pass[128];
2147 if ((p = getenv("PASSWD_FD")) != NULL) {
2148 pstrcpy(spec, "descriptor ");
2149 pstrcat(spec, p);
2150 sscanf(p, "%d", &fd);
2151 close_it = False;
2152 } else if ((p = getenv("PASSWD_FILE")) != NULL) {
2153 fd = sys_open(p, O_RDONLY, 0);
2154 pstrcpy(spec, p);
2155 if (fd < 0) {
2156 fprintf(stderr, "Error opening PASSWD_FILE %s: %s\n",
2157 spec, strerror(errno));
2158 exit(1);
2160 close_it = True;
2163 for(p = pass, *p = '\0'; /* ensure that pass is null-terminated */
2164 p && p - pass < sizeof(pass);) {
2165 switch (read(fd, p, 1)) {
2166 case 1:
2167 if (*p != '\n' && *p != '\0') {
2168 *++p = '\0'; /* advance p, and null-terminate pass */
2169 break;
2171 case 0:
2172 if (p - pass) {
2173 *p = '\0'; /* null-terminate it, just in case... */
2174 p = NULL; /* then force the loop condition to become false */
2175 break;
2176 } else {
2177 fprintf(stderr, "Error reading password from file %s: %s\n",
2178 spec, "empty password\n");
2179 exit(1);
2182 default:
2183 fprintf(stderr, "Error reading password from file %s: %s\n",
2184 spec, strerror(errno));
2185 exit(1);
2188 pstrcpy(password, pass);
2189 if (close_it)
2190 close(fd);
2195 /****************************************************************************
2196 handle a -L query
2197 ****************************************************************************/
2198 static int do_host_query(char *query_host)
2200 cli = do_connect(query_host, "IPC$");
2201 if (!cli)
2202 return 1;
2204 browse_host(True);
2205 list_servers(workgroup);
2207 cli_shutdown(cli);
2209 return(0);
2213 /****************************************************************************
2214 handle a tar operation
2215 ****************************************************************************/
2216 static int do_tar_op(char *base_directory)
2218 int ret;
2219 cli = do_connect(desthost, service);
2220 if (!cli)
2221 return 1;
2223 recurse=True;
2225 if (*base_directory) do_cd(base_directory);
2227 ret=process_tar();
2229 cli_shutdown(cli);
2231 return(ret);
2234 /****************************************************************************
2235 handle a message operation
2236 ****************************************************************************/
2237 static int do_message_op(void)
2239 struct in_addr ip;
2240 struct nmb_name called, calling;
2242 ip = ipzero;
2244 make_nmb_name(&calling, global_myname, 0x0);
2245 make_nmb_name(&called , desthost, name_type);
2247 ip = ipzero;
2248 if (have_ip) ip = dest_ip;
2250 if (!(cli=cli_initialise(NULL)) || (cli_set_port(cli, port) == 0) || !cli_connect(cli, desthost, &ip)) {
2251 DEBUG(0,("Connection to %s failed\n", desthost));
2252 return 1;
2255 if (!cli_session_request(cli, &calling, &called)) {
2256 DEBUG(0,("session request failed\n"));
2257 cli_shutdown(cli);
2258 return 1;
2261 send_message();
2262 cli_shutdown(cli);
2264 return 0;
2268 /****************************************************************************
2269 main program
2270 ****************************************************************************/
2271 int main(int argc,char *argv[])
2273 fstring base_directory;
2274 char *pname = argv[0];
2275 int opt;
2276 extern FILE *dbf;
2277 extern char *optarg;
2278 extern int optind;
2279 int old_debug;
2280 pstring query_host;
2281 BOOL message = False;
2282 extern char tar_type;
2283 static pstring servicesf = CONFIGFILE;
2284 pstring term_code;
2285 pstring new_name_resolve_order;
2286 char *p;
2288 #ifdef KANJI
2289 pstrcpy(term_code, KANJI);
2290 #else /* KANJI */
2291 *term_code = 0;
2292 #endif /* KANJI */
2294 *query_host = 0;
2295 *base_directory = 0;
2297 *new_name_resolve_order = 0;
2299 DEBUGLEVEL = 2;
2301 setup_logging(pname,True);
2304 * If the -E option is given, be careful not to clobber stdout
2305 * before processing the options. 28.Feb.99, richard@hacom.nl.
2306 * Also pre-parse the -s option to get the service file name.
2309 for (opt = 1; opt < argc; opt++) {
2310 if (strcmp(argv[opt], "-E") == 0)
2311 dbf = stderr;
2312 else if(strncmp(argv[opt], "-s", 2) == 0) {
2313 if(argv[opt][2] != '\0')
2314 pstrcpy(servicesf, &argv[opt][2]);
2315 else if(argv[opt+1] != NULL) {
2317 * At least one more arg left.
2319 pstrcpy(servicesf, argv[opt+1]);
2320 } else {
2321 usage(pname);
2322 exit(1);
2327 TimeInit();
2329 in_client = True; /* Make sure that we tell lp_load we are */
2331 old_debug = DEBUGLEVEL;
2332 if (!lp_load(servicesf,True,False,False)) {
2333 fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
2335 DEBUGLEVEL = old_debug;
2337 #ifdef WITH_SSL
2338 sslutil_init(0);
2339 #endif
2341 pstrcpy(workgroup,lp_workgroup());
2343 load_interfaces();
2344 myumask = umask(0);
2345 umask(myumask);
2347 if (getenv("USER")) {
2348 pstrcpy(username,getenv("USER"));
2350 /* modification to support userid%passwd syntax in the USER var
2351 25.Aug.97, jdblair@uab.edu */
2353 if ((p=strchr_m(username,'%'))) {
2354 *p = 0;
2355 pstrcpy(password,p+1);
2356 got_pass = True;
2357 memset(strchr_m(getenv("USER"),'%')+1,'X',strlen(password));
2359 strupper(username);
2362 /* modification to support PASSWD environmental var
2363 25.Aug.97, jdblair@uab.edu */
2364 if (getenv("PASSWD")) {
2365 pstrcpy(password,getenv("PASSWD"));
2366 got_pass = True;
2369 if (getenv("PASSWD_FD") || getenv("PASSWD_FILE")) {
2370 get_password_file();
2371 got_pass = True;
2374 if (*username == 0 && getenv("LOGNAME")) {
2375 pstrcpy(username,getenv("LOGNAME"));
2376 strupper(username);
2379 if (*username == 0) {
2380 pstrcpy(username,"GUEST");
2383 if (argc < 2) {
2384 usage(pname);
2385 exit(1);
2388 if (*argv[1] != '-') {
2389 pstrcpy(service,argv[1]);
2390 /* Convert any '/' characters in the service name to '\' characters */
2391 string_replace( service, '/','\\');
2392 argc--;
2393 argv++;
2395 if (count_chars(service,'\\') < 3) {
2396 usage(pname);
2397 printf("\n%s: Not enough '\\' characters in service\n",service);
2398 exit(1);
2401 if (argc > 1 && (*argv[1] != '-')) {
2402 got_pass = True;
2403 pstrcpy(password,argv[1]);
2404 memset(argv[1],'X',strlen(argv[1]));
2405 argc--;
2406 argv++;
2410 while ((opt =
2411 getopt(argc, argv,"s:O:R:M:i:Nn:d:Pp:l:hI:EU:L:t:m:W:T:D:c:b:A:")) != EOF) {
2412 switch (opt) {
2413 case 's':
2414 pstrcpy(servicesf, optarg);
2415 break;
2416 case 'O':
2417 pstrcpy(user_socket_options,optarg);
2418 break;
2419 case 'R':
2420 pstrcpy(new_name_resolve_order, optarg);
2421 break;
2422 case 'M':
2423 name_type = 0x03; /* messages are sent to NetBIOS name type 0x3 */
2424 pstrcpy(desthost,optarg);
2425 message = True;
2426 break;
2427 case 'i':
2429 extern pstring global_scope;
2430 pstrcpy(global_scope,optarg);
2431 strupper(global_scope);
2433 break;
2434 case 'N':
2435 got_pass = True;
2436 break;
2437 case 'n':
2438 pstrcpy(global_myname,optarg);
2439 break;
2440 case 'd':
2441 if (*optarg == 'A')
2442 DEBUGLEVEL = 10000;
2443 else
2444 DEBUGLEVEL = atoi(optarg);
2445 break;
2446 case 'P':
2447 /* not needed anymore */
2448 break;
2449 case 'p':
2450 port = atoi(optarg);
2451 break;
2452 case 'l':
2453 slprintf(debugf,sizeof(debugf)-1, "%s.client",optarg);
2454 break;
2455 case 'h':
2456 usage(pname);
2457 exit(0);
2458 break;
2459 case 'I':
2461 dest_ip = *interpret_addr2(optarg);
2462 if (zero_ip(dest_ip))
2463 exit(1);
2464 have_ip = True;
2466 break;
2467 case 'E':
2468 dbf = stderr;
2469 break;
2470 case 'U':
2472 char *lp;
2473 pstrcpy(username,optarg);
2474 if ((lp=strchr_m(username,'%'))) {
2475 *lp = 0;
2476 pstrcpy(password,lp+1);
2477 got_pass = True;
2478 memset(strchr_m(optarg,'%')+1,'X',strlen(password));
2481 break;
2483 case 'A':
2485 FILE *auth;
2486 fstring buf;
2487 uint16 len = 0;
2488 char *ptr, *val, *param;
2490 if ((auth=sys_fopen(optarg, "r")) == NULL)
2492 /* fail if we can't open the credentials file */
2493 DEBUG(0,("ERROR: Unable to open credentials file!\n"));
2494 exit (-1);
2497 while (!feof(auth))
2499 /* get a line from the file */
2500 if (!fgets (buf, sizeof(buf), auth))
2501 continue;
2502 len = strlen(buf);
2504 if ((len) && (buf[len-1]=='\n'))
2506 buf[len-1] = '\0';
2507 len--;
2509 if (len == 0)
2510 continue;
2512 /* break up the line into parameter & value.
2513 will need to eat a little whitespace possibly */
2514 param = buf;
2515 if (!(ptr = strchr_m (buf, '=')))
2516 continue;
2517 val = ptr+1;
2518 *ptr = '\0';
2520 /* eat leading white space */
2521 while ((*val!='\0') && ((*val==' ') || (*val=='\t')))
2522 val++;
2524 if (strwicmp("password", param) == 0)
2526 pstrcpy(password, val);
2527 got_pass = True;
2529 else if (strwicmp("username", param) == 0)
2530 pstrcpy(username, val);
2532 memset(buf, 0, sizeof(buf));
2534 fclose(auth);
2536 break;
2538 case 'L':
2539 p = optarg;
2540 while(*p == '\\' || *p == '/')
2541 p++;
2542 pstrcpy(query_host,p);
2543 break;
2544 case 't':
2545 pstrcpy(term_code, optarg);
2546 break;
2547 case 'm':
2548 max_protocol = interpret_protocol(optarg, max_protocol);
2549 break;
2550 case 'W':
2551 pstrcpy(workgroup,optarg);
2552 break;
2553 case 'T':
2554 if (!tar_parseargs(argc, argv, optarg, optind)) {
2555 usage(pname);
2556 exit(1);
2558 break;
2559 case 'D':
2560 pstrcpy(base_directory,optarg);
2561 break;
2562 case 'c':
2563 cmdstr = optarg;
2564 break;
2565 case 'b':
2566 io_bufsize = MAX(1, atoi(optarg));
2567 break;
2568 default:
2569 usage(pname);
2570 exit(1);
2574 get_myname((*global_myname)?NULL:global_myname);
2576 if(*new_name_resolve_order)
2577 lp_set_name_resolve_order(new_name_resolve_order);
2579 if (!tar_type && !*query_host && !*service && !message) {
2580 usage(pname);
2581 exit(1);
2584 DEBUG( 3, ( "Client started (version %s).\n", VERSION ) );
2586 if (tar_type) {
2587 if (cmdstr)
2588 process_command_string(cmdstr);
2589 return do_tar_op(base_directory);
2592 if ((p=strchr_m(query_host,'#'))) {
2593 *p = 0;
2594 p++;
2595 sscanf(p, "%x", &name_type);
2598 if (*query_host) {
2599 return do_host_query(query_host);
2602 if (message) {
2603 return do_message_op();
2606 if (!process(base_directory)) {
2607 return(1);
2610 return(0);