More null deref fixes.
[Samba/vl.git] / source / client / client.c
blob18758c02166d3bc4406d46d7f659f0e73fc34838
1 /*
2 Unix SMB/CIFS implementation.
3 SMB client
4 Copyright (C) Andrew Tridgell 1994-1998
5 Copyright (C) Simo Sorce 2001-2002
6 Copyright (C) Jelmer Vernooij 2003
7 Copyright (C) Gerald (Jerry) Carter 2004
8 Copyright (C) Jeremy Allison 1994-2007
10 This program is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 3 of the License, or
13 (at your option) any later version.
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/>.
24 #include "includes.h"
25 #include "client/client_proto.h"
26 #include "include/rpc_client.h"
27 #ifndef REGISTER
28 #define REGISTER 0
29 #endif
31 extern bool AllowDebugChange;
32 extern bool override_logfile;
33 extern char tar_type;
34 extern bool in_client;
35 static int port = 0;
36 static char *service;
37 static char *desthost;
38 static char *calling_name;
39 static bool grepable = false;
40 static char *cmdstr = NULL;
42 static int io_bufsize = 64512;
44 static int name_type = 0x20;
45 extern int max_protocol;
47 static int process_tok(char *tok);
48 static int cmd_help(void);
50 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
52 /* 30 second timeout on most commands */
53 #define CLIENT_TIMEOUT (30*1000)
54 #define SHORT_TIMEOUT (5*1000)
56 /* value for unused fid field in trans2 secondary request */
57 #define FID_UNUSED (0xFFFF)
59 time_t newer_than = 0;
60 static int archive_level = 0;
62 static bool translation = false;
63 static bool have_ip;
65 /* clitar bits insert */
66 extern int blocksize;
67 extern bool tar_inc;
68 extern bool tar_reset;
69 /* clitar bits end */
71 static bool prompt = true;
73 static bool recurse = false;
74 static bool showacls = false;
75 bool lowercase = false;
77 static struct sockaddr_storage dest_ss;
79 #define SEPARATORS " \t\n\r"
81 static bool abort_mget = true;
83 /* timing globals */
84 SMB_BIG_UINT get_total_size = 0;
85 unsigned int get_total_time_ms = 0;
86 static SMB_BIG_UINT put_total_size = 0;
87 static unsigned int put_total_time_ms = 0;
89 /* totals globals */
90 static double dir_total;
92 /* root cli_state connection */
94 struct cli_state *cli;
96 static char CLI_DIRSEP_CHAR = '\\';
97 static char CLI_DIRSEP_STR[] = { '\\', '\0' };
99 /* Accessor functions for directory paths. */
100 static char *fileselection;
101 static const char *client_get_fileselection(void)
103 if (fileselection) {
104 return fileselection;
106 return "";
109 static const char *client_set_fileselection(const char *new_fs)
111 SAFE_FREE(fileselection);
112 if (new_fs) {
113 fileselection = SMB_STRDUP(new_fs);
115 return client_get_fileselection();
118 static char *cwd;
119 static const char *client_get_cwd(void)
121 if (cwd) {
122 return cwd;
124 return CLI_DIRSEP_STR;
127 static const char *client_set_cwd(const char *new_cwd)
129 SAFE_FREE(cwd);
130 if (new_cwd) {
131 cwd = SMB_STRDUP(new_cwd);
133 return client_get_cwd();
136 static char *cur_dir;
137 const char *client_get_cur_dir(void)
139 if (cur_dir) {
140 return cur_dir;
142 return CLI_DIRSEP_STR;
145 const char *client_set_cur_dir(const char *newdir)
147 SAFE_FREE(cur_dir);
148 if (newdir) {
149 cur_dir = SMB_STRDUP(newdir);
151 return client_get_cur_dir();
154 /****************************************************************************
155 Write to a local file with CR/LF->LF translation if appropriate. Return the
156 number taken from the buffer. This may not equal the number written.
157 ****************************************************************************/
159 static int writefile(int f, char *b, int n)
161 int i;
163 if (!translation) {
164 return write(f,b,n);
167 i = 0;
168 while (i < n) {
169 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
170 b++;i++;
172 if (write(f, b, 1) != 1) {
173 break;
175 b++;
176 i++;
179 return(i);
182 /****************************************************************************
183 Read from a file with LF->CR/LF translation if appropriate. Return the
184 number read. read approx n bytes.
185 ****************************************************************************/
187 static int readfile(char *b, int n, XFILE *f)
189 int i;
190 int c;
192 if (!translation)
193 return x_fread(b,1,n,f);
195 i = 0;
196 while (i < (n - 1) && (i < BUFFER_SIZE)) {
197 if ((c = x_getc(f)) == EOF) {
198 break;
201 if (c == '\n') { /* change all LFs to CR/LF */
202 b[i++] = '\r';
205 b[i++] = c;
208 return(i);
211 /****************************************************************************
212 Send a message.
213 ****************************************************************************/
215 static void send_message(void)
217 int total_len = 0;
218 int grp_id;
220 if (!cli_message_start(cli, desthost,
221 get_cmdline_auth_info_username(), &grp_id)) {
222 d_printf("message start: %s\n", cli_errstr(cli));
223 return;
227 d_printf("Connected. Type your message, ending it with a Control-D\n");
229 while (!feof(stdin) && total_len < 1600) {
230 int maxlen = MIN(1600 - total_len,127);
231 char msg[1024];
232 int l=0;
233 int c;
235 ZERO_ARRAY(msg);
237 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
238 if (c == '\n')
239 msg[l++] = '\r';
240 msg[l] = c;
243 if ((total_len > 0) && (strlen(msg) == 0)) {
244 break;
247 if (!cli_message_text(cli, msg, l, grp_id)) {
248 d_printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
249 return;
252 total_len += l;
255 if (total_len >= 1600)
256 d_printf("the message was truncated to 1600 bytes\n");
257 else
258 d_printf("sent %d bytes\n",total_len);
260 if (!cli_message_end(cli, grp_id)) {
261 d_printf("SMBsendend failed (%s)\n",cli_errstr(cli));
262 return;
266 /****************************************************************************
267 Check the space on a device.
268 ****************************************************************************/
270 static int do_dskattr(void)
272 int total, bsize, avail;
273 struct cli_state *targetcli = NULL;
274 char *targetpath = NULL;
275 TALLOC_CTX *ctx = talloc_tos();
277 if ( !cli_resolve_path(ctx, "", cli, client_get_cur_dir(), &targetcli, &targetpath)) {
278 d_printf("Error in dskattr: %s\n", cli_errstr(cli));
279 return 1;
282 if (!cli_dskattr(targetcli, &bsize, &total, &avail)) {
283 d_printf("Error in dskattr: %s\n",cli_errstr(targetcli));
284 return 1;
287 d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
288 total, bsize, avail);
290 return 0;
293 /****************************************************************************
294 Show cd/pwd.
295 ****************************************************************************/
297 static int cmd_pwd(void)
299 d_printf("Current directory is %s",service);
300 d_printf("%s\n",client_get_cur_dir());
301 return 0;
304 /****************************************************************************
305 Change directory - inner section.
306 ****************************************************************************/
308 static int do_cd(const char *new_dir)
310 char *newdir = NULL;
311 char *saved_dir = NULL;
312 char *new_cd = NULL;
313 char *targetpath = NULL;
314 struct cli_state *targetcli = NULL;
315 SMB_STRUCT_STAT sbuf;
316 uint32 attributes;
317 int ret = 1;
318 TALLOC_CTX *ctx = talloc_stackframe();
320 newdir = talloc_strdup(ctx, new_dir);
321 if (!newdir) {
322 TALLOC_FREE(ctx);
323 return 1;
325 string_replace(newdir,'/','\\');
327 /* Save the current directory in case the new directory is invalid */
329 saved_dir = talloc_strdup(ctx, client_get_cur_dir());
330 if (!saved_dir) {
331 TALLOC_FREE(ctx);
332 return 1;
335 if (*newdir == CLI_DIRSEP_CHAR) {
336 client_set_cur_dir(newdir);
337 new_cd = newdir;
338 } else {
339 new_cd = talloc_asprintf(ctx, "%s%s",
340 client_get_cur_dir(),
341 newdir);
342 if (!new_cd) {
343 goto out;
345 if ((new_cd[0] != '\0') && (*(new_cd+strlen(new_cd)-1) != CLI_DIRSEP_CHAR)) {
346 new_cd = talloc_asprintf_append(new_cd, CLI_DIRSEP_STR);
347 if (!new_cd) {
348 goto out;
351 client_set_cur_dir(new_cd);
353 if (!new_cd) {
354 goto out;
357 new_cd = clean_name(ctx, new_cd);
358 client_set_cur_dir(new_cd);
360 if ( !cli_resolve_path(ctx, "", cli, new_cd, &targetcli, &targetpath)) {
361 d_printf("cd %s: %s\n", new_cd, cli_errstr(cli));
362 client_set_cur_dir(saved_dir);
363 goto out;
366 if (strequal(targetpath,CLI_DIRSEP_STR )) {
367 TALLOC_FREE(ctx);
368 return 0;
371 /* Use a trans2_qpathinfo to test directories for modern servers.
372 Except Win9x doesn't support the qpathinfo_basic() call..... */
374 if (targetcli->protocol > PROTOCOL_LANMAN2 && !targetcli->win95) {
375 if (!cli_qpathinfo_basic( targetcli, targetpath, &sbuf, &attributes ) ) {
376 d_printf("cd %s: %s\n", new_cd, cli_errstr(targetcli));
377 client_set_cur_dir(saved_dir);
378 goto out;
381 if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
382 d_printf("cd %s: not a directory\n", new_cd);
383 client_set_cur_dir(saved_dir);
384 goto out;
386 } else {
387 targetpath = talloc_asprintf(ctx,
388 "%s%s",
389 targetpath,
390 CLI_DIRSEP_STR );
391 if (!targetpath) {
392 client_set_cur_dir(saved_dir);
393 goto out;
395 targetpath = clean_name(ctx, targetpath);
396 if (!targetpath) {
397 client_set_cur_dir(saved_dir);
398 goto out;
401 if (!cli_chkpath(targetcli, targetpath)) {
402 d_printf("cd %s: %s\n", new_cd, cli_errstr(targetcli));
403 client_set_cur_dir(saved_dir);
404 goto out;
408 ret = 0;
410 out:
412 TALLOC_FREE(ctx);
413 return ret;
416 /****************************************************************************
417 Change directory.
418 ****************************************************************************/
420 static int cmd_cd(void)
422 char *buf = NULL;
423 int rc = 0;
425 if (next_token_nr_talloc(talloc_tos(), NULL, &buf,NULL)) {
426 rc = do_cd(buf);
427 } else {
428 d_printf("Current directory is %s\n",client_get_cur_dir());
431 return rc;
434 /****************************************************************************
435 Change directory.
436 ****************************************************************************/
438 static int cmd_cd_oneup(void)
440 return do_cd("..");
443 /*******************************************************************
444 Decide if a file should be operated on.
445 ********************************************************************/
447 static bool do_this_one(file_info *finfo)
449 if (!finfo->name) {
450 return false;
453 if (finfo->mode & aDIR) {
454 return true;
457 if (*client_get_fileselection() &&
458 !mask_match(finfo->name,client_get_fileselection(),false)) {
459 DEBUG(3,("mask_match %s failed\n", finfo->name));
460 return false;
463 if (newer_than && finfo->mtime_ts.tv_sec < newer_than) {
464 DEBUG(3,("newer_than %s failed\n", finfo->name));
465 return false;
468 if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
469 DEBUG(3,("archive %s failed\n", finfo->name));
470 return false;
473 return true;
476 /****************************************************************************
477 Display info about a file.
478 ****************************************************************************/
480 static void display_finfo(file_info *finfo, const char *dir)
482 time_t t;
483 TALLOC_CTX *ctx = talloc_tos();
485 if (!do_this_one(finfo)) {
486 return;
489 t = finfo->mtime_ts.tv_sec; /* the time is assumed to be passed as GMT */
490 if (!showacls) {
491 d_printf(" %-30s%7.7s %8.0f %s",
492 finfo->name,
493 attrib_string(finfo->mode),
494 (double)finfo->size,
495 time_to_asc(t));
496 dir_total += finfo->size;
497 } else {
498 char *afname = NULL;
499 int fnum;
501 /* skip if this is . or .. */
502 if ( strequal(finfo->name,"..") || strequal(finfo->name,".") )
503 return;
504 /* create absolute filename for cli_nt_create() FIXME */
505 afname = talloc_asprintf(ctx,
506 "%s%s%s",
507 client_get_cwd(),
508 CLI_DIRSEP_STR,
509 finfo->name);
510 if (!afname) {
511 return;
513 /* print file meta date header */
514 d_printf( "FILENAME:%s\n", afname);
515 d_printf( "MODE:%s\n", attrib_string(finfo->mode));
516 d_printf( "SIZE:%.0f\n", (double)finfo->size);
517 d_printf( "MTIME:%s", time_to_asc(t));
518 fnum = cli_nt_create(finfo->cli, afname, CREATE_ACCESS_READ);
519 if (fnum == -1) {
520 DEBUG( 0, ("display_finfo() Failed to open %s: %s\n",
521 afname,
522 cli_errstr( finfo->cli)));
523 } else {
524 SEC_DESC *sd = NULL;
525 sd = cli_query_secdesc(finfo->cli, fnum, ctx);
526 if (!sd) {
527 DEBUG( 0, ("display_finfo() failed to "
528 "get security descriptor: %s",
529 cli_errstr( finfo->cli)));
530 } else {
531 display_sec_desc(sd);
533 TALLOC_FREE(sd);
535 TALLOC_FREE(afname);
539 /****************************************************************************
540 Accumulate size of a file.
541 ****************************************************************************/
543 static void do_du(file_info *finfo, const char *dir)
545 if (do_this_one(finfo)) {
546 dir_total += finfo->size;
550 static bool do_list_recurse;
551 static bool do_list_dirs;
552 static char *do_list_queue = 0;
553 static long do_list_queue_size = 0;
554 static long do_list_queue_start = 0;
555 static long do_list_queue_end = 0;
556 static void (*do_list_fn)(file_info *, const char *dir);
558 /****************************************************************************
559 Functions for do_list_queue.
560 ****************************************************************************/
563 * The do_list_queue is a NUL-separated list of strings stored in a
564 * char*. Since this is a FIFO, we keep track of the beginning and
565 * ending locations of the data in the queue. When we overflow, we
566 * double the size of the char*. When the start of the data passes
567 * the midpoint, we move everything back. This is logically more
568 * complex than a linked list, but easier from a memory management
569 * angle. In any memory error condition, do_list_queue is reset.
570 * Functions check to ensure that do_list_queue is non-NULL before
571 * accessing it.
574 static void reset_do_list_queue(void)
576 SAFE_FREE(do_list_queue);
577 do_list_queue_size = 0;
578 do_list_queue_start = 0;
579 do_list_queue_end = 0;
582 static void init_do_list_queue(void)
584 reset_do_list_queue();
585 do_list_queue_size = 1024;
586 do_list_queue = (char *)SMB_MALLOC(do_list_queue_size);
587 if (do_list_queue == 0) {
588 d_printf("malloc fail for size %d\n",
589 (int)do_list_queue_size);
590 reset_do_list_queue();
591 } else {
592 memset(do_list_queue, 0, do_list_queue_size);
596 static void adjust_do_list_queue(void)
599 * If the starting point of the queue is more than half way through,
600 * move everything toward the beginning.
603 if (do_list_queue == NULL) {
604 DEBUG(4,("do_list_queue is empty\n"));
605 do_list_queue_start = do_list_queue_end = 0;
606 return;
609 if (do_list_queue_start == do_list_queue_end) {
610 DEBUG(4,("do_list_queue is empty\n"));
611 do_list_queue_start = do_list_queue_end = 0;
612 *do_list_queue = '\0';
613 } else if (do_list_queue_start > (do_list_queue_size / 2)) {
614 DEBUG(4,("sliding do_list_queue backward\n"));
615 memmove(do_list_queue,
616 do_list_queue + do_list_queue_start,
617 do_list_queue_end - do_list_queue_start);
618 do_list_queue_end -= do_list_queue_start;
619 do_list_queue_start = 0;
623 static void add_to_do_list_queue(const char *entry)
625 long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
626 while (new_end > do_list_queue_size) {
627 do_list_queue_size *= 2;
628 DEBUG(4,("enlarging do_list_queue to %d\n",
629 (int)do_list_queue_size));
630 do_list_queue = (char *)SMB_REALLOC(do_list_queue, do_list_queue_size);
631 if (! do_list_queue) {
632 d_printf("failure enlarging do_list_queue to %d bytes\n",
633 (int)do_list_queue_size);
634 reset_do_list_queue();
635 } else {
636 memset(do_list_queue + do_list_queue_size / 2,
637 0, do_list_queue_size / 2);
640 if (do_list_queue) {
641 safe_strcpy_base(do_list_queue + do_list_queue_end,
642 entry, do_list_queue, do_list_queue_size);
643 do_list_queue_end = new_end;
644 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
645 entry, (int)do_list_queue_start, (int)do_list_queue_end));
649 static char *do_list_queue_head(void)
651 return do_list_queue + do_list_queue_start;
654 static void remove_do_list_queue_head(void)
656 if (do_list_queue_end > do_list_queue_start) {
657 do_list_queue_start += strlen(do_list_queue_head()) + 1;
658 adjust_do_list_queue();
659 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
660 (int)do_list_queue_start, (int)do_list_queue_end));
664 static int do_list_queue_empty(void)
666 return (! (do_list_queue && *do_list_queue));
669 /****************************************************************************
670 A helper for do_list.
671 ****************************************************************************/
673 static void do_list_helper(const char *mntpoint, file_info *f, const char *mask, void *state)
675 TALLOC_CTX *ctx = talloc_tos();
676 char *dir = NULL;
677 char *dir_end = NULL;
679 /* Work out the directory. */
680 dir = talloc_strdup(ctx, mask);
681 if (!dir) {
682 return;
684 if ((dir_end = strrchr(dir, CLI_DIRSEP_CHAR)) != NULL) {
685 *dir_end = '\0';
688 if (f->mode & aDIR) {
689 if (do_list_dirs && do_this_one(f)) {
690 do_list_fn(f, dir);
692 if (do_list_recurse &&
693 f->name &&
694 !strequal(f->name,".") &&
695 !strequal(f->name,"..")) {
696 char *mask2 = NULL;
697 char *p = NULL;
699 if (!f->name[0]) {
700 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
701 TALLOC_FREE(dir);
702 return;
705 mask2 = talloc_asprintf(ctx,
706 "%s%s",
707 mntpoint,
708 mask);
709 if (!mask2) {
710 TALLOC_FREE(dir);
711 return;
713 p = strrchr_m(mask2,CLI_DIRSEP_CHAR);
714 if (!p) {
715 TALLOC_FREE(dir);
716 return;
718 p[1] = 0;
719 mask2 = talloc_asprintf_append(mask2,
720 "%s%s*",
721 f->name,
722 CLI_DIRSEP_STR);
723 if (!mask2) {
724 TALLOC_FREE(dir);
725 return;
727 add_to_do_list_queue(mask2);
728 TALLOC_FREE(mask2);
730 TALLOC_FREE(dir);
731 return;
734 if (do_this_one(f)) {
735 do_list_fn(f,dir);
737 TALLOC_FREE(dir);
740 /****************************************************************************
741 A wrapper around cli_list that adds recursion.
742 ****************************************************************************/
744 void do_list(const char *mask,
745 uint16 attribute,
746 void (*fn)(file_info *, const char *dir),
747 bool rec,
748 bool dirs)
750 static int in_do_list = 0;
751 TALLOC_CTX *ctx = talloc_tos();
752 struct cli_state *targetcli = NULL;
753 char *targetpath = NULL;
755 if (in_do_list && rec) {
756 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
757 exit(1);
760 in_do_list = 1;
762 do_list_recurse = rec;
763 do_list_dirs = dirs;
764 do_list_fn = fn;
766 if (rec) {
767 init_do_list_queue();
768 add_to_do_list_queue(mask);
770 while (!do_list_queue_empty()) {
772 * Need to copy head so that it doesn't become
773 * invalid inside the call to cli_list. This
774 * would happen if the list were expanded
775 * during the call.
776 * Fix from E. Jay Berkenbilt (ejb@ql.org)
778 char *head = talloc_strdup(ctx, do_list_queue_head());
780 if (!head) {
781 return;
784 /* check for dfs */
786 if ( !cli_resolve_path(ctx, "", cli, head, &targetcli, &targetpath ) ) {
787 d_printf("do_list: [%s] %s\n", head, cli_errstr(cli));
788 remove_do_list_queue_head();
789 continue;
792 cli_list(targetcli, targetpath, attribute, do_list_helper, NULL);
793 remove_do_list_queue_head();
794 if ((! do_list_queue_empty()) && (fn == display_finfo)) {
795 char *next_file = do_list_queue_head();
796 char *save_ch = 0;
797 if ((strlen(next_file) >= 2) &&
798 (next_file[strlen(next_file) - 1] == '*') &&
799 (next_file[strlen(next_file) - 2] == CLI_DIRSEP_CHAR)) {
800 save_ch = next_file +
801 strlen(next_file) - 2;
802 *save_ch = '\0';
803 if (showacls) {
804 /* cwd is only used if showacls is on */
805 client_set_cwd(next_file);
808 if (!showacls) /* don't disturbe the showacls output */
809 d_printf("\n%s\n",next_file);
810 if (save_ch) {
811 *save_ch = CLI_DIRSEP_CHAR;
814 TALLOC_FREE(head);
815 TALLOC_FREE(targetpath);
817 } else {
818 /* check for dfs */
819 if (cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetpath)) {
820 if (cli_list(targetcli, targetpath, attribute, do_list_helper, NULL) == -1) {
821 d_printf("%s listing %s\n",
822 cli_errstr(targetcli), targetpath);
824 TALLOC_FREE(targetpath);
825 } else {
826 d_printf("do_list: [%s] %s\n", mask, cli_errstr(cli));
830 in_do_list = 0;
831 reset_do_list_queue();
834 /****************************************************************************
835 Get a directory listing.
836 ****************************************************************************/
838 static int cmd_dir(void)
840 TALLOC_CTX *ctx = talloc_tos();
841 uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
842 char *mask = NULL;
843 char *buf = NULL;
844 int rc = 1;
846 dir_total = 0;
847 if (strcmp(client_get_cur_dir(), CLI_DIRSEP_STR) != 0) {
848 mask = talloc_strdup(ctx, client_get_cur_dir());
849 if (!mask) {
850 return 1;
852 if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
853 mask = talloc_asprintf_append(mask, CLI_DIRSEP_STR);
855 } else {
856 mask = talloc_strdup(ctx, CLI_DIRSEP_STR);
859 if (!mask) {
860 return 1;
863 if (next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
864 string_replace(buf,'/','\\');
865 if (*buf == CLI_DIRSEP_CHAR) {
866 mask = talloc_strdup(ctx, buf + 1);
867 } else {
868 mask = talloc_asprintf_append(mask, buf);
870 } else {
871 mask = talloc_asprintf_append(mask, "*");
873 if (!mask) {
874 return 1;
877 if (showacls) {
878 /* cwd is only used if showacls is on */
879 client_set_cwd(client_get_cur_dir());
882 do_list(mask, attribute, display_finfo, recurse, true);
884 rc = do_dskattr();
886 DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
888 return rc;
891 /****************************************************************************
892 Get a directory listing.
893 ****************************************************************************/
895 static int cmd_du(void)
897 TALLOC_CTX *ctx = talloc_tos();
898 uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
899 char *mask = NULL;
900 char *buf = NULL;
901 int rc = 1;
903 dir_total = 0;
904 mask = talloc_strdup(ctx, client_get_cur_dir());
905 if (!mask) {
906 return 1;
908 if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
909 mask = talloc_asprintf_append(mask, CLI_DIRSEP_STR);
910 if (!mask) {
911 return 1;
915 if (next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
916 string_replace(buf,'/','\\');
917 if (*buf == CLI_DIRSEP_CHAR) {
918 mask = talloc_strdup(ctx, buf);
919 } else {
920 mask = talloc_asprintf_append(mask, buf);
922 } else {
923 mask = talloc_strdup(ctx, "*");
926 do_list(mask, attribute, do_du, recurse, true);
928 rc = do_dskattr();
930 d_printf("Total number of bytes: %.0f\n", dir_total);
932 return rc;
935 static int cmd_echo(void)
937 TALLOC_CTX *ctx = talloc_tos();
938 char *num;
939 char *data;
941 if (!next_token_nr_talloc(ctx, NULL, &num, NULL)
942 || !next_token_nr_talloc(ctx, NULL, &data, NULL)) {
943 d_printf("echo <num> <data>\n");
944 return 1;
947 if (!cli_echo(cli, atoi(num), (uint8 *)data, strlen(data))) {
948 d_printf("echo failed: %s\n",
949 nt_errstr(cli_get_nt_error(cli)));
950 return 1;
953 return 0;
956 /****************************************************************************
957 Get a file from rname to lname
958 ****************************************************************************/
960 static int do_get(const char *rname, const char *lname_in, bool reget)
962 TALLOC_CTX *ctx = talloc_tos();
963 int handle = 0, fnum;
964 bool newhandle = false;
965 char *data = NULL;
966 struct timeval tp_start;
967 int read_size = io_bufsize;
968 uint16 attr;
969 SMB_OFF_T size;
970 off_t start = 0;
971 off_t nread = 0;
972 int rc = 0;
973 struct cli_state *targetcli = NULL;
974 char *targetname = NULL;
975 char *lname = NULL;
977 lname = talloc_strdup(ctx, lname_in);
978 if (!lname) {
979 return 1;
982 if (lowercase) {
983 strlower_m(lname);
986 if (!cli_resolve_path(ctx, "", cli, rname, &targetcli, &targetname ) ) {
987 d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
988 return 1;
991 GetTimeOfDay(&tp_start);
993 fnum = cli_open(targetcli, targetname, O_RDONLY, DENY_NONE);
995 if (fnum == -1) {
996 d_printf("%s opening remote file %s\n",cli_errstr(cli),rname);
997 return 1;
1000 if(!strcmp(lname,"-")) {
1001 handle = fileno(stdout);
1002 } else {
1003 if (reget) {
1004 handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
1005 if (handle >= 0) {
1006 start = sys_lseek(handle, 0, SEEK_END);
1007 if (start == -1) {
1008 d_printf("Error seeking local file\n");
1009 return 1;
1012 } else {
1013 handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1015 newhandle = true;
1017 if (handle < 0) {
1018 d_printf("Error opening local file %s\n",lname);
1019 return 1;
1023 if (!cli_qfileinfo(targetcli, fnum,
1024 &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
1025 !cli_getattrE(targetcli, fnum,
1026 &attr, &size, NULL, NULL, NULL)) {
1027 d_printf("getattrib: %s\n",cli_errstr(targetcli));
1028 return 1;
1031 DEBUG(1,("getting file %s of size %.0f as %s ",
1032 rname, (double)size, lname));
1034 if(!(data = (char *)SMB_MALLOC(read_size))) {
1035 d_printf("malloc fail for size %d\n", read_size);
1036 cli_close(targetcli, fnum);
1037 return 1;
1040 while (1) {
1041 int n = cli_read(targetcli, fnum, data, nread + start, read_size);
1043 if (n <= 0)
1044 break;
1046 if (writefile(handle,data, n) != n) {
1047 d_printf("Error writing local file\n");
1048 rc = 1;
1049 break;
1052 nread += n;
1055 if (nread + start < size) {
1056 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
1057 rname, (long)nread));
1059 rc = 1;
1062 SAFE_FREE(data);
1064 if (!cli_close(targetcli, fnum)) {
1065 d_printf("Error %s closing remote file\n",cli_errstr(cli));
1066 rc = 1;
1069 if (newhandle) {
1070 close(handle);
1073 if (archive_level >= 2 && (attr & aARCH)) {
1074 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
1078 struct timeval tp_end;
1079 int this_time;
1081 GetTimeOfDay(&tp_end);
1082 this_time =
1083 (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1084 (tp_end.tv_usec - tp_start.tv_usec)/1000;
1085 get_total_time_ms += this_time;
1086 get_total_size += nread;
1088 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1089 nread / (1.024*this_time + 1.0e-4),
1090 get_total_size / (1.024*get_total_time_ms)));
1093 TALLOC_FREE(targetname);
1094 return rc;
1097 /****************************************************************************
1098 Get a file.
1099 ****************************************************************************/
1101 static int cmd_get(void)
1103 TALLOC_CTX *ctx = talloc_tos();
1104 char *lname = NULL;
1105 char *rname = NULL;
1106 char *fname = NULL;
1108 rname = talloc_asprintf(ctx,
1109 "%s%s",
1110 client_get_cur_dir(),
1111 CLI_DIRSEP_STR);
1112 if (!rname) {
1113 return 1;
1116 if (!next_token_nr_talloc(ctx, NULL,&fname,NULL)) {
1117 d_printf("get <filename> [localname]\n");
1118 return 1;
1120 rname = talloc_asprintf_append(rname, fname);
1121 if (!rname) {
1122 return 1;
1124 rname = clean_name(ctx, rname);
1125 if (!rname) {
1126 return 1;
1129 next_token_nr_talloc(ctx, NULL,&lname,NULL);
1130 if (!lname) {
1131 lname = fname;
1134 return do_get(rname, lname, false);
1137 /****************************************************************************
1138 Do an mget operation on one file.
1139 ****************************************************************************/
1141 static void do_mget(file_info *finfo, const char *dir)
1143 TALLOC_CTX *ctx = talloc_tos();
1144 char *rname = NULL;
1145 char *quest = NULL;
1146 char *saved_curdir = NULL;
1147 char *mget_mask = NULL;
1148 char *new_cd = NULL;
1150 if (!finfo->name) {
1151 return;
1154 if (strequal(finfo->name,".") || strequal(finfo->name,".."))
1155 return;
1157 if (abort_mget) {
1158 d_printf("mget aborted\n");
1159 return;
1162 if (finfo->mode & aDIR) {
1163 if (asprintf(&quest,
1164 "Get directory %s? ",finfo->name) < 0) {
1165 return;
1167 } else {
1168 if (asprintf(&quest,
1169 "Get file %s? ",finfo->name) < 0) {
1170 return;
1174 if (prompt && !yesno(quest)) {
1175 SAFE_FREE(quest);
1176 return;
1178 SAFE_FREE(quest);
1180 if (!(finfo->mode & aDIR)) {
1181 rname = talloc_asprintf(ctx,
1182 "%s%s",
1183 client_get_cur_dir(),
1184 finfo->name);
1185 if (!rname) {
1186 return;
1188 do_get(rname, finfo->name, false);
1189 TALLOC_FREE(rname);
1190 return;
1193 /* handle directories */
1194 saved_curdir = talloc_strdup(ctx, client_get_cur_dir());
1195 if (!saved_curdir) {
1196 return;
1199 new_cd = talloc_asprintf(ctx,
1200 "%s%s%s",
1201 client_get_cur_dir(),
1202 finfo->name,
1203 CLI_DIRSEP_STR);
1204 if (!new_cd) {
1205 return;
1207 client_set_cur_dir(new_cd);
1209 string_replace(finfo->name,'\\','/');
1210 if (lowercase) {
1211 strlower_m(finfo->name);
1214 if (!directory_exist(finfo->name,NULL) &&
1215 mkdir(finfo->name,0777) != 0) {
1216 d_printf("failed to create directory %s\n",finfo->name);
1217 client_set_cur_dir(saved_curdir);
1218 return;
1221 if (chdir(finfo->name) != 0) {
1222 d_printf("failed to chdir to directory %s\n",finfo->name);
1223 client_set_cur_dir(saved_curdir);
1224 return;
1227 mget_mask = talloc_asprintf(ctx,
1228 "%s*",
1229 client_get_cur_dir());
1231 if (!mget_mask) {
1232 return;
1235 do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,false, true);
1236 chdir("..");
1237 client_set_cur_dir(saved_curdir);
1238 TALLOC_FREE(mget_mask);
1239 TALLOC_FREE(saved_curdir);
1240 TALLOC_FREE(new_cd);
1243 /****************************************************************************
1244 View the file using the pager.
1245 ****************************************************************************/
1247 static int cmd_more(void)
1249 TALLOC_CTX *ctx = talloc_tos();
1250 char *rname = NULL;
1251 char *fname = NULL;
1252 char *lname = NULL;
1253 char *pager_cmd = NULL;
1254 const char *pager;
1255 int fd;
1256 int rc = 0;
1258 rname = talloc_asprintf(ctx,
1259 "%s%s",
1260 client_get_cur_dir(),
1261 CLI_DIRSEP_STR);
1262 if (!rname) {
1263 return 1;
1266 lname = talloc_asprintf(ctx, "%s/smbmore.XXXXXX",tmpdir());
1267 if (!lname) {
1268 return 1;
1270 fd = smb_mkstemp(lname);
1271 if (fd == -1) {
1272 d_printf("failed to create temporary file for more\n");
1273 return 1;
1275 close(fd);
1277 if (!next_token_nr_talloc(ctx,NULL,&fname,NULL)) {
1278 d_printf("more <filename>\n");
1279 unlink(lname);
1280 return 1;
1282 rname = talloc_asprintf_append(rname, fname);
1283 if (!rname) {
1284 return 1;
1286 rname = clean_name(ctx,rname);
1287 if (!rname) {
1288 return 1;
1291 rc = do_get(rname, lname, false);
1293 pager=getenv("PAGER");
1295 pager_cmd = talloc_asprintf(ctx,
1296 "%s %s",
1297 (pager? pager:PAGER),
1298 lname);
1299 if (!pager_cmd) {
1300 return 1;
1302 system(pager_cmd);
1303 unlink(lname);
1305 return rc;
1308 /****************************************************************************
1309 Do a mget command.
1310 ****************************************************************************/
1312 static int cmd_mget(void)
1314 TALLOC_CTX *ctx = talloc_tos();
1315 uint16 attribute = aSYSTEM | aHIDDEN;
1316 char *mget_mask = NULL;
1317 char *buf = NULL;
1319 if (recurse) {
1320 attribute |= aDIR;
1323 abort_mget = false;
1325 while (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
1326 mget_mask = talloc_strdup(ctx, client_get_cur_dir());
1327 if (!mget_mask) {
1328 return 1;
1330 if ((mget_mask[0] != '\0') &&
1331 (mget_mask[strlen(mget_mask)-1]!=CLI_DIRSEP_CHAR)) {
1332 mget_mask = talloc_asprintf_append(mget_mask,
1333 CLI_DIRSEP_STR);
1334 if (!mget_mask) {
1335 return 1;
1339 if (*buf == CLI_DIRSEP_CHAR) {
1340 mget_mask = talloc_strdup(ctx, buf);
1341 } else {
1342 mget_mask = talloc_asprintf_append(mget_mask,
1343 buf);
1345 if (!mget_mask) {
1346 return 1;
1348 do_list(mget_mask, attribute, do_mget, false, true);
1351 if (!*mget_mask) {
1352 mget_mask = talloc_strdup(ctx, client_get_cur_dir());
1353 if (!mget_mask) {
1354 return 1;
1356 if(mget_mask[strlen(mget_mask)-1]!=CLI_DIRSEP_CHAR) {
1357 mget_mask = talloc_asprintf_append(mget_mask,
1358 CLI_DIRSEP_STR);
1359 if (!mget_mask) {
1360 return 1;
1363 mget_mask = talloc_asprintf_append(mget_mask, "*");
1364 if (!mget_mask) {
1365 return 1;
1367 do_list(mget_mask, attribute, do_mget, false, true);
1370 return 0;
1373 /****************************************************************************
1374 Make a directory of name "name".
1375 ****************************************************************************/
1377 static bool do_mkdir(const char *name)
1379 TALLOC_CTX *ctx = talloc_tos();
1380 struct cli_state *targetcli;
1381 char *targetname = NULL;
1383 if (!cli_resolve_path(ctx, "", cli, name, &targetcli, &targetname)) {
1384 d_printf("mkdir %s: %s\n", name, cli_errstr(cli));
1385 return false;
1388 if (!cli_mkdir(targetcli, targetname)) {
1389 d_printf("%s making remote directory %s\n",
1390 cli_errstr(targetcli),name);
1391 return false;
1394 return true;
1397 /****************************************************************************
1398 Show 8.3 name of a file.
1399 ****************************************************************************/
1401 static bool do_altname(const char *name)
1403 fstring altname;
1405 if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
1406 d_printf("%s getting alt name for %s\n",
1407 cli_errstr(cli),name);
1408 return false;
1410 d_printf("%s\n", altname);
1412 return true;
1415 /****************************************************************************
1416 Exit client.
1417 ****************************************************************************/
1419 static int cmd_quit(void)
1421 cli_cm_shutdown();
1422 exit(0);
1423 /* NOTREACHED */
1424 return 0;
1427 /****************************************************************************
1428 Make a directory.
1429 ****************************************************************************/
1431 static int cmd_mkdir(void)
1433 TALLOC_CTX *ctx = talloc_tos();
1434 char *mask = NULL;
1435 char *buf = NULL;
1437 mask = talloc_strdup(ctx, client_get_cur_dir());
1438 if (!mask) {
1439 return 1;
1442 if (!next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
1443 if (!recurse) {
1444 d_printf("mkdir <dirname>\n");
1446 return 1;
1448 mask = talloc_asprintf_append(mask, buf);
1449 if (!mask) {
1450 return 1;
1453 if (recurse) {
1454 char *ddir = NULL;
1455 char *ddir2 = NULL;
1456 struct cli_state *targetcli;
1457 char *targetname = NULL;
1458 char *p = NULL;
1460 ddir2 = talloc_strdup(ctx, "");
1461 if (!ddir2) {
1462 return 1;
1465 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
1466 return 1;
1469 ddir = talloc_strdup(ctx, targetname);
1470 if (!ddir) {
1471 return 1;
1473 trim_char(ddir,'.','\0');
1474 p = strtok(ddir,"/\\");
1475 while (p) {
1476 ddir2 = talloc_asprintf_append(ddir2, p);
1477 if (!ddir2) {
1478 return 1;
1480 if (!cli_chkpath(targetcli, ddir2)) {
1481 do_mkdir(ddir2);
1483 ddir2 = talloc_asprintf_append(ddir2, CLI_DIRSEP_STR);
1484 if (!ddir2) {
1485 return 1;
1487 p = strtok(NULL,"/\\");
1489 } else {
1490 do_mkdir(mask);
1493 return 0;
1496 /****************************************************************************
1497 Show alt name.
1498 ****************************************************************************/
1500 static int cmd_altname(void)
1502 TALLOC_CTX *ctx = talloc_tos();
1503 char *name;
1504 char *buf;
1506 name = talloc_strdup(ctx, client_get_cur_dir());
1507 if (!name) {
1508 return 1;
1511 if (!next_token_nr_talloc(ctx, NULL, &buf, NULL)) {
1512 d_printf("altname <file>\n");
1513 return 1;
1515 name = talloc_asprintf_append(name, buf);
1516 if (!name) {
1517 return 1;
1519 do_altname(name);
1520 return 0;
1523 /****************************************************************************
1524 Put a single file.
1525 ****************************************************************************/
1527 static int do_put(const char *rname, const char *lname, bool reput)
1529 TALLOC_CTX *ctx = talloc_tos();
1530 int fnum;
1531 XFILE *f;
1532 SMB_OFF_T start = 0;
1533 off_t nread = 0;
1534 char *buf = NULL;
1535 int maxwrite = io_bufsize;
1536 int rc = 0;
1537 struct timeval tp_start;
1538 struct cli_state *targetcli;
1539 char *targetname = NULL;
1541 if (!cli_resolve_path(ctx, "", cli, rname, &targetcli, &targetname)) {
1542 d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
1543 return 1;
1546 GetTimeOfDay(&tp_start);
1548 if (reput) {
1549 fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT, DENY_NONE);
1550 if (fnum >= 0) {
1551 if (!cli_qfileinfo(targetcli, fnum, NULL, &start, NULL, NULL, NULL, NULL, NULL) &&
1552 !cli_getattrE(targetcli, fnum, NULL, &start, NULL, NULL, NULL)) {
1553 d_printf("getattrib: %s\n",cli_errstr(cli));
1554 return 1;
1557 } else {
1558 fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
1561 if (fnum == -1) {
1562 d_printf("%s opening remote file %s\n",cli_errstr(targetcli),rname);
1563 return 1;
1566 /* allow files to be piped into smbclient
1567 jdblair 24.jun.98
1569 Note that in this case this function will exit(0) rather
1570 than returning. */
1571 if (!strcmp(lname, "-")) {
1572 f = x_stdin;
1573 /* size of file is not known */
1574 } else {
1575 f = x_fopen(lname,O_RDONLY, 0);
1576 if (f && reput) {
1577 if (x_tseek(f, start, SEEK_SET) == -1) {
1578 d_printf("Error seeking local file\n");
1579 return 1;
1584 if (!f) {
1585 d_printf("Error opening local file %s\n",lname);
1586 return 1;
1589 DEBUG(1,("putting file %s as %s ",lname,
1590 rname));
1592 buf = (char *)SMB_MALLOC(maxwrite);
1593 if (!buf) {
1594 d_printf("ERROR: Not enough memory!\n");
1595 return 1;
1597 while (!x_feof(f)) {
1598 int n = maxwrite;
1599 int ret;
1601 if ((n = readfile(buf,n,f)) < 1) {
1602 if((n == 0) && x_feof(f))
1603 break; /* Empty local file. */
1605 d_printf("Error reading local file: %s\n", strerror(errno));
1606 rc = 1;
1607 break;
1610 ret = cli_write(targetcli, fnum, 0, buf, nread + start, n);
1612 if (n != ret) {
1613 d_printf("Error writing file: %s\n", cli_errstr(cli));
1614 rc = 1;
1615 break;
1618 nread += n;
1621 if (!cli_close(targetcli, fnum)) {
1622 d_printf("%s closing remote file %s\n",cli_errstr(cli),rname);
1623 x_fclose(f);
1624 SAFE_FREE(buf);
1625 return 1;
1628 if (f != x_stdin) {
1629 x_fclose(f);
1632 SAFE_FREE(buf);
1635 struct timeval tp_end;
1636 int this_time;
1638 GetTimeOfDay(&tp_end);
1639 this_time =
1640 (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1641 (tp_end.tv_usec - tp_start.tv_usec)/1000;
1642 put_total_time_ms += this_time;
1643 put_total_size += nread;
1645 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1646 nread / (1.024*this_time + 1.0e-4),
1647 put_total_size / (1.024*put_total_time_ms)));
1650 if (f == x_stdin) {
1651 cli_cm_shutdown();
1652 exit(0);
1655 return rc;
1658 /****************************************************************************
1659 Put a file.
1660 ****************************************************************************/
1662 static int cmd_put(void)
1664 TALLOC_CTX *ctx = talloc_tos();
1665 char *lname;
1666 char *rname;
1667 char *buf;
1669 rname = talloc_asprintf(ctx,
1670 "%s%s",
1671 client_get_cur_dir(),
1672 CLI_DIRSEP_STR);
1673 if (!rname) {
1674 return 1;
1677 if (!next_token_nr_talloc(ctx,NULL,&lname,NULL)) {
1678 d_printf("put <filename>\n");
1679 return 1;
1682 if (next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
1683 rname = talloc_asprintf_append(rname, buf);
1684 } else {
1685 rname = talloc_asprintf_append(rname, lname);
1687 if (!rname) {
1688 return 1;
1691 rname = clean_name(ctx, rname);
1692 if (!rname) {
1693 return 1;
1697 SMB_STRUCT_STAT st;
1698 /* allow '-' to represent stdin
1699 jdblair, 24.jun.98 */
1700 if (!file_exist(lname,&st) &&
1701 (strcmp(lname,"-"))) {
1702 d_printf("%s does not exist\n",lname);
1703 return 1;
1707 return do_put(rname, lname, false);
1710 /*************************************
1711 File list structure.
1712 *************************************/
1714 static struct file_list {
1715 struct file_list *prev, *next;
1716 char *file_path;
1717 bool isdir;
1718 } *file_list;
1720 /****************************************************************************
1721 Free a file_list structure.
1722 ****************************************************************************/
1724 static void free_file_list (struct file_list *list_head)
1726 struct file_list *list, *next;
1728 for (list = list_head; list; list = next) {
1729 next = list->next;
1730 DLIST_REMOVE(list_head, list);
1731 SAFE_FREE(list->file_path);
1732 SAFE_FREE(list);
1736 /****************************************************************************
1737 Seek in a directory/file list until you get something that doesn't start with
1738 the specified name.
1739 ****************************************************************************/
1741 static bool seek_list(struct file_list *list, char *name)
1743 while (list) {
1744 trim_string(list->file_path,"./","\n");
1745 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1746 return true;
1748 list = list->next;
1751 return false;
1754 /****************************************************************************
1755 Set the file selection mask.
1756 ****************************************************************************/
1758 static int cmd_select(void)
1760 TALLOC_CTX *ctx = talloc_tos();
1761 char *new_fs = NULL;
1762 next_token_nr_talloc(ctx, NULL,&new_fs,NULL)
1764 if (new_fs) {
1765 client_set_fileselection(new_fs);
1766 } else {
1767 client_set_fileselection("");
1769 return 0;
1772 /****************************************************************************
1773 Recursive file matching function act as find
1774 match must be always set to true when calling this function
1775 ****************************************************************************/
1777 static int file_find(struct file_list **list, const char *directory,
1778 const char *expression, bool match)
1780 SMB_STRUCT_DIR *dir;
1781 struct file_list *entry;
1782 struct stat statbuf;
1783 int ret;
1784 char *path;
1785 bool isdir;
1786 const char *dname;
1788 dir = sys_opendir(directory);
1789 if (!dir)
1790 return -1;
1792 while ((dname = readdirname(dir))) {
1793 if (!strcmp("..", dname))
1794 continue;
1795 if (!strcmp(".", dname))
1796 continue;
1798 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1799 continue;
1802 isdir = false;
1803 if (!match || !gen_fnmatch(expression, dname)) {
1804 if (recurse) {
1805 ret = stat(path, &statbuf);
1806 if (ret == 0) {
1807 if (S_ISDIR(statbuf.st_mode)) {
1808 isdir = true;
1809 ret = file_find(list, path, expression, false);
1811 } else {
1812 d_printf("file_find: cannot stat file %s\n", path);
1815 if (ret == -1) {
1816 SAFE_FREE(path);
1817 sys_closedir(dir);
1818 return -1;
1821 entry = SMB_MALLOC_P(struct file_list);
1822 if (!entry) {
1823 d_printf("Out of memory in file_find\n");
1824 sys_closedir(dir);
1825 return -1;
1827 entry->file_path = path;
1828 entry->isdir = isdir;
1829 DLIST_ADD(*list, entry);
1830 } else {
1831 SAFE_FREE(path);
1835 sys_closedir(dir);
1836 return 0;
1839 /****************************************************************************
1840 mput some files.
1841 ****************************************************************************/
1843 static int cmd_mput(void)
1845 TALLOC_CTX *ctx = talloc_tos();
1846 char *p = NULL;
1848 while (next_token_nr_talloc(ctx, NULL,&p,NULL)) {
1849 int ret;
1850 struct file_list *temp_list;
1851 char *quest, *lname, *rname;
1853 file_list = NULL;
1855 ret = file_find(&file_list, ".", p, true);
1856 if (ret) {
1857 free_file_list(file_list);
1858 continue;
1861 quest = NULL;
1862 lname = NULL;
1863 rname = NULL;
1865 for (temp_list = file_list; temp_list;
1866 temp_list = temp_list->next) {
1868 SAFE_FREE(lname);
1869 if (asprintf(&lname, "%s/", temp_list->file_path) <= 0) {
1870 continue;
1872 trim_string(lname, "./", "/");
1874 /* check if it's a directory */
1875 if (temp_list->isdir) {
1876 /* if (!recurse) continue; */
1878 SAFE_FREE(quest);
1879 if (asprintf(&quest, "Put directory %s? ", lname) < 0) {
1880 break;
1882 if (prompt && !yesno(quest)) { /* No */
1883 /* Skip the directory */
1884 lname[strlen(lname)-1] = '/';
1885 if (!seek_list(temp_list, lname))
1886 break;
1887 } else { /* Yes */
1888 SAFE_FREE(rname);
1889 if(asprintf(&rname, "%s%s", cur_dir, lname) < 0) {
1890 break;
1892 string_replace(rname,'/','\\');
1893 if (!cli_chkpath(cli, rname) &&
1894 !do_mkdir(rname)) {
1895 DEBUG (0, ("Unable to make dir, skipping..."));
1896 /* Skip the directory */
1897 lname[strlen(lname)-1] = '/';
1898 if (!seek_list(temp_list, lname)) {
1899 break;
1903 continue;
1904 } else {
1905 SAFE_FREE(quest);
1906 if (asprintf(&quest,"Put file %s? ", lname) < 0) {
1907 break;
1909 if (prompt && !yesno(quest)) {
1910 /* No */
1911 continue;
1914 /* Yes */
1915 SAFE_FREE(rname);
1916 if (asprintf(&rname, "%s%s", cur_dir, lname) < 0) {
1917 break;
1921 string_replace(rname,'/','\\');
1923 do_put(rname, lname, false);
1925 free_file_list(file_list);
1926 SAFE_FREE(quest);
1927 SAFE_FREE(lname);
1928 SAFE_FREE(rname);
1931 return 0;
1934 /****************************************************************************
1935 Cancel a print job.
1936 ****************************************************************************/
1938 static int do_cancel(int job)
1940 if (cli_printjob_del(cli, job)) {
1941 d_printf("Job %d cancelled\n",job);
1942 return 0;
1943 } else {
1944 d_printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1945 return 1;
1949 /****************************************************************************
1950 Cancel a print job.
1951 ****************************************************************************/
1953 static int cmd_cancel(void)
1955 TALLOC_CTX *ctx = talloc_tos();
1956 char *buf = NULL;
1957 int job;
1959 if (!next_token_nr_talloc(ctx, NULL, &buf,NULL)) {
1960 d_printf("cancel <jobid> ...\n");
1961 return 1;
1963 do {
1964 job = atoi(buf);
1965 do_cancel(job);
1966 } while (next_token_nr_talloc(ctx,NULL,&buf,NULL));
1968 return 0;
1971 /****************************************************************************
1972 Print a file.
1973 ****************************************************************************/
1975 static int cmd_print(void)
1977 TALLOC_CTX *ctx = talloc_tos();
1978 char *lname = NULL;
1979 char *rname = NULL;
1980 char *p = NULL;
1982 if (!next_token_nr_talloc(ctx, NULL, &lname,NULL)) {
1983 d_printf("print <filename>\n");
1984 return 1;
1987 rname = talloc_strdup(ctx, lname);
1988 if (!rname) {
1989 return 1;
1991 p = strrchr_m(rname,'/');
1992 if (p) {
1993 rname = talloc_asprintf(ctx,
1994 "%s-%d",
1995 p+1,
1996 (int)sys_getpid());
1998 if (strequal(lname,"-")) {
1999 rname = talloc_asprintf(ctx,
2000 "stdin-%d",
2001 (int)sys_getpid());
2003 if (!rname) {
2004 return 1;
2007 return do_put(rname, lname, false);
2010 /****************************************************************************
2011 Show a print queue entry.
2012 ****************************************************************************/
2014 static void queue_fn(struct print_job_info *p)
2016 d_printf("%-6d %-9d %s\n", (int)p->id, (int)p->size, p->name);
2019 /****************************************************************************
2020 Show a print queue.
2021 ****************************************************************************/
2023 static int cmd_queue(void)
2025 cli_print_queue(cli, queue_fn);
2026 return 0;
2029 /****************************************************************************
2030 Delete some files.
2031 ****************************************************************************/
2033 static void do_del(file_info *finfo, const char *dir)
2035 TALLOC_CTX *ctx = talloc_tos();
2036 char *mask = NULL;
2038 mask = talloc_asprintf(ctx,
2039 "%s%c%s",
2040 dir,
2041 CLI_DIRSEP_CHAR,
2042 finfo->name);
2043 if (!mask) {
2044 return;
2047 if (finfo->mode & aDIR) {
2048 TALLOC_FREE(mask);
2049 return;
2052 if (!cli_unlink(finfo->cli, mask)) {
2053 d_printf("%s deleting remote file %s\n",
2054 cli_errstr(finfo->cli),mask);
2056 TALLOC_FREE(mask);
2059 /****************************************************************************
2060 Delete some files.
2061 ****************************************************************************/
2063 static int cmd_del(void)
2065 TALLOC_CTX *ctx = talloc_tos();
2066 char *mask = NULL;
2067 char *buf = NULL;
2068 uint16 attribute = aSYSTEM | aHIDDEN;
2070 if (recurse) {
2071 attribute |= aDIR;
2074 mask = talloc_strdup(ctx, client_get_cur_dir());
2075 if (!mask) {
2076 return 1;
2078 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2079 d_printf("del <filename>\n");
2080 return 1;
2082 mask = talloc_asprintf_append(mask, buf);
2083 if (!mask) {
2084 return 1;
2087 do_list(mask,attribute,do_del,false,false);
2088 return 0;
2091 /****************************************************************************
2092 Wildcard delete some files.
2093 ****************************************************************************/
2095 static int cmd_wdel(void)
2097 TALLOC_CTX *ctx = talloc_tos();
2098 char *mask = NULL;
2099 char *buf = NULL;
2100 uint16 attribute;
2101 struct cli_state *targetcli;
2102 char *targetname = NULL;
2104 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2105 d_printf("wdel 0x<attrib> <wcard>\n");
2106 return 1;
2109 attribute = (uint16)strtol(buf, (char **)NULL, 16);
2111 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2112 d_printf("wdel 0x<attrib> <wcard>\n");
2113 return 1;
2116 mask = talloc_asprintf(ctx, "%s%s",
2117 client_get_cur_dir(),
2118 buf);
2119 if (!mask) {
2120 return 1;
2123 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2124 d_printf("cmd_wdel %s: %s\n", mask, cli_errstr(cli));
2125 return 1;
2128 if (!cli_unlink_full(targetcli, targetname, attribute)) {
2129 d_printf("%s deleting remote files %s\n",cli_errstr(targetcli),targetname);
2131 return 0;
2134 /****************************************************************************
2135 ****************************************************************************/
2137 static int cmd_open(void)
2139 TALLOC_CTX *ctx = talloc_tos();
2140 char *mask = NULL;
2141 char *buf = NULL;
2142 char *targetname = NULL;
2143 struct cli_state *targetcli;
2144 int fnum;
2146 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2147 d_printf("open <filename>\n");
2148 return 1;
2150 mask = talloc_asprintf(ctx,
2151 "%s%s",
2152 client_get_cur_dir(),
2153 buf);
2154 if (!mask) {
2155 return 1;
2158 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2159 d_printf("open %s: %s\n", mask, cli_errstr(cli));
2160 return 1;
2163 fnum = cli_nt_create(targetcli, targetname, FILE_READ_DATA|FILE_WRITE_DATA);
2164 if (fnum == -1) {
2165 fnum = cli_nt_create(targetcli, targetname, FILE_READ_DATA);
2166 if (fnum != -1) {
2167 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2168 } else {
2169 d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
2171 } else {
2172 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2174 return 0;
2177 /****************************************************************************
2178 ****************************************************************************/
2180 static int cmd_posix_open(void)
2182 TALLOC_CTX *ctx = talloc_tos();
2183 char *mask = NULL;
2184 char *buf = NULL;
2185 char *targetname = NULL;
2186 struct cli_state *targetcli;
2187 mode_t mode;
2188 int fnum;
2190 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2191 d_printf("posix_open <filename> 0<mode>\n");
2192 return 1;
2194 mask = talloc_asprintf(ctx,
2195 "%s%s",
2196 client_get_cur_dir(),
2197 buf);
2198 if (!mask) {
2199 return 1;
2202 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2203 d_printf("posix_open <filename> 0<mode>\n");
2204 return 1;
2206 mode = (mode_t)strtol(buf, (char **)NULL, 8);
2208 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2209 d_printf("posix_open %s: %s\n", mask, cli_errstr(cli));
2210 return 1;
2213 fnum = cli_posix_open(targetcli, targetname, O_CREAT|O_RDWR, mode);
2214 if (fnum == -1) {
2215 fnum = cli_posix_open(targetcli, targetname, O_CREAT|O_RDONLY, mode);
2216 if (fnum != -1) {
2217 d_printf("posix_open file %s: for read/write fnum %d\n", targetname, fnum);
2218 } else {
2219 d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
2221 } else {
2222 d_printf("posix_open file %s: for read/write fnum %d\n", targetname, fnum);
2225 return 0;
2228 static int cmd_posix_mkdir(void)
2230 TALLOC_CTX *ctx = talloc_tos();
2231 char *mask = NULL;
2232 char *buf = NULL;
2233 char *targetname = NULL;
2234 struct cli_state *targetcli;
2235 mode_t mode;
2236 int fnum;
2238 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2239 d_printf("posix_mkdir <filename> 0<mode>\n");
2240 return 1;
2242 mask = talloc_asprintf(ctx,
2243 "%s%s",
2244 client_get_cur_dir(),
2245 buf);
2246 if (!mask) {
2247 return 1;
2250 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2251 d_printf("posix_mkdir <filename> 0<mode>\n");
2252 return 1;
2254 mode = (mode_t)strtol(buf, (char **)NULL, 8);
2256 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2257 d_printf("posix_mkdir %s: %s\n", mask, cli_errstr(cli));
2258 return 1;
2261 fnum = cli_posix_mkdir(targetcli, targetname, mode);
2262 if (fnum == -1) {
2263 d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
2264 } else {
2265 d_printf("posix_mkdir created directory %s\n", targetname);
2267 return 0;
2270 static int cmd_posix_unlink(void)
2272 TALLOC_CTX *ctx = talloc_tos();
2273 char *mask = NULL;
2274 char *buf = NULL;
2275 char *targetname = NULL;
2276 struct cli_state *targetcli;
2278 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2279 d_printf("posix_unlink <filename>\n");
2280 return 1;
2282 mask = talloc_asprintf(ctx,
2283 "%s%s",
2284 client_get_cur_dir(),
2285 buf);
2286 if (!mask) {
2287 return 1;
2290 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2291 d_printf("posix_unlink %s: %s\n", mask, cli_errstr(cli));
2292 return 1;
2295 if (!cli_posix_unlink(targetcli, targetname)) {
2296 d_printf("Failed to unlink file %s. %s\n", targetname, cli_errstr(cli));
2297 } else {
2298 d_printf("posix_unlink deleted file %s\n", targetname);
2301 return 0;
2304 static int cmd_posix_rmdir(void)
2306 TALLOC_CTX *ctx = talloc_tos();
2307 char *mask = NULL;
2308 char *buf = NULL;
2309 char *targetname = NULL;
2310 struct cli_state *targetcli;
2312 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2313 d_printf("posix_rmdir <filename>\n");
2314 return 1;
2316 mask = talloc_asprintf(ctx,
2317 "%s%s",
2318 client_get_cur_dir(),
2319 buf);
2320 if (!mask) {
2321 return 1;
2324 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2325 d_printf("posix_rmdir %s: %s\n", mask, cli_errstr(cli));
2326 return 1;
2329 if (!cli_posix_rmdir(targetcli, targetname)) {
2330 d_printf("Failed to unlink directory %s. %s\n", targetname, cli_errstr(cli));
2331 } else {
2332 d_printf("posix_rmdir deleted directory %s\n", targetname);
2335 return 0;
2338 static int cmd_close(void)
2340 TALLOC_CTX *ctx = talloc_tos();
2341 char *buf = NULL;
2342 int fnum;
2344 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2345 d_printf("close <fnum>\n");
2346 return 1;
2349 fnum = atoi(buf);
2350 /* We really should use the targetcli here.... */
2351 if (!cli_close(cli, fnum)) {
2352 d_printf("close %d: %s\n", fnum, cli_errstr(cli));
2353 return 1;
2355 return 0;
2358 static int cmd_posix(void)
2360 TALLOC_CTX *ctx = talloc_tos();
2361 uint16 major, minor;
2362 uint32 caplow, caphigh;
2363 char *caps;
2365 if (!SERVER_HAS_UNIX_CIFS(cli)) {
2366 d_printf("Server doesn't support UNIX CIFS extensions.\n");
2367 return 1;
2370 if (!cli_unix_extensions_version(cli, &major, &minor, &caplow, &caphigh)) {
2371 d_printf("Can't get UNIX CIFS extensions version from server.\n");
2372 return 1;
2375 d_printf("Server supports CIFS extensions %u.%u\n", (unsigned int)major, (unsigned int)minor);
2377 caps = talloc_strdup(ctx, "");
2378 if (!caps) {
2379 return 1;
2381 if (caplow & CIFS_UNIX_FCNTL_LOCKS_CAP) {
2382 caps = talloc_asprintf_append(caps, "locks ");
2383 if (!caps) {
2384 return 1;
2387 if (caplow & CIFS_UNIX_POSIX_ACLS_CAP) {
2388 caps = talloc_asprintf_append(caps, "acls ");
2389 if (!caps) {
2390 return 1;
2393 if (caplow & CIFS_UNIX_XATTTR_CAP) {
2394 caps = talloc_asprintf_append(caps, "eas ");
2395 if (!caps) {
2396 return 1;
2399 if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2400 caps = talloc_asprintf_append(caps, "pathnames ");
2401 if (!caps) {
2402 return 1;
2405 if (caplow & CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP) {
2406 caps = talloc_asprintf_append(caps, "posix_path_operations ");
2407 if (!caps) {
2408 return 1;
2411 if (caplow & CIFS_UNIX_LARGE_READ_CAP) {
2412 caps = talloc_asprintf_append(caps, "large_read ");
2413 if (!caps) {
2414 return 1;
2417 if (caplow & CIFS_UNIX_LARGE_WRITE_CAP) {
2418 caps = talloc_asprintf_append(caps, "large_write ");
2419 if (!caps) {
2420 return 1;
2424 if (*caps && caps[strlen(caps)-1] == ' ') {
2425 caps[strlen(caps)-1] = '\0';
2427 if (!cli_set_unix_extensions_capabilities(cli, major, minor, caplow, caphigh)) {
2428 d_printf("Can't set UNIX CIFS extensions capabilities. %s.\n", cli_errstr(cli));
2429 return 1;
2432 d_printf("Selecting server supported CIFS capabilities %s\n", caps);
2434 if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2435 CLI_DIRSEP_CHAR = '/';
2436 *CLI_DIRSEP_STR = '/';
2437 client_set_cur_dir(CLI_DIRSEP_STR);
2440 return 0;
2443 static int cmd_lock(void)
2445 TALLOC_CTX *ctx = talloc_tos();
2446 char *buf = NULL;
2447 SMB_BIG_UINT start, len;
2448 enum brl_type lock_type;
2449 int fnum;
2451 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2452 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2453 return 1;
2455 fnum = atoi(buf);
2457 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2458 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2459 return 1;
2462 if (*buf == 'r' || *buf == 'R') {
2463 lock_type = READ_LOCK;
2464 } else if (*buf == 'w' || *buf == 'W') {
2465 lock_type = WRITE_LOCK;
2466 } else {
2467 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2468 return 1;
2471 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2472 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2473 return 1;
2476 start = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2478 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2479 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2480 return 1;
2483 len = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2485 if (!cli_posix_lock(cli, fnum, start, len, true, lock_type)) {
2486 d_printf("lock failed %d: %s\n", fnum, cli_errstr(cli));
2489 return 0;
2492 static int cmd_unlock(void)
2494 TALLOC_CTX *ctx = talloc_tos();
2495 char *buf = NULL;
2496 SMB_BIG_UINT start, len;
2497 int fnum;
2499 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2500 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2501 return 1;
2503 fnum = atoi(buf);
2505 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2506 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2507 return 1;
2510 start = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2512 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2513 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2514 return 1;
2517 len = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2519 if (!cli_posix_unlock(cli, fnum, start, len)) {
2520 d_printf("unlock failed %d: %s\n", fnum, cli_errstr(cli));
2523 return 0;
2527 /****************************************************************************
2528 Remove a directory.
2529 ****************************************************************************/
2531 static int cmd_rmdir(void)
2533 TALLOC_CTX *ctx = talloc_tos();
2534 char *mask = NULL;
2535 char *buf = NULL;
2536 char *targetname = NULL;
2537 struct cli_state *targetcli;
2539 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2540 d_printf("rmdir <dirname>\n");
2541 return 1;
2543 mask = talloc_asprintf(ctx,
2544 "%s%s",
2545 client_get_cur_dir(),
2546 buf);
2547 if (!mask) {
2548 return 1;
2551 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2552 d_printf("rmdir %s: %s\n", mask, cli_errstr(cli));
2553 return 1;
2556 if (!cli_rmdir(targetcli, targetname)) {
2557 d_printf("%s removing remote directory file %s\n",
2558 cli_errstr(targetcli),mask);
2561 return 0;
2564 /****************************************************************************
2565 UNIX hardlink.
2566 ****************************************************************************/
2568 static int cmd_link(void)
2570 TALLOC_CTX *ctx = talloc_tos();
2571 char *oldname = NULL;
2572 char *newname = NULL;
2573 char *buf = NULL;
2574 char *buf2 = NULL;
2575 char *targetname = NULL;
2576 struct cli_state *targetcli;
2578 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
2579 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
2580 d_printf("link <oldname> <newname>\n");
2581 return 1;
2583 oldname = talloc_asprintf(ctx,
2584 "%s%s",
2585 client_get_cur_dir(),
2586 buf);
2587 if (!oldname) {
2588 return 1;
2590 newname = talloc_asprintf(ctx,
2591 "%s%s",
2592 client_get_cur_dir(),
2593 buf2);
2594 if (!newname) {
2595 return 1;
2598 if (!cli_resolve_path(ctx, "", cli, oldname, &targetcli, &targetname)) {
2599 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
2600 return 1;
2603 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2604 d_printf("Server doesn't support UNIX CIFS calls.\n");
2605 return 1;
2608 if (!cli_unix_hardlink(targetcli, targetname, newname)) {
2609 d_printf("%s linking files (%s -> %s)\n", cli_errstr(targetcli), newname, oldname);
2610 return 1;
2612 return 0;
2615 /****************************************************************************
2616 UNIX symlink.
2617 ****************************************************************************/
2619 static int cmd_symlink(void)
2621 TALLOC_CTX *ctx = talloc_tos();
2622 char *oldname = NULL;
2623 char *newname = NULL;
2624 char *buf = NULL;
2625 char *buf2 = NULL;
2626 char *targetname = NULL;
2627 struct cli_state *targetcli;
2629 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
2630 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
2631 d_printf("symlink <oldname> <newname>\n");
2632 return 1;
2634 oldname = talloc_asprintf(ctx,
2635 "%s%s",
2636 client_get_cur_dir(),
2637 buf);
2638 if (!oldname) {
2639 return 1;
2641 newname = talloc_asprintf(ctx,
2642 "%s%s",
2643 client_get_cur_dir(),
2644 buf2);
2645 if (!newname) {
2646 return 1;
2649 if (!cli_resolve_path(ctx, "", cli, oldname, &targetcli, &targetname)) {
2650 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
2651 return 1;
2654 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2655 d_printf("Server doesn't support UNIX CIFS calls.\n");
2656 return 1;
2659 if (!cli_unix_symlink(targetcli, targetname, newname)) {
2660 d_printf("%s symlinking files (%s -> %s)\n",
2661 cli_errstr(targetcli), newname, targetname);
2662 return 1;
2665 return 0;
2668 /****************************************************************************
2669 UNIX chmod.
2670 ****************************************************************************/
2672 static int cmd_chmod(void)
2674 TALLOC_CTX *ctx = talloc_tos();
2675 char *src = NULL;
2676 char *buf = NULL;
2677 char *buf2 = NULL;
2678 char *targetname = NULL;
2679 struct cli_state *targetcli;
2680 mode_t mode;
2682 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
2683 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
2684 d_printf("chmod mode file\n");
2685 return 1;
2687 src = talloc_asprintf(ctx,
2688 "%s%s",
2689 client_get_cur_dir(),
2690 buf2);
2691 if (!src) {
2692 return 1;
2695 mode = (mode_t)strtol(buf, NULL, 8);
2697 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
2698 d_printf("chmod %s: %s\n", src, cli_errstr(cli));
2699 return 1;
2702 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2703 d_printf("Server doesn't support UNIX CIFS calls.\n");
2704 return 1;
2707 if (!cli_unix_chmod(targetcli, targetname, mode)) {
2708 d_printf("%s chmod file %s 0%o\n",
2709 cli_errstr(targetcli), src, (unsigned int)mode);
2710 return 1;
2713 return 0;
2716 static const char *filetype_to_str(mode_t mode)
2718 if (S_ISREG(mode)) {
2719 return "regular file";
2720 } else if (S_ISDIR(mode)) {
2721 return "directory";
2722 } else
2723 #ifdef S_ISCHR
2724 if (S_ISCHR(mode)) {
2725 return "character device";
2726 } else
2727 #endif
2728 #ifdef S_ISBLK
2729 if (S_ISBLK(mode)) {
2730 return "block device";
2731 } else
2732 #endif
2733 #ifdef S_ISFIFO
2734 if (S_ISFIFO(mode)) {
2735 return "fifo";
2736 } else
2737 #endif
2738 #ifdef S_ISLNK
2739 if (S_ISLNK(mode)) {
2740 return "symbolic link";
2741 } else
2742 #endif
2743 #ifdef S_ISSOCK
2744 if (S_ISSOCK(mode)) {
2745 return "socket";
2746 } else
2747 #endif
2748 return "";
2751 static char rwx_to_str(mode_t m, mode_t bt, char ret)
2753 if (m & bt) {
2754 return ret;
2755 } else {
2756 return '-';
2760 static char *unix_mode_to_str(char *s, mode_t m)
2762 char *p = s;
2763 const char *str = filetype_to_str(m);
2765 switch(str[0]) {
2766 case 'd':
2767 *p++ = 'd';
2768 break;
2769 case 'c':
2770 *p++ = 'c';
2771 break;
2772 case 'b':
2773 *p++ = 'b';
2774 break;
2775 case 'f':
2776 *p++ = 'p';
2777 break;
2778 case 's':
2779 *p++ = str[1] == 'y' ? 'l' : 's';
2780 break;
2781 case 'r':
2782 default:
2783 *p++ = '-';
2784 break;
2786 *p++ = rwx_to_str(m, S_IRUSR, 'r');
2787 *p++ = rwx_to_str(m, S_IWUSR, 'w');
2788 *p++ = rwx_to_str(m, S_IXUSR, 'x');
2789 *p++ = rwx_to_str(m, S_IRGRP, 'r');
2790 *p++ = rwx_to_str(m, S_IWGRP, 'w');
2791 *p++ = rwx_to_str(m, S_IXGRP, 'x');
2792 *p++ = rwx_to_str(m, S_IROTH, 'r');
2793 *p++ = rwx_to_str(m, S_IWOTH, 'w');
2794 *p++ = rwx_to_str(m, S_IXOTH, 'x');
2795 *p++ = '\0';
2796 return s;
2799 /****************************************************************************
2800 Utility function for UNIX getfacl.
2801 ****************************************************************************/
2803 static char *perms_to_string(fstring permstr, unsigned char perms)
2805 fstrcpy(permstr, "---");
2806 if (perms & SMB_POSIX_ACL_READ) {
2807 permstr[0] = 'r';
2809 if (perms & SMB_POSIX_ACL_WRITE) {
2810 permstr[1] = 'w';
2812 if (perms & SMB_POSIX_ACL_EXECUTE) {
2813 permstr[2] = 'x';
2815 return permstr;
2818 /****************************************************************************
2819 UNIX getfacl.
2820 ****************************************************************************/
2822 static int cmd_getfacl(void)
2824 TALLOC_CTX *ctx = talloc_tos();
2825 char *src = NULL;
2826 char *name = NULL;
2827 char *targetname = NULL;
2828 struct cli_state *targetcli;
2829 uint16 major, minor;
2830 uint32 caplow, caphigh;
2831 char *retbuf = NULL;
2832 size_t rb_size = 0;
2833 SMB_STRUCT_STAT sbuf;
2834 uint16 num_file_acls = 0;
2835 uint16 num_dir_acls = 0;
2836 uint16 i;
2838 if (!next_token_nr_talloc(ctx,NULL,&name,NULL)) {
2839 d_printf("getfacl filename\n");
2840 return 1;
2842 src = talloc_asprintf(ctx,
2843 "%s%s",
2844 client_get_cur_dir(),
2845 name);
2846 if (!src) {
2847 return 1;
2850 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
2851 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2852 return 1;
2855 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2856 d_printf("Server doesn't support UNIX CIFS calls.\n");
2857 return 1;
2860 if (!cli_unix_extensions_version(targetcli, &major, &minor,
2861 &caplow, &caphigh)) {
2862 d_printf("Can't get UNIX CIFS version from server.\n");
2863 return 1;
2866 if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
2867 d_printf("This server supports UNIX extensions "
2868 "but doesn't support POSIX ACLs.\n");
2869 return 1;
2872 if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2873 d_printf("%s getfacl doing a stat on file %s\n",
2874 cli_errstr(targetcli), src);
2875 return 1;
2878 if (!cli_unix_getfacl(targetcli, targetname, &rb_size, &retbuf)) {
2879 d_printf("%s getfacl file %s\n",
2880 cli_errstr(targetcli), src);
2881 return 1;
2884 /* ToDo : Print out the ACL values. */
2885 if (SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION || rb_size < 6) {
2886 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
2887 src, (unsigned int)CVAL(retbuf,0) );
2888 SAFE_FREE(retbuf);
2889 return 1;
2892 num_file_acls = SVAL(retbuf,2);
2893 num_dir_acls = SVAL(retbuf,4);
2894 if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
2895 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
2896 src,
2897 (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
2898 (unsigned int)rb_size);
2900 SAFE_FREE(retbuf);
2901 return 1;
2904 d_printf("# file: %s\n", src);
2905 d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_uid, (unsigned int)sbuf.st_gid);
2907 if (num_file_acls == 0 && num_dir_acls == 0) {
2908 d_printf("No acls found.\n");
2911 for (i = 0; i < num_file_acls; i++) {
2912 uint32 uorg;
2913 fstring permstring;
2914 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
2915 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2917 switch(tagtype) {
2918 case SMB_POSIX_ACL_USER_OBJ:
2919 d_printf("user::");
2920 break;
2921 case SMB_POSIX_ACL_USER:
2922 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2923 d_printf("user:%u:", uorg);
2924 break;
2925 case SMB_POSIX_ACL_GROUP_OBJ:
2926 d_printf("group::");
2927 break;
2928 case SMB_POSIX_ACL_GROUP:
2929 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2930 d_printf("group:%u", uorg);
2931 break;
2932 case SMB_POSIX_ACL_MASK:
2933 d_printf("mask::");
2934 break;
2935 case SMB_POSIX_ACL_OTHER:
2936 d_printf("other::");
2937 break;
2938 default:
2939 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2940 src, (unsigned int)tagtype );
2941 SAFE_FREE(retbuf);
2942 return 1;
2945 d_printf("%s\n", perms_to_string(permstring, perms));
2948 for (i = 0; i < num_dir_acls; i++) {
2949 uint32 uorg;
2950 fstring permstring;
2951 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
2952 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2954 switch(tagtype) {
2955 case SMB_POSIX_ACL_USER_OBJ:
2956 d_printf("default:user::");
2957 break;
2958 case SMB_POSIX_ACL_USER:
2959 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2960 d_printf("default:user:%u:", uorg);
2961 break;
2962 case SMB_POSIX_ACL_GROUP_OBJ:
2963 d_printf("default:group::");
2964 break;
2965 case SMB_POSIX_ACL_GROUP:
2966 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2967 d_printf("default:group:%u", uorg);
2968 break;
2969 case SMB_POSIX_ACL_MASK:
2970 d_printf("default:mask::");
2971 break;
2972 case SMB_POSIX_ACL_OTHER:
2973 d_printf("default:other::");
2974 break;
2975 default:
2976 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2977 src, (unsigned int)tagtype );
2978 SAFE_FREE(retbuf);
2979 return 1;
2982 d_printf("%s\n", perms_to_string(permstring, perms));
2985 SAFE_FREE(retbuf);
2986 return 0;
2989 /****************************************************************************
2990 UNIX stat.
2991 ****************************************************************************/
2993 static int cmd_stat(void)
2995 TALLOC_CTX *ctx = talloc_tos();
2996 char *src = NULL;
2997 char *name = NULL;
2998 char *targetname = NULL;
2999 struct cli_state *targetcli;
3000 fstring mode_str;
3001 SMB_STRUCT_STAT sbuf;
3002 struct tm *lt;
3004 if (!next_token_nr_talloc(ctx,NULL,&name,NULL)) {
3005 d_printf("stat file\n");
3006 return 1;
3008 src = talloc_asprintf(ctx,
3009 "%s%s",
3010 client_get_cur_dir(),
3011 name);
3012 if (!src) {
3013 return 1;
3016 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
3017 d_printf("stat %s: %s\n", src, cli_errstr(cli));
3018 return 1;
3021 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3022 d_printf("Server doesn't support UNIX CIFS calls.\n");
3023 return 1;
3026 if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
3027 d_printf("%s stat file %s\n",
3028 cli_errstr(targetcli), src);
3029 return 1;
3032 /* Print out the stat values. */
3033 d_printf("File: %s\n", src);
3034 d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
3035 (double)sbuf.st_size,
3036 (unsigned int)sbuf.st_blocks,
3037 filetype_to_str(sbuf.st_mode));
3039 #if defined(S_ISCHR) && defined(S_ISBLK)
3040 if (S_ISCHR(sbuf.st_mode) || S_ISBLK(sbuf.st_mode)) {
3041 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
3042 (double)sbuf.st_ino,
3043 (unsigned int)sbuf.st_nlink,
3044 unix_dev_major(sbuf.st_rdev),
3045 unix_dev_minor(sbuf.st_rdev));
3046 } else
3047 #endif
3048 d_printf("Inode: %.0f\tLinks: %u\n",
3049 (double)sbuf.st_ino,
3050 (unsigned int)sbuf.st_nlink);
3052 d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
3053 ((int)sbuf.st_mode & 0777),
3054 unix_mode_to_str(mode_str, sbuf.st_mode),
3055 (unsigned int)sbuf.st_uid,
3056 (unsigned int)sbuf.st_gid);
3058 lt = localtime(&sbuf.st_atime);
3059 if (lt) {
3060 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3061 } else {
3062 fstrcpy(mode_str, "unknown");
3064 d_printf("Access: %s\n", mode_str);
3066 lt = localtime(&sbuf.st_mtime);
3067 if (lt) {
3068 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3069 } else {
3070 fstrcpy(mode_str, "unknown");
3072 d_printf("Modify: %s\n", mode_str);
3074 lt = localtime(&sbuf.st_ctime);
3075 if (lt) {
3076 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3077 } else {
3078 fstrcpy(mode_str, "unknown");
3080 d_printf("Change: %s\n", mode_str);
3082 return 0;
3086 /****************************************************************************
3087 UNIX chown.
3088 ****************************************************************************/
3090 static int cmd_chown(void)
3092 TALLOC_CTX *ctx = talloc_tos();
3093 char *src = NULL;
3094 uid_t uid;
3095 gid_t gid;
3096 char *buf, *buf2, *buf3;
3097 struct cli_state *targetcli;
3098 char *targetname = NULL;
3100 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
3101 !next_token_nr_talloc(ctx,NULL,&buf2,NULL) ||
3102 !next_token_nr_talloc(ctx,NULL,&buf3,NULL)) {
3103 d_printf("chown uid gid file\n");
3104 return 1;
3107 uid = (uid_t)atoi(buf);
3108 gid = (gid_t)atoi(buf2);
3110 src = talloc_asprintf(ctx,
3111 "%s%s",
3112 client_get_cur_dir(),
3113 buf3);
3114 if (!src) {
3115 return 1;
3117 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname) ) {
3118 d_printf("chown %s: %s\n", src, cli_errstr(cli));
3119 return 1;
3122 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3123 d_printf("Server doesn't support UNIX CIFS calls.\n");
3124 return 1;
3127 if (!cli_unix_chown(targetcli, targetname, uid, gid)) {
3128 d_printf("%s chown file %s uid=%d, gid=%d\n",
3129 cli_errstr(targetcli), src, (int)uid, (int)gid);
3130 return 1;
3133 return 0;
3136 /****************************************************************************
3137 Rename some file.
3138 ****************************************************************************/
3140 static int cmd_rename(void)
3142 TALLOC_CTX *ctx = talloc_tos();
3143 char *src, *dest;
3144 char *buf, *buf2;
3145 struct cli_state *targetcli;
3146 char *targetsrc;
3147 char *targetdest;
3149 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
3150 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
3151 d_printf("rename <src> <dest>\n");
3152 return 1;
3155 src = talloc_asprintf(ctx,
3156 "%s%s",
3157 client_get_cur_dir(),
3158 buf);
3159 if (!src) {
3160 return 1;
3163 dest = talloc_asprintf(ctx,
3164 "%s%s",
3165 client_get_cur_dir(),
3166 buf2);
3167 if (!dest) {
3168 return 1;
3171 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetsrc)) {
3172 d_printf("rename %s: %s\n", src, cli_errstr(cli));
3173 return 1;
3176 if (!cli_resolve_path(ctx, "", cli, dest, &targetcli, &targetdest)) {
3177 d_printf("rename %s: %s\n", dest, cli_errstr(cli));
3178 return 1;
3181 if (!cli_rename(targetcli, targetsrc, targetdest)) {
3182 d_printf("%s renaming files %s -> %s \n",
3183 cli_errstr(targetcli),
3184 targetsrc,
3185 targetdest);
3186 return 1;
3189 return 0;
3192 /****************************************************************************
3193 Print the volume name.
3194 ****************************************************************************/
3196 static int cmd_volume(void)
3198 fstring volname;
3199 uint32 serial_num;
3200 time_t create_date;
3202 if (!cli_get_fs_volume_info(cli, volname, &serial_num, &create_date)) {
3203 d_printf("Errr %s getting volume info\n",cli_errstr(cli));
3204 return 1;
3207 d_printf("Volume: |%s| serial number 0x%x\n",
3208 volname, (unsigned int)serial_num);
3209 return 0;
3212 /****************************************************************************
3213 Hard link files using the NT call.
3214 ****************************************************************************/
3216 static int cmd_hardlink(void)
3218 TALLOC_CTX *ctx = talloc_tos();
3219 char *src, *dest;
3220 char *buf, *buf2;
3221 struct cli_state *targetcli;
3222 char *targetname;
3224 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
3225 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
3226 d_printf("hardlink <src> <dest>\n");
3227 return 1;
3230 src = talloc_asprintf(ctx,
3231 "%s%s",
3232 client_get_cur_dir(),
3233 buf);
3234 if (!src) {
3235 return 1;
3238 dest = talloc_asprintf(ctx,
3239 "%s%s",
3240 client_get_cur_dir(),
3241 buf2);
3242 if (!dest) {
3243 return 1;
3246 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
3247 d_printf("hardlink %s: %s\n", src, cli_errstr(cli));
3248 return 1;
3251 if (!cli_nt_hardlink(targetcli, targetname, dest)) {
3252 d_printf("%s doing an NT hard link of files\n",cli_errstr(targetcli));
3253 return 1;
3256 return 0;
3259 /****************************************************************************
3260 Toggle the prompt flag.
3261 ****************************************************************************/
3263 static int cmd_prompt(void)
3265 prompt = !prompt;
3266 DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
3267 return 1;
3270 /****************************************************************************
3271 Set the newer than time.
3272 ****************************************************************************/
3274 static int cmd_newer(void)
3276 TALLOC_CTX *ctx = talloc_tos();
3277 char *buf;
3278 bool ok;
3279 SMB_STRUCT_STAT sbuf;
3281 ok = next_token_nr_talloc(ctx,NULL,&buf,NULL);
3282 if (ok && (sys_stat(buf,&sbuf) == 0)) {
3283 newer_than = sbuf.st_mtime;
3284 DEBUG(1,("Getting files newer than %s",
3285 time_to_asc(newer_than)));
3286 } else {
3287 newer_than = 0;
3290 if (ok && newer_than == 0) {
3291 d_printf("Error setting newer-than time\n");
3292 return 1;
3295 return 0;
3298 /****************************************************************************
3299 Set the archive level.
3300 ****************************************************************************/
3302 static int cmd_archive(void)
3304 TALLOC_CTX *ctx = talloc_tos();
3305 char *buf;
3307 if (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3308 archive_level = atoi(buf);
3309 } else {
3310 d_printf("Archive level is %d\n",archive_level);
3313 return 0;
3316 /****************************************************************************
3317 Toggle the lowercaseflag.
3318 ****************************************************************************/
3320 static int cmd_lowercase(void)
3322 lowercase = !lowercase;
3323 DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
3324 return 0;
3327 /****************************************************************************
3328 Toggle the case sensitive flag.
3329 ****************************************************************************/
3331 static int cmd_setcase(void)
3333 bool orig_case_sensitive = cli_set_case_sensitive(cli, false);
3335 cli_set_case_sensitive(cli, !orig_case_sensitive);
3336 DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
3337 "on":"off"));
3338 return 0;
3341 /****************************************************************************
3342 Toggle the showacls flag.
3343 ****************************************************************************/
3345 static int cmd_showacls(void)
3347 showacls = !showacls;
3348 DEBUG(2,("showacls is now %s\n",showacls?"on":"off"));
3349 return 0;
3353 /****************************************************************************
3354 Toggle the recurse flag.
3355 ****************************************************************************/
3357 static int cmd_recurse(void)
3359 recurse = !recurse;
3360 DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
3361 return 0;
3364 /****************************************************************************
3365 Toggle the translate flag.
3366 ****************************************************************************/
3368 static int cmd_translate(void)
3370 translation = !translation;
3371 DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
3372 translation?"on":"off"));
3373 return 0;
3376 /****************************************************************************
3377 Do the lcd command.
3378 ****************************************************************************/
3380 static int cmd_lcd(void)
3382 TALLOC_CTX *ctx = talloc_tos();
3383 char *buf;
3384 char *d;
3386 if (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3387 chdir(buf);
3389 d = TALLOC_ARRAY(ctx, char, PATH_MAX+1);
3390 if (!d) {
3391 return 1;
3393 DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
3394 return 0;
3397 /****************************************************************************
3398 Get a file restarting at end of local file.
3399 ****************************************************************************/
3401 static int cmd_reget(void)
3403 TALLOC_CTX *ctx = talloc_tos();
3404 char *local_name = NULL;
3405 char *remote_name = NULL;
3406 char *fname = NULL;
3407 char *p = NULL;
3409 remote_name = talloc_asprintf(ctx,
3410 "%s%s",
3411 client_get_cur_dir(),
3412 CLI_DIRSEP_STR);
3413 if (!remote_name) {
3414 return 1;
3417 if (!next_token_nr_talloc(ctx, NULL, &fname, NULL)) {
3418 d_printf("reget <filename>\n");
3419 return 1;
3421 remote_name = talloc_asprintf_append(remote_name, fname);
3422 if (!remote_name) {
3423 return 1;
3425 remote_name = clean_name(ctx,remote_name);
3426 if (!remote_name) {
3427 return 1;
3430 local_name = fname;
3431 next_token_nr_talloc(ctx, NULL, &p, NULL);
3432 if (p) {
3433 local_name = p;
3436 return do_get(remote_name, local_name, true);
3439 /****************************************************************************
3440 Put a file restarting at end of local file.
3441 ****************************************************************************/
3443 static int cmd_reput(void)
3445 TALLOC_CTX *ctx = talloc_tos();
3446 char *local_name = NULL;
3447 char *remote_name = NULL;
3448 char *buf;
3449 SMB_STRUCT_STAT st;
3451 remote_name = talloc_asprintf(ctx,
3452 "%s%s",
3453 client_get_cur_dir(),
3454 CLI_DIRSEP_STR);
3455 if (!remote_name) {
3456 return 1;
3459 if (!next_token_nr_talloc(ctx, NULL, &local_name, NULL)) {
3460 d_printf("reput <filename>\n");
3461 return 1;
3464 if (!file_exist(local_name, &st)) {
3465 d_printf("%s does not exist\n", local_name);
3466 return 1;
3469 if (next_token_nr_talloc(ctx, NULL, &buf, NULL)) {
3470 remote_name = talloc_asprintf_append(remote_name,
3471 buf);
3472 } else {
3473 remote_name = talloc_asprintf_append(remote_name,
3474 local_name);
3476 if (!remote_name) {
3477 return 1;
3480 remote_name = clean_name(ctx, remote_name);
3481 if (!remote_name) {
3482 return 1;
3485 return do_put(remote_name, local_name, true);
3488 /****************************************************************************
3489 List a share name.
3490 ****************************************************************************/
3492 static void browse_fn(const char *name, uint32 m,
3493 const char *comment, void *state)
3495 const char *typestr = "";
3497 switch (m & 7) {
3498 case STYPE_DISKTREE:
3499 typestr = "Disk";
3500 break;
3501 case STYPE_PRINTQ:
3502 typestr = "Printer";
3503 break;
3504 case STYPE_DEVICE:
3505 typestr = "Device";
3506 break;
3507 case STYPE_IPC:
3508 typestr = "IPC";
3509 break;
3511 /* FIXME: If the remote machine returns non-ascii characters
3512 in any of these fields, they can corrupt the output. We
3513 should remove them. */
3514 if (!grepable) {
3515 d_printf("\t%-15s %-10.10s%s\n",
3516 name,typestr,comment);
3517 } else {
3518 d_printf ("%s|%s|%s\n",typestr,name,comment);
3522 static bool browse_host_rpc(bool sort)
3524 NTSTATUS status;
3525 struct rpc_pipe_client *pipe_hnd;
3526 TALLOC_CTX *frame = talloc_stackframe();
3527 ENUM_HND enum_hnd;
3528 WERROR werr;
3529 SRV_SHARE_INFO_CTR ctr;
3530 int i;
3532 init_enum_hnd(&enum_hnd, 0);
3534 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &status);
3536 if (pipe_hnd == NULL) {
3537 DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
3538 nt_errstr(status)));
3539 TALLOC_FREE(frame);
3540 return false;
3543 werr = rpccli_srvsvc_net_share_enum(pipe_hnd, frame, 1, &ctr,
3544 0xffffffff, &enum_hnd);
3546 if (!W_ERROR_IS_OK(werr)) {
3547 cli_rpc_pipe_close(pipe_hnd);
3548 TALLOC_FREE(frame);
3549 return false;
3552 for (i=0; i<ctr.num_entries; i++) {
3553 SRV_SHARE_INFO_1 *info = &ctr.share.info1[i];
3554 char *name, *comment;
3555 name = rpcstr_pull_unistr2_talloc(
3556 frame, &info->info_1_str.uni_netname);
3557 comment = rpcstr_pull_unistr2_talloc(
3558 frame, &info->info_1_str.uni_remark);
3559 browse_fn(name, info->info_1.type, comment, NULL);
3562 cli_rpc_pipe_close(pipe_hnd);
3563 TALLOC_FREE(frame);
3564 return true;
3567 /****************************************************************************
3568 Try and browse available connections on a host.
3569 ****************************************************************************/
3571 static bool browse_host(bool sort)
3573 int ret;
3574 if (!grepable) {
3575 d_printf("\n\tSharename Type Comment\n");
3576 d_printf("\t--------- ---- -------\n");
3579 if (browse_host_rpc(sort)) {
3580 return true;
3583 if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
3584 d_printf("Error returning browse list: %s\n", cli_errstr(cli));
3586 return (ret != -1);
3589 /****************************************************************************
3590 List a server name.
3591 ****************************************************************************/
3593 static void server_fn(const char *name, uint32 m,
3594 const char *comment, void *state)
3597 if (!grepable){
3598 d_printf("\t%-16s %s\n", name, comment);
3599 } else {
3600 d_printf("%s|%s|%s\n",(char *)state, name, comment);
3604 /****************************************************************************
3605 Try and browse available connections on a host.
3606 ****************************************************************************/
3608 static bool list_servers(const char *wk_grp)
3610 fstring state;
3612 if (!cli->server_domain)
3613 return false;
3615 if (!grepable) {
3616 d_printf("\n\tServer Comment\n");
3617 d_printf("\t--------- -------\n");
3619 fstrcpy( state, "Server" );
3620 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
3621 state);
3623 if (!grepable) {
3624 d_printf("\n\tWorkgroup Master\n");
3625 d_printf("\t--------- -------\n");
3628 fstrcpy( state, "Workgroup" );
3629 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
3630 server_fn, state);
3631 return true;
3634 /****************************************************************************
3635 Print or set current VUID
3636 ****************************************************************************/
3638 static int cmd_vuid(void)
3640 TALLOC_CTX *ctx = talloc_tos();
3641 char *buf;
3643 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3644 d_printf("Current VUID is %d\n", cli->vuid);
3645 return 0;
3648 cli->vuid = atoi(buf);
3649 return 0;
3652 /****************************************************************************
3653 Setup a new VUID, by issuing a session setup
3654 ****************************************************************************/
3656 static int cmd_logon(void)
3658 TALLOC_CTX *ctx = talloc_tos();
3659 char *l_username, *l_password;
3661 if (!next_token_nr_talloc(ctx,NULL,&l_username,NULL)) {
3662 d_printf("logon <username> [<password>]\n");
3663 return 0;
3666 if (!next_token_nr_talloc(ctx,NULL,&l_password,NULL)) {
3667 char *pass = getpass("Password: ");
3668 if (pass) {
3669 l_password = talloc_strdup(ctx,pass);
3672 if (!l_password) {
3673 return 1;
3676 if (!NT_STATUS_IS_OK(cli_session_setup(cli, l_username,
3677 l_password, strlen(l_password),
3678 l_password, strlen(l_password),
3679 lp_workgroup()))) {
3680 d_printf("session setup failed: %s\n", cli_errstr(cli));
3681 return -1;
3684 d_printf("Current VUID is %d\n", cli->vuid);
3685 return 0;
3689 /****************************************************************************
3690 list active connections
3691 ****************************************************************************/
3693 static int cmd_list_connect(void)
3695 cli_cm_display();
3696 return 0;
3699 /****************************************************************************
3700 display the current active client connection
3701 ****************************************************************************/
3703 static int cmd_show_connect( void )
3705 TALLOC_CTX *ctx = talloc_tos();
3706 struct cli_state *targetcli;
3707 char *targetpath;
3709 if (!cli_resolve_path(ctx, "", cli, client_get_cur_dir(),
3710 &targetcli, &targetpath ) ) {
3711 d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
3712 return 1;
3715 d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
3716 return 0;
3719 /****************************************************************************
3720 iosize command
3721 ***************************************************************************/
3723 int cmd_iosize(void)
3725 TALLOC_CTX *ctx = talloc_tos();
3726 char *buf;
3727 int iosize;
3729 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3730 d_printf("iosize <n> or iosize 0x<n>. "
3731 "Minimum is 16384 (0x4000), "
3732 "max is 16776960 (0xFFFF00)\n");
3733 return 1;
3736 iosize = strtol(buf,NULL,0);
3737 if (iosize < 0 || iosize > 0xFFFF00) {
3738 d_printf("iosize out of range (min = 16384 (0x4000), "
3739 "max = 16776960 (0x0xFFFF00)");
3740 return 1;
3743 io_bufsize = iosize;
3744 d_printf("iosize is now %d\n", io_bufsize);
3745 return 0;
3749 /* Some constants for completing filename arguments */
3751 #define COMPL_NONE 0 /* No completions */
3752 #define COMPL_REMOTE 1 /* Complete remote filename */
3753 #define COMPL_LOCAL 2 /* Complete local filename */
3755 /* This defines the commands supported by this client.
3756 * NOTE: The "!" must be the last one in the list because it's fn pointer
3757 * field is NULL, and NULL in that field is used in process_tok()
3758 * (below) to indicate the end of the list. crh
3760 static struct {
3761 const char *name;
3762 int (*fn)(void);
3763 const char *description;
3764 char compl_args[2]; /* Completion argument info */
3765 } commands[] = {
3766 {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
3767 {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
3768 {"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}},
3769 {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
3770 {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
3771 {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
3772 {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
3773 {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
3774 {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
3775 {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_REMOTE}},
3776 {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
3777 {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3778 {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3779 {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
3780 {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
3781 {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
3782 {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}},
3783 {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
3784 {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
3785 {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
3786 {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
3787 {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
3788 {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
3789 {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
3790 {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
3791 {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3792 {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3793 {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
3794 {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
3795 {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
3796 {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
3797 {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
3798 {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
3799 {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
3800 {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
3801 {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
3802 {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3803 {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3804 {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3805 {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3806 {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
3807 {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
3808 {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
3809 {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
3810 {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
3811 {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
3812 {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
3813 {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
3814 {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
3815 {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
3816 {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
3817 {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
3818 {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
3819 {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
3820 {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},
3821 {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
3822 {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},
3823 {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
3824 {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
3825 {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
3826 {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
3827 {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
3828 {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
3829 {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
3830 {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
3831 {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
3832 {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
3833 {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
3834 {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
3836 /* Yes, this must be here, see crh's comment above. */
3837 {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
3838 {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
3841 /*******************************************************************
3842 Lookup a command string in the list of commands, including
3843 abbreviations.
3844 ******************************************************************/
3846 static int process_tok(char *tok)
3848 int i = 0, matches = 0;
3849 int cmd=0;
3850 int tok_len = strlen(tok);
3852 while (commands[i].fn != NULL) {
3853 if (strequal(commands[i].name,tok)) {
3854 matches = 1;
3855 cmd = i;
3856 break;
3857 } else if (strnequal(commands[i].name, tok, tok_len)) {
3858 matches++;
3859 cmd = i;
3861 i++;
3864 if (matches == 0)
3865 return(-1);
3866 else if (matches == 1)
3867 return(cmd);
3868 else
3869 return(-2);
3872 /****************************************************************************
3873 Help.
3874 ****************************************************************************/
3876 static int cmd_help(void)
3878 TALLOC_CTX *ctx = talloc_tos();
3879 int i=0,j;
3880 char *buf;
3882 if (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3883 if ((i = process_tok(buf)) >= 0)
3884 d_printf("HELP %s:\n\t%s\n\n",
3885 commands[i].name,commands[i].description);
3886 } else {
3887 while (commands[i].description) {
3888 for (j=0; commands[i].description && (j<5); j++) {
3889 d_printf("%-15s",commands[i].name);
3890 i++;
3892 d_printf("\n");
3895 return 0;
3898 /****************************************************************************
3899 Process a -c command string.
3900 ****************************************************************************/
3902 static int process_command_string(const char *cmd_in)
3904 TALLOC_CTX *ctx = talloc_tos();
3905 char *cmd = talloc_strdup(ctx, cmd_in);
3906 int rc = 0;
3908 if (!cmd) {
3909 return 1;
3911 /* establish the connection if not already */
3913 if (!cli) {
3914 cli = cli_cm_open(talloc_tos(), NULL, desthost, service, true);
3915 if (!cli) {
3916 return 1;
3920 while (cmd[0] != '\0') {
3921 char *line;
3922 const char *ptr;
3923 char *p;
3924 char *tok;
3925 int i;
3927 if ((p = strchr_m(cmd, ';')) == 0) {
3928 line = cmd;
3929 cmd += strlen(cmd);
3930 } else {
3931 *p = '\0';
3932 line = cmd;
3933 cmd = p + 1;
3936 /* and get the first part of the command */
3937 ptr = line;
3938 if (!next_token_nr_talloc(ctx,&ptr,&tok,NULL)) {
3939 continue;
3942 if ((i = process_tok(tok)) >= 0) {
3943 rc = commands[i].fn();
3944 } else if (i == -2) {
3945 d_printf("%s: command abbreviation ambiguous\n",tok);
3946 } else {
3947 d_printf("%s: command not found\n",tok);
3951 return rc;
3954 #define MAX_COMPLETIONS 100
3956 typedef struct {
3957 char *dirmask;
3958 char **matches;
3959 int count, samelen;
3960 const char *text;
3961 int len;
3962 } completion_remote_t;
3964 static void completion_remote_filter(const char *mnt,
3965 file_info *f,
3966 const char *mask,
3967 void *state)
3969 completion_remote_t *info = (completion_remote_t *)state;
3971 if ((info->count < MAX_COMPLETIONS - 1) &&
3972 (strncmp(info->text, f->name, info->len) == 0) &&
3973 (strcmp(f->name, ".") != 0) &&
3974 (strcmp(f->name, "..") != 0)) {
3975 if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
3976 info->matches[info->count] = SMB_STRDUP(f->name);
3977 else {
3978 TALLOC_CTX *ctx = talloc_stackframe();
3979 char *tmp;
3981 if (info->dirmask && info->dirmask[0] != 0) {
3982 tmp = talloc_strdup(ctx,info->dirmask);
3983 } else {
3984 tmp = talloc_strdup(ctx,"");
3986 if (!tmp) {
3987 TALLOC_FREE(ctx);
3988 return;
3990 tmp = talloc_asprintf_append(tmp, f->name);
3991 if (!tmp) {
3992 TALLOC_FREE(ctx);
3993 return;
3995 if (f->mode & aDIR) {
3996 tmp = talloc_asprintf_append(tmp, "/");
3998 if (!tmp) {
3999 TALLOC_FREE(ctx);
4000 return;
4002 info->matches[info->count] = SMB_STRDUP(tmp);
4003 TALLOC_FREE(ctx);
4005 if (info->matches[info->count] == NULL) {
4006 return;
4008 if (f->mode & aDIR) {
4009 smb_readline_ca_char(0);
4011 if (info->count == 1) {
4012 info->samelen = strlen(info->matches[info->count]);
4013 } else {
4014 while (strncmp(info->matches[info->count],
4015 info->matches[info->count-1],
4016 info->samelen) != 0) {
4017 info->samelen--;
4020 info->count++;
4024 static char **remote_completion(const char *text, int len)
4026 TALLOC_CTX *ctx = talloc_stackframe();
4027 char *dirmask = NULL;
4028 char *targetpath = NULL;
4029 struct cli_state *targetcli = NULL;
4030 int i;
4031 completion_remote_t info = { NULL, NULL, 1, 0, NULL, 0 };
4033 /* can't have non-static intialisation on Sun CC, so do it
4034 at run time here */
4035 info.samelen = len;
4036 info.text = text;
4037 info.len = len;
4039 info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
4040 if (!info.matches) {
4041 TALLOC_FREE(ctx);
4042 return NULL;
4046 * We're leaving matches[0] free to fill it later with the text to
4047 * display: Either the one single match or the longest common subset
4048 * of the matches.
4050 info.matches[0] = NULL;
4051 info.count = 1;
4053 for (i = len-1; i >= 0; i--) {
4054 if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
4055 break;
4059 info.text = text+i+1;
4060 info.samelen = info.len = len-i-1;
4062 if (i > 0) {
4063 info.dirmask = SMB_MALLOC(i+2);
4064 if (!info.dirmask) {
4065 goto cleanup;
4067 strncpy(info.dirmask, text, i+1);
4068 info.dirmask[i+1] = 0;
4069 dirmask = talloc_asprintf(ctx,
4070 "%s%*s*",
4071 client_get_cur_dir(),
4072 i-1,
4073 text);
4074 } else {
4075 info.dirmask = SMB_STRDUP("");
4076 if (!info.dirmask) {
4077 goto cleanup;
4079 dirmask = talloc_asprintf(ctx,
4080 "%s*",
4081 client_get_cur_dir());
4083 if (!dirmask) {
4084 goto cleanup;
4087 if (!cli_resolve_path(ctx, "", cli, dirmask, &targetcli, &targetpath)) {
4088 goto cleanup;
4090 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN,
4091 completion_remote_filter, (void *)&info) < 0) {
4092 goto cleanup;
4095 if (info.count == 1) {
4097 * No matches at all, NULL indicates there is nothing
4099 SAFE_FREE(info.matches[0]);
4100 SAFE_FREE(info.matches);
4101 TALLOC_FREE(ctx);
4102 return NULL;
4105 if (info.count == 2) {
4107 * Exactly one match in matches[1], indicate this is the one
4108 * in matches[0].
4110 info.matches[0] = info.matches[1];
4111 info.matches[1] = NULL;
4112 info.count -= 1;
4113 TALLOC_FREE(ctx);
4114 return info.matches;
4118 * We got more than one possible match, set the result to the maximum
4119 * common subset
4122 info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
4123 info.matches[info.count] = NULL;
4124 return info.matches;
4126 cleanup:
4127 for (i = 0; i < info.count; i++) {
4128 SAFE_FREE(info.matches[i]);
4130 SAFE_FREE(info.matches);
4131 SAFE_FREE(info.dirmask);
4132 TALLOC_FREE(ctx);
4133 return NULL;
4136 static char **completion_fn(const char *text, int start, int end)
4138 smb_readline_ca_char(' ');
4140 if (start) {
4141 const char *buf, *sp;
4142 int i;
4143 char compl_type;
4145 buf = smb_readline_get_line_buffer();
4146 if (buf == NULL)
4147 return NULL;
4149 sp = strchr(buf, ' ');
4150 if (sp == NULL)
4151 return NULL;
4153 for (i = 0; commands[i].name; i++) {
4154 if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
4155 (commands[i].name[sp - buf] == 0)) {
4156 break;
4159 if (commands[i].name == NULL)
4160 return NULL;
4162 while (*sp == ' ')
4163 sp++;
4165 if (sp == (buf + start))
4166 compl_type = commands[i].compl_args[0];
4167 else
4168 compl_type = commands[i].compl_args[1];
4170 if (compl_type == COMPL_REMOTE)
4171 return remote_completion(text, end - start);
4172 else /* fall back to local filename completion */
4173 return NULL;
4174 } else {
4175 char **matches;
4176 int i, len, samelen = 0, count=1;
4178 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
4179 if (!matches) {
4180 return NULL;
4182 matches[0] = NULL;
4184 len = strlen(text);
4185 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
4186 if (strncmp(text, commands[i].name, len) == 0) {
4187 matches[count] = SMB_STRDUP(commands[i].name);
4188 if (!matches[count])
4189 goto cleanup;
4190 if (count == 1)
4191 samelen = strlen(matches[count]);
4192 else
4193 while (strncmp(matches[count], matches[count-1], samelen) != 0)
4194 samelen--;
4195 count++;
4199 switch (count) {
4200 case 0: /* should never happen */
4201 case 1:
4202 goto cleanup;
4203 case 2:
4204 matches[0] = SMB_STRDUP(matches[1]);
4205 break;
4206 default:
4207 matches[0] = (char *)SMB_MALLOC(samelen+1);
4208 if (!matches[0])
4209 goto cleanup;
4210 strncpy(matches[0], matches[1], samelen);
4211 matches[0][samelen] = 0;
4213 matches[count] = NULL;
4214 return matches;
4216 cleanup:
4217 for (i = 0; i < count; i++)
4218 free(matches[i]);
4220 free(matches);
4221 return NULL;
4225 /****************************************************************************
4226 Make sure we swallow keepalives during idle time.
4227 ****************************************************************************/
4229 static void readline_callback(void)
4231 fd_set fds;
4232 struct timeval timeout;
4233 static time_t last_t;
4234 time_t t;
4236 t = time(NULL);
4238 if (t - last_t < 5)
4239 return;
4241 last_t = t;
4243 again:
4245 if (cli->fd == -1)
4246 return;
4248 FD_ZERO(&fds);
4249 FD_SET(cli->fd,&fds);
4251 timeout.tv_sec = 0;
4252 timeout.tv_usec = 0;
4253 sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
4255 /* We deliberately use receive_smb instead of
4256 client_receive_smb as we want to receive
4257 session keepalives and then drop them here.
4259 if (FD_ISSET(cli->fd,&fds)) {
4260 if (!receive_smb(cli->fd,cli->inbuf,0,&cli->smb_rw_error)) {
4261 DEBUG(0, ("Read from server failed, maybe it closed the "
4262 "connection\n"));
4263 return;
4265 goto again;
4268 /* Ping the server to keep the connection alive using SMBecho. */
4270 unsigned char garbage[16];
4271 memset(garbage, 0xf0, sizeof(garbage));
4272 cli_echo(cli, 1, garbage, sizeof(garbage));
4276 /****************************************************************************
4277 Process commands on stdin.
4278 ****************************************************************************/
4280 static int process_stdin(void)
4282 const char *ptr;
4283 int rc = 0;
4285 while (1) {
4286 TALLOC_CTX *frame = talloc_stackframe();
4287 char *tok = NULL;
4288 char *the_prompt = NULL;
4289 char *line = NULL;
4290 int i;
4292 /* display a prompt */
4293 if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
4294 TALLOC_FREE(frame);
4295 break;
4297 line = smb_readline(the_prompt, readline_callback, completion_fn);
4298 SAFE_FREE(the_prompt);
4299 if (!line) {
4300 TALLOC_FREE(frame);
4301 break;
4304 /* special case - first char is ! */
4305 if (*line == '!') {
4306 system(line + 1);
4307 SAFE_FREE(line);
4308 TALLOC_FREE(frame);
4309 continue;
4312 /* and get the first part of the command */
4313 ptr = line;
4314 if (!next_token_nr_talloc(frame,&ptr,&tok,NULL)) {
4315 TALLOC_FREE(frame);
4316 SAFE_FREE(line);
4317 continue;
4320 if ((i = process_tok(tok)) >= 0) {
4321 rc = commands[i].fn();
4322 } else if (i == -2) {
4323 d_printf("%s: command abbreviation ambiguous\n",tok);
4324 } else {
4325 d_printf("%s: command not found\n",tok);
4327 SAFE_FREE(line);
4328 TALLOC_FREE(frame);
4330 return rc;
4333 /****************************************************************************
4334 Process commands from the client.
4335 ****************************************************************************/
4337 static int process(const char *base_directory)
4339 int rc = 0;
4341 cli = cli_cm_open(talloc_tos(), NULL, desthost, service, true);
4342 if (!cli) {
4343 return 1;
4346 if (*base_directory) {
4347 rc = do_cd(base_directory);
4348 if (rc) {
4349 cli_cm_shutdown();
4350 return rc;
4354 if (cmdstr) {
4355 rc = process_command_string(cmdstr);
4356 } else {
4357 process_stdin();
4360 cli_cm_shutdown();
4361 return rc;
4364 /****************************************************************************
4365 Handle a -L query.
4366 ****************************************************************************/
4368 static int do_host_query(const char *query_host)
4370 cli = cli_cm_open(talloc_tos(), NULL, query_host, "IPC$", true);
4371 if (!cli)
4372 return 1;
4374 browse_host(true);
4376 if (port != 139) {
4378 /* Workgroups simply don't make sense over anything
4379 else but port 139... */
4381 cli_cm_shutdown();
4382 cli_cm_set_port( 139 );
4383 cli = cli_cm_open(talloc_tos(), NULL, query_host, "IPC$", true);
4386 if (cli == NULL) {
4387 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
4388 return 1;
4391 list_servers(lp_workgroup());
4393 cli_cm_shutdown();
4395 return(0);
4398 /****************************************************************************
4399 Handle a tar operation.
4400 ****************************************************************************/
4402 static int do_tar_op(const char *base_directory)
4404 int ret;
4406 /* do we already have a connection? */
4407 if (!cli) {
4408 cli = cli_cm_open(talloc_tos(), NULL, desthost, service, true);
4409 if (!cli)
4410 return 1;
4413 recurse=true;
4415 if (*base_directory) {
4416 ret = do_cd(base_directory);
4417 if (ret) {
4418 cli_cm_shutdown();
4419 return ret;
4423 ret=process_tar();
4425 cli_cm_shutdown();
4427 return(ret);
4430 /****************************************************************************
4431 Handle a message operation.
4432 ****************************************************************************/
4434 static int do_message_op(void)
4436 struct sockaddr_storage ss;
4437 struct nmb_name called, calling;
4438 fstring server_name;
4439 char name_type_hex[10];
4440 int msg_port;
4441 NTSTATUS status;
4443 make_nmb_name(&calling, calling_name, 0x0);
4444 make_nmb_name(&called , desthost, name_type);
4446 fstrcpy(server_name, desthost);
4447 snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
4448 fstrcat(server_name, name_type_hex);
4450 zero_addr(&ss);
4451 if (have_ip)
4452 ss = dest_ss;
4454 /* we can only do messages over port 139 (to windows clients at least) */
4456 msg_port = port ? port : 139;
4458 if (!(cli=cli_initialise()) || (cli_set_port(cli, msg_port) != msg_port)) {
4459 d_printf("Connection to %s failed\n", desthost);
4460 return 1;
4463 status = cli_connect(cli, server_name, &ss);
4464 if (!NT_STATUS_IS_OK(status)) {
4465 d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
4466 return 1;
4469 if (!cli_session_request(cli, &calling, &called)) {
4470 d_printf("session request failed\n");
4471 cli_cm_shutdown();
4472 return 1;
4475 send_message();
4476 cli_cm_shutdown();
4478 return 0;
4481 /****************************************************************************
4482 main program
4483 ****************************************************************************/
4485 int main(int argc,char *argv[])
4487 char *base_directory = NULL;
4488 int opt;
4489 char *query_host = NULL;
4490 bool message = false;
4491 char *term_code = NULL;
4492 static const char *new_name_resolve_order = NULL;
4493 poptContext pc;
4494 char *p;
4495 int rc = 0;
4496 fstring new_workgroup;
4497 bool tar_opt = false;
4498 bool service_opt = false;
4499 struct poptOption long_options[] = {
4500 POPT_AUTOHELP
4502 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
4503 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
4504 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
4505 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
4506 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
4507 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
4508 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
4509 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
4510 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
4511 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" },
4512 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
4513 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
4514 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
4515 POPT_COMMON_SAMBA
4516 POPT_COMMON_CONNECTION
4517 POPT_COMMON_CREDENTIALS
4518 POPT_TABLEEND
4520 TALLOC_CTX *frame = talloc_stackframe();
4522 if (!client_set_cur_dir("\\")) {
4523 exit(ENOMEM);
4525 load_case_tables();
4527 #ifdef KANJI
4528 term_code = talloc_strdup(frame,KANJI);
4529 #else /* KANJI */
4530 term_code = talloc_strdup(frame,"");
4531 #endif /* KANJI */
4532 if (!term_code) {
4533 exit(ENOMEM);
4536 /* initialize the workgroup name so we can determine whether or
4537 not it was set by a command line option */
4539 set_global_myworkgroup( "" );
4540 set_global_myname( "" );
4542 /* set default debug level to 0 regardless of what smb.conf sets */
4543 setup_logging( "smbclient", true );
4544 DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
4545 if ((dbf = x_fdup(x_stderr))) {
4546 x_setbuf( dbf, NULL );
4549 /* skip argv(0) */
4550 pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 0);
4551 poptSetOtherOptionHelp(pc, "service <password>");
4553 in_client = true; /* Make sure that we tell lp_load we are */
4555 while ((opt = poptGetNextOpt(pc)) != -1) {
4557 /* if the tar option has been called previouslt, now we need to eat out the leftovers */
4558 /* I see no other way to keep things sane --SSS */
4559 if (tar_opt == true) {
4560 while (poptPeekArg(pc)) {
4561 poptGetArg(pc);
4563 tar_opt = false;
4566 /* if the service has not yet been specified lets see if it is available in the popt stack */
4567 if (!service_opt && poptPeekArg(pc)) {
4568 service = talloc_strdup(frame, poptGetArg(pc));
4569 if (!service) {
4570 exit(ENOMEM);
4572 service_opt = true;
4575 /* if the service has already been retrieved then check if we have also a password */
4576 if (service_opt && (!get_cmdline_auth_info_got_pass()) && poptPeekArg(pc)) {
4577 set_cmdline_auth_info_password(poptGetArg(pc));
4580 switch (opt) {
4581 case 'M':
4582 /* Messages are sent to NetBIOS name type 0x3
4583 * (Messenger Service). Make sure we default
4584 * to port 139 instead of port 445. srl,crh
4586 name_type = 0x03;
4587 cli_cm_set_dest_name_type( name_type );
4588 desthost = talloc_strdup(frame,poptGetOptArg(pc));
4589 if (!desthost) {
4590 exit(ENOMEM);
4592 if( !port )
4593 cli_cm_set_port( 139 );
4594 message = true;
4595 break;
4596 case 'I':
4598 if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
4599 exit(1);
4601 have_ip = true;
4603 cli_cm_set_dest_ss(&dest_ss);
4605 break;
4606 case 'E':
4607 if (dbf) {
4608 x_fclose(dbf);
4610 dbf = x_stderr;
4611 display_set_stderr();
4612 break;
4614 case 'L':
4615 query_host = talloc_strdup(frame, poptGetOptArg(pc));
4616 if (!query_host) {
4617 exit(ENOMEM);
4619 break;
4620 case 't':
4621 term_code = talloc_strdup(frame,poptGetOptArg(pc));
4622 if (!term_code) {
4623 exit(ENOMEM);
4625 break;
4626 case 'm':
4627 max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
4628 break;
4629 case 'T':
4630 /* We must use old option processing for this. Find the
4631 * position of the -T option in the raw argv[]. */
4633 int i;
4634 for (i = 1; i < argc; i++) {
4635 if (strncmp("-T", argv[i],2)==0)
4636 break;
4638 i++;
4639 if (!tar_parseargs(argc, argv, poptGetOptArg(pc), i)) {
4640 poptPrintUsage(pc, stderr, 0);
4641 exit(1);
4644 /* this must be the last option, mark we have parsed it so that we know we have */
4645 tar_opt = true;
4646 break;
4647 case 'D':
4648 base_directory = talloc_strdup(frame, poptGetOptArg(pc));
4649 if (!base_directory) {
4650 exit(ENOMEM);
4652 break;
4653 case 'g':
4654 grepable=true;
4655 break;
4659 /* We may still have some leftovers after the last popt option has been called */
4660 if (tar_opt == true) {
4661 while (poptPeekArg(pc)) {
4662 poptGetArg(pc);
4664 tar_opt = false;
4667 /* if the service has not yet been specified lets see if it is available in the popt stack */
4668 if (!service_opt && poptPeekArg(pc)) {
4669 service = talloc_strdup(frame,poptGetArg(pc));
4670 if (!service) {
4671 exit(ENOMEM);
4673 service_opt = true;
4676 /* if the service has already been retrieved then check if we have also a password */
4677 if (service_opt && !get_cmdline_auth_info_got_pass() && poptPeekArg(pc)) {
4678 set_cmdline_auth_info_password(poptGetArg(pc));
4681 /* check for the -P option */
4683 if ( port != 0 )
4684 cli_cm_set_port( port );
4687 * Don't load debug level from smb.conf. It should be
4688 * set by cmdline arg or remain default (0)
4690 AllowDebugChange = false;
4692 /* save the workgroup...
4694 FIXME!! do we need to do this for other options as well
4695 (or maybe a generic way to keep lp_load() from overwriting
4696 everything)? */
4698 fstrcpy( new_workgroup, lp_workgroup() );
4699 calling_name = talloc_strdup(frame, global_myname() );
4700 if (!calling_name) {
4701 exit(ENOMEM);
4704 if ( override_logfile )
4705 setup_logging( lp_logfile(), false );
4707 if (!lp_load(dyn_CONFIGFILE,true,false,false,true)) {
4708 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
4709 argv[0], dyn_CONFIGFILE);
4712 load_interfaces();
4714 if (service_opt) {
4715 size_t len;
4717 /* Convert any '/' characters in the service name to '\' characters */
4718 string_replace(service, '/','\\');
4719 if (count_chars(service,'\\') < 3) {
4720 d_printf("\n%s: Not enough '\\' characters in service\n",service);
4721 poptPrintUsage(pc, stderr, 0);
4722 exit(1);
4724 /* Remove trailing slashes */
4725 len = strlen(service);
4726 while(len > 0 && service[len - 1] == '\\') {
4727 --len;
4728 service[len] = '\0';
4732 if ( strlen(new_workgroup) != 0 ) {
4733 set_global_myworkgroup( new_workgroup );
4736 if ( strlen(calling_name) != 0 ) {
4737 set_global_myname( calling_name );
4738 } else {
4739 TALLOC_FREE(calling_name);
4740 calling_name = talloc_strdup(frame, global_myname() );
4743 init_names();
4745 if(new_name_resolve_order)
4746 lp_set_name_resolve_order(new_name_resolve_order);
4748 if (!tar_type && !query_host && !service && !message) {
4749 poptPrintUsage(pc, stderr, 0);
4750 exit(1);
4753 poptFreeContext(pc);
4755 /* Store the username and password for dfs support */
4757 cli_cm_set_credentials();
4759 DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
4761 if (tar_type) {
4762 if (cmdstr)
4763 process_command_string(cmdstr);
4764 return do_tar_op(base_directory);
4767 if (query_host) {
4768 char *qhost = query_host;
4769 char *slash;
4771 while (*qhost == '\\' || *qhost == '/')
4772 qhost++;
4774 if ((slash = strchr_m(qhost, '/'))
4775 || (slash = strchr_m(qhost, '\\'))) {
4776 *slash = 0;
4779 if ((p=strchr_m(qhost, '#'))) {
4780 *p = 0;
4781 p++;
4782 sscanf(p, "%x", &name_type);
4783 cli_cm_set_dest_name_type( name_type );
4786 return do_host_query(qhost);
4789 if (message) {
4790 return do_message_op();
4793 if (process(base_directory)) {
4794 return 1;
4797 TALLOC_FREE(frame);
4798 return rc;