Remove Get_Pwnam and its associated static variable
[Samba/gbeck.git] / source3 / client / client.c
blob97d7cf0e0be6f7df3615a466d57a3ed3feb42e35
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 int do_smb_browse(void); /* mDNS browsing */
33 extern bool AllowDebugChange;
34 extern bool override_logfile;
35 extern char tar_type;
36 extern bool in_client;
38 static int port = 0;
39 static char *service;
40 static char *desthost;
41 static char *calling_name;
42 static bool grepable = false;
43 static char *cmdstr = NULL;
45 static int io_bufsize = 64512;
47 static int name_type = 0x20;
48 extern int max_protocol;
50 static int process_tok(char *tok);
51 static int cmd_help(void);
53 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
55 /* 30 second timeout on most commands */
56 #define CLIENT_TIMEOUT (30*1000)
57 #define SHORT_TIMEOUT (5*1000)
59 /* value for unused fid field in trans2 secondary request */
60 #define FID_UNUSED (0xFFFF)
62 time_t newer_than = 0;
63 static int archive_level = 0;
65 static bool translation = false;
66 static bool have_ip;
68 /* clitar bits insert */
69 extern int blocksize;
70 extern bool tar_inc;
71 extern bool tar_reset;
72 /* clitar bits end */
74 static bool prompt = true;
76 static bool recurse = false;
77 static bool showacls = false;
78 bool lowercase = false;
80 static struct sockaddr_storage dest_ss;
82 #define SEPARATORS " \t\n\r"
84 static bool abort_mget = true;
86 /* timing globals */
87 SMB_BIG_UINT get_total_size = 0;
88 unsigned int get_total_time_ms = 0;
89 static SMB_BIG_UINT put_total_size = 0;
90 static unsigned int put_total_time_ms = 0;
92 /* totals globals */
93 static double dir_total;
95 /* root cli_state connection */
97 struct cli_state *cli;
99 static char CLI_DIRSEP_CHAR = '\\';
100 static char CLI_DIRSEP_STR[] = { '\\', '\0' };
102 /* Accessor functions for directory paths. */
103 static char *fileselection;
104 static const char *client_get_fileselection(void)
106 if (fileselection) {
107 return fileselection;
109 return "";
112 static const char *client_set_fileselection(const char *new_fs)
114 SAFE_FREE(fileselection);
115 if (new_fs) {
116 fileselection = SMB_STRDUP(new_fs);
118 return client_get_fileselection();
121 static char *cwd;
122 static const char *client_get_cwd(void)
124 if (cwd) {
125 return cwd;
127 return CLI_DIRSEP_STR;
130 static const char *client_set_cwd(const char *new_cwd)
132 SAFE_FREE(cwd);
133 if (new_cwd) {
134 cwd = SMB_STRDUP(new_cwd);
136 return client_get_cwd();
139 static char *cur_dir;
140 const char *client_get_cur_dir(void)
142 if (cur_dir) {
143 return cur_dir;
145 return CLI_DIRSEP_STR;
148 const char *client_set_cur_dir(const char *newdir)
150 SAFE_FREE(cur_dir);
151 if (newdir) {
152 cur_dir = SMB_STRDUP(newdir);
154 return client_get_cur_dir();
157 /****************************************************************************
158 Write to a local file with CR/LF->LF translation if appropriate. Return the
159 number taken from the buffer. This may not equal the number written.
160 ****************************************************************************/
162 static int writefile(int f, char *b, int n)
164 int i;
166 if (!translation) {
167 return write(f,b,n);
170 i = 0;
171 while (i < n) {
172 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
173 b++;i++;
175 if (write(f, b, 1) != 1) {
176 break;
178 b++;
179 i++;
182 return(i);
185 /****************************************************************************
186 Read from a file with LF->CR/LF translation if appropriate. Return the
187 number read. read approx n bytes.
188 ****************************************************************************/
190 static int readfile(char *b, int n, XFILE *f)
192 int i;
193 int c;
195 if (!translation)
196 return x_fread(b,1,n,f);
198 i = 0;
199 while (i < (n - 1) && (i < BUFFER_SIZE)) {
200 if ((c = x_getc(f)) == EOF) {
201 break;
204 if (c == '\n') { /* change all LFs to CR/LF */
205 b[i++] = '\r';
208 b[i++] = c;
211 return(i);
214 /****************************************************************************
215 Send a message.
216 ****************************************************************************/
218 static void send_message(void)
220 int total_len = 0;
221 int grp_id;
223 if (!cli_message_start(cli, desthost,
224 get_cmdline_auth_info_username(), &grp_id)) {
225 d_printf("message start: %s\n", cli_errstr(cli));
226 return;
230 d_printf("Connected. Type your message, ending it with a Control-D\n");
232 while (!feof(stdin) && total_len < 1600) {
233 int maxlen = MIN(1600 - total_len,127);
234 char msg[1024];
235 int l=0;
236 int c;
238 ZERO_ARRAY(msg);
240 for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
241 if (c == '\n')
242 msg[l++] = '\r';
243 msg[l] = c;
246 if ((total_len > 0) && (strlen(msg) == 0)) {
247 break;
250 if (!cli_message_text(cli, msg, l, grp_id)) {
251 d_printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
252 return;
255 total_len += l;
258 if (total_len >= 1600)
259 d_printf("the message was truncated to 1600 bytes\n");
260 else
261 d_printf("sent %d bytes\n",total_len);
263 if (!cli_message_end(cli, grp_id)) {
264 d_printf("SMBsendend failed (%s)\n",cli_errstr(cli));
265 return;
269 /****************************************************************************
270 Check the space on a device.
271 ****************************************************************************/
273 static int do_dskattr(void)
275 int total, bsize, avail;
276 struct cli_state *targetcli = NULL;
277 char *targetpath = NULL;
278 TALLOC_CTX *ctx = talloc_tos();
280 if ( !cli_resolve_path(ctx, "", cli, client_get_cur_dir(), &targetcli, &targetpath)) {
281 d_printf("Error in dskattr: %s\n", cli_errstr(cli));
282 return 1;
285 if (!cli_dskattr(targetcli, &bsize, &total, &avail)) {
286 d_printf("Error in dskattr: %s\n",cli_errstr(targetcli));
287 return 1;
290 d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
291 total, bsize, avail);
293 return 0;
296 /****************************************************************************
297 Show cd/pwd.
298 ****************************************************************************/
300 static int cmd_pwd(void)
302 d_printf("Current directory is %s",service);
303 d_printf("%s\n",client_get_cur_dir());
304 return 0;
307 /****************************************************************************
308 Change directory - inner section.
309 ****************************************************************************/
311 static int do_cd(const char *new_dir)
313 char *newdir = NULL;
314 char *saved_dir = NULL;
315 char *new_cd = NULL;
316 char *targetpath = NULL;
317 struct cli_state *targetcli = NULL;
318 SMB_STRUCT_STAT sbuf;
319 uint32 attributes;
320 int ret = 1;
321 TALLOC_CTX *ctx = talloc_stackframe();
323 newdir = talloc_strdup(ctx, new_dir);
324 if (!newdir) {
325 TALLOC_FREE(ctx);
326 return 1;
328 string_replace(newdir,'/','\\');
330 /* Save the current directory in case the new directory is invalid */
332 saved_dir = talloc_strdup(ctx, client_get_cur_dir());
333 if (!saved_dir) {
334 TALLOC_FREE(ctx);
335 return 1;
338 if (*newdir == CLI_DIRSEP_CHAR) {
339 client_set_cur_dir(newdir);
340 new_cd = newdir;
341 } else {
342 new_cd = talloc_asprintf(ctx, "%s%s",
343 client_get_cur_dir(),
344 newdir);
345 if (!new_cd) {
346 goto out;
348 if ((new_cd[0] != '\0') && (*(new_cd+strlen(new_cd)-1) != CLI_DIRSEP_CHAR)) {
349 new_cd = talloc_asprintf_append(new_cd, CLI_DIRSEP_STR);
350 if (!new_cd) {
351 goto out;
354 client_set_cur_dir(new_cd);
356 if (!new_cd) {
357 goto out;
360 new_cd = clean_name(ctx, new_cd);
361 client_set_cur_dir(new_cd);
363 if ( !cli_resolve_path(ctx, "", cli, new_cd, &targetcli, &targetpath)) {
364 d_printf("cd %s: %s\n", new_cd, cli_errstr(cli));
365 client_set_cur_dir(saved_dir);
366 goto out;
369 if (strequal(targetpath,CLI_DIRSEP_STR )) {
370 TALLOC_FREE(ctx);
371 return 0;
374 /* Use a trans2_qpathinfo to test directories for modern servers.
375 Except Win9x doesn't support the qpathinfo_basic() call..... */
377 if (targetcli->protocol > PROTOCOL_LANMAN2 && !targetcli->win95) {
378 if (!cli_qpathinfo_basic( targetcli, targetpath, &sbuf, &attributes ) ) {
379 d_printf("cd %s: %s\n", new_cd, cli_errstr(targetcli));
380 client_set_cur_dir(saved_dir);
381 goto out;
384 if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
385 d_printf("cd %s: not a directory\n", new_cd);
386 client_set_cur_dir(saved_dir);
387 goto out;
389 } else {
390 targetpath = talloc_asprintf(ctx,
391 "%s%s",
392 targetpath,
393 CLI_DIRSEP_STR );
394 if (!targetpath) {
395 client_set_cur_dir(saved_dir);
396 goto out;
398 targetpath = clean_name(ctx, targetpath);
399 if (!targetpath) {
400 client_set_cur_dir(saved_dir);
401 goto out;
404 if (!cli_chkpath(targetcli, targetpath)) {
405 d_printf("cd %s: %s\n", new_cd, cli_errstr(targetcli));
406 client_set_cur_dir(saved_dir);
407 goto out;
411 ret = 0;
413 out:
415 TALLOC_FREE(ctx);
416 return ret;
419 /****************************************************************************
420 Change directory.
421 ****************************************************************************/
423 static int cmd_cd(void)
425 char *buf = NULL;
426 int rc = 0;
428 if (next_token_nr_talloc(talloc_tos(), NULL, &buf,NULL)) {
429 rc = do_cd(buf);
430 } else {
431 d_printf("Current directory is %s\n",client_get_cur_dir());
434 return rc;
437 /****************************************************************************
438 Change directory.
439 ****************************************************************************/
441 static int cmd_cd_oneup(void)
443 return do_cd("..");
446 /*******************************************************************
447 Decide if a file should be operated on.
448 ********************************************************************/
450 static bool do_this_one(file_info *finfo)
452 if (!finfo->name) {
453 return false;
456 if (finfo->mode & aDIR) {
457 return true;
460 if (*client_get_fileselection() &&
461 !mask_match(finfo->name,client_get_fileselection(),false)) {
462 DEBUG(3,("mask_match %s failed\n", finfo->name));
463 return false;
466 if (newer_than && finfo->mtime_ts.tv_sec < newer_than) {
467 DEBUG(3,("newer_than %s failed\n", finfo->name));
468 return false;
471 if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
472 DEBUG(3,("archive %s failed\n", finfo->name));
473 return false;
476 return true;
479 /****************************************************************************
480 Display info about a file.
481 ****************************************************************************/
483 static void display_finfo(file_info *finfo, const char *dir)
485 time_t t;
486 TALLOC_CTX *ctx = talloc_tos();
488 if (!do_this_one(finfo)) {
489 return;
492 t = finfo->mtime_ts.tv_sec; /* the time is assumed to be passed as GMT */
493 if (!showacls) {
494 d_printf(" %-30s%7.7s %8.0f %s",
495 finfo->name,
496 attrib_string(finfo->mode),
497 (double)finfo->size,
498 time_to_asc(t));
499 dir_total += finfo->size;
500 } else {
501 char *afname = NULL;
502 int fnum;
504 /* skip if this is . or .. */
505 if ( strequal(finfo->name,"..") || strequal(finfo->name,".") )
506 return;
507 /* create absolute filename for cli_nt_create() FIXME */
508 afname = talloc_asprintf(ctx,
509 "%s%s%s",
510 client_get_cwd(),
511 CLI_DIRSEP_STR,
512 finfo->name);
513 if (!afname) {
514 return;
516 /* print file meta date header */
517 d_printf( "FILENAME:%s\n", afname);
518 d_printf( "MODE:%s\n", attrib_string(finfo->mode));
519 d_printf( "SIZE:%.0f\n", (double)finfo->size);
520 d_printf( "MTIME:%s", time_to_asc(t));
521 fnum = cli_nt_create(finfo->cli, afname, CREATE_ACCESS_READ);
522 if (fnum == -1) {
523 DEBUG( 0, ("display_finfo() Failed to open %s: %s\n",
524 afname,
525 cli_errstr( finfo->cli)));
526 } else {
527 SEC_DESC *sd = NULL;
528 sd = cli_query_secdesc(finfo->cli, fnum, ctx);
529 if (!sd) {
530 DEBUG( 0, ("display_finfo() failed to "
531 "get security descriptor: %s",
532 cli_errstr( finfo->cli)));
533 } else {
534 display_sec_desc(sd);
536 TALLOC_FREE(sd);
538 TALLOC_FREE(afname);
542 /****************************************************************************
543 Accumulate size of a file.
544 ****************************************************************************/
546 static void do_du(file_info *finfo, const char *dir)
548 if (do_this_one(finfo)) {
549 dir_total += finfo->size;
553 static bool do_list_recurse;
554 static bool do_list_dirs;
555 static char *do_list_queue = 0;
556 static long do_list_queue_size = 0;
557 static long do_list_queue_start = 0;
558 static long do_list_queue_end = 0;
559 static void (*do_list_fn)(file_info *, const char *dir);
561 /****************************************************************************
562 Functions for do_list_queue.
563 ****************************************************************************/
566 * The do_list_queue is a NUL-separated list of strings stored in a
567 * char*. Since this is a FIFO, we keep track of the beginning and
568 * ending locations of the data in the queue. When we overflow, we
569 * double the size of the char*. When the start of the data passes
570 * the midpoint, we move everything back. This is logically more
571 * complex than a linked list, but easier from a memory management
572 * angle. In any memory error condition, do_list_queue is reset.
573 * Functions check to ensure that do_list_queue is non-NULL before
574 * accessing it.
577 static void reset_do_list_queue(void)
579 SAFE_FREE(do_list_queue);
580 do_list_queue_size = 0;
581 do_list_queue_start = 0;
582 do_list_queue_end = 0;
585 static void init_do_list_queue(void)
587 reset_do_list_queue();
588 do_list_queue_size = 1024;
589 do_list_queue = (char *)SMB_MALLOC(do_list_queue_size);
590 if (do_list_queue == 0) {
591 d_printf("malloc fail for size %d\n",
592 (int)do_list_queue_size);
593 reset_do_list_queue();
594 } else {
595 memset(do_list_queue, 0, do_list_queue_size);
599 static void adjust_do_list_queue(void)
602 * If the starting point of the queue is more than half way through,
603 * move everything toward the beginning.
606 if (do_list_queue == NULL) {
607 DEBUG(4,("do_list_queue is empty\n"));
608 do_list_queue_start = do_list_queue_end = 0;
609 return;
612 if (do_list_queue_start == do_list_queue_end) {
613 DEBUG(4,("do_list_queue is empty\n"));
614 do_list_queue_start = do_list_queue_end = 0;
615 *do_list_queue = '\0';
616 } else if (do_list_queue_start > (do_list_queue_size / 2)) {
617 DEBUG(4,("sliding do_list_queue backward\n"));
618 memmove(do_list_queue,
619 do_list_queue + do_list_queue_start,
620 do_list_queue_end - do_list_queue_start);
621 do_list_queue_end -= do_list_queue_start;
622 do_list_queue_start = 0;
626 static void add_to_do_list_queue(const char *entry)
628 long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
629 while (new_end > do_list_queue_size) {
630 do_list_queue_size *= 2;
631 DEBUG(4,("enlarging do_list_queue to %d\n",
632 (int)do_list_queue_size));
633 do_list_queue = (char *)SMB_REALLOC(do_list_queue, do_list_queue_size);
634 if (! do_list_queue) {
635 d_printf("failure enlarging do_list_queue to %d bytes\n",
636 (int)do_list_queue_size);
637 reset_do_list_queue();
638 } else {
639 memset(do_list_queue + do_list_queue_size / 2,
640 0, do_list_queue_size / 2);
643 if (do_list_queue) {
644 safe_strcpy_base(do_list_queue + do_list_queue_end,
645 entry, do_list_queue, do_list_queue_size);
646 do_list_queue_end = new_end;
647 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
648 entry, (int)do_list_queue_start, (int)do_list_queue_end));
652 static char *do_list_queue_head(void)
654 return do_list_queue + do_list_queue_start;
657 static void remove_do_list_queue_head(void)
659 if (do_list_queue_end > do_list_queue_start) {
660 do_list_queue_start += strlen(do_list_queue_head()) + 1;
661 adjust_do_list_queue();
662 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
663 (int)do_list_queue_start, (int)do_list_queue_end));
667 static int do_list_queue_empty(void)
669 return (! (do_list_queue && *do_list_queue));
672 /****************************************************************************
673 A helper for do_list.
674 ****************************************************************************/
676 static void do_list_helper(const char *mntpoint, file_info *f, const char *mask, void *state)
678 TALLOC_CTX *ctx = talloc_tos();
679 char *dir = NULL;
680 char *dir_end = NULL;
682 /* Work out the directory. */
683 dir = talloc_strdup(ctx, mask);
684 if (!dir) {
685 return;
687 if ((dir_end = strrchr(dir, CLI_DIRSEP_CHAR)) != NULL) {
688 *dir_end = '\0';
691 if (f->mode & aDIR) {
692 if (do_list_dirs && do_this_one(f)) {
693 do_list_fn(f, dir);
695 if (do_list_recurse &&
696 f->name &&
697 !strequal(f->name,".") &&
698 !strequal(f->name,"..")) {
699 char *mask2 = NULL;
700 char *p = NULL;
702 if (!f->name[0]) {
703 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
704 TALLOC_FREE(dir);
705 return;
708 mask2 = talloc_asprintf(ctx,
709 "%s%s",
710 mntpoint,
711 mask);
712 if (!mask2) {
713 TALLOC_FREE(dir);
714 return;
716 p = strrchr_m(mask2,CLI_DIRSEP_CHAR);
717 if (!p) {
718 TALLOC_FREE(dir);
719 return;
721 p[1] = 0;
722 mask2 = talloc_asprintf_append(mask2,
723 "%s%s*",
724 f->name,
725 CLI_DIRSEP_STR);
726 if (!mask2) {
727 TALLOC_FREE(dir);
728 return;
730 add_to_do_list_queue(mask2);
731 TALLOC_FREE(mask2);
733 TALLOC_FREE(dir);
734 return;
737 if (do_this_one(f)) {
738 do_list_fn(f,dir);
740 TALLOC_FREE(dir);
743 /****************************************************************************
744 A wrapper around cli_list that adds recursion.
745 ****************************************************************************/
747 void do_list(const char *mask,
748 uint16 attribute,
749 void (*fn)(file_info *, const char *dir),
750 bool rec,
751 bool dirs)
753 static int in_do_list = 0;
754 TALLOC_CTX *ctx = talloc_tos();
755 struct cli_state *targetcli = NULL;
756 char *targetpath = NULL;
758 if (in_do_list && rec) {
759 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
760 exit(1);
763 in_do_list = 1;
765 do_list_recurse = rec;
766 do_list_dirs = dirs;
767 do_list_fn = fn;
769 if (rec) {
770 init_do_list_queue();
771 add_to_do_list_queue(mask);
773 while (!do_list_queue_empty()) {
775 * Need to copy head so that it doesn't become
776 * invalid inside the call to cli_list. This
777 * would happen if the list were expanded
778 * during the call.
779 * Fix from E. Jay Berkenbilt (ejb@ql.org)
781 char *head = talloc_strdup(ctx, do_list_queue_head());
783 if (!head) {
784 return;
787 /* check for dfs */
789 if ( !cli_resolve_path(ctx, "", cli, head, &targetcli, &targetpath ) ) {
790 d_printf("do_list: [%s] %s\n", head, cli_errstr(cli));
791 remove_do_list_queue_head();
792 continue;
795 cli_list(targetcli, targetpath, attribute, do_list_helper, NULL);
796 remove_do_list_queue_head();
797 if ((! do_list_queue_empty()) && (fn == display_finfo)) {
798 char *next_file = do_list_queue_head();
799 char *save_ch = 0;
800 if ((strlen(next_file) >= 2) &&
801 (next_file[strlen(next_file) - 1] == '*') &&
802 (next_file[strlen(next_file) - 2] == CLI_DIRSEP_CHAR)) {
803 save_ch = next_file +
804 strlen(next_file) - 2;
805 *save_ch = '\0';
806 if (showacls) {
807 /* cwd is only used if showacls is on */
808 client_set_cwd(next_file);
811 if (!showacls) /* don't disturbe the showacls output */
812 d_printf("\n%s\n",next_file);
813 if (save_ch) {
814 *save_ch = CLI_DIRSEP_CHAR;
817 TALLOC_FREE(head);
818 TALLOC_FREE(targetpath);
820 } else {
821 /* check for dfs */
822 if (cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetpath)) {
823 if (cli_list(targetcli, targetpath, attribute, do_list_helper, NULL) == -1) {
824 d_printf("%s listing %s\n",
825 cli_errstr(targetcli), targetpath);
827 TALLOC_FREE(targetpath);
828 } else {
829 d_printf("do_list: [%s] %s\n", mask, cli_errstr(cli));
833 in_do_list = 0;
834 reset_do_list_queue();
837 /****************************************************************************
838 Get a directory listing.
839 ****************************************************************************/
841 static int cmd_dir(void)
843 TALLOC_CTX *ctx = talloc_tos();
844 uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
845 char *mask = NULL;
846 char *buf = NULL;
847 int rc = 1;
849 dir_total = 0;
850 if (strcmp(client_get_cur_dir(), CLI_DIRSEP_STR) != 0) {
851 mask = talloc_strdup(ctx, client_get_cur_dir());
852 if (!mask) {
853 return 1;
855 if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
856 mask = talloc_asprintf_append(mask, CLI_DIRSEP_STR);
858 } else {
859 mask = talloc_strdup(ctx, CLI_DIRSEP_STR);
862 if (!mask) {
863 return 1;
866 if (next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
867 string_replace(buf,'/','\\');
868 if (*buf == CLI_DIRSEP_CHAR) {
869 mask = talloc_strdup(ctx, buf + 1);
870 } else {
871 mask = talloc_asprintf_append(mask, buf);
873 } else {
874 mask = talloc_asprintf_append(mask, "*");
876 if (!mask) {
877 return 1;
880 if (showacls) {
881 /* cwd is only used if showacls is on */
882 client_set_cwd(client_get_cur_dir());
885 do_list(mask, attribute, display_finfo, recurse, true);
887 rc = do_dskattr();
889 DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
891 return rc;
894 /****************************************************************************
895 Get a directory listing.
896 ****************************************************************************/
898 static int cmd_du(void)
900 TALLOC_CTX *ctx = talloc_tos();
901 uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
902 char *mask = NULL;
903 char *buf = NULL;
904 int rc = 1;
906 dir_total = 0;
907 mask = talloc_strdup(ctx, client_get_cur_dir());
908 if (!mask) {
909 return 1;
911 if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
912 mask = talloc_asprintf_append(mask, CLI_DIRSEP_STR);
913 if (!mask) {
914 return 1;
918 if (next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
919 string_replace(buf,'/','\\');
920 if (*buf == CLI_DIRSEP_CHAR) {
921 mask = talloc_strdup(ctx, buf);
922 } else {
923 mask = talloc_asprintf_append(mask, buf);
925 } else {
926 mask = talloc_strdup(ctx, "*");
929 do_list(mask, attribute, do_du, recurse, true);
931 rc = do_dskattr();
933 d_printf("Total number of bytes: %.0f\n", dir_total);
935 return rc;
938 static int cmd_echo(void)
940 TALLOC_CTX *ctx = talloc_tos();
941 char *num;
942 char *data;
944 if (!next_token_nr_talloc(ctx, NULL, &num, NULL)
945 || !next_token_nr_talloc(ctx, NULL, &data, NULL)) {
946 d_printf("echo <num> <data>\n");
947 return 1;
950 if (!cli_echo(cli, atoi(num), (uint8 *)data, strlen(data))) {
951 d_printf("echo failed: %s\n",
952 nt_errstr(cli_get_nt_error(cli)));
953 return 1;
956 return 0;
959 /****************************************************************************
960 Get a file from rname to lname
961 ****************************************************************************/
963 static int do_get(const char *rname, const char *lname_in, bool reget)
965 TALLOC_CTX *ctx = talloc_tos();
966 int handle = 0, fnum;
967 bool newhandle = false;
968 char *data = NULL;
969 struct timeval tp_start;
970 int read_size = io_bufsize;
971 uint16 attr;
972 SMB_OFF_T size;
973 off_t start = 0;
974 off_t nread = 0;
975 int rc = 0;
976 struct cli_state *targetcli = NULL;
977 char *targetname = NULL;
978 char *lname = NULL;
980 lname = talloc_strdup(ctx, lname_in);
981 if (!lname) {
982 return 1;
985 if (lowercase) {
986 strlower_m(lname);
989 if (!cli_resolve_path(ctx, "", cli, rname, &targetcli, &targetname ) ) {
990 d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
991 return 1;
994 GetTimeOfDay(&tp_start);
996 fnum = cli_open(targetcli, targetname, O_RDONLY, DENY_NONE);
998 if (fnum == -1) {
999 d_printf("%s opening remote file %s\n",cli_errstr(cli),rname);
1000 return 1;
1003 if(!strcmp(lname,"-")) {
1004 handle = fileno(stdout);
1005 } else {
1006 if (reget) {
1007 handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
1008 if (handle >= 0) {
1009 start = sys_lseek(handle, 0, SEEK_END);
1010 if (start == -1) {
1011 d_printf("Error seeking local file\n");
1012 return 1;
1015 } else {
1016 handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1018 newhandle = true;
1020 if (handle < 0) {
1021 d_printf("Error opening local file %s\n",lname);
1022 return 1;
1026 if (!cli_qfileinfo(targetcli, fnum,
1027 &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
1028 !cli_getattrE(targetcli, fnum,
1029 &attr, &size, NULL, NULL, NULL)) {
1030 d_printf("getattrib: %s\n",cli_errstr(targetcli));
1031 return 1;
1034 DEBUG(1,("getting file %s of size %.0f as %s ",
1035 rname, (double)size, lname));
1037 if(!(data = (char *)SMB_MALLOC(read_size))) {
1038 d_printf("malloc fail for size %d\n", read_size);
1039 cli_close(targetcli, fnum);
1040 return 1;
1043 while (1) {
1044 int n = cli_read(targetcli, fnum, data, nread + start, read_size);
1046 if (n <= 0)
1047 break;
1049 if (writefile(handle,data, n) != n) {
1050 d_printf("Error writing local file\n");
1051 rc = 1;
1052 break;
1055 nread += n;
1058 if (nread + start < size) {
1059 DEBUG (0, ("Short read when getting file %s. Only got %ld bytes.\n",
1060 rname, (long)nread));
1062 rc = 1;
1065 SAFE_FREE(data);
1067 if (!cli_close(targetcli, fnum)) {
1068 d_printf("Error %s closing remote file\n",cli_errstr(cli));
1069 rc = 1;
1072 if (newhandle) {
1073 close(handle);
1076 if (archive_level >= 2 && (attr & aARCH)) {
1077 cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
1081 struct timeval tp_end;
1082 int this_time;
1084 GetTimeOfDay(&tp_end);
1085 this_time =
1086 (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1087 (tp_end.tv_usec - tp_start.tv_usec)/1000;
1088 get_total_time_ms += this_time;
1089 get_total_size += nread;
1091 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1092 nread / (1.024*this_time + 1.0e-4),
1093 get_total_size / (1.024*get_total_time_ms)));
1096 TALLOC_FREE(targetname);
1097 return rc;
1100 /****************************************************************************
1101 Get a file.
1102 ****************************************************************************/
1104 static int cmd_get(void)
1106 TALLOC_CTX *ctx = talloc_tos();
1107 char *lname = NULL;
1108 char *rname = NULL;
1109 char *fname = NULL;
1111 rname = talloc_asprintf(ctx,
1112 "%s%s",
1113 client_get_cur_dir(),
1114 CLI_DIRSEP_STR);
1115 if (!rname) {
1116 return 1;
1119 if (!next_token_nr_talloc(ctx, NULL,&fname,NULL)) {
1120 d_printf("get <filename> [localname]\n");
1121 return 1;
1123 rname = talloc_asprintf_append(rname, fname);
1124 if (!rname) {
1125 return 1;
1127 rname = clean_name(ctx, rname);
1128 if (!rname) {
1129 return 1;
1132 next_token_nr_talloc(ctx, NULL,&lname,NULL);
1133 if (!lname) {
1134 lname = fname;
1137 return do_get(rname, lname, false);
1140 /****************************************************************************
1141 Do an mget operation on one file.
1142 ****************************************************************************/
1144 static void do_mget(file_info *finfo, const char *dir)
1146 TALLOC_CTX *ctx = talloc_tos();
1147 char *rname = NULL;
1148 char *quest = NULL;
1149 char *saved_curdir = NULL;
1150 char *mget_mask = NULL;
1151 char *new_cd = NULL;
1153 if (!finfo->name) {
1154 return;
1157 if (strequal(finfo->name,".") || strequal(finfo->name,".."))
1158 return;
1160 if (abort_mget) {
1161 d_printf("mget aborted\n");
1162 return;
1165 if (finfo->mode & aDIR) {
1166 if (asprintf(&quest,
1167 "Get directory %s? ",finfo->name) < 0) {
1168 return;
1170 } else {
1171 if (asprintf(&quest,
1172 "Get file %s? ",finfo->name) < 0) {
1173 return;
1177 if (prompt && !yesno(quest)) {
1178 SAFE_FREE(quest);
1179 return;
1181 SAFE_FREE(quest);
1183 if (!(finfo->mode & aDIR)) {
1184 rname = talloc_asprintf(ctx,
1185 "%s%s",
1186 client_get_cur_dir(),
1187 finfo->name);
1188 if (!rname) {
1189 return;
1191 do_get(rname, finfo->name, false);
1192 TALLOC_FREE(rname);
1193 return;
1196 /* handle directories */
1197 saved_curdir = talloc_strdup(ctx, client_get_cur_dir());
1198 if (!saved_curdir) {
1199 return;
1202 new_cd = talloc_asprintf(ctx,
1203 "%s%s%s",
1204 client_get_cur_dir(),
1205 finfo->name,
1206 CLI_DIRSEP_STR);
1207 if (!new_cd) {
1208 return;
1210 client_set_cur_dir(new_cd);
1212 string_replace(finfo->name,'\\','/');
1213 if (lowercase) {
1214 strlower_m(finfo->name);
1217 if (!directory_exist(finfo->name,NULL) &&
1218 mkdir(finfo->name,0777) != 0) {
1219 d_printf("failed to create directory %s\n",finfo->name);
1220 client_set_cur_dir(saved_curdir);
1221 return;
1224 if (chdir(finfo->name) != 0) {
1225 d_printf("failed to chdir to directory %s\n",finfo->name);
1226 client_set_cur_dir(saved_curdir);
1227 return;
1230 mget_mask = talloc_asprintf(ctx,
1231 "%s*",
1232 client_get_cur_dir());
1234 if (!mget_mask) {
1235 return;
1238 do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,false, true);
1239 chdir("..");
1240 client_set_cur_dir(saved_curdir);
1241 TALLOC_FREE(mget_mask);
1242 TALLOC_FREE(saved_curdir);
1243 TALLOC_FREE(new_cd);
1246 /****************************************************************************
1247 View the file using the pager.
1248 ****************************************************************************/
1250 static int cmd_more(void)
1252 TALLOC_CTX *ctx = talloc_tos();
1253 char *rname = NULL;
1254 char *fname = NULL;
1255 char *lname = NULL;
1256 char *pager_cmd = NULL;
1257 const char *pager;
1258 int fd;
1259 int rc = 0;
1261 rname = talloc_asprintf(ctx,
1262 "%s%s",
1263 client_get_cur_dir(),
1264 CLI_DIRSEP_STR);
1265 if (!rname) {
1266 return 1;
1269 lname = talloc_asprintf(ctx, "%s/smbmore.XXXXXX",tmpdir());
1270 if (!lname) {
1271 return 1;
1273 fd = smb_mkstemp(lname);
1274 if (fd == -1) {
1275 d_printf("failed to create temporary file for more\n");
1276 return 1;
1278 close(fd);
1280 if (!next_token_nr_talloc(ctx,NULL,&fname,NULL)) {
1281 d_printf("more <filename>\n");
1282 unlink(lname);
1283 return 1;
1285 rname = talloc_asprintf_append(rname, fname);
1286 if (!rname) {
1287 return 1;
1289 rname = clean_name(ctx,rname);
1290 if (!rname) {
1291 return 1;
1294 rc = do_get(rname, lname, false);
1296 pager=getenv("PAGER");
1298 pager_cmd = talloc_asprintf(ctx,
1299 "%s %s",
1300 (pager? pager:PAGER),
1301 lname);
1302 if (!pager_cmd) {
1303 return 1;
1305 system(pager_cmd);
1306 unlink(lname);
1308 return rc;
1311 /****************************************************************************
1312 Do a mget command.
1313 ****************************************************************************/
1315 static int cmd_mget(void)
1317 TALLOC_CTX *ctx = talloc_tos();
1318 uint16 attribute = aSYSTEM | aHIDDEN;
1319 char *mget_mask = NULL;
1320 char *buf = NULL;
1322 if (recurse) {
1323 attribute |= aDIR;
1326 abort_mget = false;
1328 while (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
1329 mget_mask = talloc_strdup(ctx, client_get_cur_dir());
1330 if (!mget_mask) {
1331 return 1;
1333 if ((mget_mask[0] != '\0') &&
1334 (mget_mask[strlen(mget_mask)-1]!=CLI_DIRSEP_CHAR)) {
1335 mget_mask = talloc_asprintf_append(mget_mask,
1336 CLI_DIRSEP_STR);
1337 if (!mget_mask) {
1338 return 1;
1342 if (*buf == CLI_DIRSEP_CHAR) {
1343 mget_mask = talloc_strdup(ctx, buf);
1344 } else {
1345 mget_mask = talloc_asprintf_append(mget_mask,
1346 buf);
1348 if (!mget_mask) {
1349 return 1;
1351 do_list(mget_mask, attribute, do_mget, false, true);
1354 if (!*mget_mask) {
1355 mget_mask = talloc_strdup(ctx, client_get_cur_dir());
1356 if (!mget_mask) {
1357 return 1;
1359 if(mget_mask[strlen(mget_mask)-1]!=CLI_DIRSEP_CHAR) {
1360 mget_mask = talloc_asprintf_append(mget_mask,
1361 CLI_DIRSEP_STR);
1362 if (!mget_mask) {
1363 return 1;
1366 mget_mask = talloc_asprintf_append(mget_mask, "*");
1367 if (!mget_mask) {
1368 return 1;
1370 do_list(mget_mask, attribute, do_mget, false, true);
1373 return 0;
1376 /****************************************************************************
1377 Make a directory of name "name".
1378 ****************************************************************************/
1380 static bool do_mkdir(const char *name)
1382 TALLOC_CTX *ctx = talloc_tos();
1383 struct cli_state *targetcli;
1384 char *targetname = NULL;
1386 if (!cli_resolve_path(ctx, "", cli, name, &targetcli, &targetname)) {
1387 d_printf("mkdir %s: %s\n", name, cli_errstr(cli));
1388 return false;
1391 if (!cli_mkdir(targetcli, targetname)) {
1392 d_printf("%s making remote directory %s\n",
1393 cli_errstr(targetcli),name);
1394 return false;
1397 return true;
1400 /****************************************************************************
1401 Show 8.3 name of a file.
1402 ****************************************************************************/
1404 static bool do_altname(const char *name)
1406 fstring altname;
1408 if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
1409 d_printf("%s getting alt name for %s\n",
1410 cli_errstr(cli),name);
1411 return false;
1413 d_printf("%s\n", altname);
1415 return true;
1418 /****************************************************************************
1419 Exit client.
1420 ****************************************************************************/
1422 static int cmd_quit(void)
1424 cli_cm_shutdown();
1425 exit(0);
1426 /* NOTREACHED */
1427 return 0;
1430 /****************************************************************************
1431 Make a directory.
1432 ****************************************************************************/
1434 static int cmd_mkdir(void)
1436 TALLOC_CTX *ctx = talloc_tos();
1437 char *mask = NULL;
1438 char *buf = NULL;
1440 mask = talloc_strdup(ctx, client_get_cur_dir());
1441 if (!mask) {
1442 return 1;
1445 if (!next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
1446 if (!recurse) {
1447 d_printf("mkdir <dirname>\n");
1449 return 1;
1451 mask = talloc_asprintf_append(mask, buf);
1452 if (!mask) {
1453 return 1;
1456 if (recurse) {
1457 char *ddir = NULL;
1458 char *ddir2 = NULL;
1459 struct cli_state *targetcli;
1460 char *targetname = NULL;
1461 char *p = NULL;
1463 ddir2 = talloc_strdup(ctx, "");
1464 if (!ddir2) {
1465 return 1;
1468 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
1469 return 1;
1472 ddir = talloc_strdup(ctx, targetname);
1473 if (!ddir) {
1474 return 1;
1476 trim_char(ddir,'.','\0');
1477 p = strtok(ddir,"/\\");
1478 while (p) {
1479 ddir2 = talloc_asprintf_append(ddir2, p);
1480 if (!ddir2) {
1481 return 1;
1483 if (!cli_chkpath(targetcli, ddir2)) {
1484 do_mkdir(ddir2);
1486 ddir2 = talloc_asprintf_append(ddir2, CLI_DIRSEP_STR);
1487 if (!ddir2) {
1488 return 1;
1490 p = strtok(NULL,"/\\");
1492 } else {
1493 do_mkdir(mask);
1496 return 0;
1499 /****************************************************************************
1500 Show alt name.
1501 ****************************************************************************/
1503 static int cmd_altname(void)
1505 TALLOC_CTX *ctx = talloc_tos();
1506 char *name;
1507 char *buf;
1509 name = talloc_strdup(ctx, client_get_cur_dir());
1510 if (!name) {
1511 return 1;
1514 if (!next_token_nr_talloc(ctx, NULL, &buf, NULL)) {
1515 d_printf("altname <file>\n");
1516 return 1;
1518 name = talloc_asprintf_append(name, buf);
1519 if (!name) {
1520 return 1;
1522 do_altname(name);
1523 return 0;
1526 /****************************************************************************
1527 Put a single file.
1528 ****************************************************************************/
1530 static int do_put(const char *rname, const char *lname, bool reput)
1532 TALLOC_CTX *ctx = talloc_tos();
1533 int fnum;
1534 XFILE *f;
1535 SMB_OFF_T start = 0;
1536 off_t nread = 0;
1537 char *buf = NULL;
1538 int maxwrite = io_bufsize;
1539 int rc = 0;
1540 struct timeval tp_start;
1541 struct cli_state *targetcli;
1542 char *targetname = NULL;
1544 if (!cli_resolve_path(ctx, "", cli, rname, &targetcli, &targetname)) {
1545 d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
1546 return 1;
1549 GetTimeOfDay(&tp_start);
1551 if (reput) {
1552 fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT, DENY_NONE);
1553 if (fnum >= 0) {
1554 if (!cli_qfileinfo(targetcli, fnum, NULL, &start, NULL, NULL, NULL, NULL, NULL) &&
1555 !cli_getattrE(targetcli, fnum, NULL, &start, NULL, NULL, NULL)) {
1556 d_printf("getattrib: %s\n",cli_errstr(cli));
1557 return 1;
1560 } else {
1561 fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
1564 if (fnum == -1) {
1565 d_printf("%s opening remote file %s\n",cli_errstr(targetcli),rname);
1566 return 1;
1569 /* allow files to be piped into smbclient
1570 jdblair 24.jun.98
1572 Note that in this case this function will exit(0) rather
1573 than returning. */
1574 if (!strcmp(lname, "-")) {
1575 f = x_stdin;
1576 /* size of file is not known */
1577 } else {
1578 f = x_fopen(lname,O_RDONLY, 0);
1579 if (f && reput) {
1580 if (x_tseek(f, start, SEEK_SET) == -1) {
1581 d_printf("Error seeking local file\n");
1582 return 1;
1587 if (!f) {
1588 d_printf("Error opening local file %s\n",lname);
1589 return 1;
1592 DEBUG(1,("putting file %s as %s ",lname,
1593 rname));
1595 buf = (char *)SMB_MALLOC(maxwrite);
1596 if (!buf) {
1597 d_printf("ERROR: Not enough memory!\n");
1598 return 1;
1600 while (!x_feof(f)) {
1601 int n = maxwrite;
1602 int ret;
1604 if ((n = readfile(buf,n,f)) < 1) {
1605 if((n == 0) && x_feof(f))
1606 break; /* Empty local file. */
1608 d_printf("Error reading local file: %s\n", strerror(errno));
1609 rc = 1;
1610 break;
1613 ret = cli_write(targetcli, fnum, 0, buf, nread + start, n);
1615 if (n != ret) {
1616 d_printf("Error writing file: %s\n", cli_errstr(cli));
1617 rc = 1;
1618 break;
1621 nread += n;
1624 if (!cli_close(targetcli, fnum)) {
1625 d_printf("%s closing remote file %s\n",cli_errstr(cli),rname);
1626 x_fclose(f);
1627 SAFE_FREE(buf);
1628 return 1;
1631 if (f != x_stdin) {
1632 x_fclose(f);
1635 SAFE_FREE(buf);
1638 struct timeval tp_end;
1639 int this_time;
1641 GetTimeOfDay(&tp_end);
1642 this_time =
1643 (tp_end.tv_sec - tp_start.tv_sec)*1000 +
1644 (tp_end.tv_usec - tp_start.tv_usec)/1000;
1645 put_total_time_ms += this_time;
1646 put_total_size += nread;
1648 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
1649 nread / (1.024*this_time + 1.0e-4),
1650 put_total_size / (1.024*put_total_time_ms)));
1653 if (f == x_stdin) {
1654 cli_cm_shutdown();
1655 exit(0);
1658 return rc;
1661 /****************************************************************************
1662 Put a file.
1663 ****************************************************************************/
1665 static int cmd_put(void)
1667 TALLOC_CTX *ctx = talloc_tos();
1668 char *lname;
1669 char *rname;
1670 char *buf;
1672 rname = talloc_asprintf(ctx,
1673 "%s%s",
1674 client_get_cur_dir(),
1675 CLI_DIRSEP_STR);
1676 if (!rname) {
1677 return 1;
1680 if (!next_token_nr_talloc(ctx,NULL,&lname,NULL)) {
1681 d_printf("put <filename>\n");
1682 return 1;
1685 if (next_token_nr_talloc(ctx, NULL,&buf,NULL)) {
1686 rname = talloc_asprintf_append(rname, buf);
1687 } else {
1688 rname = talloc_asprintf_append(rname, lname);
1690 if (!rname) {
1691 return 1;
1694 rname = clean_name(ctx, rname);
1695 if (!rname) {
1696 return 1;
1700 SMB_STRUCT_STAT st;
1701 /* allow '-' to represent stdin
1702 jdblair, 24.jun.98 */
1703 if (!file_exist(lname,&st) &&
1704 (strcmp(lname,"-"))) {
1705 d_printf("%s does not exist\n",lname);
1706 return 1;
1710 return do_put(rname, lname, false);
1713 /*************************************
1714 File list structure.
1715 *************************************/
1717 static struct file_list {
1718 struct file_list *prev, *next;
1719 char *file_path;
1720 bool isdir;
1721 } *file_list;
1723 /****************************************************************************
1724 Free a file_list structure.
1725 ****************************************************************************/
1727 static void free_file_list (struct file_list *list_head)
1729 struct file_list *list, *next;
1731 for (list = list_head; list; list = next) {
1732 next = list->next;
1733 DLIST_REMOVE(list_head, list);
1734 SAFE_FREE(list->file_path);
1735 SAFE_FREE(list);
1739 /****************************************************************************
1740 Seek in a directory/file list until you get something that doesn't start with
1741 the specified name.
1742 ****************************************************************************/
1744 static bool seek_list(struct file_list *list, char *name)
1746 while (list) {
1747 trim_string(list->file_path,"./","\n");
1748 if (strncmp(list->file_path, name, strlen(name)) != 0) {
1749 return true;
1751 list = list->next;
1754 return false;
1757 /****************************************************************************
1758 Set the file selection mask.
1759 ****************************************************************************/
1761 static int cmd_select(void)
1763 TALLOC_CTX *ctx = talloc_tos();
1764 char *new_fs = NULL;
1765 next_token_nr_talloc(ctx, NULL,&new_fs,NULL)
1767 if (new_fs) {
1768 client_set_fileselection(new_fs);
1769 } else {
1770 client_set_fileselection("");
1772 return 0;
1775 /****************************************************************************
1776 Recursive file matching function act as find
1777 match must be always set to true when calling this function
1778 ****************************************************************************/
1780 static int file_find(struct file_list **list, const char *directory,
1781 const char *expression, bool match)
1783 SMB_STRUCT_DIR *dir;
1784 struct file_list *entry;
1785 struct stat statbuf;
1786 int ret;
1787 char *path;
1788 bool isdir;
1789 const char *dname;
1791 dir = sys_opendir(directory);
1792 if (!dir)
1793 return -1;
1795 while ((dname = readdirname(dir))) {
1796 if (!strcmp("..", dname))
1797 continue;
1798 if (!strcmp(".", dname))
1799 continue;
1801 if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
1802 continue;
1805 isdir = false;
1806 if (!match || !gen_fnmatch(expression, dname)) {
1807 if (recurse) {
1808 ret = stat(path, &statbuf);
1809 if (ret == 0) {
1810 if (S_ISDIR(statbuf.st_mode)) {
1811 isdir = true;
1812 ret = file_find(list, path, expression, false);
1814 } else {
1815 d_printf("file_find: cannot stat file %s\n", path);
1818 if (ret == -1) {
1819 SAFE_FREE(path);
1820 sys_closedir(dir);
1821 return -1;
1824 entry = SMB_MALLOC_P(struct file_list);
1825 if (!entry) {
1826 d_printf("Out of memory in file_find\n");
1827 sys_closedir(dir);
1828 return -1;
1830 entry->file_path = path;
1831 entry->isdir = isdir;
1832 DLIST_ADD(*list, entry);
1833 } else {
1834 SAFE_FREE(path);
1838 sys_closedir(dir);
1839 return 0;
1842 /****************************************************************************
1843 mput some files.
1844 ****************************************************************************/
1846 static int cmd_mput(void)
1848 TALLOC_CTX *ctx = talloc_tos();
1849 char *p = NULL;
1851 while (next_token_nr_talloc(ctx, NULL,&p,NULL)) {
1852 int ret;
1853 struct file_list *temp_list;
1854 char *quest, *lname, *rname;
1856 file_list = NULL;
1858 ret = file_find(&file_list, ".", p, true);
1859 if (ret) {
1860 free_file_list(file_list);
1861 continue;
1864 quest = NULL;
1865 lname = NULL;
1866 rname = NULL;
1868 for (temp_list = file_list; temp_list;
1869 temp_list = temp_list->next) {
1871 SAFE_FREE(lname);
1872 if (asprintf(&lname, "%s/", temp_list->file_path) <= 0) {
1873 continue;
1875 trim_string(lname, "./", "/");
1877 /* check if it's a directory */
1878 if (temp_list->isdir) {
1879 /* if (!recurse) continue; */
1881 SAFE_FREE(quest);
1882 if (asprintf(&quest, "Put directory %s? ", lname) < 0) {
1883 break;
1885 if (prompt && !yesno(quest)) { /* No */
1886 /* Skip the directory */
1887 lname[strlen(lname)-1] = '/';
1888 if (!seek_list(temp_list, lname))
1889 break;
1890 } else { /* Yes */
1891 SAFE_FREE(rname);
1892 if(asprintf(&rname, "%s%s", cur_dir, lname) < 0) {
1893 break;
1895 string_replace(rname,'/','\\');
1896 if (!cli_chkpath(cli, rname) &&
1897 !do_mkdir(rname)) {
1898 DEBUG (0, ("Unable to make dir, skipping..."));
1899 /* Skip the directory */
1900 lname[strlen(lname)-1] = '/';
1901 if (!seek_list(temp_list, lname)) {
1902 break;
1906 continue;
1907 } else {
1908 SAFE_FREE(quest);
1909 if (asprintf(&quest,"Put file %s? ", lname) < 0) {
1910 break;
1912 if (prompt && !yesno(quest)) {
1913 /* No */
1914 continue;
1917 /* Yes */
1918 SAFE_FREE(rname);
1919 if (asprintf(&rname, "%s%s", cur_dir, lname) < 0) {
1920 break;
1924 string_replace(rname,'/','\\');
1926 do_put(rname, lname, false);
1928 free_file_list(file_list);
1929 SAFE_FREE(quest);
1930 SAFE_FREE(lname);
1931 SAFE_FREE(rname);
1934 return 0;
1937 /****************************************************************************
1938 Cancel a print job.
1939 ****************************************************************************/
1941 static int do_cancel(int job)
1943 if (cli_printjob_del(cli, job)) {
1944 d_printf("Job %d cancelled\n",job);
1945 return 0;
1946 } else {
1947 d_printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
1948 return 1;
1952 /****************************************************************************
1953 Cancel a print job.
1954 ****************************************************************************/
1956 static int cmd_cancel(void)
1958 TALLOC_CTX *ctx = talloc_tos();
1959 char *buf = NULL;
1960 int job;
1962 if (!next_token_nr_talloc(ctx, NULL, &buf,NULL)) {
1963 d_printf("cancel <jobid> ...\n");
1964 return 1;
1966 do {
1967 job = atoi(buf);
1968 do_cancel(job);
1969 } while (next_token_nr_talloc(ctx,NULL,&buf,NULL));
1971 return 0;
1974 /****************************************************************************
1975 Print a file.
1976 ****************************************************************************/
1978 static int cmd_print(void)
1980 TALLOC_CTX *ctx = talloc_tos();
1981 char *lname = NULL;
1982 char *rname = NULL;
1983 char *p = NULL;
1985 if (!next_token_nr_talloc(ctx, NULL, &lname,NULL)) {
1986 d_printf("print <filename>\n");
1987 return 1;
1990 rname = talloc_strdup(ctx, lname);
1991 if (!rname) {
1992 return 1;
1994 p = strrchr_m(rname,'/');
1995 if (p) {
1996 rname = talloc_asprintf(ctx,
1997 "%s-%d",
1998 p+1,
1999 (int)sys_getpid());
2001 if (strequal(lname,"-")) {
2002 rname = talloc_asprintf(ctx,
2003 "stdin-%d",
2004 (int)sys_getpid());
2006 if (!rname) {
2007 return 1;
2010 return do_put(rname, lname, false);
2013 /****************************************************************************
2014 Show a print queue entry.
2015 ****************************************************************************/
2017 static void queue_fn(struct print_job_info *p)
2019 d_printf("%-6d %-9d %s\n", (int)p->id, (int)p->size, p->name);
2022 /****************************************************************************
2023 Show a print queue.
2024 ****************************************************************************/
2026 static int cmd_queue(void)
2028 cli_print_queue(cli, queue_fn);
2029 return 0;
2032 /****************************************************************************
2033 Delete some files.
2034 ****************************************************************************/
2036 static void do_del(file_info *finfo, const char *dir)
2038 TALLOC_CTX *ctx = talloc_tos();
2039 char *mask = NULL;
2041 mask = talloc_asprintf(ctx,
2042 "%s%c%s",
2043 dir,
2044 CLI_DIRSEP_CHAR,
2045 finfo->name);
2046 if (!mask) {
2047 return;
2050 if (finfo->mode & aDIR) {
2051 TALLOC_FREE(mask);
2052 return;
2055 if (!cli_unlink(finfo->cli, mask)) {
2056 d_printf("%s deleting remote file %s\n",
2057 cli_errstr(finfo->cli),mask);
2059 TALLOC_FREE(mask);
2062 /****************************************************************************
2063 Delete some files.
2064 ****************************************************************************/
2066 static int cmd_del(void)
2068 TALLOC_CTX *ctx = talloc_tos();
2069 char *mask = NULL;
2070 char *buf = NULL;
2071 uint16 attribute = aSYSTEM | aHIDDEN;
2073 if (recurse) {
2074 attribute |= aDIR;
2077 mask = talloc_strdup(ctx, client_get_cur_dir());
2078 if (!mask) {
2079 return 1;
2081 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2082 d_printf("del <filename>\n");
2083 return 1;
2085 mask = talloc_asprintf_append(mask, buf);
2086 if (!mask) {
2087 return 1;
2090 do_list(mask,attribute,do_del,false,false);
2091 return 0;
2094 /****************************************************************************
2095 Wildcard delete some files.
2096 ****************************************************************************/
2098 static int cmd_wdel(void)
2100 TALLOC_CTX *ctx = talloc_tos();
2101 char *mask = NULL;
2102 char *buf = NULL;
2103 uint16 attribute;
2104 struct cli_state *targetcli;
2105 char *targetname = NULL;
2107 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2108 d_printf("wdel 0x<attrib> <wcard>\n");
2109 return 1;
2112 attribute = (uint16)strtol(buf, (char **)NULL, 16);
2114 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2115 d_printf("wdel 0x<attrib> <wcard>\n");
2116 return 1;
2119 mask = talloc_asprintf(ctx, "%s%s",
2120 client_get_cur_dir(),
2121 buf);
2122 if (!mask) {
2123 return 1;
2126 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2127 d_printf("cmd_wdel %s: %s\n", mask, cli_errstr(cli));
2128 return 1;
2131 if (!cli_unlink_full(targetcli, targetname, attribute)) {
2132 d_printf("%s deleting remote files %s\n",cli_errstr(targetcli),targetname);
2134 return 0;
2137 /****************************************************************************
2138 ****************************************************************************/
2140 static int cmd_open(void)
2142 TALLOC_CTX *ctx = talloc_tos();
2143 char *mask = NULL;
2144 char *buf = NULL;
2145 char *targetname = NULL;
2146 struct cli_state *targetcli;
2147 int fnum;
2149 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2150 d_printf("open <filename>\n");
2151 return 1;
2153 mask = talloc_asprintf(ctx,
2154 "%s%s",
2155 client_get_cur_dir(),
2156 buf);
2157 if (!mask) {
2158 return 1;
2161 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2162 d_printf("open %s: %s\n", mask, cli_errstr(cli));
2163 return 1;
2166 fnum = cli_nt_create(targetcli, targetname, FILE_READ_DATA|FILE_WRITE_DATA);
2167 if (fnum == -1) {
2168 fnum = cli_nt_create(targetcli, targetname, FILE_READ_DATA);
2169 if (fnum != -1) {
2170 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2171 } else {
2172 d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
2174 } else {
2175 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2177 return 0;
2180 /****************************************************************************
2181 ****************************************************************************/
2183 static int cmd_posix_open(void)
2185 TALLOC_CTX *ctx = talloc_tos();
2186 char *mask = NULL;
2187 char *buf = NULL;
2188 char *targetname = NULL;
2189 struct cli_state *targetcli;
2190 mode_t mode;
2191 int fnum;
2193 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2194 d_printf("posix_open <filename> 0<mode>\n");
2195 return 1;
2197 mask = talloc_asprintf(ctx,
2198 "%s%s",
2199 client_get_cur_dir(),
2200 buf);
2201 if (!mask) {
2202 return 1;
2205 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2206 d_printf("posix_open <filename> 0<mode>\n");
2207 return 1;
2209 mode = (mode_t)strtol(buf, (char **)NULL, 8);
2211 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2212 d_printf("posix_open %s: %s\n", mask, cli_errstr(cli));
2213 return 1;
2216 fnum = cli_posix_open(targetcli, targetname, O_CREAT|O_RDWR, mode);
2217 if (fnum == -1) {
2218 fnum = cli_posix_open(targetcli, targetname, O_CREAT|O_RDONLY, mode);
2219 if (fnum != -1) {
2220 d_printf("posix_open file %s: for read/write fnum %d\n", targetname, fnum);
2221 } else {
2222 d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
2224 } else {
2225 d_printf("posix_open file %s: for read/write fnum %d\n", targetname, fnum);
2228 return 0;
2231 static int cmd_posix_mkdir(void)
2233 TALLOC_CTX *ctx = talloc_tos();
2234 char *mask = NULL;
2235 char *buf = NULL;
2236 char *targetname = NULL;
2237 struct cli_state *targetcli;
2238 mode_t mode;
2239 int fnum;
2241 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2242 d_printf("posix_mkdir <filename> 0<mode>\n");
2243 return 1;
2245 mask = talloc_asprintf(ctx,
2246 "%s%s",
2247 client_get_cur_dir(),
2248 buf);
2249 if (!mask) {
2250 return 1;
2253 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2254 d_printf("posix_mkdir <filename> 0<mode>\n");
2255 return 1;
2257 mode = (mode_t)strtol(buf, (char **)NULL, 8);
2259 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2260 d_printf("posix_mkdir %s: %s\n", mask, cli_errstr(cli));
2261 return 1;
2264 fnum = cli_posix_mkdir(targetcli, targetname, mode);
2265 if (fnum == -1) {
2266 d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
2267 } else {
2268 d_printf("posix_mkdir created directory %s\n", targetname);
2270 return 0;
2273 static int cmd_posix_unlink(void)
2275 TALLOC_CTX *ctx = talloc_tos();
2276 char *mask = NULL;
2277 char *buf = NULL;
2278 char *targetname = NULL;
2279 struct cli_state *targetcli;
2281 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2282 d_printf("posix_unlink <filename>\n");
2283 return 1;
2285 mask = talloc_asprintf(ctx,
2286 "%s%s",
2287 client_get_cur_dir(),
2288 buf);
2289 if (!mask) {
2290 return 1;
2293 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2294 d_printf("posix_unlink %s: %s\n", mask, cli_errstr(cli));
2295 return 1;
2298 if (!cli_posix_unlink(targetcli, targetname)) {
2299 d_printf("Failed to unlink file %s. %s\n", targetname, cli_errstr(cli));
2300 } else {
2301 d_printf("posix_unlink deleted file %s\n", targetname);
2304 return 0;
2307 static int cmd_posix_rmdir(void)
2309 TALLOC_CTX *ctx = talloc_tos();
2310 char *mask = NULL;
2311 char *buf = NULL;
2312 char *targetname = NULL;
2313 struct cli_state *targetcli;
2315 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2316 d_printf("posix_rmdir <filename>\n");
2317 return 1;
2319 mask = talloc_asprintf(ctx,
2320 "%s%s",
2321 client_get_cur_dir(),
2322 buf);
2323 if (!mask) {
2324 return 1;
2327 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2328 d_printf("posix_rmdir %s: %s\n", mask, cli_errstr(cli));
2329 return 1;
2332 if (!cli_posix_rmdir(targetcli, targetname)) {
2333 d_printf("Failed to unlink directory %s. %s\n", targetname, cli_errstr(cli));
2334 } else {
2335 d_printf("posix_rmdir deleted directory %s\n", targetname);
2338 return 0;
2341 static int cmd_close(void)
2343 TALLOC_CTX *ctx = talloc_tos();
2344 char *buf = NULL;
2345 int fnum;
2347 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2348 d_printf("close <fnum>\n");
2349 return 1;
2352 fnum = atoi(buf);
2353 /* We really should use the targetcli here.... */
2354 if (!cli_close(cli, fnum)) {
2355 d_printf("close %d: %s\n", fnum, cli_errstr(cli));
2356 return 1;
2358 return 0;
2361 static int cmd_posix(void)
2363 TALLOC_CTX *ctx = talloc_tos();
2364 uint16 major, minor;
2365 uint32 caplow, caphigh;
2366 char *caps;
2368 if (!SERVER_HAS_UNIX_CIFS(cli)) {
2369 d_printf("Server doesn't support UNIX CIFS extensions.\n");
2370 return 1;
2373 if (!cli_unix_extensions_version(cli, &major, &minor, &caplow, &caphigh)) {
2374 d_printf("Can't get UNIX CIFS extensions version from server.\n");
2375 return 1;
2378 d_printf("Server supports CIFS extensions %u.%u\n", (unsigned int)major, (unsigned int)minor);
2380 caps = talloc_strdup(ctx, "");
2381 if (!caps) {
2382 return 1;
2384 if (caplow & CIFS_UNIX_FCNTL_LOCKS_CAP) {
2385 caps = talloc_asprintf_append(caps, "locks ");
2386 if (!caps) {
2387 return 1;
2390 if (caplow & CIFS_UNIX_POSIX_ACLS_CAP) {
2391 caps = talloc_asprintf_append(caps, "acls ");
2392 if (!caps) {
2393 return 1;
2396 if (caplow & CIFS_UNIX_XATTTR_CAP) {
2397 caps = talloc_asprintf_append(caps, "eas ");
2398 if (!caps) {
2399 return 1;
2402 if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2403 caps = talloc_asprintf_append(caps, "pathnames ");
2404 if (!caps) {
2405 return 1;
2408 if (caplow & CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP) {
2409 caps = talloc_asprintf_append(caps, "posix_path_operations ");
2410 if (!caps) {
2411 return 1;
2414 if (caplow & CIFS_UNIX_LARGE_READ_CAP) {
2415 caps = talloc_asprintf_append(caps, "large_read ");
2416 if (!caps) {
2417 return 1;
2420 if (caplow & CIFS_UNIX_LARGE_WRITE_CAP) {
2421 caps = talloc_asprintf_append(caps, "large_write ");
2422 if (!caps) {
2423 return 1;
2427 if (*caps && caps[strlen(caps)-1] == ' ') {
2428 caps[strlen(caps)-1] = '\0';
2430 if (!cli_set_unix_extensions_capabilities(cli, major, minor, caplow, caphigh)) {
2431 d_printf("Can't set UNIX CIFS extensions capabilities. %s.\n", cli_errstr(cli));
2432 return 1;
2435 d_printf("Selecting server supported CIFS capabilities %s\n", caps);
2437 if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
2438 CLI_DIRSEP_CHAR = '/';
2439 *CLI_DIRSEP_STR = '/';
2440 client_set_cur_dir(CLI_DIRSEP_STR);
2443 return 0;
2446 static int cmd_lock(void)
2448 TALLOC_CTX *ctx = talloc_tos();
2449 char *buf = NULL;
2450 SMB_BIG_UINT start, len;
2451 enum brl_type lock_type;
2452 int fnum;
2454 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2455 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2456 return 1;
2458 fnum = atoi(buf);
2460 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2461 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2462 return 1;
2465 if (*buf == 'r' || *buf == 'R') {
2466 lock_type = READ_LOCK;
2467 } else if (*buf == 'w' || *buf == 'W') {
2468 lock_type = WRITE_LOCK;
2469 } else {
2470 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2471 return 1;
2474 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2475 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2476 return 1;
2479 start = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2481 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2482 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
2483 return 1;
2486 len = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2488 if (!cli_posix_lock(cli, fnum, start, len, true, lock_type)) {
2489 d_printf("lock failed %d: %s\n", fnum, cli_errstr(cli));
2492 return 0;
2495 static int cmd_unlock(void)
2497 TALLOC_CTX *ctx = talloc_tos();
2498 char *buf = NULL;
2499 SMB_BIG_UINT start, len;
2500 int fnum;
2502 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2503 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2504 return 1;
2506 fnum = atoi(buf);
2508 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2509 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2510 return 1;
2513 start = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2515 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2516 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
2517 return 1;
2520 len = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
2522 if (!cli_posix_unlock(cli, fnum, start, len)) {
2523 d_printf("unlock failed %d: %s\n", fnum, cli_errstr(cli));
2526 return 0;
2530 /****************************************************************************
2531 Remove a directory.
2532 ****************************************************************************/
2534 static int cmd_rmdir(void)
2536 TALLOC_CTX *ctx = talloc_tos();
2537 char *mask = NULL;
2538 char *buf = NULL;
2539 char *targetname = NULL;
2540 struct cli_state *targetcli;
2542 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
2543 d_printf("rmdir <dirname>\n");
2544 return 1;
2546 mask = talloc_asprintf(ctx,
2547 "%s%s",
2548 client_get_cur_dir(),
2549 buf);
2550 if (!mask) {
2551 return 1;
2554 if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
2555 d_printf("rmdir %s: %s\n", mask, cli_errstr(cli));
2556 return 1;
2559 if (!cli_rmdir(targetcli, targetname)) {
2560 d_printf("%s removing remote directory file %s\n",
2561 cli_errstr(targetcli),mask);
2564 return 0;
2567 /****************************************************************************
2568 UNIX hardlink.
2569 ****************************************************************************/
2571 static int cmd_link(void)
2573 TALLOC_CTX *ctx = talloc_tos();
2574 char *oldname = NULL;
2575 char *newname = NULL;
2576 char *buf = NULL;
2577 char *buf2 = NULL;
2578 char *targetname = NULL;
2579 struct cli_state *targetcli;
2581 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
2582 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
2583 d_printf("link <oldname> <newname>\n");
2584 return 1;
2586 oldname = talloc_asprintf(ctx,
2587 "%s%s",
2588 client_get_cur_dir(),
2589 buf);
2590 if (!oldname) {
2591 return 1;
2593 newname = talloc_asprintf(ctx,
2594 "%s%s",
2595 client_get_cur_dir(),
2596 buf2);
2597 if (!newname) {
2598 return 1;
2601 if (!cli_resolve_path(ctx, "", cli, oldname, &targetcli, &targetname)) {
2602 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
2603 return 1;
2606 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2607 d_printf("Server doesn't support UNIX CIFS calls.\n");
2608 return 1;
2611 if (!cli_unix_hardlink(targetcli, targetname, newname)) {
2612 d_printf("%s linking files (%s -> %s)\n", cli_errstr(targetcli), newname, oldname);
2613 return 1;
2615 return 0;
2618 /****************************************************************************
2619 UNIX symlink.
2620 ****************************************************************************/
2622 static int cmd_symlink(void)
2624 TALLOC_CTX *ctx = talloc_tos();
2625 char *oldname = NULL;
2626 char *newname = NULL;
2627 char *buf = NULL;
2628 char *buf2 = NULL;
2629 char *targetname = NULL;
2630 struct cli_state *targetcli;
2632 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
2633 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
2634 d_printf("symlink <oldname> <newname>\n");
2635 return 1;
2637 oldname = talloc_asprintf(ctx,
2638 "%s%s",
2639 client_get_cur_dir(),
2640 buf);
2641 if (!oldname) {
2642 return 1;
2644 newname = talloc_asprintf(ctx,
2645 "%s%s",
2646 client_get_cur_dir(),
2647 buf2);
2648 if (!newname) {
2649 return 1;
2652 if (!cli_resolve_path(ctx, "", cli, oldname, &targetcli, &targetname)) {
2653 d_printf("link %s: %s\n", oldname, cli_errstr(cli));
2654 return 1;
2657 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2658 d_printf("Server doesn't support UNIX CIFS calls.\n");
2659 return 1;
2662 if (!cli_unix_symlink(targetcli, targetname, newname)) {
2663 d_printf("%s symlinking files (%s -> %s)\n",
2664 cli_errstr(targetcli), newname, targetname);
2665 return 1;
2668 return 0;
2671 /****************************************************************************
2672 UNIX chmod.
2673 ****************************************************************************/
2675 static int cmd_chmod(void)
2677 TALLOC_CTX *ctx = talloc_tos();
2678 char *src = NULL;
2679 char *buf = NULL;
2680 char *buf2 = NULL;
2681 char *targetname = NULL;
2682 struct cli_state *targetcli;
2683 mode_t mode;
2685 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
2686 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
2687 d_printf("chmod mode file\n");
2688 return 1;
2690 src = talloc_asprintf(ctx,
2691 "%s%s",
2692 client_get_cur_dir(),
2693 buf2);
2694 if (!src) {
2695 return 1;
2698 mode = (mode_t)strtol(buf, NULL, 8);
2700 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
2701 d_printf("chmod %s: %s\n", src, cli_errstr(cli));
2702 return 1;
2705 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2706 d_printf("Server doesn't support UNIX CIFS calls.\n");
2707 return 1;
2710 if (!cli_unix_chmod(targetcli, targetname, mode)) {
2711 d_printf("%s chmod file %s 0%o\n",
2712 cli_errstr(targetcli), src, (unsigned int)mode);
2713 return 1;
2716 return 0;
2719 static const char *filetype_to_str(mode_t mode)
2721 if (S_ISREG(mode)) {
2722 return "regular file";
2723 } else if (S_ISDIR(mode)) {
2724 return "directory";
2725 } else
2726 #ifdef S_ISCHR
2727 if (S_ISCHR(mode)) {
2728 return "character device";
2729 } else
2730 #endif
2731 #ifdef S_ISBLK
2732 if (S_ISBLK(mode)) {
2733 return "block device";
2734 } else
2735 #endif
2736 #ifdef S_ISFIFO
2737 if (S_ISFIFO(mode)) {
2738 return "fifo";
2739 } else
2740 #endif
2741 #ifdef S_ISLNK
2742 if (S_ISLNK(mode)) {
2743 return "symbolic link";
2744 } else
2745 #endif
2746 #ifdef S_ISSOCK
2747 if (S_ISSOCK(mode)) {
2748 return "socket";
2749 } else
2750 #endif
2751 return "";
2754 static char rwx_to_str(mode_t m, mode_t bt, char ret)
2756 if (m & bt) {
2757 return ret;
2758 } else {
2759 return '-';
2763 static char *unix_mode_to_str(char *s, mode_t m)
2765 char *p = s;
2766 const char *str = filetype_to_str(m);
2768 switch(str[0]) {
2769 case 'd':
2770 *p++ = 'd';
2771 break;
2772 case 'c':
2773 *p++ = 'c';
2774 break;
2775 case 'b':
2776 *p++ = 'b';
2777 break;
2778 case 'f':
2779 *p++ = 'p';
2780 break;
2781 case 's':
2782 *p++ = str[1] == 'y' ? 'l' : 's';
2783 break;
2784 case 'r':
2785 default:
2786 *p++ = '-';
2787 break;
2789 *p++ = rwx_to_str(m, S_IRUSR, 'r');
2790 *p++ = rwx_to_str(m, S_IWUSR, 'w');
2791 *p++ = rwx_to_str(m, S_IXUSR, 'x');
2792 *p++ = rwx_to_str(m, S_IRGRP, 'r');
2793 *p++ = rwx_to_str(m, S_IWGRP, 'w');
2794 *p++ = rwx_to_str(m, S_IXGRP, 'x');
2795 *p++ = rwx_to_str(m, S_IROTH, 'r');
2796 *p++ = rwx_to_str(m, S_IWOTH, 'w');
2797 *p++ = rwx_to_str(m, S_IXOTH, 'x');
2798 *p++ = '\0';
2799 return s;
2802 /****************************************************************************
2803 Utility function for UNIX getfacl.
2804 ****************************************************************************/
2806 static char *perms_to_string(fstring permstr, unsigned char perms)
2808 fstrcpy(permstr, "---");
2809 if (perms & SMB_POSIX_ACL_READ) {
2810 permstr[0] = 'r';
2812 if (perms & SMB_POSIX_ACL_WRITE) {
2813 permstr[1] = 'w';
2815 if (perms & SMB_POSIX_ACL_EXECUTE) {
2816 permstr[2] = 'x';
2818 return permstr;
2821 /****************************************************************************
2822 UNIX getfacl.
2823 ****************************************************************************/
2825 static int cmd_getfacl(void)
2827 TALLOC_CTX *ctx = talloc_tos();
2828 char *src = NULL;
2829 char *name = NULL;
2830 char *targetname = NULL;
2831 struct cli_state *targetcli;
2832 uint16 major, minor;
2833 uint32 caplow, caphigh;
2834 char *retbuf = NULL;
2835 size_t rb_size = 0;
2836 SMB_STRUCT_STAT sbuf;
2837 uint16 num_file_acls = 0;
2838 uint16 num_dir_acls = 0;
2839 uint16 i;
2841 if (!next_token_nr_talloc(ctx,NULL,&name,NULL)) {
2842 d_printf("getfacl filename\n");
2843 return 1;
2845 src = talloc_asprintf(ctx,
2846 "%s%s",
2847 client_get_cur_dir(),
2848 name);
2849 if (!src) {
2850 return 1;
2853 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
2854 d_printf("stat %s: %s\n", src, cli_errstr(cli));
2855 return 1;
2858 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
2859 d_printf("Server doesn't support UNIX CIFS calls.\n");
2860 return 1;
2863 if (!cli_unix_extensions_version(targetcli, &major, &minor,
2864 &caplow, &caphigh)) {
2865 d_printf("Can't get UNIX CIFS version from server.\n");
2866 return 1;
2869 if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
2870 d_printf("This server supports UNIX extensions "
2871 "but doesn't support POSIX ACLs.\n");
2872 return 1;
2875 if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
2876 d_printf("%s getfacl doing a stat on file %s\n",
2877 cli_errstr(targetcli), src);
2878 return 1;
2881 if (!cli_unix_getfacl(targetcli, targetname, &rb_size, &retbuf)) {
2882 d_printf("%s getfacl file %s\n",
2883 cli_errstr(targetcli), src);
2884 return 1;
2887 /* ToDo : Print out the ACL values. */
2888 if (SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION || rb_size < 6) {
2889 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
2890 src, (unsigned int)CVAL(retbuf,0) );
2891 SAFE_FREE(retbuf);
2892 return 1;
2895 num_file_acls = SVAL(retbuf,2);
2896 num_dir_acls = SVAL(retbuf,4);
2897 if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
2898 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
2899 src,
2900 (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
2901 (unsigned int)rb_size);
2903 SAFE_FREE(retbuf);
2904 return 1;
2907 d_printf("# file: %s\n", src);
2908 d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_uid, (unsigned int)sbuf.st_gid);
2910 if (num_file_acls == 0 && num_dir_acls == 0) {
2911 d_printf("No acls found.\n");
2914 for (i = 0; i < num_file_acls; i++) {
2915 uint32 uorg;
2916 fstring permstring;
2917 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
2918 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2920 switch(tagtype) {
2921 case SMB_POSIX_ACL_USER_OBJ:
2922 d_printf("user::");
2923 break;
2924 case SMB_POSIX_ACL_USER:
2925 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2926 d_printf("user:%u:", uorg);
2927 break;
2928 case SMB_POSIX_ACL_GROUP_OBJ:
2929 d_printf("group::");
2930 break;
2931 case SMB_POSIX_ACL_GROUP:
2932 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2933 d_printf("group:%u", uorg);
2934 break;
2935 case SMB_POSIX_ACL_MASK:
2936 d_printf("mask::");
2937 break;
2938 case SMB_POSIX_ACL_OTHER:
2939 d_printf("other::");
2940 break;
2941 default:
2942 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2943 src, (unsigned int)tagtype );
2944 SAFE_FREE(retbuf);
2945 return 1;
2948 d_printf("%s\n", perms_to_string(permstring, perms));
2951 for (i = 0; i < num_dir_acls; i++) {
2952 uint32 uorg;
2953 fstring permstring;
2954 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
2955 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
2957 switch(tagtype) {
2958 case SMB_POSIX_ACL_USER_OBJ:
2959 d_printf("default:user::");
2960 break;
2961 case SMB_POSIX_ACL_USER:
2962 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2963 d_printf("default:user:%u:", uorg);
2964 break;
2965 case SMB_POSIX_ACL_GROUP_OBJ:
2966 d_printf("default:group::");
2967 break;
2968 case SMB_POSIX_ACL_GROUP:
2969 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
2970 d_printf("default:group:%u", uorg);
2971 break;
2972 case SMB_POSIX_ACL_MASK:
2973 d_printf("default:mask::");
2974 break;
2975 case SMB_POSIX_ACL_OTHER:
2976 d_printf("default:other::");
2977 break;
2978 default:
2979 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
2980 src, (unsigned int)tagtype );
2981 SAFE_FREE(retbuf);
2982 return 1;
2985 d_printf("%s\n", perms_to_string(permstring, perms));
2988 SAFE_FREE(retbuf);
2989 return 0;
2992 /****************************************************************************
2993 UNIX stat.
2994 ****************************************************************************/
2996 static int cmd_stat(void)
2998 TALLOC_CTX *ctx = talloc_tos();
2999 char *src = NULL;
3000 char *name = NULL;
3001 char *targetname = NULL;
3002 struct cli_state *targetcli;
3003 fstring mode_str;
3004 SMB_STRUCT_STAT sbuf;
3005 struct tm *lt;
3007 if (!next_token_nr_talloc(ctx,NULL,&name,NULL)) {
3008 d_printf("stat file\n");
3009 return 1;
3011 src = talloc_asprintf(ctx,
3012 "%s%s",
3013 client_get_cur_dir(),
3014 name);
3015 if (!src) {
3016 return 1;
3019 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
3020 d_printf("stat %s: %s\n", src, cli_errstr(cli));
3021 return 1;
3024 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3025 d_printf("Server doesn't support UNIX CIFS calls.\n");
3026 return 1;
3029 if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
3030 d_printf("%s stat file %s\n",
3031 cli_errstr(targetcli), src);
3032 return 1;
3035 /* Print out the stat values. */
3036 d_printf("File: %s\n", src);
3037 d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
3038 (double)sbuf.st_size,
3039 (unsigned int)sbuf.st_blocks,
3040 filetype_to_str(sbuf.st_mode));
3042 #if defined(S_ISCHR) && defined(S_ISBLK)
3043 if (S_ISCHR(sbuf.st_mode) || S_ISBLK(sbuf.st_mode)) {
3044 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
3045 (double)sbuf.st_ino,
3046 (unsigned int)sbuf.st_nlink,
3047 unix_dev_major(sbuf.st_rdev),
3048 unix_dev_minor(sbuf.st_rdev));
3049 } else
3050 #endif
3051 d_printf("Inode: %.0f\tLinks: %u\n",
3052 (double)sbuf.st_ino,
3053 (unsigned int)sbuf.st_nlink);
3055 d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
3056 ((int)sbuf.st_mode & 0777),
3057 unix_mode_to_str(mode_str, sbuf.st_mode),
3058 (unsigned int)sbuf.st_uid,
3059 (unsigned int)sbuf.st_gid);
3061 lt = localtime(&sbuf.st_atime);
3062 if (lt) {
3063 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3064 } else {
3065 fstrcpy(mode_str, "unknown");
3067 d_printf("Access: %s\n", mode_str);
3069 lt = localtime(&sbuf.st_mtime);
3070 if (lt) {
3071 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3072 } else {
3073 fstrcpy(mode_str, "unknown");
3075 d_printf("Modify: %s\n", mode_str);
3077 lt = localtime(&sbuf.st_ctime);
3078 if (lt) {
3079 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
3080 } else {
3081 fstrcpy(mode_str, "unknown");
3083 d_printf("Change: %s\n", mode_str);
3085 return 0;
3089 /****************************************************************************
3090 UNIX chown.
3091 ****************************************************************************/
3093 static int cmd_chown(void)
3095 TALLOC_CTX *ctx = talloc_tos();
3096 char *src = NULL;
3097 uid_t uid;
3098 gid_t gid;
3099 char *buf, *buf2, *buf3;
3100 struct cli_state *targetcli;
3101 char *targetname = NULL;
3103 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
3104 !next_token_nr_talloc(ctx,NULL,&buf2,NULL) ||
3105 !next_token_nr_talloc(ctx,NULL,&buf3,NULL)) {
3106 d_printf("chown uid gid file\n");
3107 return 1;
3110 uid = (uid_t)atoi(buf);
3111 gid = (gid_t)atoi(buf2);
3113 src = talloc_asprintf(ctx,
3114 "%s%s",
3115 client_get_cur_dir(),
3116 buf3);
3117 if (!src) {
3118 return 1;
3120 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname) ) {
3121 d_printf("chown %s: %s\n", src, cli_errstr(cli));
3122 return 1;
3125 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3126 d_printf("Server doesn't support UNIX CIFS calls.\n");
3127 return 1;
3130 if (!cli_unix_chown(targetcli, targetname, uid, gid)) {
3131 d_printf("%s chown file %s uid=%d, gid=%d\n",
3132 cli_errstr(targetcli), src, (int)uid, (int)gid);
3133 return 1;
3136 return 0;
3139 /****************************************************************************
3140 Rename some file.
3141 ****************************************************************************/
3143 static int cmd_rename(void)
3145 TALLOC_CTX *ctx = talloc_tos();
3146 char *src, *dest;
3147 char *buf, *buf2;
3148 struct cli_state *targetcli;
3149 char *targetsrc;
3150 char *targetdest;
3152 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
3153 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
3154 d_printf("rename <src> <dest>\n");
3155 return 1;
3158 src = talloc_asprintf(ctx,
3159 "%s%s",
3160 client_get_cur_dir(),
3161 buf);
3162 if (!src) {
3163 return 1;
3166 dest = talloc_asprintf(ctx,
3167 "%s%s",
3168 client_get_cur_dir(),
3169 buf2);
3170 if (!dest) {
3171 return 1;
3174 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetsrc)) {
3175 d_printf("rename %s: %s\n", src, cli_errstr(cli));
3176 return 1;
3179 if (!cli_resolve_path(ctx, "", cli, dest, &targetcli, &targetdest)) {
3180 d_printf("rename %s: %s\n", dest, cli_errstr(cli));
3181 return 1;
3184 if (!cli_rename(targetcli, targetsrc, targetdest)) {
3185 d_printf("%s renaming files %s -> %s \n",
3186 cli_errstr(targetcli),
3187 targetsrc,
3188 targetdest);
3189 return 1;
3192 return 0;
3195 /****************************************************************************
3196 Print the volume name.
3197 ****************************************************************************/
3199 static int cmd_volume(void)
3201 fstring volname;
3202 uint32 serial_num;
3203 time_t create_date;
3205 if (!cli_get_fs_volume_info(cli, volname, &serial_num, &create_date)) {
3206 d_printf("Errr %s getting volume info\n",cli_errstr(cli));
3207 return 1;
3210 d_printf("Volume: |%s| serial number 0x%x\n",
3211 volname, (unsigned int)serial_num);
3212 return 0;
3215 /****************************************************************************
3216 Hard link files using the NT call.
3217 ****************************************************************************/
3219 static int cmd_hardlink(void)
3221 TALLOC_CTX *ctx = talloc_tos();
3222 char *src, *dest;
3223 char *buf, *buf2;
3224 struct cli_state *targetcli;
3225 char *targetname;
3227 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL) ||
3228 !next_token_nr_talloc(ctx,NULL,&buf2,NULL)) {
3229 d_printf("hardlink <src> <dest>\n");
3230 return 1;
3233 src = talloc_asprintf(ctx,
3234 "%s%s",
3235 client_get_cur_dir(),
3236 buf);
3237 if (!src) {
3238 return 1;
3241 dest = talloc_asprintf(ctx,
3242 "%s%s",
3243 client_get_cur_dir(),
3244 buf2);
3245 if (!dest) {
3246 return 1;
3249 if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
3250 d_printf("hardlink %s: %s\n", src, cli_errstr(cli));
3251 return 1;
3254 if (!cli_nt_hardlink(targetcli, targetname, dest)) {
3255 d_printf("%s doing an NT hard link of files\n",cli_errstr(targetcli));
3256 return 1;
3259 return 0;
3262 /****************************************************************************
3263 Toggle the prompt flag.
3264 ****************************************************************************/
3266 static int cmd_prompt(void)
3268 prompt = !prompt;
3269 DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
3270 return 1;
3273 /****************************************************************************
3274 Set the newer than time.
3275 ****************************************************************************/
3277 static int cmd_newer(void)
3279 TALLOC_CTX *ctx = talloc_tos();
3280 char *buf;
3281 bool ok;
3282 SMB_STRUCT_STAT sbuf;
3284 ok = next_token_nr_talloc(ctx,NULL,&buf,NULL);
3285 if (ok && (sys_stat(buf,&sbuf) == 0)) {
3286 newer_than = sbuf.st_mtime;
3287 DEBUG(1,("Getting files newer than %s",
3288 time_to_asc(newer_than)));
3289 } else {
3290 newer_than = 0;
3293 if (ok && newer_than == 0) {
3294 d_printf("Error setting newer-than time\n");
3295 return 1;
3298 return 0;
3301 /****************************************************************************
3302 Set the archive level.
3303 ****************************************************************************/
3305 static int cmd_archive(void)
3307 TALLOC_CTX *ctx = talloc_tos();
3308 char *buf;
3310 if (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3311 archive_level = atoi(buf);
3312 } else {
3313 d_printf("Archive level is %d\n",archive_level);
3316 return 0;
3319 /****************************************************************************
3320 Toggle the lowercaseflag.
3321 ****************************************************************************/
3323 static int cmd_lowercase(void)
3325 lowercase = !lowercase;
3326 DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
3327 return 0;
3330 /****************************************************************************
3331 Toggle the case sensitive flag.
3332 ****************************************************************************/
3334 static int cmd_setcase(void)
3336 bool orig_case_sensitive = cli_set_case_sensitive(cli, false);
3338 cli_set_case_sensitive(cli, !orig_case_sensitive);
3339 DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
3340 "on":"off"));
3341 return 0;
3344 /****************************************************************************
3345 Toggle the showacls flag.
3346 ****************************************************************************/
3348 static int cmd_showacls(void)
3350 showacls = !showacls;
3351 DEBUG(2,("showacls is now %s\n",showacls?"on":"off"));
3352 return 0;
3356 /****************************************************************************
3357 Toggle the recurse flag.
3358 ****************************************************************************/
3360 static int cmd_recurse(void)
3362 recurse = !recurse;
3363 DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
3364 return 0;
3367 /****************************************************************************
3368 Toggle the translate flag.
3369 ****************************************************************************/
3371 static int cmd_translate(void)
3373 translation = !translation;
3374 DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
3375 translation?"on":"off"));
3376 return 0;
3379 /****************************************************************************
3380 Do the lcd command.
3381 ****************************************************************************/
3383 static int cmd_lcd(void)
3385 TALLOC_CTX *ctx = talloc_tos();
3386 char *buf;
3387 char *d;
3389 if (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3390 chdir(buf);
3392 d = TALLOC_ARRAY(ctx, char, PATH_MAX+1);
3393 if (!d) {
3394 return 1;
3396 DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
3397 return 0;
3400 /****************************************************************************
3401 Get a file restarting at end of local file.
3402 ****************************************************************************/
3404 static int cmd_reget(void)
3406 TALLOC_CTX *ctx = talloc_tos();
3407 char *local_name = NULL;
3408 char *remote_name = NULL;
3409 char *fname = NULL;
3410 char *p = NULL;
3412 remote_name = talloc_asprintf(ctx,
3413 "%s%s",
3414 client_get_cur_dir(),
3415 CLI_DIRSEP_STR);
3416 if (!remote_name) {
3417 return 1;
3420 if (!next_token_nr_talloc(ctx, NULL, &fname, NULL)) {
3421 d_printf("reget <filename>\n");
3422 return 1;
3424 remote_name = talloc_asprintf_append(remote_name, fname);
3425 if (!remote_name) {
3426 return 1;
3428 remote_name = clean_name(ctx,remote_name);
3429 if (!remote_name) {
3430 return 1;
3433 local_name = fname;
3434 next_token_nr_talloc(ctx, NULL, &p, NULL);
3435 if (p) {
3436 local_name = p;
3439 return do_get(remote_name, local_name, true);
3442 /****************************************************************************
3443 Put a file restarting at end of local file.
3444 ****************************************************************************/
3446 static int cmd_reput(void)
3448 TALLOC_CTX *ctx = talloc_tos();
3449 char *local_name = NULL;
3450 char *remote_name = NULL;
3451 char *buf;
3452 SMB_STRUCT_STAT st;
3454 remote_name = talloc_asprintf(ctx,
3455 "%s%s",
3456 client_get_cur_dir(),
3457 CLI_DIRSEP_STR);
3458 if (!remote_name) {
3459 return 1;
3462 if (!next_token_nr_talloc(ctx, NULL, &local_name, NULL)) {
3463 d_printf("reput <filename>\n");
3464 return 1;
3467 if (!file_exist(local_name, &st)) {
3468 d_printf("%s does not exist\n", local_name);
3469 return 1;
3472 if (next_token_nr_talloc(ctx, NULL, &buf, NULL)) {
3473 remote_name = talloc_asprintf_append(remote_name,
3474 buf);
3475 } else {
3476 remote_name = talloc_asprintf_append(remote_name,
3477 local_name);
3479 if (!remote_name) {
3480 return 1;
3483 remote_name = clean_name(ctx, remote_name);
3484 if (!remote_name) {
3485 return 1;
3488 return do_put(remote_name, local_name, true);
3491 /****************************************************************************
3492 List a share name.
3493 ****************************************************************************/
3495 static void browse_fn(const char *name, uint32 m,
3496 const char *comment, void *state)
3498 const char *typestr = "";
3500 switch (m & 7) {
3501 case STYPE_DISKTREE:
3502 typestr = "Disk";
3503 break;
3504 case STYPE_PRINTQ:
3505 typestr = "Printer";
3506 break;
3507 case STYPE_DEVICE:
3508 typestr = "Device";
3509 break;
3510 case STYPE_IPC:
3511 typestr = "IPC";
3512 break;
3514 /* FIXME: If the remote machine returns non-ascii characters
3515 in any of these fields, they can corrupt the output. We
3516 should remove them. */
3517 if (!grepable) {
3518 d_printf("\t%-15s %-10.10s%s\n",
3519 name,typestr,comment);
3520 } else {
3521 d_printf ("%s|%s|%s\n",typestr,name,comment);
3525 static bool browse_host_rpc(bool sort)
3527 NTSTATUS status;
3528 struct rpc_pipe_client *pipe_hnd;
3529 TALLOC_CTX *frame = talloc_stackframe();
3530 ENUM_HND enum_hnd;
3531 WERROR werr;
3532 SRV_SHARE_INFO_CTR ctr;
3533 int i;
3535 init_enum_hnd(&enum_hnd, 0);
3537 pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SRVSVC, &status);
3539 if (pipe_hnd == NULL) {
3540 DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
3541 nt_errstr(status)));
3542 TALLOC_FREE(frame);
3543 return false;
3546 werr = rpccli_srvsvc_net_share_enum(pipe_hnd, frame, 1, &ctr,
3547 0xffffffff, &enum_hnd);
3549 if (!W_ERROR_IS_OK(werr)) {
3550 cli_rpc_pipe_close(pipe_hnd);
3551 TALLOC_FREE(frame);
3552 return false;
3555 for (i=0; i<ctr.num_entries; i++) {
3556 SRV_SHARE_INFO_1 *info = &ctr.share.info1[i];
3557 char *name, *comment;
3558 name = rpcstr_pull_unistr2_talloc(
3559 frame, &info->info_1_str.uni_netname);
3560 comment = rpcstr_pull_unistr2_talloc(
3561 frame, &info->info_1_str.uni_remark);
3562 browse_fn(name, info->info_1.type, comment, NULL);
3565 cli_rpc_pipe_close(pipe_hnd);
3566 TALLOC_FREE(frame);
3567 return true;
3570 /****************************************************************************
3571 Try and browse available connections on a host.
3572 ****************************************************************************/
3574 static bool browse_host(bool sort)
3576 int ret;
3577 if (!grepable) {
3578 d_printf("\n\tSharename Type Comment\n");
3579 d_printf("\t--------- ---- -------\n");
3582 if (browse_host_rpc(sort)) {
3583 return true;
3586 if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
3587 d_printf("Error returning browse list: %s\n", cli_errstr(cli));
3589 return (ret != -1);
3592 /****************************************************************************
3593 List a server name.
3594 ****************************************************************************/
3596 static void server_fn(const char *name, uint32 m,
3597 const char *comment, void *state)
3600 if (!grepable){
3601 d_printf("\t%-16s %s\n", name, comment);
3602 } else {
3603 d_printf("%s|%s|%s\n",(char *)state, name, comment);
3607 /****************************************************************************
3608 Try and browse available connections on a host.
3609 ****************************************************************************/
3611 static bool list_servers(const char *wk_grp)
3613 fstring state;
3615 if (!cli->server_domain)
3616 return false;
3618 if (!grepable) {
3619 d_printf("\n\tServer Comment\n");
3620 d_printf("\t--------- -------\n");
3622 fstrcpy( state, "Server" );
3623 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
3624 state);
3626 if (!grepable) {
3627 d_printf("\n\tWorkgroup Master\n");
3628 d_printf("\t--------- -------\n");
3631 fstrcpy( state, "Workgroup" );
3632 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
3633 server_fn, state);
3634 return true;
3637 /****************************************************************************
3638 Print or set current VUID
3639 ****************************************************************************/
3641 static int cmd_vuid(void)
3643 TALLOC_CTX *ctx = talloc_tos();
3644 char *buf;
3646 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3647 d_printf("Current VUID is %d\n", cli->vuid);
3648 return 0;
3651 cli->vuid = atoi(buf);
3652 return 0;
3655 /****************************************************************************
3656 Setup a new VUID, by issuing a session setup
3657 ****************************************************************************/
3659 static int cmd_logon(void)
3661 TALLOC_CTX *ctx = talloc_tos();
3662 char *l_username, *l_password;
3664 if (!next_token_nr_talloc(ctx,NULL,&l_username,NULL)) {
3665 d_printf("logon <username> [<password>]\n");
3666 return 0;
3669 if (!next_token_nr_talloc(ctx,NULL,&l_password,NULL)) {
3670 char *pass = getpass("Password: ");
3671 if (pass) {
3672 l_password = talloc_strdup(ctx,pass);
3675 if (!l_password) {
3676 return 1;
3679 if (!NT_STATUS_IS_OK(cli_session_setup(cli, l_username,
3680 l_password, strlen(l_password),
3681 l_password, strlen(l_password),
3682 lp_workgroup()))) {
3683 d_printf("session setup failed: %s\n", cli_errstr(cli));
3684 return -1;
3687 d_printf("Current VUID is %d\n", cli->vuid);
3688 return 0;
3692 /****************************************************************************
3693 list active connections
3694 ****************************************************************************/
3696 static int cmd_list_connect(void)
3698 cli_cm_display();
3699 return 0;
3702 /****************************************************************************
3703 display the current active client connection
3704 ****************************************************************************/
3706 static int cmd_show_connect( void )
3708 TALLOC_CTX *ctx = talloc_tos();
3709 struct cli_state *targetcli;
3710 char *targetpath;
3712 if (!cli_resolve_path(ctx, "", cli, client_get_cur_dir(),
3713 &targetcli, &targetpath ) ) {
3714 d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
3715 return 1;
3718 d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
3719 return 0;
3722 /****************************************************************************
3723 iosize command
3724 ***************************************************************************/
3726 int cmd_iosize(void)
3728 TALLOC_CTX *ctx = talloc_tos();
3729 char *buf;
3730 int iosize;
3732 if (!next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3733 d_printf("iosize <n> or iosize 0x<n>. "
3734 "Minimum is 16384 (0x4000), "
3735 "max is 16776960 (0xFFFF00)\n");
3736 return 1;
3739 iosize = strtol(buf,NULL,0);
3740 if (iosize < 0 || iosize > 0xFFFF00) {
3741 d_printf("iosize out of range (min = 16384 (0x4000), "
3742 "max = 16776960 (0x0xFFFF00)");
3743 return 1;
3746 io_bufsize = iosize;
3747 d_printf("iosize is now %d\n", io_bufsize);
3748 return 0;
3752 /* Some constants for completing filename arguments */
3754 #define COMPL_NONE 0 /* No completions */
3755 #define COMPL_REMOTE 1 /* Complete remote filename */
3756 #define COMPL_LOCAL 2 /* Complete local filename */
3758 /* This defines the commands supported by this client.
3759 * NOTE: The "!" must be the last one in the list because it's fn pointer
3760 * field is NULL, and NULL in that field is used in process_tok()
3761 * (below) to indicate the end of the list. crh
3763 static struct {
3764 const char *name;
3765 int (*fn)(void);
3766 const char *description;
3767 char compl_args[2]; /* Completion argument info */
3768 } commands[] = {
3769 {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
3770 {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
3771 {"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}},
3772 {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
3773 {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
3774 {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
3775 {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
3776 {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
3777 {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
3778 {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_REMOTE}},
3779 {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
3780 {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3781 {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3782 {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
3783 {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
3784 {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
3785 {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}},
3786 {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
3787 {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
3788 {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
3789 {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
3790 {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
3791 {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
3792 {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
3793 {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
3794 {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3795 {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
3796 {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
3797 {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
3798 {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
3799 {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
3800 {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
3801 {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
3802 {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
3803 {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
3804 {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
3805 {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3806 {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3807 {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3808 {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
3809 {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
3810 {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
3811 {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
3812 {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
3813 {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
3814 {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
3815 {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
3816 {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
3817 {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
3818 {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
3819 {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
3820 {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
3821 {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
3822 {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
3823 {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},
3824 {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
3825 {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},
3826 {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
3827 {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
3828 {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
3829 {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
3830 {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
3831 {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
3832 {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
3833 {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
3834 {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
3835 {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
3836 {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
3837 {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
3839 /* Yes, this must be here, see crh's comment above. */
3840 {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
3841 {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
3844 /*******************************************************************
3845 Lookup a command string in the list of commands, including
3846 abbreviations.
3847 ******************************************************************/
3849 static int process_tok(char *tok)
3851 int i = 0, matches = 0;
3852 int cmd=0;
3853 int tok_len = strlen(tok);
3855 while (commands[i].fn != NULL) {
3856 if (strequal(commands[i].name,tok)) {
3857 matches = 1;
3858 cmd = i;
3859 break;
3860 } else if (strnequal(commands[i].name, tok, tok_len)) {
3861 matches++;
3862 cmd = i;
3864 i++;
3867 if (matches == 0)
3868 return(-1);
3869 else if (matches == 1)
3870 return(cmd);
3871 else
3872 return(-2);
3875 /****************************************************************************
3876 Help.
3877 ****************************************************************************/
3879 static int cmd_help(void)
3881 TALLOC_CTX *ctx = talloc_tos();
3882 int i=0,j;
3883 char *buf;
3885 if (next_token_nr_talloc(ctx,NULL,&buf,NULL)) {
3886 if ((i = process_tok(buf)) >= 0)
3887 d_printf("HELP %s:\n\t%s\n\n",
3888 commands[i].name,commands[i].description);
3889 } else {
3890 while (commands[i].description) {
3891 for (j=0; commands[i].description && (j<5); j++) {
3892 d_printf("%-15s",commands[i].name);
3893 i++;
3895 d_printf("\n");
3898 return 0;
3901 /****************************************************************************
3902 Process a -c command string.
3903 ****************************************************************************/
3905 static int process_command_string(const char *cmd_in)
3907 TALLOC_CTX *ctx = talloc_tos();
3908 char *cmd = talloc_strdup(ctx, cmd_in);
3909 int rc = 0;
3911 if (!cmd) {
3912 return 1;
3914 /* establish the connection if not already */
3916 if (!cli) {
3917 cli = cli_cm_open(talloc_tos(), NULL, desthost, service, true);
3918 if (!cli) {
3919 return 1;
3923 while (cmd[0] != '\0') {
3924 char *line;
3925 const char *ptr;
3926 char *p;
3927 char *tok;
3928 int i;
3930 if ((p = strchr_m(cmd, ';')) == 0) {
3931 line = cmd;
3932 cmd += strlen(cmd);
3933 } else {
3934 *p = '\0';
3935 line = cmd;
3936 cmd = p + 1;
3939 /* and get the first part of the command */
3940 ptr = line;
3941 if (!next_token_nr_talloc(ctx,&ptr,&tok,NULL)) {
3942 continue;
3945 if ((i = process_tok(tok)) >= 0) {
3946 rc = commands[i].fn();
3947 } else if (i == -2) {
3948 d_printf("%s: command abbreviation ambiguous\n",tok);
3949 } else {
3950 d_printf("%s: command not found\n",tok);
3954 return rc;
3957 #define MAX_COMPLETIONS 100
3959 typedef struct {
3960 char *dirmask;
3961 char **matches;
3962 int count, samelen;
3963 const char *text;
3964 int len;
3965 } completion_remote_t;
3967 static void completion_remote_filter(const char *mnt,
3968 file_info *f,
3969 const char *mask,
3970 void *state)
3972 completion_remote_t *info = (completion_remote_t *)state;
3974 if ((info->count < MAX_COMPLETIONS - 1) &&
3975 (strncmp(info->text, f->name, info->len) == 0) &&
3976 (strcmp(f->name, ".") != 0) &&
3977 (strcmp(f->name, "..") != 0)) {
3978 if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
3979 info->matches[info->count] = SMB_STRDUP(f->name);
3980 else {
3981 TALLOC_CTX *ctx = talloc_stackframe();
3982 char *tmp;
3984 if (info->dirmask && info->dirmask[0] != 0) {
3985 tmp = talloc_strdup(ctx,info->dirmask);
3986 } else {
3987 tmp = talloc_strdup(ctx,"");
3989 if (!tmp) {
3990 TALLOC_FREE(ctx);
3991 return;
3993 tmp = talloc_asprintf_append(tmp, f->name);
3994 if (!tmp) {
3995 TALLOC_FREE(ctx);
3996 return;
3998 if (f->mode & aDIR) {
3999 tmp = talloc_asprintf_append(tmp, "/");
4001 if (!tmp) {
4002 TALLOC_FREE(ctx);
4003 return;
4005 info->matches[info->count] = SMB_STRDUP(tmp);
4006 TALLOC_FREE(ctx);
4008 if (info->matches[info->count] == NULL) {
4009 return;
4011 if (f->mode & aDIR) {
4012 smb_readline_ca_char(0);
4014 if (info->count == 1) {
4015 info->samelen = strlen(info->matches[info->count]);
4016 } else {
4017 while (strncmp(info->matches[info->count],
4018 info->matches[info->count-1],
4019 info->samelen) != 0) {
4020 info->samelen--;
4023 info->count++;
4027 static char **remote_completion(const char *text, int len)
4029 TALLOC_CTX *ctx = talloc_stackframe();
4030 char *dirmask = NULL;
4031 char *targetpath = NULL;
4032 struct cli_state *targetcli = NULL;
4033 int i;
4034 completion_remote_t info = { NULL, NULL, 1, 0, NULL, 0 };
4036 /* can't have non-static intialisation on Sun CC, so do it
4037 at run time here */
4038 info.samelen = len;
4039 info.text = text;
4040 info.len = len;
4042 info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
4043 if (!info.matches) {
4044 TALLOC_FREE(ctx);
4045 return NULL;
4049 * We're leaving matches[0] free to fill it later with the text to
4050 * display: Either the one single match or the longest common subset
4051 * of the matches.
4053 info.matches[0] = NULL;
4054 info.count = 1;
4056 for (i = len-1; i >= 0; i--) {
4057 if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
4058 break;
4062 info.text = text+i+1;
4063 info.samelen = info.len = len-i-1;
4065 if (i > 0) {
4066 info.dirmask = SMB_MALLOC_ARRAY(char, i+2);
4067 if (!info.dirmask) {
4068 goto cleanup;
4070 strncpy(info.dirmask, text, i+1);
4071 info.dirmask[i+1] = 0;
4072 dirmask = talloc_asprintf(ctx,
4073 "%s%*s*",
4074 client_get_cur_dir(),
4075 i-1,
4076 text);
4077 } else {
4078 info.dirmask = SMB_STRDUP("");
4079 if (!info.dirmask) {
4080 goto cleanup;
4082 dirmask = talloc_asprintf(ctx,
4083 "%s*",
4084 client_get_cur_dir());
4086 if (!dirmask) {
4087 goto cleanup;
4090 if (!cli_resolve_path(ctx, "", cli, dirmask, &targetcli, &targetpath)) {
4091 goto cleanup;
4093 if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN,
4094 completion_remote_filter, (void *)&info) < 0) {
4095 goto cleanup;
4098 if (info.count == 1) {
4100 * No matches at all, NULL indicates there is nothing
4102 SAFE_FREE(info.matches[0]);
4103 SAFE_FREE(info.matches);
4104 TALLOC_FREE(ctx);
4105 return NULL;
4108 if (info.count == 2) {
4110 * Exactly one match in matches[1], indicate this is the one
4111 * in matches[0].
4113 info.matches[0] = info.matches[1];
4114 info.matches[1] = NULL;
4115 info.count -= 1;
4116 TALLOC_FREE(ctx);
4117 return info.matches;
4121 * We got more than one possible match, set the result to the maximum
4122 * common subset
4125 info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
4126 info.matches[info.count] = NULL;
4127 return info.matches;
4129 cleanup:
4130 for (i = 0; i < info.count; i++) {
4131 SAFE_FREE(info.matches[i]);
4133 SAFE_FREE(info.matches);
4134 SAFE_FREE(info.dirmask);
4135 TALLOC_FREE(ctx);
4136 return NULL;
4139 static char **completion_fn(const char *text, int start, int end)
4141 smb_readline_ca_char(' ');
4143 if (start) {
4144 const char *buf, *sp;
4145 int i;
4146 char compl_type;
4148 buf = smb_readline_get_line_buffer();
4149 if (buf == NULL)
4150 return NULL;
4152 sp = strchr(buf, ' ');
4153 if (sp == NULL)
4154 return NULL;
4156 for (i = 0; commands[i].name; i++) {
4157 if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
4158 (commands[i].name[sp - buf] == 0)) {
4159 break;
4162 if (commands[i].name == NULL)
4163 return NULL;
4165 while (*sp == ' ')
4166 sp++;
4168 if (sp == (buf + start))
4169 compl_type = commands[i].compl_args[0];
4170 else
4171 compl_type = commands[i].compl_args[1];
4173 if (compl_type == COMPL_REMOTE)
4174 return remote_completion(text, end - start);
4175 else /* fall back to local filename completion */
4176 return NULL;
4177 } else {
4178 char **matches;
4179 int i, len, samelen = 0, count=1;
4181 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
4182 if (!matches) {
4183 return NULL;
4185 matches[0] = NULL;
4187 len = strlen(text);
4188 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
4189 if (strncmp(text, commands[i].name, len) == 0) {
4190 matches[count] = SMB_STRDUP(commands[i].name);
4191 if (!matches[count])
4192 goto cleanup;
4193 if (count == 1)
4194 samelen = strlen(matches[count]);
4195 else
4196 while (strncmp(matches[count], matches[count-1], samelen) != 0)
4197 samelen--;
4198 count++;
4202 switch (count) {
4203 case 0: /* should never happen */
4204 case 1:
4205 goto cleanup;
4206 case 2:
4207 matches[0] = SMB_STRDUP(matches[1]);
4208 break;
4209 default:
4210 matches[0] = (char *)SMB_MALLOC(samelen+1);
4211 if (!matches[0])
4212 goto cleanup;
4213 strncpy(matches[0], matches[1], samelen);
4214 matches[0][samelen] = 0;
4216 matches[count] = NULL;
4217 return matches;
4219 cleanup:
4220 for (i = 0; i < count; i++)
4221 free(matches[i]);
4223 free(matches);
4224 return NULL;
4228 /****************************************************************************
4229 Make sure we swallow keepalives during idle time.
4230 ****************************************************************************/
4232 static void readline_callback(void)
4234 fd_set fds;
4235 struct timeval timeout;
4236 static time_t last_t;
4237 time_t t;
4239 t = time(NULL);
4241 if (t - last_t < 5)
4242 return;
4244 last_t = t;
4246 again:
4248 if (cli->fd == -1)
4249 return;
4251 FD_ZERO(&fds);
4252 FD_SET(cli->fd,&fds);
4254 timeout.tv_sec = 0;
4255 timeout.tv_usec = 0;
4256 sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
4258 /* We deliberately use receive_smb instead of
4259 client_receive_smb as we want to receive
4260 session keepalives and then drop them here.
4262 if (FD_ISSET(cli->fd,&fds)) {
4263 if (!receive_smb(cli->fd,cli->inbuf,0,&cli->smb_rw_error)) {
4264 DEBUG(0, ("Read from server failed, maybe it closed the "
4265 "connection\n"));
4266 return;
4268 goto again;
4271 /* Ping the server to keep the connection alive using SMBecho. */
4273 unsigned char garbage[16];
4274 memset(garbage, 0xf0, sizeof(garbage));
4275 cli_echo(cli, 1, garbage, sizeof(garbage));
4279 /****************************************************************************
4280 Process commands on stdin.
4281 ****************************************************************************/
4283 static int process_stdin(void)
4285 const char *ptr;
4286 int rc = 0;
4288 while (1) {
4289 TALLOC_CTX *frame = talloc_stackframe();
4290 char *tok = NULL;
4291 char *the_prompt = NULL;
4292 char *line = NULL;
4293 int i;
4295 /* display a prompt */
4296 if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
4297 TALLOC_FREE(frame);
4298 break;
4300 line = smb_readline(the_prompt, readline_callback, completion_fn);
4301 SAFE_FREE(the_prompt);
4302 if (!line) {
4303 TALLOC_FREE(frame);
4304 break;
4307 /* special case - first char is ! */
4308 if (*line == '!') {
4309 system(line + 1);
4310 SAFE_FREE(line);
4311 TALLOC_FREE(frame);
4312 continue;
4315 /* and get the first part of the command */
4316 ptr = line;
4317 if (!next_token_nr_talloc(frame,&ptr,&tok,NULL)) {
4318 TALLOC_FREE(frame);
4319 SAFE_FREE(line);
4320 continue;
4323 if ((i = process_tok(tok)) >= 0) {
4324 rc = commands[i].fn();
4325 } else if (i == -2) {
4326 d_printf("%s: command abbreviation ambiguous\n",tok);
4327 } else {
4328 d_printf("%s: command not found\n",tok);
4330 SAFE_FREE(line);
4331 TALLOC_FREE(frame);
4333 return rc;
4336 /****************************************************************************
4337 Process commands from the client.
4338 ****************************************************************************/
4340 static int process(const char *base_directory)
4342 int rc = 0;
4344 cli = cli_cm_open(talloc_tos(), NULL, desthost, service, true);
4345 if (!cli) {
4346 return 1;
4349 if (base_directory && *base_directory) {
4350 rc = do_cd(base_directory);
4351 if (rc) {
4352 cli_cm_shutdown();
4353 return rc;
4357 if (cmdstr) {
4358 rc = process_command_string(cmdstr);
4359 } else {
4360 process_stdin();
4363 cli_cm_shutdown();
4364 return rc;
4367 /****************************************************************************
4368 Handle a -L query.
4369 ****************************************************************************/
4371 static int do_host_query(const char *query_host)
4373 cli = cli_cm_open(talloc_tos(), NULL, query_host, "IPC$", true);
4374 if (!cli)
4375 return 1;
4377 browse_host(true);
4379 if (port != 139) {
4381 /* Workgroups simply don't make sense over anything
4382 else but port 139... */
4384 cli_cm_shutdown();
4385 cli_cm_set_port( 139 );
4386 cli = cli_cm_open(talloc_tos(), NULL, query_host, "IPC$", true);
4389 if (cli == NULL) {
4390 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
4391 return 1;
4394 list_servers(lp_workgroup());
4396 cli_cm_shutdown();
4398 return(0);
4401 /****************************************************************************
4402 Handle a tar operation.
4403 ****************************************************************************/
4405 static int do_tar_op(const char *base_directory)
4407 int ret;
4409 /* do we already have a connection? */
4410 if (!cli) {
4411 cli = cli_cm_open(talloc_tos(), NULL, desthost, service, true);
4412 if (!cli)
4413 return 1;
4416 recurse=true;
4418 if (base_directory && *base_directory) {
4419 ret = do_cd(base_directory);
4420 if (ret) {
4421 cli_cm_shutdown();
4422 return ret;
4426 ret=process_tar();
4428 cli_cm_shutdown();
4430 return(ret);
4433 /****************************************************************************
4434 Handle a message operation.
4435 ****************************************************************************/
4437 static int do_message_op(void)
4439 struct sockaddr_storage ss;
4440 struct nmb_name called, calling;
4441 fstring server_name;
4442 char name_type_hex[10];
4443 int msg_port;
4444 NTSTATUS status;
4446 make_nmb_name(&calling, calling_name, 0x0);
4447 make_nmb_name(&called , desthost, name_type);
4449 fstrcpy(server_name, desthost);
4450 snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
4451 fstrcat(server_name, name_type_hex);
4453 zero_addr(&ss);
4454 if (have_ip)
4455 ss = dest_ss;
4457 /* we can only do messages over port 139 (to windows clients at least) */
4459 msg_port = port ? port : 139;
4461 if (!(cli=cli_initialise()) || (cli_set_port(cli, msg_port) != msg_port)) {
4462 d_printf("Connection to %s failed\n", desthost);
4463 return 1;
4466 status = cli_connect(cli, server_name, &ss);
4467 if (!NT_STATUS_IS_OK(status)) {
4468 d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
4469 return 1;
4472 if (!cli_session_request(cli, &calling, &called)) {
4473 d_printf("session request failed\n");
4474 cli_cm_shutdown();
4475 return 1;
4478 send_message();
4479 cli_cm_shutdown();
4481 return 0;
4484 /****************************************************************************
4485 main program
4486 ****************************************************************************/
4488 int main(int argc,char *argv[])
4490 char *base_directory = NULL;
4491 int opt;
4492 char *query_host = NULL;
4493 bool message = false;
4494 char *term_code = NULL;
4495 static const char *new_name_resolve_order = NULL;
4496 poptContext pc;
4497 char *p;
4498 int rc = 0;
4499 fstring new_workgroup;
4500 bool tar_opt = false;
4501 bool service_opt = false;
4502 struct poptOption long_options[] = {
4503 POPT_AUTOHELP
4505 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
4506 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
4507 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
4508 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
4509 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
4510 { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
4511 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
4512 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
4513 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
4514 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" },
4515 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
4516 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
4517 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
4518 { "browse", 'B', POPT_ARG_NONE, NULL, 'B', "Browse SMB servers using DNS" },
4519 POPT_COMMON_SAMBA
4520 POPT_COMMON_CONNECTION
4521 POPT_COMMON_CREDENTIALS
4522 POPT_TABLEEND
4524 TALLOC_CTX *frame = talloc_stackframe();
4526 if (!client_set_cur_dir("\\")) {
4527 exit(ENOMEM);
4530 #ifdef KANJI
4531 term_code = talloc_strdup(frame,KANJI);
4532 #else /* KANJI */
4533 term_code = talloc_strdup(frame,"");
4534 #endif /* KANJI */
4535 if (!term_code) {
4536 exit(ENOMEM);
4539 /* initialize the workgroup name so we can determine whether or
4540 not it was set by a command line option */
4542 set_global_myworkgroup( "" );
4543 set_global_myname( "" );
4545 /* set default debug level to 0 regardless of what smb.conf sets */
4546 setup_logging( "smbclient", true );
4547 DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
4548 if ((dbf = x_fdup(x_stderr))) {
4549 x_setbuf( dbf, NULL );
4552 load_case_tables();
4554 /* skip argv(0) */
4555 pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 0);
4556 poptSetOtherOptionHelp(pc, "service <password>");
4558 in_client = true; /* Make sure that we tell lp_load we are */
4560 while ((opt = poptGetNextOpt(pc)) != -1) {
4562 /* if the tar option has been called previouslt, now we need to eat out the leftovers */
4563 /* I see no other way to keep things sane --SSS */
4564 if (tar_opt == true) {
4565 while (poptPeekArg(pc)) {
4566 poptGetArg(pc);
4568 tar_opt = false;
4571 /* if the service has not yet been specified lets see if it is available in the popt stack */
4572 if (!service_opt && poptPeekArg(pc)) {
4573 service = talloc_strdup(frame, poptGetArg(pc));
4574 if (!service) {
4575 exit(ENOMEM);
4577 service_opt = true;
4580 /* if the service has already been retrieved then check if we have also a password */
4581 if (service_opt && (!get_cmdline_auth_info_got_pass()) && poptPeekArg(pc)) {
4582 set_cmdline_auth_info_password(poptGetArg(pc));
4585 switch (opt) {
4586 case 'M':
4587 /* Messages are sent to NetBIOS name type 0x3
4588 * (Messenger Service). Make sure we default
4589 * to port 139 instead of port 445. srl,crh
4591 name_type = 0x03;
4592 cli_cm_set_dest_name_type( name_type );
4593 desthost = talloc_strdup(frame,poptGetOptArg(pc));
4594 if (!desthost) {
4595 exit(ENOMEM);
4597 if( !port )
4598 cli_cm_set_port( 139 );
4599 message = true;
4600 break;
4601 case 'I':
4603 if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
4604 exit(1);
4606 have_ip = true;
4608 cli_cm_set_dest_ss(&dest_ss);
4610 break;
4611 case 'E':
4612 if (dbf) {
4613 x_fclose(dbf);
4615 dbf = x_stderr;
4616 display_set_stderr();
4617 break;
4619 case 'L':
4620 query_host = talloc_strdup(frame, poptGetOptArg(pc));
4621 if (!query_host) {
4622 exit(ENOMEM);
4624 break;
4625 case 't':
4626 term_code = talloc_strdup(frame,poptGetOptArg(pc));
4627 if (!term_code) {
4628 exit(ENOMEM);
4630 break;
4631 case 'm':
4632 max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
4633 break;
4634 case 'T':
4635 /* We must use old option processing for this. Find the
4636 * position of the -T option in the raw argv[]. */
4638 int i;
4639 for (i = 1; i < argc; i++) {
4640 if (strncmp("-T", argv[i],2)==0)
4641 break;
4643 i++;
4644 if (!tar_parseargs(argc, argv, poptGetOptArg(pc), i)) {
4645 poptPrintUsage(pc, stderr, 0);
4646 exit(1);
4649 /* this must be the last option, mark we have parsed it so that we know we have */
4650 tar_opt = true;
4651 break;
4652 case 'D':
4653 base_directory = talloc_strdup(frame, poptGetOptArg(pc));
4654 if (!base_directory) {
4655 exit(ENOMEM);
4657 break;
4658 case 'g':
4659 grepable=true;
4660 break;
4661 case 'B':
4662 return(do_smb_browse());
4667 /* We may still have some leftovers after the last popt option has been called */
4668 if (tar_opt == true) {
4669 while (poptPeekArg(pc)) {
4670 poptGetArg(pc);
4672 tar_opt = false;
4675 /* if the service has not yet been specified lets see if it is available in the popt stack */
4676 if (!service_opt && poptPeekArg(pc)) {
4677 service = talloc_strdup(frame,poptGetArg(pc));
4678 if (!service) {
4679 exit(ENOMEM);
4681 service_opt = true;
4684 /* if the service has already been retrieved then check if we have also a password */
4685 if (service_opt && !get_cmdline_auth_info_got_pass() && poptPeekArg(pc)) {
4686 set_cmdline_auth_info_password(poptGetArg(pc));
4689 /* check for the -P option */
4691 if ( port != 0 )
4692 cli_cm_set_port( port );
4695 * Don't load debug level from smb.conf. It should be
4696 * set by cmdline arg or remain default (0)
4698 AllowDebugChange = false;
4700 /* save the workgroup...
4702 FIXME!! do we need to do this for other options as well
4703 (or maybe a generic way to keep lp_load() from overwriting
4704 everything)? */
4706 fstrcpy( new_workgroup, lp_workgroup() );
4707 calling_name = talloc_strdup(frame, global_myname() );
4708 if (!calling_name) {
4709 exit(ENOMEM);
4712 if ( override_logfile )
4713 setup_logging( lp_logfile(), false );
4715 if (!lp_load(get_dyn_CONFIGFILE(),true,false,false,true)) {
4716 fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
4717 argv[0], get_dyn_CONFIGFILE());
4720 load_interfaces();
4722 if (service_opt && service) {
4723 size_t len;
4725 /* Convert any '/' characters in the service name to '\' characters */
4726 string_replace(service, '/','\\');
4727 if (count_chars(service,'\\') < 3) {
4728 d_printf("\n%s: Not enough '\\' characters in service\n",service);
4729 poptPrintUsage(pc, stderr, 0);
4730 exit(1);
4732 /* Remove trailing slashes */
4733 len = strlen(service);
4734 while(len > 0 && service[len - 1] == '\\') {
4735 --len;
4736 service[len] = '\0';
4740 if ( strlen(new_workgroup) != 0 ) {
4741 set_global_myworkgroup( new_workgroup );
4744 if ( strlen(calling_name) != 0 ) {
4745 set_global_myname( calling_name );
4746 } else {
4747 TALLOC_FREE(calling_name);
4748 calling_name = talloc_strdup(frame, global_myname() );
4751 init_names();
4753 if(new_name_resolve_order)
4754 lp_set_name_resolve_order(new_name_resolve_order);
4756 if (!tar_type && !query_host && !service && !message) {
4757 poptPrintUsage(pc, stderr, 0);
4758 exit(1);
4761 poptFreeContext(pc);
4763 /* Store the username and password for dfs support */
4765 cli_cm_set_credentials();
4767 DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
4769 if (tar_type) {
4770 if (cmdstr)
4771 process_command_string(cmdstr);
4772 return do_tar_op(base_directory);
4775 if (query_host && *query_host) {
4776 char *qhost = query_host;
4777 char *slash;
4779 while (*qhost == '\\' || *qhost == '/')
4780 qhost++;
4782 if ((slash = strchr_m(qhost, '/'))
4783 || (slash = strchr_m(qhost, '\\'))) {
4784 *slash = 0;
4787 if ((p=strchr_m(qhost, '#'))) {
4788 *p = 0;
4789 p++;
4790 sscanf(p, "%x", &name_type);
4791 cli_cm_set_dest_name_type( name_type );
4794 return do_host_query(qhost);
4797 if (message) {
4798 return do_message_op();
4801 if (process(base_directory)) {
4802 return 1;
4805 TALLOC_FREE(frame);
4806 return rc;