Revert "s3/service: convert lp_force_group() to const"
[Samba.git] / source3 / client / client.c
blobf112b8c4ac1b60769ca2e5262c1871b6b813bc4b
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 "system/filesys.h"
26 #include "popt_common.h"
27 #include "rpc_client/cli_pipe.h"
28 #include "client/client_proto.h"
29 #include "client/clitar_proto.h"
30 #include "../librpc/gen_ndr/ndr_srvsvc_c.h"
31 #include "../lib/util/select.h"
32 #include "system/readline.h"
33 #include "../libcli/smbreadline/smbreadline.h"
34 #include "../libcli/security/security.h"
35 #include "system/select.h"
36 #include "libsmb/libsmb.h"
37 #include "libsmb/clirap.h"
38 #include "trans2.h"
39 #include "libsmb/nmblib.h"
40 #include "include/ntioctl.h"
41 #include "../libcli/smb/smbXcli_base.h"
43 #ifndef REGISTER
44 #define REGISTER 0
45 #endif
47 extern int do_smb_browse(void); /* mDNS browsing */
49 extern bool override_logfile;
51 static int port = 0;
52 static char *service;
53 static char *desthost;
54 static bool grepable = false;
55 static bool quiet = false;
56 static char *cmdstr = NULL;
57 const char *cmd_ptr = NULL;
59 static int io_bufsize = 0; /* we use the default size */
60 static int io_timeout = (CLIENT_TIMEOUT/1000); /* Per operation timeout (in seconds). */
62 static int name_type = 0x20;
63 static int max_protocol = -1;
65 static int process_tok(char *tok);
66 static int cmd_help(void);
68 #define CREATE_ACCESS_READ READ_CONTROL_ACCESS
70 /* value for unused fid field in trans2 secondary request */
71 #define FID_UNUSED (0xFFFF)
73 time_t newer_than = 0;
74 static int archive_level = 0;
76 static bool translation = false;
77 static bool have_ip;
79 static bool prompt = true;
81 static bool recurse = false;
82 static bool showacls = false;
83 bool lowercase = false;
84 static bool backup_intent = false;
86 static struct sockaddr_storage dest_ss;
87 static char dest_ss_str[INET6_ADDRSTRLEN];
89 #define SEPARATORS " \t\n\r"
91 static bool abort_mget = true;
93 /* timing globals */
94 uint64_t get_total_size = 0;
95 unsigned int get_total_time_ms = 0;
96 static uint64_t put_total_size = 0;
97 static unsigned int put_total_time_ms = 0;
99 /* totals globals */
100 static double dir_total;
102 /* encrypted state. */
103 static bool smb_encrypt;
105 /* root cli_state connection */
107 struct cli_state *cli;
109 static char CLI_DIRSEP_CHAR = '\\';
110 static char CLI_DIRSEP_STR[] = { '\\', '\0' };
112 /* Accessor functions for directory paths. */
113 static char *fileselection;
114 static const char *client_get_fileselection(void)
116 if (fileselection) {
117 return fileselection;
119 return "";
122 static const char *client_set_fileselection(const char *new_fs)
124 SAFE_FREE(fileselection);
125 if (new_fs) {
126 fileselection = SMB_STRDUP(new_fs);
128 return client_get_fileselection();
131 static char *cwd;
132 static const char *client_get_cwd(void)
134 if (cwd) {
135 return cwd;
137 return CLI_DIRSEP_STR;
140 static const char *client_set_cwd(const char *new_cwd)
142 SAFE_FREE(cwd);
143 if (new_cwd) {
144 cwd = SMB_STRDUP(new_cwd);
146 return client_get_cwd();
149 static char *cur_dir;
150 const char *client_get_cur_dir(void)
152 if (cur_dir) {
153 return cur_dir;
155 return CLI_DIRSEP_STR;
158 const char *client_set_cur_dir(const char *newdir)
160 SAFE_FREE(cur_dir);
161 if (newdir) {
162 cur_dir = SMB_STRDUP(newdir);
164 return client_get_cur_dir();
167 /****************************************************************************
168 Put up a yes/no prompt.
169 ****************************************************************************/
171 static bool yesno(const char *p)
173 char ans[20];
174 printf("%s",p);
176 if (!fgets(ans,sizeof(ans)-1,stdin))
177 return(False);
179 if (*ans == 'y' || *ans == 'Y')
180 return(True);
182 return(False);
185 /****************************************************************************
186 Write to a local file with CR/LF->LF translation if appropriate. Return the
187 number taken from the buffer. This may not equal the number written.
188 ****************************************************************************/
190 static ssize_t writefile(int f, char *b, size_t n)
192 size_t i = 0;
194 if (n == 0) {
195 errno = EINVAL;
196 return -1;
199 if (!translation) {
200 return write(f,b,n);
203 do {
204 if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
205 b++;i++;
207 if (write(f, b, 1) != 1) {
208 break;
210 b++;
211 i++;
212 } while (i < n);
214 return (ssize_t)i;
217 /****************************************************************************
218 Read from a file with LF->CR/LF translation if appropriate. Return the
219 number read. read approx n bytes.
220 ****************************************************************************/
222 static int readfile(uint8_t *b, int n, FILE *f)
224 int i;
225 int c;
227 if (!translation)
228 return fread(b,1,n,f);
230 i = 0;
231 while (i < (n - 1)) {
232 if ((c = getc(f)) == EOF) {
233 break;
236 if (c == '\n') { /* change all LFs to CR/LF */
237 b[i++] = '\r';
240 b[i++] = c;
243 return(i);
246 struct push_state {
247 FILE *f;
248 off_t nread;
251 static size_t push_source(uint8_t *buf, size_t n, void *priv)
253 struct push_state *state = (struct push_state *)priv;
254 int result;
256 if (feof(state->f)) {
257 return 0;
260 result = readfile(buf, n, state->f);
261 state->nread += result;
262 return result;
265 /****************************************************************************
266 Send a message.
267 ****************************************************************************/
269 static void send_message(const char *username)
271 char buf[1600];
272 NTSTATUS status;
273 int i;
275 d_printf("Type your message, ending it with a Control-D\n");
277 i = 0;
278 while (i<sizeof(buf)-2) {
279 int c = fgetc(stdin);
280 if (c == EOF) {
281 break;
283 if (c == '\n') {
284 buf[i++] = '\r';
286 buf[i++] = c;
288 buf[i] = '\0';
290 status = cli_message(cli, desthost, username, buf);
291 if (!NT_STATUS_IS_OK(status)) {
292 d_fprintf(stderr, "cli_message returned %s\n",
293 nt_errstr(status));
297 /****************************************************************************
298 Check the space on a device.
299 ****************************************************************************/
301 static int do_dskattr(void)
303 uint64_t total, bsize, avail;
304 struct cli_state *targetcli = NULL;
305 char *targetpath = NULL;
306 TALLOC_CTX *ctx = talloc_tos();
307 NTSTATUS status;
309 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(), cli,
310 client_get_cur_dir(), &targetcli,
311 &targetpath);
312 if (!NT_STATUS_IS_OK(status)) {
313 d_printf("Error in dskattr: %s\n", nt_errstr(status));
314 return 1;
317 status = cli_disk_size(targetcli, targetpath, &bsize, &total, &avail);
318 if (!NT_STATUS_IS_OK(status)) {
319 d_printf("Error in dskattr: %s\n", nt_errstr(status));
320 return 1;
323 d_printf("\n\t\t%" PRIu64
324 " blocks of size %" PRIu64
325 ". %" PRIu64 " blocks available\n",
326 total, bsize, avail);
328 return 0;
331 /****************************************************************************
332 Show cd/pwd.
333 ****************************************************************************/
335 static int cmd_pwd(void)
337 d_printf("Current directory is %s",service);
338 d_printf("%s\n",client_get_cur_dir());
339 return 0;
342 /****************************************************************************
343 Ensure name has correct directory separators.
344 ****************************************************************************/
346 static void normalize_name(char *newdir)
348 if (!(cli->requested_posix_capabilities & CIFS_UNIX_POSIX_PATHNAMES_CAP)) {
349 string_replace(newdir,'/','\\');
353 /****************************************************************************
354 Local name cleanup before sending to server. SMB1 allows relative pathnames,
355 but SMB2 does not, so we need to resolve them locally.
356 ****************************************************************************/
358 char *client_clean_name(TALLOC_CTX *ctx, const char *name)
360 char *newname = NULL;
361 if (name == NULL) {
362 return NULL;
365 /* First ensure any path separators are correct. */
366 newname = talloc_strdup(ctx, name);
367 if (newname == NULL) {
368 return NULL;
370 normalize_name(newname);
372 /* Now remove any relative (..) path components. */
373 if (cli->requested_posix_capabilities & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
374 newname = unix_clean_name(ctx, newname);
375 } else {
376 newname = clean_name(ctx, newname);
378 if (newname == NULL) {
379 return NULL;
381 return newname;
384 /****************************************************************************
385 Change directory - inner section.
386 ****************************************************************************/
388 static int do_cd(const char *new_dir)
390 char *newdir = NULL;
391 char *saved_dir = NULL;
392 char *new_cd = NULL;
393 char *targetpath = NULL;
394 struct cli_state *targetcli = NULL;
395 SMB_STRUCT_STAT sbuf;
396 uint32_t attributes;
397 int ret = 1;
398 TALLOC_CTX *ctx = talloc_stackframe();
399 NTSTATUS status;
401 newdir = talloc_strdup(ctx, new_dir);
402 if (!newdir) {
403 TALLOC_FREE(ctx);
404 return 1;
407 normalize_name(newdir);
409 /* Save the current directory in case the new directory is invalid */
411 saved_dir = talloc_strdup(ctx, client_get_cur_dir());
412 if (!saved_dir) {
413 TALLOC_FREE(ctx);
414 return 1;
417 if (*newdir == CLI_DIRSEP_CHAR) {
418 client_set_cur_dir(newdir);
419 new_cd = newdir;
420 } else {
421 new_cd = talloc_asprintf(ctx, "%s%s",
422 client_get_cur_dir(),
423 newdir);
424 if (!new_cd) {
425 goto out;
429 /* Ensure cur_dir ends in a DIRSEP */
430 if ((new_cd[0] != '\0') && (*(new_cd+strlen(new_cd)-1) != CLI_DIRSEP_CHAR)) {
431 new_cd = talloc_asprintf_append(new_cd, "%s", CLI_DIRSEP_STR);
432 if (!new_cd) {
433 goto out;
436 client_set_cur_dir(new_cd);
438 new_cd = client_clean_name(ctx, new_cd);
439 client_set_cur_dir(new_cd);
441 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
442 cli, new_cd, &targetcli, &targetpath);
443 if (!NT_STATUS_IS_OK(status)) {
444 d_printf("cd %s: %s\n", new_cd, nt_errstr(status));
445 client_set_cur_dir(saved_dir);
446 goto out;
449 if (strequal(targetpath,CLI_DIRSEP_STR )) {
450 TALLOC_FREE(ctx);
451 return 0;
454 /* Use a trans2_qpathinfo to test directories for modern servers.
455 Except Win9x doesn't support the qpathinfo_basic() call..... */
457 if (smbXcli_conn_protocol(targetcli->conn) > PROTOCOL_LANMAN2 && !targetcli->win95) {
459 status = cli_qpathinfo_basic(targetcli, targetpath, &sbuf,
460 &attributes);
461 if (!NT_STATUS_IS_OK(status)) {
462 d_printf("cd %s: %s\n", new_cd, nt_errstr(status));
463 client_set_cur_dir(saved_dir);
464 goto out;
467 if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
468 d_printf("cd %s: not a directory\n", new_cd);
469 client_set_cur_dir(saved_dir);
470 goto out;
472 } else {
474 targetpath = talloc_asprintf(ctx,
475 "%s%s",
476 targetpath,
477 CLI_DIRSEP_STR );
478 if (!targetpath) {
479 client_set_cur_dir(saved_dir);
480 goto out;
482 targetpath = client_clean_name(ctx, targetpath);
483 if (!targetpath) {
484 client_set_cur_dir(saved_dir);
485 goto out;
488 status = cli_chkpath(targetcli, targetpath);
489 if (!NT_STATUS_IS_OK(status)) {
490 d_printf("cd %s: %s\n", new_cd, nt_errstr(status));
491 client_set_cur_dir(saved_dir);
492 goto out;
496 ret = 0;
498 out:
500 TALLOC_FREE(ctx);
501 return ret;
504 /****************************************************************************
505 Change directory.
506 ****************************************************************************/
508 static int cmd_cd(void)
510 char *buf = NULL;
511 int rc = 0;
513 if (next_token_talloc(talloc_tos(), &cmd_ptr, &buf,NULL)) {
514 rc = do_cd(buf);
515 } else {
516 d_printf("Current directory is %s\n",client_get_cur_dir());
519 return rc;
522 /****************************************************************************
523 Change directory.
524 ****************************************************************************/
526 static int cmd_cd_oneup(void)
528 return do_cd("..");
531 /*******************************************************************
532 Decide if a file should be operated on.
533 ********************************************************************/
535 static bool do_this_one(struct file_info *finfo)
537 if (!finfo->name) {
538 return false;
541 if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
542 return true;
545 if (*client_get_fileselection() &&
546 !mask_match(finfo->name,client_get_fileselection(),false)) {
547 DEBUG(3,("mask_match %s failed\n", finfo->name));
548 return false;
551 if (newer_than && finfo->mtime_ts.tv_sec < newer_than) {
552 DEBUG(3,("newer_than %s failed\n", finfo->name));
553 return false;
556 if ((archive_level==1 || archive_level==2) && !(finfo->mode & FILE_ATTRIBUTE_ARCHIVE)) {
557 DEBUG(3,("archive %s failed\n", finfo->name));
558 return false;
561 return true;
564 /****************************************************************************
565 Display info about a file.
566 ****************************************************************************/
568 static NTSTATUS display_finfo(struct cli_state *cli_state, struct file_info *finfo,
569 const char *dir)
571 time_t t;
572 TALLOC_CTX *ctx = talloc_tos();
573 NTSTATUS status = NT_STATUS_OK;
575 if (!do_this_one(finfo)) {
576 return NT_STATUS_OK;
579 t = finfo->mtime_ts.tv_sec; /* the time is assumed to be passed as GMT */
580 if (!showacls) {
581 d_printf(" %-30s%7.7s %8.0f %s",
582 finfo->name,
583 attrib_string(talloc_tos(), finfo->mode),
584 (double)finfo->size,
585 time_to_asc(t));
586 dir_total += finfo->size;
587 } else {
588 char *afname = NULL;
589 uint16_t fnum;
591 /* skip if this is . or .. */
592 if ( strequal(finfo->name,"..") || strequal(finfo->name,".") )
593 return NT_STATUS_OK;
594 /* create absolute filename for cli_ntcreate() FIXME */
595 afname = talloc_asprintf(ctx,
596 "%s%s%s",
597 dir,
598 CLI_DIRSEP_STR,
599 finfo->name);
600 if (!afname) {
601 return NT_STATUS_NO_MEMORY;
603 /* print file meta date header */
604 d_printf( "FILENAME:%s\n", finfo->name);
605 d_printf( "MODE:%s\n", attrib_string(talloc_tos(), finfo->mode));
606 d_printf( "SIZE:%.0f\n", (double)finfo->size);
607 d_printf( "MTIME:%s", time_to_asc(t));
608 status = cli_ntcreate(cli_state, afname, 0,
609 CREATE_ACCESS_READ, 0,
610 FILE_SHARE_READ|FILE_SHARE_WRITE,
611 FILE_OPEN, 0x0, 0x0, &fnum, NULL);
612 if (!NT_STATUS_IS_OK(status)) {
613 DEBUG( 0, ("display_finfo() Failed to open %s: %s\n",
614 afname, nt_errstr(status)));
615 } else {
616 struct security_descriptor *sd = NULL;
617 status = cli_query_secdesc(cli_state, fnum,
618 ctx, &sd);
619 if (!NT_STATUS_IS_OK(status)) {
620 DEBUG( 0, ("display_finfo() failed to "
621 "get security descriptor: %s",
622 nt_errstr(status)));
623 } else {
624 display_sec_desc(sd);
626 TALLOC_FREE(sd);
628 TALLOC_FREE(afname);
630 return status;
633 /****************************************************************************
634 Accumulate size of a file.
635 ****************************************************************************/
637 static NTSTATUS do_du(struct cli_state *cli_state, struct file_info *finfo,
638 const char *dir)
640 if (do_this_one(finfo)) {
641 dir_total += finfo->size;
643 return NT_STATUS_OK;
646 static bool do_list_recurse;
647 static bool do_list_dirs;
648 static char *do_list_queue = 0;
649 static long do_list_queue_size = 0;
650 static long do_list_queue_start = 0;
651 static long do_list_queue_end = 0;
652 static NTSTATUS (*do_list_fn)(struct cli_state *cli_state, struct file_info *,
653 const char *dir);
655 /****************************************************************************
656 Functions for do_list_queue.
657 ****************************************************************************/
660 * The do_list_queue is a NUL-separated list of strings stored in a
661 * char*. Since this is a FIFO, we keep track of the beginning and
662 * ending locations of the data in the queue. When we overflow, we
663 * double the size of the char*. When the start of the data passes
664 * the midpoint, we move everything back. This is logically more
665 * complex than a linked list, but easier from a memory management
666 * angle. In any memory error condition, do_list_queue is reset.
667 * Functions check to ensure that do_list_queue is non-NULL before
668 * accessing it.
671 static void reset_do_list_queue(void)
673 SAFE_FREE(do_list_queue);
674 do_list_queue_size = 0;
675 do_list_queue_start = 0;
676 do_list_queue_end = 0;
679 static void init_do_list_queue(void)
681 reset_do_list_queue();
682 do_list_queue_size = 1024;
683 do_list_queue = (char *)SMB_MALLOC(do_list_queue_size);
684 if (do_list_queue == 0) {
685 d_printf("malloc fail for size %d\n",
686 (int)do_list_queue_size);
687 reset_do_list_queue();
688 } else {
689 memset(do_list_queue, 0, do_list_queue_size);
693 static void adjust_do_list_queue(void)
696 * If the starting point of the queue is more than half way through,
697 * move everything toward the beginning.
700 if (do_list_queue == NULL) {
701 DEBUG(4,("do_list_queue is empty\n"));
702 do_list_queue_start = do_list_queue_end = 0;
703 return;
706 if (do_list_queue_start == do_list_queue_end) {
707 DEBUG(4,("do_list_queue is empty\n"));
708 do_list_queue_start = do_list_queue_end = 0;
709 *do_list_queue = '\0';
710 } else if (do_list_queue_start > (do_list_queue_size / 2)) {
711 DEBUG(4,("sliding do_list_queue backward\n"));
712 memmove(do_list_queue,
713 do_list_queue + do_list_queue_start,
714 do_list_queue_end - do_list_queue_start);
715 do_list_queue_end -= do_list_queue_start;
716 do_list_queue_start = 0;
720 static void add_to_do_list_queue(const char *entry)
722 long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
723 while (new_end > do_list_queue_size) {
724 do_list_queue_size *= 2;
725 DEBUG(4,("enlarging do_list_queue to %d\n",
726 (int)do_list_queue_size));
727 do_list_queue = (char *)SMB_REALLOC(do_list_queue, do_list_queue_size);
728 if (! do_list_queue) {
729 d_printf("failure enlarging do_list_queue to %d bytes\n",
730 (int)do_list_queue_size);
731 reset_do_list_queue();
732 } else {
733 memset(do_list_queue + do_list_queue_size / 2,
734 0, do_list_queue_size / 2);
737 if (do_list_queue) {
738 strlcpy_base(do_list_queue + do_list_queue_end,
739 entry, do_list_queue, do_list_queue_size);
740 do_list_queue_end = new_end;
741 DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
742 entry, (int)do_list_queue_start, (int)do_list_queue_end));
746 static char *do_list_queue_head(void)
748 return do_list_queue + do_list_queue_start;
751 static void remove_do_list_queue_head(void)
753 if (do_list_queue_end > do_list_queue_start) {
754 do_list_queue_start += strlen(do_list_queue_head()) + 1;
755 adjust_do_list_queue();
756 DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
757 (int)do_list_queue_start, (int)do_list_queue_end));
761 static int do_list_queue_empty(void)
763 return (! (do_list_queue && *do_list_queue));
766 /****************************************************************************
767 A helper for do_list.
768 ****************************************************************************/
770 static NTSTATUS do_list_helper(const char *mntpoint, struct file_info *f,
771 const char *mask, void *state)
773 struct cli_state *cli_state = (struct cli_state *)state;
774 TALLOC_CTX *ctx = talloc_tos();
775 char *dir = NULL;
776 char *dir_end = NULL;
777 NTSTATUS status = NT_STATUS_OK;
779 /* Work out the directory. */
780 dir = talloc_strdup(ctx, mask);
781 if (!dir) {
782 return NT_STATUS_NO_MEMORY;
784 if ((dir_end = strrchr(dir, CLI_DIRSEP_CHAR)) != NULL) {
785 *dir_end = '\0';
788 if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
789 if (do_list_dirs && do_this_one(f)) {
790 status = do_list_fn(cli_state, f, dir);
791 if (!NT_STATUS_IS_OK(status)) {
792 return status;
795 if (do_list_recurse &&
796 f->name &&
797 !strequal(f->name,".") &&
798 !strequal(f->name,"..")) {
799 char *mask2 = NULL;
800 char *p = NULL;
802 if (!f->name[0]) {
803 d_printf("Empty dir name returned. Possible server misconfiguration.\n");
804 TALLOC_FREE(dir);
805 return NT_STATUS_UNSUCCESSFUL;
808 mask2 = talloc_asprintf(ctx,
809 "%s%s",
810 mntpoint,
811 mask);
812 if (!mask2) {
813 TALLOC_FREE(dir);
814 return NT_STATUS_NO_MEMORY;
816 p = strrchr_m(mask2,CLI_DIRSEP_CHAR);
817 if (p) {
818 p[1] = 0;
819 } else {
820 mask2[0] = '\0';
822 mask2 = talloc_asprintf_append(mask2,
823 "%s%s*",
824 f->name,
825 CLI_DIRSEP_STR);
826 if (!mask2) {
827 TALLOC_FREE(dir);
828 return NT_STATUS_NO_MEMORY;
830 add_to_do_list_queue(mask2);
831 TALLOC_FREE(mask2);
833 TALLOC_FREE(dir);
834 return NT_STATUS_OK;
837 if (do_this_one(f)) {
838 status = do_list_fn(cli_state, f, dir);
840 TALLOC_FREE(dir);
841 return status;
844 /****************************************************************************
845 A wrapper around cli_list that adds recursion.
846 ****************************************************************************/
848 NTSTATUS do_list(const char *mask,
849 uint16_t attribute,
850 NTSTATUS (*fn)(struct cli_state *cli_state, struct file_info *,
851 const char *dir),
852 bool rec,
853 bool dirs)
855 static int in_do_list = 0;
856 TALLOC_CTX *ctx = talloc_tos();
857 struct cli_state *targetcli = NULL;
858 char *targetpath = NULL;
859 NTSTATUS ret_status = NT_STATUS_OK;
860 NTSTATUS status = NT_STATUS_OK;
862 if (in_do_list && rec) {
863 fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
864 exit(1);
867 in_do_list = 1;
869 do_list_recurse = rec;
870 do_list_dirs = dirs;
871 do_list_fn = fn;
873 if (rec) {
874 init_do_list_queue();
875 add_to_do_list_queue(mask);
877 while (!do_list_queue_empty()) {
879 * Need to copy head so that it doesn't become
880 * invalid inside the call to cli_list. This
881 * would happen if the list were expanded
882 * during the call.
883 * Fix from E. Jay Berkenbilt (ejb@ql.org)
885 char *head = talloc_strdup(ctx, do_list_queue_head());
887 if (!head) {
888 return NT_STATUS_NO_MEMORY;
891 /* check for dfs */
893 status = cli_resolve_path(ctx, "",
894 popt_get_cmdline_auth_info(),
895 cli, head, &targetcli, &targetpath);
896 if (!NT_STATUS_IS_OK(status)) {
897 d_printf("do_list: [%s] %s\n", head,
898 nt_errstr(status));
899 remove_do_list_queue_head();
900 continue;
903 status = cli_list(targetcli, targetpath, attribute,
904 do_list_helper, targetcli);
905 if (!NT_STATUS_IS_OK(status)) {
906 d_printf("%s listing %s\n",
907 nt_errstr(status), targetpath);
908 ret_status = status;
910 remove_do_list_queue_head();
911 if ((! do_list_queue_empty()) && (fn == display_finfo)) {
912 char *next_file = do_list_queue_head();
913 char *save_ch = 0;
914 if ((strlen(next_file) >= 2) &&
915 (next_file[strlen(next_file) - 1] == '*') &&
916 (next_file[strlen(next_file) - 2] == CLI_DIRSEP_CHAR)) {
917 save_ch = next_file +
918 strlen(next_file) - 2;
919 *save_ch = '\0';
920 if (showacls) {
921 /* cwd is only used if showacls is on */
922 client_set_cwd(next_file);
925 if (!showacls) /* don't disturbe the showacls output */
926 d_printf("\n%s\n",next_file);
927 if (save_ch) {
928 *save_ch = CLI_DIRSEP_CHAR;
931 TALLOC_FREE(head);
932 TALLOC_FREE(targetpath);
934 } else {
935 /* check for dfs */
936 status = cli_resolve_path(ctx, "",
937 popt_get_cmdline_auth_info(), cli, mask,
938 &targetcli, &targetpath);
939 if (NT_STATUS_IS_OK(status)) {
940 status = cli_list(targetcli, targetpath, attribute,
941 do_list_helper, targetcli);
942 if (!NT_STATUS_IS_OK(status)) {
943 d_printf("%s listing %s\n",
944 nt_errstr(status), targetpath);
945 ret_status = status;
947 TALLOC_FREE(targetpath);
948 } else {
949 d_printf("do_list: [%s] %s\n", mask, nt_errstr(status));
950 ret_status = status;
954 in_do_list = 0;
955 reset_do_list_queue();
956 return ret_status;
959 /****************************************************************************
960 Get a directory listing.
961 ****************************************************************************/
963 static int cmd_dir(void)
965 TALLOC_CTX *ctx = talloc_tos();
966 uint16_t attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
967 char *mask = NULL;
968 char *buf = NULL;
969 int rc = 1;
970 NTSTATUS status;
972 dir_total = 0;
973 mask = talloc_strdup(ctx, client_get_cur_dir());
974 if (!mask) {
975 return 1;
978 if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
979 normalize_name(buf);
980 if (*buf == CLI_DIRSEP_CHAR) {
981 mask = talloc_strdup(ctx, buf);
982 } else {
983 mask = talloc_asprintf_append(mask, "%s", buf);
985 } else {
986 mask = talloc_asprintf_append(mask, "*");
988 if (!mask) {
989 return 1;
992 mask = client_clean_name(ctx, mask);
993 if (mask == NULL) {
994 return 1;
997 if (showacls) {
998 /* cwd is only used if showacls is on */
999 client_set_cwd(client_get_cur_dir());
1002 status = do_list(mask, attribute, display_finfo, recurse, true);
1003 if (!NT_STATUS_IS_OK(status)) {
1004 return 1;
1007 rc = do_dskattr();
1009 DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
1011 return rc;
1014 /****************************************************************************
1015 Get a directory listing.
1016 ****************************************************************************/
1018 static int cmd_du(void)
1020 TALLOC_CTX *ctx = talloc_tos();
1021 uint16_t attribute = FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
1022 char *mask = NULL;
1023 char *buf = NULL;
1024 NTSTATUS status;
1025 int rc = 1;
1027 dir_total = 0;
1028 mask = talloc_strdup(ctx, client_get_cur_dir());
1029 if (!mask) {
1030 return 1;
1032 if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
1033 mask = talloc_asprintf_append(mask, "%s", CLI_DIRSEP_STR);
1034 if (!mask) {
1035 return 1;
1039 if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
1040 normalize_name(buf);
1041 if (*buf == CLI_DIRSEP_CHAR) {
1042 mask = talloc_strdup(ctx, buf);
1043 } else {
1044 mask = talloc_asprintf_append(mask, "%s", buf);
1046 } else {
1047 mask = talloc_strdup(ctx, "*");
1049 if (!mask) {
1050 return 1;
1053 mask = client_clean_name(ctx, mask);
1054 if (mask == NULL) {
1055 return 1;
1058 status = do_list(mask, attribute, do_du, recurse, true);
1059 if (!NT_STATUS_IS_OK(status)) {
1060 return 1;
1063 rc = do_dskattr();
1065 d_printf("Total number of bytes: %.0f\n", dir_total);
1067 return rc;
1070 static int cmd_echo(void)
1072 TALLOC_CTX *ctx = talloc_tos();
1073 char *num;
1074 char *data;
1075 NTSTATUS status;
1077 if (!next_token_talloc(ctx, &cmd_ptr, &num, NULL)
1078 || !next_token_talloc(ctx, &cmd_ptr, &data, NULL)) {
1079 d_printf("echo <num> <data>\n");
1080 return 1;
1083 status = cli_echo(cli, atoi(num), data_blob_const(data, strlen(data)));
1085 if (!NT_STATUS_IS_OK(status)) {
1086 d_printf("echo failed: %s\n", nt_errstr(status));
1087 return 1;
1090 return 0;
1093 /****************************************************************************
1094 Get a file from rname to lname
1095 ****************************************************************************/
1097 static NTSTATUS writefile_sink(char *buf, size_t n, void *priv)
1099 int *pfd = (int *)priv;
1100 ssize_t rc;
1102 rc = writefile(*pfd, buf, n);
1103 if (rc == -1) {
1104 return map_nt_error_from_unix(errno);
1106 return NT_STATUS_OK;
1109 static int do_get(const char *rname, const char *lname_in, bool reget)
1111 TALLOC_CTX *ctx = talloc_tos();
1112 int handle = 0;
1113 uint16_t fnum;
1114 bool newhandle = false;
1115 struct timespec tp_start;
1116 uint16_t attr;
1117 off_t size;
1118 off_t start = 0;
1119 off_t nread = 0;
1120 int rc = 0;
1121 struct cli_state *targetcli = NULL;
1122 char *targetname = NULL;
1123 char *lname = NULL;
1124 NTSTATUS status;
1126 lname = talloc_strdup(ctx, lname_in);
1127 if (!lname) {
1128 return 1;
1131 if (lowercase) {
1132 if (!strlower_m(lname)) {
1133 d_printf("strlower_m %s failed\n", lname);
1134 return 1;
1138 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
1139 cli, rname, &targetcli, &targetname);
1140 if (!NT_STATUS_IS_OK(status)) {
1141 d_printf("Failed to open %s: %s\n", rname, nt_errstr(status));
1142 return 1;
1145 clock_gettime_mono(&tp_start);
1147 status = cli_open(targetcli, targetname, O_RDONLY, DENY_NONE, &fnum);
1148 if (!NT_STATUS_IS_OK(status)) {
1149 d_printf("%s opening remote file %s\n", nt_errstr(status),
1150 rname);
1151 return 1;
1154 if(!strcmp(lname,"-")) {
1155 handle = fileno(stdout);
1156 } else {
1157 if (reget) {
1158 handle = open(lname, O_WRONLY|O_CREAT, 0644);
1159 if (handle >= 0) {
1160 start = lseek(handle, 0, SEEK_END);
1161 if (start == -1) {
1162 d_printf("Error seeking local file\n");
1163 return 1;
1166 } else {
1167 handle = open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
1169 newhandle = true;
1171 if (handle < 0) {
1172 d_printf("Error opening local file %s\n",lname);
1173 return 1;
1177 status = cli_qfileinfo_basic(targetcli, fnum, &attr, &size, NULL, NULL,
1178 NULL, NULL, NULL);
1179 if (!NT_STATUS_IS_OK(status)) {
1180 status = cli_getattrE(targetcli, fnum, &attr, &size, NULL, NULL,
1181 NULL);
1182 if(!NT_STATUS_IS_OK(status)) {
1183 d_printf("getattrib: %s\n", nt_errstr(status));
1184 return 1;
1188 DEBUG(1,("getting file %s of size %.0f as %s ",
1189 rname, (double)size, lname));
1191 status = cli_pull(targetcli, fnum, start, size, io_bufsize,
1192 writefile_sink, (void *)&handle, &nread);
1193 if (!NT_STATUS_IS_OK(status)) {
1194 d_fprintf(stderr, "parallel_read returned %s\n",
1195 nt_errstr(status));
1196 cli_close(targetcli, fnum);
1197 return 1;
1200 status = cli_close(targetcli, fnum);
1201 if (!NT_STATUS_IS_OK(status)) {
1202 d_printf("Error %s closing remote file\n", nt_errstr(status));
1203 rc = 1;
1206 if (newhandle) {
1207 close(handle);
1210 if (archive_level >= 2 && (attr & FILE_ATTRIBUTE_ARCHIVE)) {
1211 cli_setatr(cli, rname, attr & ~(uint16_t)FILE_ATTRIBUTE_ARCHIVE, 0);
1215 struct timespec tp_end;
1216 int this_time;
1218 clock_gettime_mono(&tp_end);
1219 this_time = nsec_time_diff(&tp_end,&tp_start)/1000000;
1220 get_total_time_ms += this_time;
1221 get_total_size += nread;
1223 DEBUG(1,("(%3.1f KiloBytes/sec) (average %3.1f KiloBytes/sec)\n",
1224 nread / (1.024*this_time + 1.0e-4),
1225 get_total_size / (1.024*get_total_time_ms)));
1228 TALLOC_FREE(targetname);
1229 return rc;
1232 /****************************************************************************
1233 Get a file.
1234 ****************************************************************************/
1236 static int cmd_get(void)
1238 TALLOC_CTX *ctx = talloc_tos();
1239 char *lname = NULL;
1240 char *rname = NULL;
1241 char *fname = NULL;
1243 rname = talloc_strdup(ctx, client_get_cur_dir());
1244 if (!rname) {
1245 return 1;
1248 if (!next_token_talloc(ctx, &cmd_ptr,&fname,NULL)) {
1249 d_printf("get <filename> [localname]\n");
1250 return 1;
1252 rname = talloc_asprintf_append(rname, "%s", fname);
1253 if (!rname) {
1254 return 1;
1256 rname = client_clean_name(ctx, rname);
1257 if (!rname) {
1258 return 1;
1261 next_token_talloc(ctx, &cmd_ptr,&lname,NULL);
1262 if (!lname) {
1263 lname = fname;
1266 return do_get(rname, lname, false);
1269 /****************************************************************************
1270 Do an mget operation on one file.
1271 ****************************************************************************/
1273 static NTSTATUS do_mget(struct cli_state *cli_state, struct file_info *finfo,
1274 const char *dir)
1276 TALLOC_CTX *ctx = talloc_tos();
1277 NTSTATUS status = NT_STATUS_OK;
1278 char *rname = NULL;
1279 char *quest = NULL;
1280 char *saved_curdir = NULL;
1281 char *mget_mask = NULL;
1282 char *new_cd = NULL;
1284 if (!finfo->name) {
1285 return NT_STATUS_OK;
1288 if (strequal(finfo->name,".") || strequal(finfo->name,".."))
1289 return NT_STATUS_OK;
1291 if (abort_mget) {
1292 d_printf("mget aborted\n");
1293 return NT_STATUS_UNSUCCESSFUL;
1296 if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
1297 if (asprintf(&quest,
1298 "Get directory %s? ",finfo->name) < 0) {
1299 return NT_STATUS_NO_MEMORY;
1301 } else {
1302 if (asprintf(&quest,
1303 "Get file %s? ",finfo->name) < 0) {
1304 return NT_STATUS_NO_MEMORY;
1308 if (prompt && !yesno(quest)) {
1309 SAFE_FREE(quest);
1310 return NT_STATUS_OK;
1312 SAFE_FREE(quest);
1314 if (!(finfo->mode & FILE_ATTRIBUTE_DIRECTORY)) {
1315 rname = talloc_asprintf(ctx,
1316 "%s%s",
1317 client_get_cur_dir(),
1318 finfo->name);
1319 if (!rname) {
1320 return NT_STATUS_NO_MEMORY;
1322 rname = client_clean_name(ctx, rname);
1323 if (rname == NULL) {
1324 return NT_STATUS_NO_MEMORY;
1326 do_get(rname, finfo->name, false);
1327 TALLOC_FREE(rname);
1328 return NT_STATUS_OK;
1331 /* handle directories */
1332 saved_curdir = talloc_strdup(ctx, client_get_cur_dir());
1333 if (!saved_curdir) {
1334 return NT_STATUS_NO_MEMORY;
1337 new_cd = talloc_asprintf(ctx,
1338 "%s%s%s",
1339 client_get_cur_dir(),
1340 finfo->name,
1341 CLI_DIRSEP_STR);
1342 if (!new_cd) {
1343 return NT_STATUS_NO_MEMORY;
1345 new_cd = client_clean_name(ctx, new_cd);
1346 if (new_cd == NULL) {
1347 return NT_STATUS_NO_MEMORY;
1349 client_set_cur_dir(new_cd);
1351 string_replace(finfo->name,'\\','/');
1352 if (lowercase) {
1353 if (!strlower_m(finfo->name)) {
1354 return NT_STATUS_INVALID_PARAMETER;
1358 if (!directory_exist(finfo->name) &&
1359 mkdir(finfo->name,0777) != 0) {
1360 d_printf("failed to create directory %s\n",finfo->name);
1361 client_set_cur_dir(saved_curdir);
1362 return map_nt_error_from_unix(errno);
1365 if (chdir(finfo->name) != 0) {
1366 d_printf("failed to chdir to directory %s\n",finfo->name);
1367 client_set_cur_dir(saved_curdir);
1368 return map_nt_error_from_unix(errno);
1371 mget_mask = talloc_asprintf(ctx,
1372 "%s*",
1373 client_get_cur_dir());
1375 if (!mget_mask) {
1376 return NT_STATUS_NO_MEMORY;
1379 mget_mask = client_clean_name(ctx, mget_mask);
1380 if (mget_mask == NULL) {
1381 return NT_STATUS_NO_MEMORY;
1383 status = do_list(mget_mask,
1384 (FILE_ATTRIBUTE_SYSTEM
1385 | FILE_ATTRIBUTE_HIDDEN
1386 | FILE_ATTRIBUTE_DIRECTORY),
1387 do_mget, false, true);
1388 if (!NT_STATUS_IS_OK(status)
1389 && !NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1391 * Ignore access denied errors to ensure all permitted files are
1392 * pulled down.
1394 return status;
1397 if (chdir("..") == -1) {
1398 d_printf("do_mget: failed to chdir to .. (error %s)\n",
1399 strerror(errno) );
1400 return map_nt_error_from_unix(errno);
1402 client_set_cur_dir(saved_curdir);
1403 TALLOC_FREE(mget_mask);
1404 TALLOC_FREE(saved_curdir);
1405 TALLOC_FREE(new_cd);
1406 return NT_STATUS_OK;
1409 /****************************************************************************
1410 View the file using the pager.
1411 ****************************************************************************/
1413 static int cmd_more(void)
1415 TALLOC_CTX *ctx = talloc_tos();
1416 char *rname = NULL;
1417 char *fname = NULL;
1418 char *lname = NULL;
1419 char *pager_cmd = NULL;
1420 const char *pager;
1421 int fd;
1422 int rc = 0;
1423 mode_t mask;
1425 rname = talloc_strdup(ctx, client_get_cur_dir());
1426 if (!rname) {
1427 return 1;
1430 lname = talloc_asprintf(ctx, "%s/smbmore.XXXXXX",tmpdir());
1431 if (!lname) {
1432 return 1;
1434 mask = umask(S_IRWXO | S_IRWXG);
1435 fd = mkstemp(lname);
1436 umask(mask);
1437 if (fd == -1) {
1438 d_printf("failed to create temporary file for more\n");
1439 return 1;
1441 close(fd);
1443 if (!next_token_talloc(ctx, &cmd_ptr,&fname,NULL)) {
1444 d_printf("more <filename>\n");
1445 unlink(lname);
1446 return 1;
1448 rname = talloc_asprintf_append(rname, "%s", fname);
1449 if (!rname) {
1450 return 1;
1452 rname = client_clean_name(ctx,rname);
1453 if (!rname) {
1454 return 1;
1457 rc = do_get(rname, lname, false);
1459 pager=getenv("PAGER");
1461 pager_cmd = talloc_asprintf(ctx,
1462 "%s %s",
1463 (pager? pager:PAGER),
1464 lname);
1465 if (!pager_cmd) {
1466 return 1;
1468 if (system(pager_cmd) == -1) {
1469 d_printf("system command '%s' returned -1\n",
1470 pager_cmd);
1472 unlink(lname);
1474 return rc;
1477 /****************************************************************************
1478 Do a mget command.
1479 ****************************************************************************/
1481 static int cmd_mget(void)
1483 TALLOC_CTX *ctx = talloc_tos();
1484 uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
1485 char *mget_mask = NULL;
1486 char *buf = NULL;
1487 NTSTATUS status = NT_STATUS_OK;
1489 if (recurse) {
1490 attribute |= FILE_ATTRIBUTE_DIRECTORY;
1493 abort_mget = false;
1495 while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
1497 mget_mask = talloc_strdup(ctx, client_get_cur_dir());
1498 if (!mget_mask) {
1499 return 1;
1501 if (*buf == CLI_DIRSEP_CHAR) {
1502 mget_mask = talloc_strdup(ctx, buf);
1503 } else {
1504 mget_mask = talloc_asprintf_append(mget_mask,
1505 "%s", buf);
1507 if (!mget_mask) {
1508 return 1;
1510 mget_mask = client_clean_name(ctx, mget_mask);
1511 if (mget_mask == NULL) {
1512 return 1;
1514 status = do_list(mget_mask, attribute, do_mget, false, true);
1515 if (!NT_STATUS_IS_OK(status)) {
1516 return 1;
1520 if (mget_mask == NULL) {
1521 d_printf("nothing to mget\n");
1522 return 0;
1525 if (!*mget_mask) {
1526 mget_mask = talloc_asprintf(ctx,
1527 "%s*",
1528 client_get_cur_dir());
1529 if (!mget_mask) {
1530 return 1;
1532 mget_mask = client_clean_name(ctx, mget_mask);
1533 if (mget_mask == NULL) {
1534 return 1;
1536 status = do_list(mget_mask, attribute, do_mget, false, true);
1537 if (!NT_STATUS_IS_OK(status)) {
1538 return 1;
1542 return 0;
1545 /****************************************************************************
1546 Make a directory of name "name".
1547 ****************************************************************************/
1549 static bool do_mkdir(const char *name)
1551 TALLOC_CTX *ctx = talloc_tos();
1552 struct cli_state *targetcli;
1553 char *targetname = NULL;
1554 NTSTATUS status;
1556 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
1557 cli, name, &targetcli, &targetname);
1558 if (!NT_STATUS_IS_OK(status)) {
1559 d_printf("mkdir %s: %s\n", name, nt_errstr(status));
1560 return false;
1563 status = cli_mkdir(targetcli, targetname);
1564 if (!NT_STATUS_IS_OK(status)) {
1565 d_printf("%s making remote directory %s\n",
1566 nt_errstr(status),name);
1567 return false;
1570 return true;
1573 /****************************************************************************
1574 Show 8.3 name of a file.
1575 ****************************************************************************/
1577 static bool do_altname(const char *name)
1579 fstring altname;
1580 NTSTATUS status;
1582 status = cli_qpathinfo_alt_name(cli, name, altname);
1583 if (!NT_STATUS_IS_OK(status)) {
1584 d_printf("%s getting alt name for %s\n",
1585 nt_errstr(status),name);
1586 return false;
1588 d_printf("%s\n", altname);
1590 return true;
1593 /****************************************************************************
1594 Exit client.
1595 ****************************************************************************/
1597 static int cmd_quit(void)
1599 cli_shutdown(cli);
1600 popt_free_cmdline_auth_info();
1601 exit(0);
1602 /* NOTREACHED */
1603 return 0;
1606 /****************************************************************************
1607 Make a directory.
1608 ****************************************************************************/
1610 static int cmd_mkdir(void)
1612 TALLOC_CTX *ctx = talloc_tos();
1613 char *mask = NULL;
1614 char *buf = NULL;
1615 NTSTATUS status;
1617 mask = talloc_strdup(ctx, client_get_cur_dir());
1618 if (!mask) {
1619 return 1;
1622 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
1623 if (!recurse) {
1624 d_printf("mkdir <dirname>\n");
1626 return 1;
1628 mask = talloc_asprintf_append(mask, "%s", buf);
1629 if (!mask) {
1630 return 1;
1632 mask = client_clean_name(ctx, mask);
1633 if (mask == NULL) {
1634 return 1;
1637 if (recurse) {
1638 char *ddir = NULL;
1639 char *ddir2 = NULL;
1640 struct cli_state *targetcli;
1641 char *targetname = NULL;
1642 char *p = NULL;
1643 char *saveptr;
1645 ddir2 = talloc_strdup(ctx, "");
1646 if (!ddir2) {
1647 return 1;
1650 status = cli_resolve_path(ctx, "",
1651 popt_get_cmdline_auth_info(), cli, mask,
1652 &targetcli, &targetname);
1653 if (!NT_STATUS_IS_OK(status)) {
1654 return 1;
1657 ddir = talloc_strdup(ctx, targetname);
1658 if (!ddir) {
1659 return 1;
1661 trim_char(ddir,'.','\0');
1662 p = strtok_r(ddir, "/\\", &saveptr);
1663 while (p) {
1664 ddir2 = talloc_asprintf_append(ddir2, "%s", p);
1665 if (!ddir2) {
1666 return 1;
1668 if (!NT_STATUS_IS_OK(cli_chkpath(targetcli, ddir2))) {
1669 do_mkdir(ddir2);
1671 ddir2 = talloc_asprintf_append(ddir2, "%s", CLI_DIRSEP_STR);
1672 if (!ddir2) {
1673 return 1;
1675 p = strtok_r(NULL, "/\\", &saveptr);
1677 } else {
1678 do_mkdir(mask);
1681 return 0;
1684 /****************************************************************************
1685 Show alt name.
1686 ****************************************************************************/
1688 static int cmd_altname(void)
1690 TALLOC_CTX *ctx = talloc_tos();
1691 char *name;
1692 char *buf;
1694 name = talloc_strdup(ctx, client_get_cur_dir());
1695 if (!name) {
1696 return 1;
1699 if (!next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
1700 d_printf("altname <file>\n");
1701 return 1;
1703 name = talloc_asprintf_append(name, "%s", buf);
1704 if (!name) {
1705 return 1;
1707 name = client_clean_name(ctx, name);
1708 if (name == NULL) {
1709 return 1;
1711 do_altname(name);
1712 return 0;
1715 static char *attr_str(TALLOC_CTX *mem_ctx, uint16_t mode)
1717 char *attrs = talloc_zero_array(mem_ctx, char, 17);
1718 int i = 0;
1720 if (!(mode & FILE_ATTRIBUTE_NORMAL)) {
1721 if (mode & FILE_ATTRIBUTE_ENCRYPTED) {
1722 attrs[i++] = 'E';
1724 if (mode & FILE_ATTRIBUTE_NONINDEXED) {
1725 attrs[i++] = 'N';
1727 if (mode & FILE_ATTRIBUTE_OFFLINE) {
1728 attrs[i++] = 'O';
1730 if (mode & FILE_ATTRIBUTE_COMPRESSED) {
1731 attrs[i++] = 'C';
1733 if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
1734 attrs[i++] = 'r';
1736 if (mode & FILE_ATTRIBUTE_SPARSE) {
1737 attrs[i++] = 's';
1739 if (mode & FILE_ATTRIBUTE_TEMPORARY) {
1740 attrs[i++] = 'T';
1742 if (mode & FILE_ATTRIBUTE_NORMAL) {
1743 attrs[i++] = 'N';
1745 if (mode & FILE_ATTRIBUTE_READONLY) {
1746 attrs[i++] = 'R';
1748 if (mode & FILE_ATTRIBUTE_HIDDEN) {
1749 attrs[i++] = 'H';
1751 if (mode & FILE_ATTRIBUTE_SYSTEM) {
1752 attrs[i++] = 'S';
1754 if (mode & FILE_ATTRIBUTE_DIRECTORY) {
1755 attrs[i++] = 'D';
1757 if (mode & FILE_ATTRIBUTE_ARCHIVE) {
1758 attrs[i++] = 'A';
1761 return attrs;
1764 /****************************************************************************
1765 Show all info we can get
1766 ****************************************************************************/
1768 static int do_allinfo(const char *name)
1770 fstring altname;
1771 struct timespec b_time, a_time, m_time, c_time;
1772 off_t size;
1773 uint16_t mode;
1774 NTTIME tmp;
1775 uint16_t fnum;
1776 unsigned int num_streams;
1777 struct stream_struct *streams;
1778 int num_snapshots;
1779 char **snapshots = NULL;
1780 unsigned int i;
1781 NTSTATUS status;
1783 status = cli_qpathinfo_alt_name(cli, name, altname);
1784 if (!NT_STATUS_IS_OK(status)) {
1785 d_printf("%s getting alt name for %s\n", nt_errstr(status),
1786 name);
1788 * Ignore not supported or not implemented, it does not
1789 * hurt if we can't list alternate names.
1791 if (NT_STATUS_EQUAL(status, NT_STATUS_NOT_SUPPORTED) ||
1792 NT_STATUS_EQUAL(status, NT_STATUS_NOT_IMPLEMENTED)) {
1793 altname[0] = '\0';
1794 } else {
1795 return false;
1798 d_printf("altname: %s\n", altname);
1800 status = cli_qpathinfo3(cli, name, &b_time, &a_time, &m_time, &c_time,
1801 &size, &mode, NULL);
1802 if (!NT_STATUS_IS_OK(status)) {
1803 d_printf("%s getting pathinfo for %s\n", nt_errstr(status),
1804 name);
1805 return false;
1808 tmp = unix_timespec_to_nt_time(b_time);
1809 d_printf("create_time: %s\n", nt_time_string(talloc_tos(), tmp));
1811 tmp = unix_timespec_to_nt_time(a_time);
1812 d_printf("access_time: %s\n", nt_time_string(talloc_tos(), tmp));
1814 tmp = unix_timespec_to_nt_time(m_time);
1815 d_printf("write_time: %s\n", nt_time_string(talloc_tos(), tmp));
1817 tmp = unix_timespec_to_nt_time(c_time);
1818 d_printf("change_time: %s\n", nt_time_string(talloc_tos(), tmp));
1820 d_printf("attributes: %s (%x)\n", attr_str(talloc_tos(), mode), mode);
1822 status = cli_qpathinfo_streams(cli, name, talloc_tos(), &num_streams,
1823 &streams);
1824 if (!NT_STATUS_IS_OK(status)) {
1825 d_printf("%s getting streams for %s\n", nt_errstr(status),
1826 name);
1827 return false;
1830 for (i=0; i<num_streams; i++) {
1831 d_printf("stream: [%s], %lld bytes\n", streams[i].name,
1832 (unsigned long long)streams[i].size);
1835 if (mode & FILE_ATTRIBUTE_REPARSE_POINT) {
1836 char *subst, *print;
1837 uint32_t flags;
1839 status = cli_readlink(cli, name, talloc_tos(), &subst, &print,
1840 &flags);
1841 if (!NT_STATUS_IS_OK(status)) {
1842 d_fprintf(stderr, "cli_readlink returned %s\n",
1843 nt_errstr(status));
1844 } else {
1845 d_printf("symlink: subst=[%s], print=[%s], flags=%x\n",
1846 subst, print, flags);
1847 TALLOC_FREE(subst);
1848 TALLOC_FREE(print);
1852 status = cli_ntcreate(cli, name, 0,
1853 SEC_FILE_READ_DATA | SEC_FILE_READ_ATTRIBUTE |
1854 SEC_STD_SYNCHRONIZE, 0,
1855 FILE_SHARE_READ|FILE_SHARE_WRITE
1856 |FILE_SHARE_DELETE,
1857 FILE_OPEN, 0x0, 0x0, &fnum, NULL);
1858 if (!NT_STATUS_IS_OK(status)) {
1860 * Ignore failure, it does not hurt if we can't list
1861 * snapshots
1863 return 0;
1866 * In order to get shadow copy data over SMB1 we
1867 * must call twice, once with 'get_names = false'
1868 * to get the size, then again with 'get_names = true'
1869 * to get the data or a Windows server fails to return
1870 * valid info. Samba doesn't have this bug. JRA.
1873 status = cli_shadow_copy_data(talloc_tos(), cli, fnum,
1874 false, &snapshots, &num_snapshots);
1875 if (!NT_STATUS_IS_OK(status)) {
1876 cli_close(cli, fnum);
1877 return 0;
1879 status = cli_shadow_copy_data(talloc_tos(), cli, fnum,
1880 true, &snapshots, &num_snapshots);
1881 if (!NT_STATUS_IS_OK(status)) {
1882 cli_close(cli, fnum);
1883 return 0;
1886 for (i=0; i<num_snapshots; i++) {
1887 char *snap_name;
1889 d_printf("%s\n", snapshots[i]);
1890 snap_name = talloc_asprintf(talloc_tos(), "%s%s",
1891 snapshots[i], name);
1892 status = cli_qpathinfo3(cli, snap_name, &b_time, &a_time,
1893 &m_time, &c_time, &size,
1894 NULL, NULL);
1895 if (!NT_STATUS_IS_OK(status)) {
1896 d_fprintf(stderr, "pathinfo(%s) failed: %s\n",
1897 snap_name, nt_errstr(status));
1898 TALLOC_FREE(snap_name);
1899 continue;
1901 tmp = unix_timespec_to_nt_time(b_time);
1902 d_printf("create_time: %s\n", nt_time_string(talloc_tos(), tmp));
1903 tmp = unix_timespec_to_nt_time(a_time);
1904 d_printf("access_time: %s\n", nt_time_string(talloc_tos(), tmp));
1905 tmp =unix_timespec_to_nt_time(m_time);
1906 d_printf("write_time: %s\n", nt_time_string(talloc_tos(), tmp));
1907 tmp = unix_timespec_to_nt_time(c_time);
1908 d_printf("change_time: %s\n", nt_time_string(talloc_tos(), tmp));
1909 d_printf("size: %d\n", (int)size);
1912 TALLOC_FREE(snapshots);
1913 cli_close(cli, fnum);
1915 return 0;
1918 /****************************************************************************
1919 Show all info we can get
1920 ****************************************************************************/
1922 static int cmd_allinfo(void)
1924 TALLOC_CTX *ctx = talloc_tos();
1925 char *name;
1926 char *buf;
1928 name = talloc_strdup(ctx, client_get_cur_dir());
1929 if (!name) {
1930 return 1;
1933 if (!next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
1934 d_printf("allinfo <file>\n");
1935 return 1;
1937 name = talloc_asprintf_append(name, "%s", buf);
1938 if (!name) {
1939 return 1;
1941 name = client_clean_name(ctx, name);
1942 if (name == NULL) {
1943 return 1;
1945 do_allinfo(name);
1947 return 0;
1950 /****************************************************************************
1951 Put a single file.
1952 ****************************************************************************/
1954 static int do_put(const char *rname, const char *lname, bool reput)
1956 TALLOC_CTX *ctx = talloc_tos();
1957 uint16_t fnum;
1958 FILE *f;
1959 off_t start = 0;
1960 int rc = 0;
1961 struct timespec tp_start;
1962 struct cli_state *targetcli;
1963 char *targetname = NULL;
1964 struct push_state state;
1965 NTSTATUS status;
1967 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
1968 cli, rname, &targetcli, &targetname);
1969 if (!NT_STATUS_IS_OK(status)) {
1970 d_printf("Failed to open %s: %s\n", rname, nt_errstr(status));
1971 return 1;
1974 clock_gettime_mono(&tp_start);
1976 if (reput) {
1977 status = cli_open(targetcli, targetname, O_RDWR|O_CREAT, DENY_NONE, &fnum);
1978 if (NT_STATUS_IS_OK(status)) {
1979 if (!NT_STATUS_IS_OK(status = cli_qfileinfo_basic(
1980 targetcli, fnum, NULL,
1981 &start, NULL, NULL,
1982 NULL, NULL, NULL)) &&
1983 !NT_STATUS_IS_OK(status = cli_getattrE(
1984 targetcli, fnum, NULL,
1985 &start, NULL, NULL,
1986 NULL))) {
1987 d_printf("getattrib: %s\n", nt_errstr(status));
1988 return 1;
1991 } else {
1992 status = cli_open(targetcli, targetname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE, &fnum);
1995 if (!NT_STATUS_IS_OK(status)) {
1996 d_printf("%s opening remote file %s\n", nt_errstr(status),
1997 rname);
1998 return 1;
2001 /* allow files to be piped into smbclient
2002 jdblair 24.jun.98
2004 Note that in this case this function will exit(0) rather
2005 than returning. */
2006 if (!strcmp(lname, "-")) {
2007 f = stdin;
2008 /* size of file is not known */
2009 } else {
2010 f = fopen(lname, "r");
2011 if (f && reput) {
2012 if (fseek(f, start, SEEK_SET) == -1) {
2013 d_printf("Error seeking local file\n");
2014 fclose(f);
2015 return 1;
2020 if (!f) {
2021 d_printf("Error opening local file %s\n",lname);
2022 return 1;
2025 DEBUG(1,("putting file %s as %s ",lname,
2026 rname));
2028 setvbuf(f, NULL, _IOFBF, io_bufsize);
2030 state.f = f;
2031 state.nread = 0;
2033 status = cli_push(targetcli, fnum, 0, 0, io_bufsize, push_source,
2034 &state);
2035 if (!NT_STATUS_IS_OK(status)) {
2036 d_fprintf(stderr, "cli_push returned %s\n", nt_errstr(status));
2037 rc = 1;
2040 status = cli_close(targetcli, fnum);
2041 if (!NT_STATUS_IS_OK(status)) {
2042 d_printf("%s closing remote file %s\n", nt_errstr(status),
2043 rname);
2044 if (f != stdin) {
2045 fclose(f);
2047 return 1;
2050 if (f != stdin) {
2051 fclose(f);
2055 struct timespec tp_end;
2056 int this_time;
2058 clock_gettime_mono(&tp_end);
2059 this_time = nsec_time_diff(&tp_end,&tp_start)/1000000;
2060 put_total_time_ms += this_time;
2061 put_total_size += state.nread;
2063 DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
2064 state.nread / (1.024*this_time + 1.0e-4),
2065 put_total_size / (1.024*put_total_time_ms)));
2068 if (f == stdin) {
2069 cli_shutdown(cli);
2070 popt_free_cmdline_auth_info();
2071 exit(rc);
2074 return rc;
2077 /****************************************************************************
2078 Put a file.
2079 ****************************************************************************/
2081 static int cmd_put(void)
2083 TALLOC_CTX *ctx = talloc_tos();
2084 char *lname;
2085 char *rname;
2086 char *buf;
2088 rname = talloc_strdup(ctx, client_get_cur_dir());
2089 if (!rname) {
2090 return 1;
2093 if (!next_token_talloc(ctx, &cmd_ptr,&lname,NULL)) {
2094 d_printf("put <filename>\n");
2095 return 1;
2098 if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2099 rname = talloc_asprintf_append(rname, "%s", buf);
2100 } else {
2101 rname = talloc_asprintf_append(rname, "%s", lname);
2103 if (!rname) {
2104 return 1;
2107 rname = client_clean_name(ctx, rname);
2108 if (!rname) {
2109 return 1;
2113 SMB_STRUCT_STAT st;
2114 /* allow '-' to represent stdin
2115 jdblair, 24.jun.98 */
2116 if (!file_exist_stat(lname, &st, false) &&
2117 (strcmp(lname,"-"))) {
2118 d_printf("%s does not exist\n",lname);
2119 return 1;
2123 return do_put(rname, lname, false);
2126 /*************************************
2127 File list structure.
2128 *************************************/
2130 static struct file_list {
2131 struct file_list *prev, *next;
2132 char *file_path;
2133 bool isdir;
2134 } *file_list;
2136 /****************************************************************************
2137 Free a file_list structure.
2138 ****************************************************************************/
2140 static void free_file_list (struct file_list *l_head)
2142 struct file_list *list, *next;
2144 for (list = l_head; list; list = next) {
2145 next = list->next;
2146 DLIST_REMOVE(l_head, list);
2147 TALLOC_FREE(list);
2151 /****************************************************************************
2152 Seek in a directory/file list until you get something that doesn't start with
2153 the specified name.
2154 ****************************************************************************/
2156 static bool seek_list(struct file_list *list, char *name)
2158 while (list) {
2159 trim_string(list->file_path,"./","\n");
2160 if (strncmp(list->file_path, name, strlen(name)) != 0) {
2161 return true;
2163 list = list->next;
2166 return false;
2169 /****************************************************************************
2170 Set the file selection mask.
2171 ****************************************************************************/
2173 static int cmd_select(void)
2175 TALLOC_CTX *ctx = talloc_tos();
2176 char *new_fs = NULL;
2177 next_token_talloc(ctx, &cmd_ptr,&new_fs,NULL)
2179 if (new_fs) {
2180 client_set_fileselection(new_fs);
2181 } else {
2182 client_set_fileselection("");
2184 return 0;
2187 /****************************************************************************
2188 Recursive file matching function act as find
2189 match must be always set to true when calling this function
2190 ****************************************************************************/
2192 static int file_find(TALLOC_CTX *ctx,
2193 struct file_list **list,
2194 const char *directory,
2195 const char *expression,
2196 bool match)
2198 DIR *dir;
2199 struct file_list *entry;
2200 struct stat statbuf;
2201 int ret;
2202 char *path;
2203 bool isdir;
2204 const char *dname;
2206 dir = opendir(directory);
2207 if (!dir)
2208 return -1;
2210 while ((dname = readdirname(dir))) {
2211 if (!strcmp("..", dname))
2212 continue;
2213 if (!strcmp(".", dname))
2214 continue;
2216 path = talloc_asprintf(ctx, "%s/%s", directory, dname);
2217 if (path == NULL) {
2218 continue;
2221 isdir = false;
2222 if (!match || !gen_fnmatch(expression, dname)) {
2223 if (recurse) {
2224 ret = stat(path, &statbuf);
2225 if (ret == 0) {
2226 if (S_ISDIR(statbuf.st_mode)) {
2227 isdir = true;
2228 ret = file_find(ctx,
2229 list,
2230 path,
2231 expression,
2232 false);
2234 } else {
2235 d_printf("file_find: cannot stat file %s\n", path);
2238 if (ret == -1) {
2239 TALLOC_FREE(path);
2240 closedir(dir);
2241 return -1;
2244 entry = talloc_zero(ctx, struct file_list);
2245 if (!entry) {
2246 d_printf("Out of memory in file_find\n");
2247 closedir(dir);
2248 return -1;
2250 entry->file_path = talloc_move(entry, &path);
2251 entry->isdir = isdir;
2252 DLIST_ADD(*list, entry);
2253 } else {
2254 TALLOC_FREE(path);
2258 closedir(dir);
2259 return 0;
2262 /****************************************************************************
2263 mput some files.
2264 ****************************************************************************/
2266 static int cmd_mput(void)
2268 TALLOC_CTX *ctx = talloc_tos();
2269 char *p = NULL;
2271 while (next_token_talloc(ctx, &cmd_ptr,&p,NULL)) {
2272 int ret;
2273 struct file_list *temp_list;
2274 char *quest, *lname, *rname;
2276 file_list = NULL;
2278 ret = file_find(ctx, &file_list, ".", p, true);
2279 if (ret) {
2280 free_file_list(file_list);
2281 continue;
2284 quest = NULL;
2285 lname = NULL;
2286 rname = NULL;
2288 for (temp_list = file_list; temp_list;
2289 temp_list = temp_list->next) {
2291 SAFE_FREE(lname);
2292 if (asprintf(&lname, "%s/", temp_list->file_path) <= 0) {
2293 continue;
2295 trim_string(lname, "./", "/");
2297 /* check if it's a directory */
2298 if (temp_list->isdir) {
2299 /* if (!recurse) continue; */
2301 SAFE_FREE(quest);
2302 if (asprintf(&quest, "Put directory %s? ", lname) < 0) {
2303 break;
2305 if (prompt && !yesno(quest)) { /* No */
2306 /* Skip the directory */
2307 lname[strlen(lname)-1] = '/';
2308 if (!seek_list(temp_list, lname))
2309 break;
2310 } else { /* Yes */
2311 SAFE_FREE(rname);
2312 if(asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
2313 break;
2315 normalize_name(rname);
2317 char *tmp_rname =
2318 client_clean_name(ctx, rname);
2319 if (tmp_rname == NULL) {
2320 break;
2322 SAFE_FREE(rname);
2323 rname = smb_xstrdup(tmp_rname);
2324 TALLOC_FREE(tmp_rname);
2325 if (rname == NULL) {
2326 break;
2329 if (!NT_STATUS_IS_OK(cli_chkpath(cli, rname)) &&
2330 !do_mkdir(rname)) {
2331 DEBUG (0, ("Unable to make dir, skipping..."));
2332 /* Skip the directory */
2333 lname[strlen(lname)-1] = '/';
2334 if (!seek_list(temp_list, lname)) {
2335 break;
2339 continue;
2340 } else {
2341 SAFE_FREE(quest);
2342 if (asprintf(&quest,"Put file %s? ", lname) < 0) {
2343 break;
2345 if (prompt && !yesno(quest)) {
2346 /* No */
2347 continue;
2350 /* Yes */
2351 SAFE_FREE(rname);
2352 if (asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
2353 break;
2357 normalize_name(rname);
2360 char *tmp_rname = client_clean_name(ctx, rname);
2361 if (tmp_rname == NULL) {
2362 break;
2364 SAFE_FREE(rname);
2365 rname = smb_xstrdup(tmp_rname);
2366 TALLOC_FREE(tmp_rname);
2367 if (rname == NULL) {
2368 break;
2371 do_put(rname, lname, false);
2373 free_file_list(file_list);
2374 SAFE_FREE(quest);
2375 SAFE_FREE(lname);
2376 SAFE_FREE(rname);
2379 return 0;
2382 /****************************************************************************
2383 Cancel a print job.
2384 ****************************************************************************/
2386 static int do_cancel(int job)
2388 if (cli_printjob_del(cli, job)) {
2389 d_printf("Job %d cancelled\n",job);
2390 return 0;
2391 } else {
2392 NTSTATUS status = cli_nt_error(cli);
2393 d_printf("Error cancelling job %d : %s\n",
2394 job, nt_errstr(status));
2395 return 1;
2399 /****************************************************************************
2400 Cancel a print job.
2401 ****************************************************************************/
2403 static int cmd_cancel(void)
2405 TALLOC_CTX *ctx = talloc_tos();
2406 char *buf = NULL;
2407 int job;
2409 if (!next_token_talloc(ctx, &cmd_ptr, &buf,NULL)) {
2410 d_printf("cancel <jobid> ...\n");
2411 return 1;
2413 do {
2414 job = atoi(buf);
2415 do_cancel(job);
2416 } while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL));
2418 return 0;
2421 /****************************************************************************
2422 Print a file.
2423 ****************************************************************************/
2425 static int cmd_print(void)
2427 TALLOC_CTX *ctx = talloc_tos();
2428 char *lname = NULL;
2429 char *rname = NULL;
2430 char *p = NULL;
2432 if (!next_token_talloc(ctx, &cmd_ptr, &lname,NULL)) {
2433 d_printf("print <filename>\n");
2434 return 1;
2437 rname = talloc_strdup(ctx, lname);
2438 if (!rname) {
2439 return 1;
2441 p = strrchr_m(rname,'/');
2442 if (p) {
2443 rname = talloc_asprintf(ctx,
2444 "%s-%d",
2445 p+1,
2446 (int)getpid());
2448 if (strequal(lname,"-")) {
2449 rname = talloc_asprintf(ctx,
2450 "stdin-%d",
2451 (int)getpid());
2453 if (!rname) {
2454 return 1;
2457 return do_put(rname, lname, false);
2460 /****************************************************************************
2461 Show a print queue entry.
2462 ****************************************************************************/
2464 static void queue_fn(struct print_job_info *p)
2466 d_printf("%-6d %-9d %s\n", (int)p->id, (int)p->size, p->name);
2469 /****************************************************************************
2470 Show a print queue.
2471 ****************************************************************************/
2473 static int cmd_queue(void)
2475 cli_print_queue(cli, queue_fn);
2476 return 0;
2479 /****************************************************************************
2480 Delete some files.
2481 ****************************************************************************/
2483 static NTSTATUS do_del(struct cli_state *cli_state, struct file_info *finfo,
2484 const char *dir)
2486 TALLOC_CTX *ctx = talloc_tos();
2487 char *mask = NULL;
2488 NTSTATUS status;
2490 mask = talloc_asprintf(ctx,
2491 "%s%c%s",
2492 dir,
2493 CLI_DIRSEP_CHAR,
2494 finfo->name);
2495 if (!mask) {
2496 return NT_STATUS_NO_MEMORY;
2499 if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
2500 TALLOC_FREE(mask);
2501 return NT_STATUS_OK;
2504 status = cli_unlink(cli_state, mask, FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN);
2505 if (!NT_STATUS_IS_OK(status)) {
2506 d_printf("%s deleting remote file %s\n",
2507 nt_errstr(status), mask);
2509 TALLOC_FREE(mask);
2510 return status;
2513 /****************************************************************************
2514 Delete some files.
2515 ****************************************************************************/
2517 static int cmd_del(void)
2519 TALLOC_CTX *ctx = talloc_tos();
2520 char *mask = NULL;
2521 char *buf = NULL;
2522 NTSTATUS status = NT_STATUS_OK;
2523 uint16_t attribute = FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN;
2525 if (recurse) {
2526 attribute |= FILE_ATTRIBUTE_DIRECTORY;
2529 mask = talloc_strdup(ctx, client_get_cur_dir());
2530 if (!mask) {
2531 return 1;
2533 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2534 d_printf("del <filename>\n");
2535 return 1;
2537 mask = talloc_asprintf_append(mask, "%s", buf);
2538 if (!mask) {
2539 return 1;
2541 mask = client_clean_name(ctx, mask);
2542 if (mask == NULL) {
2543 return 1;
2546 status = do_list(mask,attribute,do_del,false,false);
2547 if (!NT_STATUS_IS_OK(status)) {
2548 return 1;
2550 return 0;
2553 /****************************************************************************
2554 Delete some files.
2555 ****************************************************************************/
2557 static NTSTATUS delete_remote_files_list(struct cli_state *cli_state,
2558 struct file_list *flist)
2560 NTSTATUS status = NT_STATUS_OK;
2561 struct file_list *deltree_list_iter = NULL;
2563 for (deltree_list_iter = flist;
2564 deltree_list_iter != NULL;
2565 deltree_list_iter = deltree_list_iter->next) {
2566 if (CLI_DIRSEP_CHAR == '/') {
2567 /* POSIX. */
2568 status = cli_posix_unlink(cli_state,
2569 deltree_list_iter->file_path);
2570 } else if (deltree_list_iter->isdir) {
2571 status = cli_rmdir(cli_state,
2572 deltree_list_iter->file_path);
2573 } else {
2574 status = cli_unlink(cli_state,
2575 deltree_list_iter->file_path,
2576 FILE_ATTRIBUTE_SYSTEM |
2577 FILE_ATTRIBUTE_HIDDEN);
2579 if (!NT_STATUS_IS_OK(status)) {
2580 d_printf("%s deleting remote %s %s\n",
2581 nt_errstr(status),
2582 deltree_list_iter->isdir ?
2583 "directory" : "file",
2584 deltree_list_iter->file_path);
2585 return status;
2588 return NT_STATUS_OK;
2591 /****************************************************************************
2592 Save a list of files to delete.
2593 ****************************************************************************/
2595 static struct file_list *deltree_list_head;
2597 static NTSTATUS do_deltree_list(struct cli_state *cli_state,
2598 struct file_info *finfo,
2599 const char *dir)
2601 struct file_list **file_list_head_pp = &deltree_list_head;
2602 struct file_list *dt = NULL;
2604 if (!do_this_one(finfo)) {
2605 return NT_STATUS_OK;
2608 /* skip if this is . or .. */
2609 if (ISDOT(finfo->name) || ISDOTDOT(finfo->name)) {
2610 return NT_STATUS_OK;
2613 dt = talloc_zero(NULL, struct file_list);
2614 if (dt == NULL) {
2615 return NT_STATUS_NO_MEMORY;
2618 /* create absolute filename for cli_ntcreate() */
2619 dt->file_path = talloc_asprintf(dt,
2620 "%s%s%s",
2621 dir,
2622 CLI_DIRSEP_STR,
2623 finfo->name);
2624 if (dt->file_path == NULL) {
2625 TALLOC_FREE(dt);
2626 return NT_STATUS_NO_MEMORY;
2629 if (finfo->mode & FILE_ATTRIBUTE_DIRECTORY) {
2630 dt->isdir = true;
2633 DLIST_ADD(*file_list_head_pp, dt);
2634 return NT_STATUS_OK;
2637 static int cmd_deltree(void)
2639 TALLOC_CTX *ctx = talloc_tos();
2640 char *buf = NULL;
2641 NTSTATUS status = NT_STATUS_OK;
2642 struct file_list *deltree_list_norecurse = NULL;
2643 struct file_list *deltree_list_iter = NULL;
2644 uint16_t attribute = FILE_ATTRIBUTE_SYSTEM |
2645 FILE_ATTRIBUTE_HIDDEN |
2646 FILE_ATTRIBUTE_DIRECTORY;
2647 bool ok;
2648 char *mask = talloc_strdup(ctx, client_get_cur_dir());
2649 if (mask == NULL) {
2650 return 1;
2652 ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
2653 if (!ok) {
2654 d_printf("deltree <filename>\n");
2655 return 1;
2657 mask = talloc_asprintf_append(mask, "%s", buf);
2658 if (mask == NULL) {
2659 return 1;
2661 mask = client_clean_name(ctx, mask);
2662 if (mask == NULL) {
2663 return 1;
2666 deltree_list_head = NULL;
2669 * Get the list of directories to
2670 * delete (in case mask has a wildcard).
2672 status = do_list(mask, attribute, do_deltree_list, false, true);
2673 if (!NT_STATUS_IS_OK(status)) {
2674 goto err;
2676 deltree_list_norecurse = deltree_list_head;
2677 deltree_list_head = NULL;
2679 for (deltree_list_iter = deltree_list_norecurse;
2680 deltree_list_iter != NULL;
2681 deltree_list_iter = deltree_list_iter->next) {
2683 if (deltree_list_iter->isdir == false) {
2684 /* Just a regular file. */
2685 if (CLI_DIRSEP_CHAR == '/') {
2686 /* POSIX. */
2687 status = cli_posix_unlink(cli,
2688 deltree_list_iter->file_path);
2689 } else {
2690 status = cli_unlink(cli,
2691 deltree_list_iter->file_path,
2692 FILE_ATTRIBUTE_SYSTEM |
2693 FILE_ATTRIBUTE_HIDDEN);
2695 if (!NT_STATUS_IS_OK(status)) {
2696 goto err;
2698 continue;
2702 * Get the list of files or directories to
2703 * delete in depth order.
2705 status = do_list(deltree_list_iter->file_path,
2706 attribute,
2707 do_deltree_list,
2708 true,
2709 true);
2710 if (!NT_STATUS_IS_OK(status)) {
2711 goto err;
2713 status = delete_remote_files_list(cli, deltree_list_head);
2714 free_file_list(deltree_list_head);
2715 deltree_list_head = NULL;
2716 if (!NT_STATUS_IS_OK(status)) {
2717 goto err;
2721 free_file_list(deltree_list_norecurse);
2722 free_file_list(deltree_list_head);
2723 return 0;
2725 err:
2727 free_file_list(deltree_list_norecurse);
2728 free_file_list(deltree_list_head);
2729 deltree_list_head = NULL;
2730 return 1;
2734 /****************************************************************************
2735 Wildcard delete some files.
2736 ****************************************************************************/
2738 static int cmd_wdel(void)
2740 TALLOC_CTX *ctx = talloc_tos();
2741 char *mask = NULL;
2742 char *buf = NULL;
2743 uint16_t attribute;
2744 struct cli_state *targetcli;
2745 char *targetname = NULL;
2746 NTSTATUS status;
2748 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2749 d_printf("wdel 0x<attrib> <wcard>\n");
2750 return 1;
2753 attribute = (uint16_t)strtol(buf, (char **)NULL, 16);
2755 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2756 d_printf("wdel 0x<attrib> <wcard>\n");
2757 return 1;
2760 mask = talloc_asprintf(ctx, "%s%s",
2761 client_get_cur_dir(),
2762 buf);
2763 if (!mask) {
2764 return 1;
2766 mask = client_clean_name(ctx, mask);
2767 if (mask == NULL) {
2768 return 1;
2771 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2772 cli, mask, &targetcli, &targetname);
2773 if (!NT_STATUS_IS_OK(status)) {
2774 d_printf("cmd_wdel %s: %s\n", mask, nt_errstr(status));
2775 return 1;
2778 status = cli_unlink(targetcli, targetname, attribute);
2779 if (!NT_STATUS_IS_OK(status)) {
2780 d_printf("%s deleting remote files %s\n", nt_errstr(status),
2781 targetname);
2783 return 0;
2786 /****************************************************************************
2787 ****************************************************************************/
2789 static int cmd_open(void)
2791 TALLOC_CTX *ctx = talloc_tos();
2792 char *mask = NULL;
2793 char *buf = NULL;
2794 char *targetname = NULL;
2795 struct cli_state *targetcli;
2796 uint16_t fnum = (uint16_t)-1;
2797 NTSTATUS status;
2799 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2800 d_printf("open <filename>\n");
2801 return 1;
2803 mask = talloc_asprintf(ctx,
2804 "%s%s",
2805 client_get_cur_dir(),
2806 buf);
2807 if (!mask) {
2808 return 1;
2811 mask = client_clean_name(ctx, mask);
2812 if (mask == NULL) {
2813 return 1;
2816 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2817 cli, mask, &targetcli, &targetname);
2818 if (!NT_STATUS_IS_OK(status)) {
2819 d_printf("open %s: %s\n", mask, nt_errstr(status));
2820 return 1;
2823 status = cli_ntcreate(targetcli, targetname, 0,
2824 FILE_READ_DATA|FILE_WRITE_DATA, 0,
2825 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
2826 0x0, 0x0, &fnum, NULL);
2827 if (!NT_STATUS_IS_OK(status)) {
2828 status = cli_ntcreate(targetcli, targetname, 0,
2829 FILE_READ_DATA, 0,
2830 FILE_SHARE_READ|FILE_SHARE_WRITE, FILE_OPEN,
2831 0x0, 0x0, &fnum, NULL);
2832 if (NT_STATUS_IS_OK(status)) {
2833 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2834 } else {
2835 d_printf("Failed to open file %s. %s\n",
2836 targetname, nt_errstr(status));
2838 } else {
2839 d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
2841 return 0;
2844 static int cmd_posix_encrypt(void)
2846 TALLOC_CTX *ctx = talloc_tos();
2847 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
2848 char *domain = NULL;
2849 char *user = NULL;
2850 char *password = NULL;
2851 struct cli_credentials *creds = NULL;
2852 struct cli_credentials *lcreds = NULL;
2854 if (next_token_talloc(ctx, &cmd_ptr, &domain, NULL)) {
2856 if (!next_token_talloc(ctx, &cmd_ptr, &user, NULL)) {
2857 d_printf("posix_encrypt domain user password\n");
2858 return 1;
2861 if (!next_token_talloc(ctx, &cmd_ptr, &password, NULL)) {
2862 d_printf("posix_encrypt domain user password\n");
2863 return 1;
2866 lcreds = cli_session_creds_init(ctx,
2867 user,
2868 domain,
2869 NULL, /* realm */
2870 password,
2871 false, /* use_kerberos */
2872 false, /* fallback_after_kerberos */
2873 false, /* use_ccache */
2874 false); /* password_is_nt_hash */
2875 if (lcreds == NULL) {
2876 d_printf("cli_session_creds_init() failed.\n");
2877 return -1;
2879 creds = lcreds;
2880 } else {
2881 bool auth_requested = false;
2883 creds = get_cmdline_auth_info_creds(
2884 popt_get_cmdline_auth_info());
2886 auth_requested = cli_credentials_authentication_requested(creds);
2887 if (!auth_requested) {
2888 d_printf("posix_encrypt domain user password\n");
2889 return 1;
2893 status = cli_smb1_setup_encryption(cli, creds);
2894 /* gensec currently references the creds so we can't free them here */
2895 talloc_unlink(ctx, lcreds);
2896 if (!NT_STATUS_IS_OK(status)) {
2897 d_printf("posix_encrypt failed with error %s\n", nt_errstr(status));
2898 } else {
2899 d_printf("encryption on\n");
2900 smb_encrypt = true;
2903 return 0;
2906 /****************************************************************************
2907 ****************************************************************************/
2909 static int cmd_posix_open(void)
2911 TALLOC_CTX *ctx = talloc_tos();
2912 char *mask = NULL;
2913 char *buf = NULL;
2914 char *targetname = NULL;
2915 struct cli_state *targetcli;
2916 mode_t mode;
2917 uint16_t fnum;
2918 NTSTATUS status;
2920 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2921 d_printf("posix_open <filename> 0<mode>\n");
2922 return 1;
2924 mask = talloc_asprintf(ctx,
2925 "%s%s",
2926 client_get_cur_dir(),
2927 buf);
2928 if (!mask) {
2929 return 1;
2931 mask = client_clean_name(ctx, mask);
2932 if (mask == NULL) {
2933 return 1;
2936 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2937 d_printf("posix_open <filename> 0<mode>\n");
2938 return 1;
2940 mode = (mode_t)strtol(buf, (char **)NULL, 8);
2942 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
2943 cli, mask, &targetcli, &targetname);
2944 if (!NT_STATUS_IS_OK(status)) {
2945 d_printf("posix_open %s: %s\n", mask, nt_errstr(status));
2946 return 1;
2949 status = cli_posix_open(targetcli, targetname, O_CREAT|O_RDWR, mode,
2950 &fnum);
2951 if (!NT_STATUS_IS_OK(status)) {
2952 status = cli_posix_open(targetcli, targetname,
2953 O_CREAT|O_RDONLY, mode, &fnum);
2954 if (!NT_STATUS_IS_OK(status)) {
2955 d_printf("Failed to open file %s. %s\n", targetname,
2956 nt_errstr(status));
2957 } else {
2958 d_printf("posix_open file %s: for readonly fnum %d\n",
2959 targetname, fnum);
2961 } else {
2962 d_printf("posix_open file %s: for read/write fnum %d\n",
2963 targetname, fnum);
2966 return 0;
2969 static int cmd_posix_mkdir(void)
2971 TALLOC_CTX *ctx = talloc_tos();
2972 char *mask = NULL;
2973 char *buf = NULL;
2974 char *targetname = NULL;
2975 struct cli_state *targetcli;
2976 mode_t mode;
2977 NTSTATUS status;
2979 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2980 d_printf("posix_mkdir <filename> 0<mode>\n");
2981 return 1;
2983 mask = talloc_asprintf(ctx,
2984 "%s%s",
2985 client_get_cur_dir(),
2986 buf);
2987 if (!mask) {
2988 return 1;
2990 mask = client_clean_name(ctx, mask);
2991 if (mask == NULL) {
2992 return 1;
2995 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
2996 d_printf("posix_mkdir <filename> 0<mode>\n");
2997 return 1;
2999 mode = (mode_t)strtol(buf, (char **)NULL, 8);
3001 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3002 cli, mask, &targetcli, &targetname);
3003 if (!NT_STATUS_IS_OK(status)) {
3004 d_printf("posix_mkdir %s: %s\n", mask, nt_errstr(status));
3005 return 1;
3008 status = cli_posix_mkdir(targetcli, targetname, mode);
3009 if (!NT_STATUS_IS_OK(status)) {
3010 d_printf("Failed to open file %s. %s\n",
3011 targetname, nt_errstr(status));
3012 } else {
3013 d_printf("posix_mkdir created directory %s\n", targetname);
3015 return 0;
3018 static int cmd_posix_unlink(void)
3020 TALLOC_CTX *ctx = talloc_tos();
3021 char *mask = NULL;
3022 char *buf = NULL;
3023 char *targetname = NULL;
3024 struct cli_state *targetcli;
3025 NTSTATUS status;
3027 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3028 d_printf("posix_unlink <filename>\n");
3029 return 1;
3031 mask = talloc_asprintf(ctx,
3032 "%s%s",
3033 client_get_cur_dir(),
3034 buf);
3035 if (!mask) {
3036 return 1;
3038 mask = client_clean_name(ctx, mask);
3039 if (mask == NULL) {
3040 return 1;
3043 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3044 cli, mask, &targetcli, &targetname);
3045 if (!NT_STATUS_IS_OK(status)) {
3046 d_printf("posix_unlink %s: %s\n", mask, nt_errstr(status));
3047 return 1;
3050 status = cli_posix_unlink(targetcli, targetname);
3051 if (!NT_STATUS_IS_OK(status)) {
3052 d_printf("Failed to unlink file %s. %s\n",
3053 targetname, nt_errstr(status));
3054 } else {
3055 d_printf("posix_unlink deleted file %s\n", targetname);
3058 return 0;
3061 static int cmd_posix_rmdir(void)
3063 TALLOC_CTX *ctx = talloc_tos();
3064 char *mask = NULL;
3065 char *buf = NULL;
3066 char *targetname = NULL;
3067 struct cli_state *targetcli;
3068 NTSTATUS status;
3070 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3071 d_printf("posix_rmdir <filename>\n");
3072 return 1;
3074 mask = talloc_asprintf(ctx,
3075 "%s%s",
3076 client_get_cur_dir(),
3077 buf);
3078 if (!mask) {
3079 return 1;
3081 mask = client_clean_name(ctx, mask);
3082 if (mask == NULL) {
3083 return 1;
3086 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3087 cli, mask, &targetcli, &targetname);
3088 if (!NT_STATUS_IS_OK(status)) {
3089 d_printf("posix_rmdir %s: %s\n", mask, nt_errstr(status));
3090 return 1;
3093 status = cli_posix_rmdir(targetcli, targetname);
3094 if (!NT_STATUS_IS_OK(status)) {
3095 d_printf("Failed to unlink directory %s. %s\n",
3096 targetname, nt_errstr(status));
3097 } else {
3098 d_printf("posix_rmdir deleted directory %s\n", targetname);
3101 return 0;
3104 static int cmd_close(void)
3106 TALLOC_CTX *ctx = talloc_tos();
3107 char *buf = NULL;
3108 int fnum;
3109 NTSTATUS status;
3111 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3112 d_printf("close <fnum>\n");
3113 return 1;
3116 fnum = atoi(buf);
3117 /* We really should use the targetcli here.... */
3118 status = cli_close(cli, fnum);
3119 if (!NT_STATUS_IS_OK(status)) {
3120 d_printf("close %d: %s\n", fnum, nt_errstr(status));
3121 return 1;
3123 return 0;
3126 static int cmd_posix(void)
3128 TALLOC_CTX *ctx = talloc_tos();
3129 uint16_t major, minor;
3130 uint32_t caplow, caphigh;
3131 char *caps;
3132 NTSTATUS status;
3134 if (!SERVER_HAS_UNIX_CIFS(cli)) {
3135 d_printf("Server doesn't support UNIX CIFS extensions.\n");
3136 return 1;
3139 status = cli_unix_extensions_version(cli, &major, &minor, &caplow,
3140 &caphigh);
3141 if (!NT_STATUS_IS_OK(status)) {
3142 d_printf("Can't get UNIX CIFS extensions version from "
3143 "server: %s\n", nt_errstr(status));
3144 return 1;
3147 d_printf("Server supports CIFS extensions %u.%u\n", (unsigned int)major, (unsigned int)minor);
3149 caps = talloc_strdup(ctx, "");
3150 if (!caps) {
3151 return 1;
3153 if (caplow & CIFS_UNIX_FCNTL_LOCKS_CAP) {
3154 caps = talloc_asprintf_append(caps, "locks ");
3155 if (!caps) {
3156 return 1;
3159 if (caplow & CIFS_UNIX_POSIX_ACLS_CAP) {
3160 caps = talloc_asprintf_append(caps, "acls ");
3161 if (!caps) {
3162 return 1;
3165 if (caplow & CIFS_UNIX_XATTTR_CAP) {
3166 caps = talloc_asprintf_append(caps, "eas ");
3167 if (!caps) {
3168 return 1;
3171 if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3172 caps = talloc_asprintf_append(caps, "pathnames ");
3173 if (!caps) {
3174 return 1;
3177 if (caplow & CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP) {
3178 caps = talloc_asprintf_append(caps, "posix_path_operations ");
3179 if (!caps) {
3180 return 1;
3183 if (caplow & CIFS_UNIX_LARGE_READ_CAP) {
3184 caps = talloc_asprintf_append(caps, "large_read ");
3185 if (!caps) {
3186 return 1;
3189 if (caplow & CIFS_UNIX_LARGE_WRITE_CAP) {
3190 caps = talloc_asprintf_append(caps, "large_write ");
3191 if (!caps) {
3192 return 1;
3195 if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP) {
3196 caps = talloc_asprintf_append(caps, "posix_encrypt ");
3197 if (!caps) {
3198 return 1;
3201 if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP) {
3202 caps = talloc_asprintf_append(caps, "mandatory_posix_encrypt ");
3203 if (!caps) {
3204 return 1;
3208 if (*caps && caps[strlen(caps)-1] == ' ') {
3209 caps[strlen(caps)-1] = '\0';
3212 d_printf("Server supports CIFS capabilities %s\n", caps);
3214 status = cli_set_unix_extensions_capabilities(cli, major, minor,
3215 caplow, caphigh);
3216 if (!NT_STATUS_IS_OK(status)) {
3217 d_printf("Can't set UNIX CIFS extensions capabilities. %s.\n",
3218 nt_errstr(status));
3219 return 1;
3222 if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
3223 CLI_DIRSEP_CHAR = '/';
3224 *CLI_DIRSEP_STR = '/';
3225 client_set_cur_dir(CLI_DIRSEP_STR);
3228 return 0;
3231 static int cmd_lock(void)
3233 TALLOC_CTX *ctx = talloc_tos();
3234 char *buf = NULL;
3235 uint64_t start, len;
3236 enum brl_type lock_type;
3237 int fnum;
3238 NTSTATUS status;
3240 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3241 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3242 return 1;
3244 fnum = atoi(buf);
3246 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3247 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3248 return 1;
3251 if (*buf == 'r' || *buf == 'R') {
3252 lock_type = READ_LOCK;
3253 } else if (*buf == 'w' || *buf == 'W') {
3254 lock_type = WRITE_LOCK;
3255 } else {
3256 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3257 return 1;
3260 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3261 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3262 return 1;
3265 start = (uint64_t)strtol(buf, (char **)NULL, 16);
3267 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3268 d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
3269 return 1;
3272 len = (uint64_t)strtol(buf, (char **)NULL, 16);
3274 status = cli_posix_lock(cli, fnum, start, len, true, lock_type);
3275 if (!NT_STATUS_IS_OK(status)) {
3276 d_printf("lock failed %d: %s\n", fnum, nt_errstr(status));
3279 return 0;
3282 static int cmd_unlock(void)
3284 TALLOC_CTX *ctx = talloc_tos();
3285 char *buf = NULL;
3286 uint64_t start, len;
3287 int fnum;
3288 NTSTATUS status;
3290 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3291 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
3292 return 1;
3294 fnum = atoi(buf);
3296 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3297 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
3298 return 1;
3301 start = (uint64_t)strtol(buf, (char **)NULL, 16);
3303 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3304 d_printf("unlock <fnum> <hex-start> <hex-len>\n");
3305 return 1;
3308 len = (uint64_t)strtol(buf, (char **)NULL, 16);
3310 status = cli_posix_unlock(cli, fnum, start, len);
3311 if (!NT_STATUS_IS_OK(status)) {
3312 d_printf("unlock failed %d: %s\n", fnum, nt_errstr(status));
3315 return 0;
3318 static int cmd_posix_whoami(void)
3320 TALLOC_CTX *ctx = talloc_tos();
3321 NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
3322 uint64_t uid = 0;
3323 uint64_t gid = 0;
3324 uint32_t num_gids = 0;
3325 uint32_t num_sids = 0;
3326 uint64_t *gids = NULL;
3327 struct dom_sid *sids = NULL;
3328 bool guest = false;
3329 uint32_t i;
3331 status = cli_posix_whoami(cli,
3332 ctx,
3333 &uid,
3334 &gid,
3335 &num_gids,
3336 &gids,
3337 &num_sids,
3338 &sids,
3339 &guest);
3341 if (!NT_STATUS_IS_OK(status)) {
3342 d_printf("posix_whoami failed with error %s\n", nt_errstr(status));
3343 return 1;
3346 d_printf("GUEST:%s\n", guest ? "True" : "False");
3347 d_printf("UID:%" PRIu64 "\n", uid);
3348 d_printf("GID:%" PRIu64 "\n", gid);
3349 d_printf("NUM_GIDS:%" PRIu32 "\n", num_gids);
3350 for (i = 0; i < num_gids; i++) {
3351 d_printf("GIDS[%" PRIu32 "]:%" PRIu64 "\n", i, gids[i]);
3353 d_printf("NUM_SIDS:%" PRIu32 "\n", num_sids);
3354 for (i = 0; i < num_sids; i++) {
3355 char *sid_str = dom_sid_string(ctx, &sids[i]);
3356 d_printf("SIDS[%" PRIu32 "]:%s\n", i, sid_str);
3357 TALLOC_FREE(sid_str);
3359 return 0;
3363 /****************************************************************************
3364 Remove a directory.
3365 ****************************************************************************/
3367 static int cmd_rmdir(void)
3369 TALLOC_CTX *ctx = talloc_tos();
3370 char *mask = NULL;
3371 char *buf = NULL;
3372 char *targetname = NULL;
3373 struct cli_state *targetcli;
3374 NTSTATUS status;
3376 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3377 d_printf("rmdir <dirname>\n");
3378 return 1;
3380 mask = talloc_asprintf(ctx,
3381 "%s%s",
3382 client_get_cur_dir(),
3383 buf);
3384 if (!mask) {
3385 return 1;
3387 mask = client_clean_name(ctx, mask);
3388 if (mask == NULL) {
3389 return 1;
3392 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3393 cli, mask, &targetcli, &targetname);
3394 if (!NT_STATUS_IS_OK(status)) {
3395 d_printf("rmdir %s: %s\n", mask, nt_errstr(status));
3396 return 1;
3399 status = cli_rmdir(targetcli, targetname);
3400 if (!NT_STATUS_IS_OK(status)) {
3401 d_printf("%s removing remote directory file %s\n",
3402 nt_errstr(status), mask);
3405 return 0;
3408 /****************************************************************************
3409 UNIX hardlink.
3410 ****************************************************************************/
3412 static int cmd_link(void)
3414 TALLOC_CTX *ctx = talloc_tos();
3415 char *oldname = NULL;
3416 char *newname = NULL;
3417 char *buf = NULL;
3418 char *buf2 = NULL;
3419 char *targetname = NULL;
3420 struct cli_state *targetcli;
3421 NTSTATUS status;
3423 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3424 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3425 d_printf("link <oldname> <newname>\n");
3426 return 1;
3428 oldname = talloc_asprintf(ctx,
3429 "%s%s",
3430 client_get_cur_dir(),
3431 buf);
3432 if (!oldname) {
3433 return 1;
3435 oldname = client_clean_name(ctx, oldname);
3436 if (oldname == NULL) {
3437 return 1;
3439 newname = talloc_asprintf(ctx,
3440 "%s%s",
3441 client_get_cur_dir(),
3442 buf2);
3443 if (!newname) {
3444 return 1;
3446 newname = client_clean_name(ctx, newname);
3447 if (newname == NULL) {
3448 return 1;
3451 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3452 cli, oldname, &targetcli, &targetname);
3453 if (!NT_STATUS_IS_OK(status)) {
3454 d_printf("link %s: %s\n", oldname, nt_errstr(status));
3455 return 1;
3458 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3459 d_printf("Server doesn't support UNIX CIFS calls.\n");
3460 return 1;
3463 status = cli_posix_hardlink(targetcli, targetname, newname);
3464 if (!NT_STATUS_IS_OK(status)) {
3465 d_printf("%s linking files (%s -> %s)\n",
3466 nt_errstr(status), newname, oldname);
3467 return 1;
3469 return 0;
3472 /****************************************************************************
3473 UNIX readlink.
3474 ****************************************************************************/
3476 static int cmd_readlink(void)
3478 TALLOC_CTX *ctx = talloc_tos();
3479 char *name= NULL;
3480 char *buf = NULL;
3481 char *targetname = NULL;
3482 char linkname[PATH_MAX+1];
3483 struct cli_state *targetcli;
3484 NTSTATUS status;
3486 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
3487 d_printf("readlink <name>\n");
3488 return 1;
3490 name = talloc_asprintf(ctx,
3491 "%s%s",
3492 client_get_cur_dir(),
3493 buf);
3494 if (!name) {
3495 return 1;
3497 name = client_clean_name(ctx, name);
3498 if (name == NULL) {
3499 return 1;
3502 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3503 cli, name, &targetcli, &targetname);
3504 if (!NT_STATUS_IS_OK(status)) {
3505 d_printf("readlink %s: %s\n", name, nt_errstr(status));
3506 return 1;
3509 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3510 d_printf("Server doesn't support UNIX CIFS calls.\n");
3511 return 1;
3514 status = cli_posix_readlink(targetcli, name, linkname, PATH_MAX+1);
3515 if (!NT_STATUS_IS_OK(status)) {
3516 d_printf("%s readlink on file %s\n",
3517 nt_errstr(status), name);
3518 return 1;
3521 d_printf("%s -> %s\n", name, linkname);
3523 return 0;
3527 /****************************************************************************
3528 UNIX symlink.
3529 ****************************************************************************/
3531 static int cmd_symlink(void)
3533 TALLOC_CTX *ctx = talloc_tos();
3534 char *link_target = NULL;
3535 char *newname = NULL;
3536 char *buf = NULL;
3537 char *buf2 = NULL;
3538 struct cli_state *newcli;
3539 NTSTATUS status;
3541 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3542 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3543 d_printf("symlink <link_target> <newname>\n");
3544 return 1;
3546 /* Oldname (link target) must be an untouched blob. */
3547 link_target = buf;
3549 if (SERVER_HAS_UNIX_CIFS(cli)) {
3550 newname = talloc_asprintf(ctx, "%s%s", client_get_cur_dir(),
3551 buf2);
3552 if (!newname) {
3553 return 1;
3555 newname = client_clean_name(ctx, newname);
3556 if (newname == NULL) {
3557 return 1;
3559 /* New name must be present in share namespace. */
3560 status = cli_resolve_path(ctx, "",
3561 popt_get_cmdline_auth_info(), cli, newname,
3562 &newcli, &newname);
3563 if (!NT_STATUS_IS_OK(status)) {
3564 d_printf("link %s: %s\n", newname,
3565 nt_errstr(status));
3566 return 1;
3568 status = cli_posix_symlink(newcli, link_target, newname);
3569 } else {
3570 status = cli_symlink(
3571 cli, link_target, buf2,
3572 buf2[0] == '\\' ? 0 : SYMLINK_FLAG_RELATIVE);
3575 if (!NT_STATUS_IS_OK(status)) {
3576 d_printf("%s symlinking files (%s -> %s)\n",
3577 nt_errstr(status), newname, link_target);
3578 return 1;
3581 return 0;
3584 /****************************************************************************
3585 UNIX chmod.
3586 ****************************************************************************/
3588 static int cmd_chmod(void)
3590 TALLOC_CTX *ctx = talloc_tos();
3591 char *src = NULL;
3592 char *buf = NULL;
3593 char *buf2 = NULL;
3594 char *targetname = NULL;
3595 struct cli_state *targetcli;
3596 mode_t mode;
3597 NTSTATUS status;
3599 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
3600 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
3601 d_printf("chmod mode file\n");
3602 return 1;
3604 src = talloc_asprintf(ctx,
3605 "%s%s",
3606 client_get_cur_dir(),
3607 buf2);
3608 if (!src) {
3609 return 1;
3611 src = client_clean_name(ctx, src);
3612 if (src == NULL) {
3613 return 1;
3616 mode = (mode_t)strtol(buf, NULL, 8);
3618 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3619 cli, src, &targetcli, &targetname);
3620 if (!NT_STATUS_IS_OK(status)) {
3621 d_printf("chmod %s: %s\n", src, nt_errstr(status));
3622 return 1;
3625 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3626 d_printf("Server doesn't support UNIX CIFS calls.\n");
3627 return 1;
3630 status = cli_posix_chmod(targetcli, targetname, mode);
3631 if (!NT_STATUS_IS_OK(status)) {
3632 d_printf("%s chmod file %s 0%o\n",
3633 nt_errstr(status), src, (unsigned int)mode);
3634 return 1;
3637 return 0;
3640 static const char *filetype_to_str(mode_t mode)
3642 if (S_ISREG(mode)) {
3643 return "regular file";
3644 } else if (S_ISDIR(mode)) {
3645 return "directory";
3646 } else
3647 #ifdef S_ISCHR
3648 if (S_ISCHR(mode)) {
3649 return "character device";
3650 } else
3651 #endif
3652 #ifdef S_ISBLK
3653 if (S_ISBLK(mode)) {
3654 return "block device";
3655 } else
3656 #endif
3657 #ifdef S_ISFIFO
3658 if (S_ISFIFO(mode)) {
3659 return "fifo";
3660 } else
3661 #endif
3662 #ifdef S_ISLNK
3663 if (S_ISLNK(mode)) {
3664 return "symbolic link";
3665 } else
3666 #endif
3667 #ifdef S_ISSOCK
3668 if (S_ISSOCK(mode)) {
3669 return "socket";
3670 } else
3671 #endif
3672 return "";
3675 static char rwx_to_str(mode_t m, mode_t bt, char ret)
3677 if (m & bt) {
3678 return ret;
3679 } else {
3680 return '-';
3684 static char *unix_mode_to_str(char *s, mode_t m)
3686 char *p = s;
3687 const char *str = filetype_to_str(m);
3689 switch(str[0]) {
3690 case 'd':
3691 *p++ = 'd';
3692 break;
3693 case 'c':
3694 *p++ = 'c';
3695 break;
3696 case 'b':
3697 *p++ = 'b';
3698 break;
3699 case 'f':
3700 *p++ = 'p';
3701 break;
3702 case 's':
3703 *p++ = str[1] == 'y' ? 'l' : 's';
3704 break;
3705 case 'r':
3706 default:
3707 *p++ = '-';
3708 break;
3710 *p++ = rwx_to_str(m, S_IRUSR, 'r');
3711 *p++ = rwx_to_str(m, S_IWUSR, 'w');
3712 *p++ = rwx_to_str(m, S_IXUSR, 'x');
3713 *p++ = rwx_to_str(m, S_IRGRP, 'r');
3714 *p++ = rwx_to_str(m, S_IWGRP, 'w');
3715 *p++ = rwx_to_str(m, S_IXGRP, 'x');
3716 *p++ = rwx_to_str(m, S_IROTH, 'r');
3717 *p++ = rwx_to_str(m, S_IWOTH, 'w');
3718 *p++ = rwx_to_str(m, S_IXOTH, 'x');
3719 *p++ = '\0';
3720 return s;
3723 /****************************************************************************
3724 Utility function for UNIX getfacl.
3725 ****************************************************************************/
3727 static char *perms_to_string(fstring permstr, unsigned char perms)
3729 fstrcpy(permstr, "---");
3730 if (perms & SMB_POSIX_ACL_READ) {
3731 permstr[0] = 'r';
3733 if (perms & SMB_POSIX_ACL_WRITE) {
3734 permstr[1] = 'w';
3736 if (perms & SMB_POSIX_ACL_EXECUTE) {
3737 permstr[2] = 'x';
3739 return permstr;
3742 /****************************************************************************
3743 UNIX getfacl.
3744 ****************************************************************************/
3746 static int cmd_getfacl(void)
3748 TALLOC_CTX *ctx = talloc_tos();
3749 char *src = NULL;
3750 char *name = NULL;
3751 char *targetname = NULL;
3752 struct cli_state *targetcli;
3753 uint16_t major, minor;
3754 uint32_t caplow, caphigh;
3755 char *retbuf = NULL;
3756 size_t rb_size = 0;
3757 SMB_STRUCT_STAT sbuf;
3758 uint16_t num_file_acls = 0;
3759 uint16_t num_dir_acls = 0;
3760 uint16_t i;
3761 NTSTATUS status;
3763 if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3764 d_printf("getfacl filename\n");
3765 return 1;
3767 src = talloc_asprintf(ctx,
3768 "%s%s",
3769 client_get_cur_dir(),
3770 name);
3771 if (!src) {
3772 return 1;
3774 src = client_clean_name(ctx, src);
3775 if (src == NULL) {
3776 return 1;
3779 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3780 cli, src, &targetcli, &targetname);
3781 if (!NT_STATUS_IS_OK(status)) {
3782 d_printf("stat %s: %s\n", src, nt_errstr(status));
3783 return 1;
3786 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
3787 d_printf("Server doesn't support UNIX CIFS calls.\n");
3788 return 1;
3791 status = cli_unix_extensions_version(targetcli, &major, &minor,
3792 &caplow, &caphigh);
3793 if (!NT_STATUS_IS_OK(status)) {
3794 d_printf("Can't get UNIX CIFS version from server: %s.\n",
3795 nt_errstr(status));
3796 return 1;
3799 if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
3800 d_printf("This server supports UNIX extensions "
3801 "but doesn't support POSIX ACLs.\n");
3802 return 1;
3805 status = cli_posix_stat(targetcli, targetname, &sbuf);
3806 if (!NT_STATUS_IS_OK(cli_posix_stat(targetcli, targetname, &sbuf))) {
3807 d_printf("%s getfacl doing a stat on file %s\n",
3808 nt_errstr(status), src);
3809 return 1;
3812 status = cli_posix_getacl(targetcli, targetname, ctx, &rb_size, &retbuf);
3813 if (!NT_STATUS_IS_OK(status)) {
3814 d_printf("%s getfacl file %s\n",
3815 nt_errstr(status), src);
3816 return 1;
3819 /* ToDo : Print out the ACL values. */
3820 if (rb_size < 6 || SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION) {
3821 d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
3822 src, (unsigned int)CVAL(retbuf,0) );
3823 return 1;
3826 num_file_acls = SVAL(retbuf,2);
3827 num_dir_acls = SVAL(retbuf,4);
3828 if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
3829 d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
3830 src,
3831 (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
3832 (unsigned int)rb_size);
3833 return 1;
3836 d_printf("# file: %s\n", src);
3837 d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_ex_uid, (unsigned int)sbuf.st_ex_gid);
3839 if (num_file_acls == 0 && num_dir_acls == 0) {
3840 d_printf("No acls found.\n");
3843 for (i = 0; i < num_file_acls; i++) {
3844 uint32_t uorg;
3845 fstring permstring;
3846 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
3847 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
3849 switch(tagtype) {
3850 case SMB_POSIX_ACL_USER_OBJ:
3851 d_printf("user::");
3852 break;
3853 case SMB_POSIX_ACL_USER:
3854 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3855 d_printf("user:%u:", uorg);
3856 break;
3857 case SMB_POSIX_ACL_GROUP_OBJ:
3858 d_printf("group::");
3859 break;
3860 case SMB_POSIX_ACL_GROUP:
3861 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3862 d_printf("group:%u:", uorg);
3863 break;
3864 case SMB_POSIX_ACL_MASK:
3865 d_printf("mask::");
3866 break;
3867 case SMB_POSIX_ACL_OTHER:
3868 d_printf("other::");
3869 break;
3870 default:
3871 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
3872 src, (unsigned int)tagtype );
3873 SAFE_FREE(retbuf);
3874 return 1;
3877 d_printf("%s\n", perms_to_string(permstring, perms));
3880 for (i = 0; i < num_dir_acls; i++) {
3881 uint32_t uorg;
3882 fstring permstring;
3883 unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
3884 unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
3886 switch(tagtype) {
3887 case SMB_POSIX_ACL_USER_OBJ:
3888 d_printf("default:user::");
3889 break;
3890 case SMB_POSIX_ACL_USER:
3891 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3892 d_printf("default:user:%u:", uorg);
3893 break;
3894 case SMB_POSIX_ACL_GROUP_OBJ:
3895 d_printf("default:group::");
3896 break;
3897 case SMB_POSIX_ACL_GROUP:
3898 uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
3899 d_printf("default:group:%u:", uorg);
3900 break;
3901 case SMB_POSIX_ACL_MASK:
3902 d_printf("default:mask::");
3903 break;
3904 case SMB_POSIX_ACL_OTHER:
3905 d_printf("default:other::");
3906 break;
3907 default:
3908 d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
3909 src, (unsigned int)tagtype );
3910 SAFE_FREE(retbuf);
3911 return 1;
3914 d_printf("%s\n", perms_to_string(permstring, perms));
3917 return 0;
3920 /****************************************************************************
3921 Get the EA list of a file
3922 ****************************************************************************/
3924 static int cmd_geteas(void)
3926 TALLOC_CTX *ctx = talloc_tos();
3927 char *src = NULL;
3928 char *name = NULL;
3929 char *targetname = NULL;
3930 struct cli_state *targetcli;
3931 NTSTATUS status;
3932 size_t i, num_eas;
3933 struct ea_struct *eas;
3935 if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
3936 d_printf("geteas filename\n");
3937 return 1;
3939 src = talloc_asprintf(ctx,
3940 "%s%s",
3941 client_get_cur_dir(),
3942 name);
3943 if (!src) {
3944 return 1;
3946 src = client_clean_name(ctx, src);
3947 if (src == NULL) {
3948 return 1;
3951 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
3952 cli, src, &targetcli, &targetname);
3953 if (!NT_STATUS_IS_OK(status)) {
3954 d_printf("stat %s: %s\n", src, nt_errstr(status));
3955 return 1;
3958 status = cli_get_ea_list_path(targetcli, targetname, talloc_tos(),
3959 &num_eas, &eas);
3960 if (!NT_STATUS_IS_OK(status)) {
3961 d_printf("cli_get_ea_list_path: %s\n", nt_errstr(status));
3962 return 1;
3965 for (i=0; i<num_eas; i++) {
3966 d_printf("%s (%d) =\n", eas[i].name, (int)eas[i].flags);
3967 dump_data_file(eas[i].value.data, eas[i].value.length, false,
3968 stdout);
3969 d_printf("\n");
3972 TALLOC_FREE(eas);
3974 return 0;
3977 /****************************************************************************
3978 Set an EA of a file
3979 ****************************************************************************/
3981 static int cmd_setea(void)
3983 TALLOC_CTX *ctx = talloc_tos();
3984 char *src = NULL;
3985 char *name = NULL;
3986 char *eaname = NULL;
3987 char *eavalue = NULL;
3988 char *targetname = NULL;
3989 struct cli_state *targetcli;
3990 NTSTATUS status;
3992 if (!next_token_talloc(ctx, &cmd_ptr, &name, NULL)
3993 || !next_token_talloc(ctx, &cmd_ptr, &eaname, NULL)) {
3994 d_printf("setea filename eaname value\n");
3995 return 1;
3997 if (!next_token_talloc(ctx, &cmd_ptr, &eavalue, NULL)) {
3998 eavalue = talloc_strdup(ctx, "");
4000 src = talloc_asprintf(ctx,
4001 "%s%s",
4002 client_get_cur_dir(),
4003 name);
4004 if (!src) {
4005 return 1;
4007 src = client_clean_name(ctx, src);
4008 if (src == NULL) {
4009 return 1;
4012 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4013 cli, src, &targetcli, &targetname);
4014 if (!NT_STATUS_IS_OK(status)) {
4015 d_printf("stat %s: %s\n", src, nt_errstr(status));
4016 return 1;
4019 status = cli_set_ea_path(targetcli, targetname, eaname, eavalue,
4020 strlen(eavalue));
4021 if (!NT_STATUS_IS_OK(status)) {
4022 d_printf("set_ea %s: %s\n", src, nt_errstr(status));
4023 return 1;
4026 return 0;
4029 /****************************************************************************
4030 UNIX stat.
4031 ****************************************************************************/
4033 static int cmd_stat(void)
4035 TALLOC_CTX *ctx = talloc_tos();
4036 char *src = NULL;
4037 char *name = NULL;
4038 char *targetname = NULL;
4039 struct cli_state *targetcli;
4040 fstring mode_str;
4041 SMB_STRUCT_STAT sbuf;
4042 struct tm *lt;
4043 time_t tmp_time;
4044 NTSTATUS status;
4046 if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
4047 d_printf("stat file\n");
4048 return 1;
4050 src = talloc_asprintf(ctx,
4051 "%s%s",
4052 client_get_cur_dir(),
4053 name);
4054 if (!src) {
4055 return 1;
4057 src = client_clean_name(ctx, src);
4058 if (src == NULL) {
4059 return 1;
4062 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4063 cli, src, &targetcli, &targetname);
4064 if (!NT_STATUS_IS_OK(status)) {
4065 d_printf("stat %s: %s\n", src, nt_errstr(status));
4066 return 1;
4069 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
4070 d_printf("Server doesn't support UNIX CIFS calls.\n");
4071 return 1;
4074 status = cli_posix_stat(targetcli, targetname, &sbuf);
4075 if (!NT_STATUS_IS_OK(status)) {
4076 d_printf("%s stat file %s\n",
4077 nt_errstr(status), src);
4078 return 1;
4081 /* Print out the stat values. */
4082 d_printf("File: %s\n", src);
4083 d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
4084 (double)sbuf.st_ex_size,
4085 (unsigned int)sbuf.st_ex_blocks,
4086 filetype_to_str(sbuf.st_ex_mode));
4088 #if defined(S_ISCHR) && defined(S_ISBLK)
4089 if (S_ISCHR(sbuf.st_ex_mode) || S_ISBLK(sbuf.st_ex_mode)) {
4090 d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
4091 (double)sbuf.st_ex_ino,
4092 (unsigned int)sbuf.st_ex_nlink,
4093 unix_dev_major(sbuf.st_ex_rdev),
4094 unix_dev_minor(sbuf.st_ex_rdev));
4095 } else
4096 #endif
4097 d_printf("Inode: %.0f\tLinks: %u\n",
4098 (double)sbuf.st_ex_ino,
4099 (unsigned int)sbuf.st_ex_nlink);
4101 d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
4102 ((int)sbuf.st_ex_mode & 0777),
4103 unix_mode_to_str(mode_str, sbuf.st_ex_mode),
4104 (unsigned int)sbuf.st_ex_uid,
4105 (unsigned int)sbuf.st_ex_gid);
4107 tmp_time = convert_timespec_to_time_t(sbuf.st_ex_atime);
4108 lt = localtime(&tmp_time);
4109 if (lt) {
4110 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
4111 } else {
4112 fstrcpy(mode_str, "unknown");
4114 d_printf("Access: %s\n", mode_str);
4116 tmp_time = convert_timespec_to_time_t(sbuf.st_ex_mtime);
4117 lt = localtime(&tmp_time);
4118 if (lt) {
4119 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
4120 } else {
4121 fstrcpy(mode_str, "unknown");
4123 d_printf("Modify: %s\n", mode_str);
4125 tmp_time = convert_timespec_to_time_t(sbuf.st_ex_ctime);
4126 lt = localtime(&tmp_time);
4127 if (lt) {
4128 strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
4129 } else {
4130 fstrcpy(mode_str, "unknown");
4132 d_printf("Change: %s\n", mode_str);
4134 return 0;
4138 /****************************************************************************
4139 UNIX chown.
4140 ****************************************************************************/
4142 static int cmd_chown(void)
4144 TALLOC_CTX *ctx = talloc_tos();
4145 char *src = NULL;
4146 uid_t uid;
4147 gid_t gid;
4148 char *buf, *buf2, *buf3;
4149 struct cli_state *targetcli;
4150 char *targetname = NULL;
4151 NTSTATUS status;
4153 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4154 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL) ||
4155 !next_token_talloc(ctx, &cmd_ptr,&buf3,NULL)) {
4156 d_printf("chown uid gid file\n");
4157 return 1;
4160 uid = (uid_t)atoi(buf);
4161 gid = (gid_t)atoi(buf2);
4163 src = talloc_asprintf(ctx,
4164 "%s%s",
4165 client_get_cur_dir(),
4166 buf3);
4167 if (!src) {
4168 return 1;
4170 src = client_clean_name(ctx, src);
4171 if (src == NULL) {
4172 return 1;
4174 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4175 cli, src, &targetcli, &targetname);
4176 if (!NT_STATUS_IS_OK(status)) {
4177 d_printf("chown %s: %s\n", src, nt_errstr(status));
4178 return 1;
4181 if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
4182 d_printf("Server doesn't support UNIX CIFS calls.\n");
4183 return 1;
4186 status = cli_posix_chown(targetcli, targetname, uid, gid);
4187 if (!NT_STATUS_IS_OK(status)) {
4188 d_printf("%s chown file %s uid=%d, gid=%d\n",
4189 nt_errstr(status), src, (int)uid, (int)gid);
4190 return 1;
4193 return 0;
4196 /****************************************************************************
4197 Rename some file.
4198 ****************************************************************************/
4200 static int cmd_rename(void)
4202 TALLOC_CTX *ctx = talloc_tos();
4203 char *src, *dest;
4204 char *buf, *buf2;
4205 struct cli_state *targetcli;
4206 char *targetsrc;
4207 char *targetdest;
4208 NTSTATUS status;
4209 bool replace = false;
4211 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4212 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4213 d_printf("rename <src> <dest> [-f]\n");
4214 return 1;
4217 src = talloc_asprintf(ctx,
4218 "%s%s",
4219 client_get_cur_dir(),
4220 buf);
4221 if (!src) {
4222 return 1;
4224 src = client_clean_name(ctx, src);
4225 if (src == NULL) {
4226 return 1;
4229 dest = talloc_asprintf(ctx,
4230 "%s%s",
4231 client_get_cur_dir(),
4232 buf2);
4233 if (!dest) {
4234 return 1;
4236 dest = client_clean_name(ctx, dest);
4237 if (dest == NULL) {
4238 return 1;
4241 if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL) &&
4242 strcsequal(buf, "-f")) {
4243 replace = true;
4246 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4247 cli, src, &targetcli, &targetsrc);
4248 if (!NT_STATUS_IS_OK(status)) {
4249 d_printf("rename %s: %s\n", src, nt_errstr(status));
4250 return 1;
4253 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4254 cli, dest, &targetcli, &targetdest);
4255 if (!NT_STATUS_IS_OK(status)) {
4256 d_printf("rename %s: %s\n", dest, nt_errstr(status));
4257 return 1;
4260 status = cli_rename(targetcli, targetsrc, targetdest, replace);
4261 if (!NT_STATUS_IS_OK(status)) {
4262 d_printf("%s renaming files %s -> %s \n",
4263 nt_errstr(status),
4264 targetsrc,
4265 targetdest);
4266 return 1;
4269 return 0;
4272 struct scopy_timing {
4273 struct timespec tp_start;
4276 static int scopy_status(off_t written, void *priv)
4278 struct timespec tp_end;
4279 unsigned int scopy_total_time_ms;
4280 struct scopy_timing *st = priv;
4282 clock_gettime_mono(&tp_end);
4283 scopy_total_time_ms = nsec_time_diff(&tp_end,&st->tp_start)/1000000;
4285 DEBUG(5,("Copied %jd bytes at an average %3.1f kb/s\n",
4286 (intmax_t)written, written / (1.024*scopy_total_time_ms)));
4288 return true;
4291 /****************************************************************************
4292 Server-Side copy some file.
4293 ****************************************************************************/
4295 static int cmd_scopy(void)
4297 TALLOC_CTX *ctx = talloc_tos();
4298 char *src, *dest;
4299 char *buf, *buf2;
4300 struct cli_state *targetcli;
4301 char *targetsrc;
4302 char *targetdest;
4303 uint32_t DesiredAccess, ShareAccess, CreateDisposition, CreateOptions;
4304 struct smb_create_returns cr;
4305 uint16_t destfnum = (uint16_t)-1;
4306 uint16_t srcfnum = (uint16_t)-1;
4307 off_t written = 0;
4308 struct scopy_timing st;
4309 int rc = 0;
4310 NTSTATUS status;
4312 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4313 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4314 d_printf("scopy <src> <dest>\n");
4315 return 1;
4318 src = talloc_asprintf(ctx,
4319 "%s%s",
4320 client_get_cur_dir(),
4321 buf);
4322 if (!src) {
4323 return 1;
4325 src = client_clean_name(ctx, src);
4326 if (src == NULL) {
4327 return 1;
4330 dest = talloc_asprintf(ctx,
4331 "%s%s",
4332 client_get_cur_dir(),
4333 buf2);
4334 if (!dest) {
4335 return 1;
4337 dest = client_clean_name(ctx, dest);
4338 if (dest == NULL) {
4339 return 1;
4342 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4343 cli, src, &targetcli, &targetsrc);
4344 if (!NT_STATUS_IS_OK(status)) {
4345 d_printf("scopy %s: %s\n", src, nt_errstr(status));
4346 return 1;
4349 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4350 cli, dest, &targetcli, &targetdest);
4351 if (!NT_STATUS_IS_OK(status)) {
4352 d_printf("scopy %s: %s\n", dest, nt_errstr(status));
4353 return 1;
4357 DesiredAccess = (FILE_READ_DATA|FILE_READ_EA|FILE_READ_ATTRIBUTES|
4358 READ_CONTROL_ACCESS|SYNCHRONIZE_ACCESS);
4359 ShareAccess = FILE_SHARE_READ|FILE_SHARE_DELETE;
4360 CreateDisposition = FILE_OPEN;
4361 CreateOptions = (FILE_SEQUENTIAL_ONLY|FILE_NON_DIRECTORY_FILE|
4362 FILE_OPEN_REPARSE_POINT);
4363 status = cli_ntcreate(targetcli, targetsrc, 0, DesiredAccess, 0,
4364 ShareAccess, CreateDisposition, CreateOptions, 0x0,
4365 &srcfnum, &cr);
4366 if (!NT_STATUS_IS_OK(status)) {
4367 d_printf("Failed to open file %s. %s\n",
4368 targetsrc, nt_errstr(status));
4369 return 1;
4372 DesiredAccess = (FILE_READ_DATA|FILE_WRITE_DATA|FILE_APPEND_DATA|FILE_READ_EA|
4373 FILE_WRITE_EA|FILE_READ_ATTRIBUTES|FILE_WRITE_ATTRIBUTES|
4374 DELETE_ACCESS|READ_CONTROL_ACCESS|WRITE_DAC_ACCESS|SYNCHRONIZE_ACCESS);
4375 ShareAccess = FILE_SHARE_NONE;
4376 CreateDisposition = FILE_CREATE;
4377 CreateOptions = FILE_SEQUENTIAL_ONLY|FILE_NON_DIRECTORY_FILE;
4378 status = cli_ntcreate(targetcli, targetdest, 0, DesiredAccess,
4379 FILE_ATTRIBUTE_ARCHIVE, ShareAccess, CreateDisposition,
4380 CreateOptions, 0x0, &destfnum, NULL);
4381 if (!NT_STATUS_IS_OK(status)) {
4382 d_printf("Failed to create file %s. %s\n",
4383 targetdest, nt_errstr(status));
4384 cli_close(targetcli, srcfnum);
4385 return 1;
4388 clock_gettime_mono(&st.tp_start);
4389 status = cli_splice(targetcli, targetcli, srcfnum, destfnum,
4390 cr.end_of_file, 0, 0, &written, scopy_status, &st);
4391 if (!NT_STATUS_IS_OK(status)) {
4392 d_printf("%s copying file %s -> %s \n",
4393 nt_errstr(status),
4394 targetsrc,
4395 targetdest);
4396 rc = 1;
4399 status = cli_close(targetcli, srcfnum);
4400 if (!NT_STATUS_IS_OK(status)) {
4401 d_printf("Error %s closing remote source file\n", nt_errstr(status));
4402 rc = 1;
4404 status = cli_close(targetcli, destfnum);
4405 if (!NT_STATUS_IS_OK(status)) {
4406 d_printf("Error %s closing remote dest file\n", nt_errstr(status));
4407 rc = 1;
4410 return rc;
4413 /****************************************************************************
4414 Print the volume name.
4415 ****************************************************************************/
4417 static int cmd_volume(void)
4419 char *volname;
4420 uint32_t serial_num;
4421 time_t create_date;
4422 NTSTATUS status;
4424 status = cli_get_fs_volume_info(cli, talloc_tos(),
4425 &volname, &serial_num,
4426 &create_date);
4427 if (!NT_STATUS_IS_OK(status)) {
4428 d_printf("Error %s getting volume info\n", nt_errstr(status));
4429 return 1;
4432 d_printf("Volume: |%s| serial number 0x%x\n",
4433 volname, (unsigned int)serial_num);
4434 return 0;
4437 /****************************************************************************
4438 Hard link files using the NT call.
4439 ****************************************************************************/
4441 static int cmd_hardlink(void)
4443 TALLOC_CTX *ctx = talloc_tos();
4444 char *src, *dest;
4445 char *buf, *buf2;
4446 struct cli_state *targetcli;
4447 char *targetname;
4448 NTSTATUS status;
4450 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
4451 !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
4452 d_printf("hardlink <src> <dest>\n");
4453 return 1;
4456 src = talloc_asprintf(ctx,
4457 "%s%s",
4458 client_get_cur_dir(),
4459 buf);
4460 if (!src) {
4461 return 1;
4463 src = client_clean_name(ctx, src);
4464 if (src == NULL) {
4465 return 1;
4468 dest = talloc_asprintf(ctx,
4469 "%s%s",
4470 client_get_cur_dir(),
4471 buf2);
4472 if (!dest) {
4473 return 1;
4475 dest = client_clean_name(ctx, dest);
4476 if (dest == NULL) {
4477 return 1;
4480 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
4481 cli, src, &targetcli, &targetname);
4482 if (!NT_STATUS_IS_OK(status)) {
4483 d_printf("hardlink %s: %s\n", src, nt_errstr(status));
4484 return 1;
4487 status = cli_nt_hardlink(targetcli, targetname, dest);
4488 if (!NT_STATUS_IS_OK(status)) {
4489 d_printf("%s doing an NT hard link of files\n",
4490 nt_errstr(status));
4491 return 1;
4494 return 0;
4497 /****************************************************************************
4498 Toggle the prompt flag.
4499 ****************************************************************************/
4501 static int cmd_prompt(void)
4503 prompt = !prompt;
4504 DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
4505 return 1;
4508 /****************************************************************************
4509 Set the newer than time.
4510 ****************************************************************************/
4512 static int cmd_newer(void)
4514 TALLOC_CTX *ctx = talloc_tos();
4515 char *buf;
4516 bool ok;
4517 SMB_STRUCT_STAT sbuf;
4519 ok = next_token_talloc(ctx, &cmd_ptr,&buf,NULL);
4520 if (ok && (sys_stat(buf, &sbuf, false) == 0)) {
4521 newer_than = convert_timespec_to_time_t(sbuf.st_ex_mtime);
4522 DEBUG(1,("Getting files newer than %s",
4523 time_to_asc(newer_than)));
4524 } else {
4525 newer_than = 0;
4528 if (ok && newer_than == 0) {
4529 d_printf("Error setting newer-than time\n");
4530 return 1;
4533 return 0;
4536 /****************************************************************************
4537 Watch directory changes
4538 ****************************************************************************/
4540 static int cmd_notify(void)
4542 TALLOC_CTX *frame = talloc_stackframe();
4543 char *name, *buf;
4544 NTSTATUS status;
4545 uint16_t fnum;
4547 name = talloc_strdup(talloc_tos(), client_get_cur_dir());
4548 if (name == NULL) {
4549 goto fail;
4551 if (!next_token_talloc(talloc_tos(), &cmd_ptr, &buf, NULL)) {
4552 goto usage;
4554 name = talloc_asprintf_append(name, "%s", buf);
4555 if (name == NULL) {
4556 goto fail;
4558 name = client_clean_name(talloc_tos(), name);
4559 if (name == NULL) {
4560 return 1;
4562 status = cli_ntcreate(
4563 cli, name, 0, FILE_READ_DATA, 0,
4564 FILE_SHARE_READ|FILE_SHARE_WRITE|FILE_SHARE_DELETE,
4565 FILE_OPEN, 0, 0, &fnum, NULL);
4566 if (!NT_STATUS_IS_OK(status)) {
4567 d_printf("Could not open file: %s\n", nt_errstr(status));
4568 goto fail;
4571 while (1) {
4572 uint32_t i;
4573 uint32_t num_changes = 0;
4574 struct notify_change *changes = NULL;
4576 status = cli_notify(cli, fnum, 1000, FILE_NOTIFY_CHANGE_ALL,
4577 true,
4578 talloc_tos(), &num_changes, &changes);
4579 if (NT_STATUS_EQUAL(status, STATUS_NOTIFY_ENUM_DIR)) {
4580 printf("NOTIFY_ENUM_DIR\n");
4581 status = NT_STATUS_OK;
4583 if (!NT_STATUS_IS_OK(status)) {
4584 d_printf("notify returned %s\n",
4585 nt_errstr(status));
4586 goto fail;
4588 for (i=0; i<num_changes; i++) {
4589 printf("%4.4x %s\n", changes[i].action,
4590 changes[i].name);
4592 TALLOC_FREE(changes);
4594 usage:
4595 d_printf("notify <dir name>\n");
4596 fail:
4597 TALLOC_FREE(frame);
4598 return 1;
4601 /****************************************************************************
4602 Set the archive level.
4603 ****************************************************************************/
4605 static int cmd_archive(void)
4607 TALLOC_CTX *ctx = talloc_tos();
4608 char *buf;
4610 if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4611 archive_level = atoi(buf);
4612 } else {
4613 d_printf("Archive level is %d\n",archive_level);
4616 return 0;
4619 /****************************************************************************
4620 Toggle the backup_intent state.
4621 ****************************************************************************/
4623 static int cmd_backup(void)
4625 backup_intent = !backup_intent;
4626 cli_set_backup_intent(cli, backup_intent);
4627 DEBUG(2,("backup intent is now %s\n",backup_intent?"on":"off"));
4628 return 1;
4631 /****************************************************************************
4632 Toggle the lowercaseflag.
4633 ****************************************************************************/
4635 static int cmd_lowercase(void)
4637 lowercase = !lowercase;
4638 DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
4639 return 0;
4642 /****************************************************************************
4643 Toggle the case sensitive flag.
4644 ****************************************************************************/
4646 static int cmd_setcase(void)
4648 bool orig_case_sensitive = cli_set_case_sensitive(cli, false);
4650 cli_set_case_sensitive(cli, !orig_case_sensitive);
4651 DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
4652 "on":"off"));
4653 return 0;
4656 /****************************************************************************
4657 Toggle the showacls flag.
4658 ****************************************************************************/
4660 static int cmd_showacls(void)
4662 showacls = !showacls;
4663 DEBUG(2,("showacls is now %s\n",showacls?"on":"off"));
4664 return 0;
4668 /****************************************************************************
4669 Toggle the recurse flag.
4670 ****************************************************************************/
4672 static int cmd_recurse(void)
4674 recurse = !recurse;
4675 DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
4676 return 0;
4679 /****************************************************************************
4680 Toggle the translate flag.
4681 ****************************************************************************/
4683 static int cmd_translate(void)
4685 translation = !translation;
4686 DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
4687 translation?"on":"off"));
4688 return 0;
4691 /****************************************************************************
4692 Do the lcd command.
4693 ****************************************************************************/
4695 static int cmd_lcd(void)
4697 TALLOC_CTX *ctx = talloc_tos();
4698 char *buf;
4699 char *d;
4701 if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4702 if (chdir(buf) == -1) {
4703 d_printf("chdir to %s failed (%s)\n",
4704 buf, strerror(errno));
4707 d = sys_getwd();
4708 if (!d) {
4709 return 1;
4711 DEBUG(2,("the local directory is now %s\n",d));
4712 SAFE_FREE(d);
4713 return 0;
4716 /****************************************************************************
4717 Get a file restarting at end of local file.
4718 ****************************************************************************/
4720 static int cmd_reget(void)
4722 TALLOC_CTX *ctx = talloc_tos();
4723 char *local_name = NULL;
4724 char *remote_name = NULL;
4725 char *fname = NULL;
4726 char *p = NULL;
4728 remote_name = talloc_strdup(ctx, client_get_cur_dir());
4729 if (!remote_name) {
4730 return 1;
4733 if (!next_token_talloc(ctx, &cmd_ptr, &fname, NULL)) {
4734 d_printf("reget <filename>\n");
4735 return 1;
4737 remote_name = talloc_asprintf_append(remote_name, "%s", fname);
4738 if (!remote_name) {
4739 return 1;
4741 remote_name = client_clean_name(ctx,remote_name);
4742 if (!remote_name) {
4743 return 1;
4746 local_name = fname;
4747 next_token_talloc(ctx, &cmd_ptr, &p, NULL);
4748 if (p) {
4749 local_name = p;
4752 return do_get(remote_name, local_name, true);
4755 /****************************************************************************
4756 Put a file restarting at end of local file.
4757 ****************************************************************************/
4759 static int cmd_reput(void)
4761 TALLOC_CTX *ctx = talloc_tos();
4762 char *local_name = NULL;
4763 char *remote_name = NULL;
4764 char *buf;
4765 SMB_STRUCT_STAT st;
4767 remote_name = talloc_strdup(ctx, client_get_cur_dir());
4768 if (!remote_name) {
4769 return 1;
4772 if (!next_token_talloc(ctx, &cmd_ptr, &local_name, NULL)) {
4773 d_printf("reput <filename>\n");
4774 return 1;
4777 if (!file_exist_stat(local_name, &st, false)) {
4778 d_printf("%s does not exist\n", local_name);
4779 return 1;
4782 if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
4783 remote_name = talloc_asprintf_append(remote_name,
4784 "%s", buf);
4785 } else {
4786 remote_name = talloc_asprintf_append(remote_name,
4787 "%s", local_name);
4789 if (!remote_name) {
4790 return 1;
4793 remote_name = client_clean_name(ctx, remote_name);
4794 if (!remote_name) {
4795 return 1;
4798 return do_put(remote_name, local_name, true);
4801 /****************************************************************************
4802 List a share name.
4803 ****************************************************************************/
4805 static void browse_fn(const char *name, uint32_t m,
4806 const char *comment, void *state)
4808 const char *typestr = "";
4810 switch (m & 7) {
4811 case STYPE_DISKTREE:
4812 typestr = "Disk";
4813 break;
4814 case STYPE_PRINTQ:
4815 typestr = "Printer";
4816 break;
4817 case STYPE_DEVICE:
4818 typestr = "Device";
4819 break;
4820 case STYPE_IPC:
4821 typestr = "IPC";
4822 break;
4824 /* FIXME: If the remote machine returns non-ascii characters
4825 in any of these fields, they can corrupt the output. We
4826 should remove them. */
4827 if (!grepable) {
4828 d_printf("\t%-15s %-10.10s%s\n",
4829 name,typestr,comment);
4830 } else {
4831 d_printf ("%s|%s|%s\n",typestr,name,comment);
4835 static bool browse_host_rpc(bool sort)
4837 NTSTATUS status;
4838 struct rpc_pipe_client *pipe_hnd = NULL;
4839 TALLOC_CTX *frame = talloc_stackframe();
4840 WERROR werr;
4841 struct srvsvc_NetShareInfoCtr info_ctr;
4842 struct srvsvc_NetShareCtr1 ctr1;
4843 uint32_t resume_handle = 0;
4844 uint32_t total_entries = 0;
4845 int i;
4846 struct dcerpc_binding_handle *b;
4848 status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc,
4849 &pipe_hnd);
4851 if (!NT_STATUS_IS_OK(status)) {
4852 DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
4853 nt_errstr(status)));
4854 TALLOC_FREE(frame);
4855 return false;
4858 b = pipe_hnd->binding_handle;
4860 ZERO_STRUCT(info_ctr);
4861 ZERO_STRUCT(ctr1);
4863 info_ctr.level = 1;
4864 info_ctr.ctr.ctr1 = &ctr1;
4866 status = dcerpc_srvsvc_NetShareEnumAll(b, frame,
4867 pipe_hnd->desthost,
4868 &info_ctr,
4869 0xffffffff,
4870 &total_entries,
4871 &resume_handle,
4872 &werr);
4874 if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(werr)) {
4875 TALLOC_FREE(pipe_hnd);
4876 TALLOC_FREE(frame);
4877 return false;
4880 for (i=0; i < info_ctr.ctr.ctr1->count; i++) {
4881 struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
4882 browse_fn(info.name, info.type, info.comment, NULL);
4885 TALLOC_FREE(pipe_hnd);
4886 TALLOC_FREE(frame);
4887 return true;
4890 /****************************************************************************
4891 Try and browse available connections on a host.
4892 ****************************************************************************/
4894 static bool browse_host(bool sort)
4896 int ret;
4897 if (!grepable) {
4898 d_printf("\n\tSharename Type Comment\n");
4899 d_printf("\t--------- ---- -------\n");
4902 if (browse_host_rpc(sort)) {
4903 return true;
4906 if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1) {
4907 NTSTATUS status = cli_nt_error(cli);
4908 d_printf("Error returning browse list: %s\n",
4909 nt_errstr(status));
4912 return (ret != -1);
4915 /****************************************************************************
4916 List a server name.
4917 ****************************************************************************/
4919 static void server_fn(const char *name, uint32_t m,
4920 const char *comment, void *state)
4923 if (!grepable){
4924 d_printf("\t%-16s %s\n", name, comment);
4925 } else {
4926 d_printf("%s|%s|%s\n",(char *)state, name, comment);
4930 /****************************************************************************
4931 Try and browse available connections on a host.
4932 ****************************************************************************/
4934 static bool list_servers(const char *wk_grp)
4936 fstring state;
4938 if (!cli->server_domain)
4939 return false;
4941 if (!grepable) {
4942 d_printf("\n\tServer Comment\n");
4943 d_printf("\t--------- -------\n");
4945 fstrcpy( state, "Server" );
4946 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
4947 state);
4949 if (!grepable) {
4950 d_printf("\n\tWorkgroup Master\n");
4951 d_printf("\t--------- -------\n");
4954 fstrcpy( state, "Workgroup" );
4955 cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
4956 server_fn, state);
4957 return true;
4960 /****************************************************************************
4961 Print or set current VUID
4962 ****************************************************************************/
4964 static int cmd_vuid(void)
4966 TALLOC_CTX *ctx = talloc_tos();
4967 char *buf;
4969 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
4970 d_printf("Current VUID is %d\n",
4971 cli_state_get_uid(cli));
4972 return 0;
4975 cli_state_set_uid(cli, atoi(buf));
4976 return 0;
4979 /****************************************************************************
4980 Setup a new VUID, by issuing a session setup
4981 ****************************************************************************/
4983 static int cmd_logon(void)
4985 TALLOC_CTX *ctx = talloc_tos();
4986 char *l_username, *l_password;
4987 struct cli_credentials *creds = NULL;
4988 NTSTATUS nt_status;
4990 if (!next_token_talloc(ctx, &cmd_ptr,&l_username,NULL)) {
4991 d_printf("logon <username> [<password>]\n");
4992 return 0;
4995 if (!next_token_talloc(ctx, &cmd_ptr,&l_password,NULL)) {
4996 char pwd[256] = {0};
4997 int rc;
4999 rc = samba_getpass("Password: ", pwd, sizeof(pwd), false, false);
5000 if (rc == 0) {
5001 l_password = talloc_strdup(ctx, pwd);
5004 if (!l_password) {
5005 return 1;
5008 creds = cli_session_creds_init(ctx,
5009 l_username,
5010 lp_workgroup(),
5011 NULL, /* realm */
5012 l_password,
5013 false, /* use_kerberos */
5014 false, /* fallback_after_kerberos */
5015 false, /* use_ccache */
5016 false); /* password_is_nt_hash */
5017 if (creds == NULL) {
5018 d_printf("cli_session_creds_init() failed.\n");
5019 return -1;
5021 nt_status = cli_session_setup_creds(cli, creds);
5022 TALLOC_FREE(creds);
5023 if (!NT_STATUS_IS_OK(nt_status)) {
5024 d_printf("session setup failed: %s\n", nt_errstr(nt_status));
5025 return -1;
5028 d_printf("Current VUID is %d\n", cli_state_get_uid(cli));
5029 return 0;
5033 * close the session
5036 static int cmd_logoff(void)
5038 NTSTATUS status;
5040 status = cli_ulogoff(cli);
5041 if (!NT_STATUS_IS_OK(status)) {
5042 d_printf("logoff failed: %s\n", nt_errstr(status));
5043 return -1;
5046 d_printf("logoff successful\n");
5047 return 0;
5052 * tree connect (connect to a share)
5055 static int cmd_tcon(void)
5057 TALLOC_CTX *ctx = talloc_tos();
5058 char *sharename;
5059 NTSTATUS status;
5061 if (!next_token_talloc(ctx, &cmd_ptr, &sharename, NULL)) {
5062 d_printf("tcon <sharename>\n");
5063 return 0;
5066 if (!sharename) {
5067 return 1;
5070 status = cli_tree_connect(cli, sharename, "?????", NULL);
5071 if (!NT_STATUS_IS_OK(status)) {
5072 d_printf("tcon failed: %s\n", nt_errstr(status));
5073 return -1;
5076 talloc_free(sharename);
5078 d_printf("tcon to %s successful, tid: %u\n", sharename,
5079 cli_state_get_tid(cli));
5080 return 0;
5084 * tree disconnect (disconnect from a share)
5087 static int cmd_tdis(void)
5089 NTSTATUS status;
5091 status = cli_tdis(cli);
5092 if (!NT_STATUS_IS_OK(status)) {
5093 d_printf("tdis failed: %s\n", nt_errstr(status));
5094 return -1;
5097 d_printf("tdis successful\n");
5098 return 0;
5103 * get or set tid
5106 static int cmd_tid(void)
5108 TALLOC_CTX *ctx = talloc_tos();
5109 char *tid_str;
5111 if (!next_token_talloc(ctx, &cmd_ptr, &tid_str, NULL)) {
5112 if (cli_state_has_tcon(cli)) {
5113 d_printf("current tid is %d\n", cli_state_get_tid(cli));
5114 } else {
5115 d_printf("no tcon currently\n");
5117 } else {
5118 uint32_t tid = atoi(tid_str);
5119 if (!cli_state_has_tcon(cli)) {
5120 d_printf("no tcon currently\n");
5122 cli_state_set_tid(cli, tid);
5125 return 0;
5129 /****************************************************************************
5130 list active connections
5131 ****************************************************************************/
5133 static int cmd_list_connect(void)
5135 cli_cm_display(cli);
5136 return 0;
5139 /****************************************************************************
5140 display the current active client connection
5141 ****************************************************************************/
5143 static int cmd_show_connect( void )
5145 TALLOC_CTX *ctx = talloc_tos();
5146 struct cli_state *targetcli;
5147 char *targetpath;
5148 NTSTATUS status;
5150 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(), cli,
5151 client_get_cur_dir(), &targetcli,
5152 &targetpath);
5153 if (!NT_STATUS_IS_OK(status)) {
5154 d_printf("showconnect %s: %s\n", cur_dir, nt_errstr(status));
5155 return 1;
5158 d_printf("//%s/%s\n", smbXcli_conn_remote_name(targetcli->conn), targetcli->share);
5159 return 0;
5163 * set_remote_times - set times of a remote file
5164 * @filename: path to the file name
5165 * @create_time: New create time
5166 * @access_time: New access time
5167 * @write_time: New write time
5168 * @change_time: New metadata change time
5170 * Update the file times with the ones provided.
5172 static int set_remote_times(const char *filename, time_t create_time,
5173 time_t access_time, time_t write_time,
5174 time_t change_time)
5176 extern struct cli_state *cli;
5177 NTSTATUS status;
5179 status = cli_setpathinfo_basic(cli, filename, create_time,
5180 access_time, write_time,
5181 change_time, -1);
5182 if (!NT_STATUS_IS_OK(status)) {
5183 d_printf("cli_setpathinfo_basic failed: %s\n",
5184 nt_errstr(status));
5185 return 1;
5188 return 0;
5192 * cmd_utimes - interactive command to set the four times
5194 * Read a filename and four times from the client command line and update
5195 * the file times. A value of -1 for a time means don't change.
5197 static int cmd_utimes(void)
5199 const extern char *cmd_ptr;
5200 char *buf;
5201 char *fname = NULL;
5202 time_t times[4] = {0, 0, 0, 0};
5203 int time_count = 0;
5204 int err = 0;
5205 bool ok;
5206 TALLOC_CTX *ctx = talloc_new(NULL);
5207 if (ctx == NULL) {
5208 return 1;
5211 ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
5212 if (!ok) {
5213 d_printf("utimes <filename> <create-time> <access-time> "
5214 "<write-time> <change-time>\n");
5215 d_printf("Dates should be in YY:MM:DD-HH:MM:SS format "
5216 "or -1 for no change\n");
5217 err = 1;
5218 goto out;
5221 fname = talloc_asprintf(ctx,
5222 "%s%s",
5223 client_get_cur_dir(),
5224 buf);
5225 if (fname == NULL) {
5226 err = 1;
5227 goto out;
5229 fname = client_clean_name(ctx, fname);
5230 if (fname == NULL) {
5231 err = 1;
5232 goto out;
5235 while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL) &&
5236 time_count < 4) {
5237 const char *s = buf;
5238 struct tm tm = {0,};
5239 char *ret;
5241 if (strlen(s) == 2 && strcmp(s, "-1") == 0) {
5242 times[time_count] = 0;
5243 time_count++;
5244 continue;
5245 } else {
5246 ret = strptime(s, "%y:%m:%d-%H:%M:%S", &tm);
5249 /* We could not match all the chars, so print error */
5250 if (ret == NULL || *ret != 0) {
5251 d_printf("Invalid date format: %s\n", s);
5252 d_printf("utimes <filename> <create-time> "
5253 "<access-time> <write-time> <change-time>\n");
5254 d_printf("Dates should be in YY:MM:DD-HH:MM:SS format "
5255 "or -1 for no change\n");
5256 err = 1;
5257 goto out;
5260 /* Convert tm to a time_t */
5261 times[time_count] = mktime(&tm);
5262 time_count++;
5265 if (time_count < 4) {
5266 d_printf("Insufficient dates: %d\n", time_count);
5267 d_printf("utimes <filename> <create-time> <access-time> "
5268 "<write-time> <change-time>\n");
5269 d_printf("Dates should be in YY:MM:DD-HH:MM:SS format "
5270 "or -1 for no change\n");
5271 err = 1;
5272 goto out;
5275 DEBUG(10, ("times\nCreate: %sAccess: %s Write: %sChange: %s\n",
5276 talloc_strdup(ctx, ctime(&times[0])),
5277 talloc_strdup(ctx, ctime(&times[1])),
5278 talloc_strdup(ctx, ctime(&times[2])),
5279 talloc_strdup(ctx, ctime(&times[3]))));
5281 set_remote_times(fname, times[0], times[1], times[2], times[3]);
5282 out:
5283 talloc_free(ctx);
5284 return err;
5288 * set_remote_attr - set DOS attributes of a remote file
5289 * @filename: path to the file name
5290 * @new_attr: attribute bit mask to use
5291 * @mode: one of ATTR_SET or ATTR_UNSET
5293 * Update the file attributes with the one provided.
5295 int set_remote_attr(const char *filename, uint16_t new_attr, int mode)
5297 extern struct cli_state *cli;
5298 uint16_t old_attr;
5299 NTSTATUS status;
5301 status = cli_getatr(cli, filename, &old_attr, NULL, NULL);
5302 if (!NT_STATUS_IS_OK(status)) {
5303 d_printf("cli_getatr failed: %s\n", nt_errstr(status));
5304 return 1;
5307 if (mode == ATTR_SET) {
5308 new_attr |= old_attr;
5309 } else {
5310 new_attr = old_attr & ~new_attr;
5313 status = cli_setatr(cli, filename, new_attr, 0);
5314 if (!NT_STATUS_IS_OK(status)) {
5315 d_printf("cli_setatr failed: %s\n", nt_errstr(status));
5316 return 1;
5319 return 0;
5323 * cmd_setmode - interactive command to set DOS attributes
5325 * Read a filename and mode from the client command line and update
5326 * the file DOS attributes.
5328 int cmd_setmode(void)
5330 const extern char *cmd_ptr;
5331 char *buf;
5332 char *fname = NULL;
5333 uint16_t attr[2] = {0};
5334 int mode = ATTR_SET;
5335 int err = 0;
5336 bool ok;
5337 TALLOC_CTX *ctx = talloc_new(NULL);
5338 if (ctx == NULL) {
5339 return 1;
5342 ok = next_token_talloc(ctx, &cmd_ptr, &buf, NULL);
5343 if (!ok) {
5344 d_printf("setmode <filename> <[+|-]rsha>\n");
5345 err = 1;
5346 goto out;
5349 fname = talloc_asprintf(ctx,
5350 "%s%s",
5351 client_get_cur_dir(),
5352 buf);
5353 if (fname == NULL) {
5354 err = 1;
5355 goto out;
5357 fname = client_clean_name(ctx, fname);
5358 if (fname == NULL) {
5359 err = 1;
5360 goto out;
5363 while (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
5364 const char *s = buf;
5366 while (*s) {
5367 switch (*s++) {
5368 case '+':
5369 mode = ATTR_SET;
5370 break;
5371 case '-':
5372 mode = ATTR_UNSET;
5373 break;
5374 case 'r':
5375 attr[mode] |= FILE_ATTRIBUTE_READONLY;
5376 break;
5377 case 'h':
5378 attr[mode] |= FILE_ATTRIBUTE_HIDDEN;
5379 break;
5380 case 's':
5381 attr[mode] |= FILE_ATTRIBUTE_SYSTEM;
5382 break;
5383 case 'a':
5384 attr[mode] |= FILE_ATTRIBUTE_ARCHIVE;
5385 break;
5386 default:
5387 d_printf("setmode <filename> <perm=[+|-]rsha>\n");
5388 err = 1;
5389 goto out;
5394 if (attr[ATTR_SET] == 0 && attr[ATTR_UNSET] == 0) {
5395 d_printf("setmode <filename> <[+|-]rsha>\n");
5396 err = 1;
5397 goto out;
5400 DEBUG(2, ("perm set %d %d\n", attr[ATTR_SET], attr[ATTR_UNSET]));
5402 /* ignore return value: server might not store DOS attributes */
5403 set_remote_attr(fname, attr[ATTR_SET], ATTR_SET);
5404 set_remote_attr(fname, attr[ATTR_UNSET], ATTR_UNSET);
5405 out:
5406 talloc_free(ctx);
5407 return err;
5410 /****************************************************************************
5411 iosize command
5412 ***************************************************************************/
5414 int cmd_iosize(void)
5416 TALLOC_CTX *ctx = talloc_tos();
5417 char *buf;
5418 int iosize;
5420 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5421 if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_SMB2_02) {
5422 if (!smb_encrypt) {
5423 d_printf("iosize <n> or iosize 0x<n>. "
5424 "Minimum is 0 (default), "
5425 "max is 16776960 (0xFFFF00)\n");
5426 } else {
5427 d_printf("iosize <n> or iosize 0x<n>. "
5428 "(Encrypted connection) ,"
5429 "Minimum is 0 (default), "
5430 "max is 130048 (0x1FC00)\n");
5432 } else {
5433 d_printf("iosize <n> or iosize 0x<n>.\n");
5435 return 1;
5438 iosize = strtol(buf,NULL,0);
5439 if (smbXcli_conn_protocol(cli->conn) < PROTOCOL_SMB2_02) {
5440 if (smb_encrypt && (iosize < 0 || iosize > 0xFC00)) {
5441 d_printf("iosize out of range for encrypted "
5442 "connection (min = 0 (default), "
5443 "max = 130048 (0x1FC00)\n");
5444 return 1;
5445 } else if (!smb_encrypt && (iosize < 0 || iosize > 0xFFFF00)) {
5446 d_printf("iosize out of range (min = 0 (default), "
5447 "max = 16776960 (0xFFFF00)\n");
5448 return 1;
5452 io_bufsize = iosize;
5453 d_printf("iosize is now %d\n", io_bufsize);
5454 return 0;
5457 /****************************************************************************
5458 timeout command
5459 ***************************************************************************/
5461 static int cmd_timeout(void)
5463 TALLOC_CTX *ctx = talloc_tos();
5464 char *buf;
5466 if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5467 unsigned int old_timeout = cli_set_timeout(cli, 0);
5468 cli_set_timeout(cli, old_timeout);
5469 d_printf("timeout <n> (per-operation timeout "
5470 "in seconds - currently %u).\n",
5471 old_timeout/1000);
5472 return 1;
5475 io_timeout = strtol(buf,NULL,0);
5476 cli_set_timeout(cli, io_timeout*1000);
5477 d_printf("io_timeout per operation is now %d\n", io_timeout);
5478 return 0;
5482 /****************************************************************************
5483 history
5484 ****************************************************************************/
5485 static int cmd_history(void)
5487 #if defined(HAVE_LIBREADLINE) && defined(HAVE_HISTORY_LIST)
5488 HIST_ENTRY **hlist;
5489 int i;
5491 hlist = history_list();
5493 for (i = 0; hlist && hlist[i]; i++) {
5494 DEBUG(0, ("%d: %s\n", i, hlist[i]->line));
5496 #else
5497 DEBUG(0,("no history without readline support\n"));
5498 #endif
5500 return 0;
5503 /* Some constants for completing filename arguments */
5505 #define COMPL_NONE 0 /* No completions */
5506 #define COMPL_REMOTE 1 /* Complete remote filename */
5507 #define COMPL_LOCAL 2 /* Complete local filename */
5509 /* This defines the commands supported by this client.
5510 * NOTE: The "!" must be the last one in the list because it's fn pointer
5511 * field is NULL, and NULL in that field is used in process_tok()
5512 * (below) to indicate the end of the list. crh
5514 static struct {
5515 const char *name;
5516 int (*fn)(void);
5517 const char *description;
5518 char compl_args[2]; /* Completion argument info */
5519 } commands[] = {
5520 {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
5521 {"allinfo",cmd_allinfo,"<file> show all available info",
5522 {COMPL_NONE,COMPL_NONE}},
5523 {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
5524 {"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}},
5525 {"backup",cmd_backup,"toggle backup intent state",{COMPL_NONE,COMPL_NONE}},
5526 {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
5527 {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
5528 {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
5529 {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
5530 {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_NONE}},
5531 {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_NONE}},
5532 {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_NONE}},
5533 {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5534 {"deltree",cmd_deltree,"<mask> recursively delete all matching files and directories",{COMPL_REMOTE,COMPL_NONE}},
5535 {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5536 {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5537 {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
5538 {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5539 {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
5540 {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_NONE}},
5541 {"geteas", cmd_geteas, "<file name> get the EA list of a file",
5542 {COMPL_REMOTE, COMPL_NONE}},
5543 {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
5544 {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
5545 {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
5546 {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
5547 {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
5548 {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
5549 {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
5550 {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
5551 {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5552 {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
5553 {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
5554 {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
5555 {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
5556 {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
5557 {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
5558 {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
5559 {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
5560 {"notify",cmd_notify,"<file>Get notified of dir changes",{COMPL_REMOTE,COMPL_NONE}},
5561 {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
5562 {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
5563 {"posix_encrypt",cmd_posix_encrypt,"<domain> <user> <password> start up transport encryption",{COMPL_REMOTE,COMPL_NONE}},
5564 {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5565 {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5566 {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5567 {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5568 {"posix_whoami",cmd_posix_whoami,"return logged on user information "
5569 "using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
5570 {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
5571 {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
5572 {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
5573 {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
5574 {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5575 {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
5576 {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
5577 {"readlink",cmd_readlink,"filename Do a UNIX extensions readlink call on a symlink",{COMPL_REMOTE,COMPL_REMOTE}},
5578 {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
5579 {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
5580 {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
5581 {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
5582 {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
5583 {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5584 {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_REMOTE,COMPL_NONE}},
5585 {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},
5586 {"setea", cmd_setea, "<file name> <eaname> <eaval> Set an EA of a file",
5587 {COMPL_REMOTE, COMPL_LOCAL}},
5588 {"setmode",cmd_setmode,"<file name> <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
5589 {"scopy",cmd_scopy,"<src> <dest> server-side copy file",{COMPL_REMOTE,COMPL_REMOTE}},
5590 {"stat",cmd_stat,"<file name> Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_NONE}},
5591 {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
5592 {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
5593 {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
5594 {"timeout",cmd_timeout,"timeout <number> - set the per-operation timeout in seconds (default 20)",{COMPL_NONE,COMPL_NONE}},
5595 {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
5596 {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
5597 {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
5598 {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
5599 {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
5600 {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
5601 {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
5602 {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
5603 {"tcon",cmd_tcon,"connect to a share" ,{COMPL_NONE,COMPL_NONE}},
5604 {"tdis",cmd_tdis,"disconnect from a share",{COMPL_NONE,COMPL_NONE}},
5605 {"tid",cmd_tid,"show or set the current tid (tree-id)",{COMPL_NONE,COMPL_NONE}},
5606 {"utimes", cmd_utimes,"<file name> <create_time> <access_time> <mod_time> "
5607 "<ctime> set times", {COMPL_REMOTE,COMPL_NONE}},
5608 {"logoff",cmd_logoff,"log off (close the session)",{COMPL_NONE,COMPL_NONE}},
5609 {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
5611 /* Yes, this must be here, see crh's comment above. */
5612 {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
5613 {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
5616 /*******************************************************************
5617 Lookup a command string in the list of commands, including
5618 abbreviations.
5619 ******************************************************************/
5621 static int process_tok(char *tok)
5623 size_t i = 0, matches = 0;
5624 size_t cmd=0;
5625 size_t tok_len = strlen(tok);
5627 while (commands[i].fn != NULL) {
5628 if (strequal(commands[i].name,tok)) {
5629 matches = 1;
5630 cmd = i;
5631 break;
5632 } else if (strnequal(commands[i].name, tok, tok_len)) {
5633 matches++;
5634 cmd = i;
5636 i++;
5639 if (matches == 0)
5640 return(-1);
5641 else if (matches == 1)
5642 return(cmd);
5643 else
5644 return(-2);
5647 /****************************************************************************
5648 Help.
5649 ****************************************************************************/
5651 static int cmd_help(void)
5653 TALLOC_CTX *ctx = talloc_tos();
5654 int i=0,j;
5655 char *buf;
5657 if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
5658 if ((i = process_tok(buf)) >= 0)
5659 d_printf("HELP %s:\n\t%s\n\n",
5660 commands[i].name,commands[i].description);
5661 } else {
5662 while (commands[i].description) {
5663 for (j=0; commands[i].description && (j<5); j++) {
5664 d_printf("%-15s",commands[i].name);
5665 i++;
5667 d_printf("\n");
5670 return 0;
5673 /****************************************************************************
5674 Process a -c command string.
5675 ****************************************************************************/
5677 static int process_command_string(const char *cmd_in)
5679 TALLOC_CTX *ctx = talloc_tos();
5680 char *cmd = talloc_strdup(ctx, cmd_in);
5681 int rc = 0;
5683 if (!cmd) {
5684 return 1;
5686 /* establish the connection if not already */
5688 if (!cli) {
5689 NTSTATUS status;
5691 status = cli_cm_open(talloc_tos(), NULL,
5692 have_ip ? dest_ss_str : desthost,
5693 service, popt_get_cmdline_auth_info(),
5694 smb_encrypt,
5695 max_protocol, port, name_type,
5696 &cli);
5697 if (!NT_STATUS_IS_OK(status)) {
5698 return 1;
5700 cli_set_timeout(cli, io_timeout*1000);
5703 while (cmd[0] != '\0') {
5704 char *line;
5705 char *p;
5706 char *tok;
5707 int i;
5709 if ((p = strchr_m(cmd, ';')) == 0) {
5710 line = cmd;
5711 cmd += strlen(cmd);
5712 } else {
5713 *p = '\0';
5714 line = cmd;
5715 cmd = p + 1;
5718 /* and get the first part of the command */
5719 cmd_ptr = line;
5720 if (!next_token_talloc(ctx, &cmd_ptr,&tok,NULL)) {
5721 continue;
5724 if ((i = process_tok(tok)) >= 0) {
5725 rc = commands[i].fn();
5726 } else if (i == -2) {
5727 d_printf("%s: command abbreviation ambiguous\n",tok);
5728 } else {
5729 d_printf("%s: command not found\n",tok);
5733 return rc;
5736 #define MAX_COMPLETIONS 100
5738 struct completion_remote {
5739 char *dirmask;
5740 char **matches;
5741 int count, samelen;
5742 const char *text;
5743 int len;
5746 static NTSTATUS completion_remote_filter(const char *mnt,
5747 struct file_info *f,
5748 const char *mask,
5749 void *state)
5751 struct completion_remote *info = (struct completion_remote *)state;
5753 if (info->count >= MAX_COMPLETIONS - 1) {
5754 return NT_STATUS_OK;
5756 if (strncmp(info->text, f->name, info->len) != 0) {
5757 return NT_STATUS_OK;
5759 if (ISDOT(f->name) || ISDOTDOT(f->name)) {
5760 return NT_STATUS_OK;
5763 if ((info->dirmask[0] == 0) && !(f->mode & FILE_ATTRIBUTE_DIRECTORY))
5764 info->matches[info->count] = SMB_STRDUP(f->name);
5765 else {
5766 TALLOC_CTX *ctx = talloc_stackframe();
5767 char *tmp;
5769 tmp = talloc_strdup(ctx,info->dirmask);
5770 if (!tmp) {
5771 TALLOC_FREE(ctx);
5772 return NT_STATUS_NO_MEMORY;
5774 tmp = talloc_asprintf_append(tmp, "%s", f->name);
5775 if (!tmp) {
5776 TALLOC_FREE(ctx);
5777 return NT_STATUS_NO_MEMORY;
5779 if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
5780 tmp = talloc_asprintf_append(tmp, "%s",
5781 CLI_DIRSEP_STR);
5783 if (!tmp) {
5784 TALLOC_FREE(ctx);
5785 return NT_STATUS_NO_MEMORY;
5787 info->matches[info->count] = SMB_STRDUP(tmp);
5788 TALLOC_FREE(ctx);
5790 if (info->matches[info->count] == NULL) {
5791 return NT_STATUS_OK;
5793 if (f->mode & FILE_ATTRIBUTE_DIRECTORY) {
5794 smb_readline_ca_char(0);
5796 if (info->count == 1) {
5797 info->samelen = strlen(info->matches[info->count]);
5798 } else {
5799 while (strncmp(info->matches[info->count],
5800 info->matches[info->count-1],
5801 info->samelen) != 0) {
5802 info->samelen--;
5805 info->count++;
5806 return NT_STATUS_OK;
5809 static char **remote_completion(const char *text, int len)
5811 TALLOC_CTX *ctx = talloc_stackframe();
5812 char *dirmask = NULL;
5813 char *targetpath = NULL;
5814 struct cli_state *targetcli = NULL;
5815 int i;
5816 struct completion_remote info = { NULL, NULL, 1, 0, NULL, 0 };
5817 NTSTATUS status;
5819 /* can't have non-static initialisation on Sun CC, so do it
5820 at run time here */
5821 info.samelen = len;
5822 info.text = text;
5823 info.len = len;
5825 info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
5826 if (!info.matches) {
5827 TALLOC_FREE(ctx);
5828 return NULL;
5832 * We're leaving matches[0] free to fill it later with the text to
5833 * display: Either the one single match or the longest common subset
5834 * of the matches.
5836 info.matches[0] = NULL;
5837 info.count = 1;
5839 for (i = len-1; i >= 0; i--) {
5840 if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
5841 break;
5845 info.text = text+i+1;
5846 info.samelen = info.len = len-i-1;
5848 if (i > 0) {
5849 info.dirmask = SMB_MALLOC_ARRAY(char, i+2);
5850 if (!info.dirmask) {
5851 goto cleanup;
5853 strncpy(info.dirmask, text, i+1);
5854 info.dirmask[i+1] = 0;
5855 dirmask = talloc_asprintf(ctx,
5856 "%s%*s*",
5857 client_get_cur_dir(),
5858 i-1,
5859 text);
5860 } else {
5861 info.dirmask = SMB_STRDUP("");
5862 if (!info.dirmask) {
5863 goto cleanup;
5865 dirmask = talloc_asprintf(ctx,
5866 "%s*",
5867 client_get_cur_dir());
5869 if (!dirmask) {
5870 goto cleanup;
5872 dirmask = client_clean_name(ctx, dirmask);
5873 if (dirmask == NULL) {
5874 goto cleanup;
5877 status = cli_resolve_path(ctx, "", popt_get_cmdline_auth_info(),
5878 cli, dirmask, &targetcli, &targetpath);
5879 if (!NT_STATUS_IS_OK(status)) {
5880 goto cleanup;
5882 status = cli_list(targetcli, targetpath, FILE_ATTRIBUTE_DIRECTORY | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_HIDDEN,
5883 completion_remote_filter, (void *)&info);
5884 if (!NT_STATUS_IS_OK(status)) {
5885 goto cleanup;
5888 if (info.count == 1) {
5890 * No matches at all, NULL indicates there is nothing
5892 SAFE_FREE(info.matches[0]);
5893 SAFE_FREE(info.matches);
5894 TALLOC_FREE(ctx);
5895 return NULL;
5898 if (info.count == 2) {
5900 * Exactly one match in matches[1], indicate this is the one
5901 * in matches[0].
5903 info.matches[0] = info.matches[1];
5904 info.matches[1] = NULL;
5905 info.count -= 1;
5906 TALLOC_FREE(ctx);
5907 return info.matches;
5911 * We got more than one possible match, set the result to the maximum
5912 * common subset
5915 info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
5916 info.matches[info.count] = NULL;
5917 TALLOC_FREE(ctx);
5918 return info.matches;
5920 cleanup:
5921 for (i = 0; i < info.count; i++) {
5922 SAFE_FREE(info.matches[i]);
5924 SAFE_FREE(info.matches);
5925 SAFE_FREE(info.dirmask);
5926 TALLOC_FREE(ctx);
5927 return NULL;
5930 static char **completion_fn(const char *text, int start, int end)
5932 smb_readline_ca_char(' ');
5934 if (start) {
5935 const char *buf, *sp;
5936 int i;
5937 char compl_type;
5939 buf = smb_readline_get_line_buffer();
5940 if (buf == NULL)
5941 return NULL;
5943 sp = strchr(buf, ' ');
5944 if (sp == NULL)
5945 return NULL;
5947 for (i = 0; commands[i].name; i++) {
5948 if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
5949 (commands[i].name[sp - buf] == 0)) {
5950 break;
5953 if (commands[i].name == NULL)
5954 return NULL;
5956 while (*sp == ' ')
5957 sp++;
5959 if (sp == (buf + start))
5960 compl_type = commands[i].compl_args[0];
5961 else
5962 compl_type = commands[i].compl_args[1];
5964 if (compl_type == COMPL_REMOTE)
5965 return remote_completion(text, end - start);
5966 else /* fall back to local filename completion */
5967 return NULL;
5968 } else {
5969 char **matches;
5970 size_t i, len, samelen = 0, count=1;
5972 matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
5973 if (!matches) {
5974 return NULL;
5976 matches[0] = NULL;
5978 len = strlen(text);
5979 for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
5980 if (strncmp(text, commands[i].name, len) == 0) {
5981 matches[count] = SMB_STRDUP(commands[i].name);
5982 if (!matches[count])
5983 goto cleanup;
5984 if (count == 1)
5985 samelen = strlen(matches[count]);
5986 else
5987 while (strncmp(matches[count], matches[count-1], samelen) != 0)
5988 samelen--;
5989 count++;
5993 switch (count) {
5994 case 0: /* should never happen */
5995 case 1:
5996 goto cleanup;
5997 case 2:
5998 matches[0] = SMB_STRDUP(matches[1]);
5999 break;
6000 default:
6001 matches[0] = (char *)SMB_MALLOC(samelen+1);
6002 if (!matches[0])
6003 goto cleanup;
6004 strncpy(matches[0], matches[1], samelen);
6005 matches[0][samelen] = 0;
6007 matches[count] = NULL;
6008 return matches;
6010 cleanup:
6011 for (i = 0; i < count; i++)
6012 free(matches[i]);
6014 free(matches);
6015 return NULL;
6019 static bool finished;
6021 /****************************************************************************
6022 Make sure we swallow keepalives during idle time.
6023 ****************************************************************************/
6025 static void readline_callback(void)
6027 static time_t last_t;
6028 struct timespec now;
6029 time_t t;
6030 NTSTATUS status;
6031 unsigned char garbage[16];
6033 clock_gettime_mono(&now);
6034 t = now.tv_sec;
6036 if (t - last_t < 5)
6037 return;
6039 last_t = t;
6041 /* Ping the server to keep the connection alive using SMBecho. */
6042 memset(garbage, 0xf0, sizeof(garbage));
6043 status = cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
6044 if (NT_STATUS_IS_OK(status) ||
6045 NT_STATUS_EQUAL(status, NT_STATUS_INVALID_PARAMETER)) {
6047 * Even if server returns NT_STATUS_INVALID_PARAMETER
6048 * it still responded.
6049 * BUG: https://bugzilla.samba.org/show_bug.cgi?id=13007
6051 return;
6054 if (!cli_state_is_connected(cli)) {
6055 DEBUG(0,("SMBecho failed (%s). The connection is "
6056 "disconnected now\n", nt_errstr(status)));
6057 finished = true;
6058 smb_readline_done();
6062 /****************************************************************************
6063 Process commands on stdin.
6064 ****************************************************************************/
6066 static int process_stdin(void)
6068 int rc = 0;
6070 if (!quiet) {
6071 d_printf("Try \"help\" to get a list of possible commands.\n");
6074 while (!finished) {
6075 TALLOC_CTX *frame = talloc_stackframe();
6076 char *tok = NULL;
6077 char *the_prompt = NULL;
6078 char *line = NULL;
6079 int i;
6081 /* display a prompt */
6082 if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
6083 TALLOC_FREE(frame);
6084 break;
6086 line = smb_readline(the_prompt, readline_callback, completion_fn);
6087 SAFE_FREE(the_prompt);
6088 if (!line) {
6089 TALLOC_FREE(frame);
6090 break;
6093 /* special case - first char is ! */
6094 if (*line == '!') {
6095 if (system(line + 1) == -1) {
6096 d_printf("system() command %s failed.\n",
6097 line+1);
6099 SAFE_FREE(line);
6100 TALLOC_FREE(frame);
6101 continue;
6104 /* and get the first part of the command */
6105 cmd_ptr = line;
6106 if (!next_token_talloc(frame, &cmd_ptr,&tok,NULL)) {
6107 TALLOC_FREE(frame);
6108 SAFE_FREE(line);
6109 continue;
6112 if ((i = process_tok(tok)) >= 0) {
6113 rc = commands[i].fn();
6114 } else if (i == -2) {
6115 d_printf("%s: command abbreviation ambiguous\n",tok);
6116 } else {
6117 d_printf("%s: command not found\n",tok);
6119 SAFE_FREE(line);
6120 TALLOC_FREE(frame);
6122 return rc;
6125 /****************************************************************************
6126 Process commands from the client.
6127 ****************************************************************************/
6129 static int process(const char *base_directory)
6131 int rc = 0;
6132 NTSTATUS status;
6134 status = cli_cm_open(talloc_tos(), NULL,
6135 have_ip ? dest_ss_str : desthost,
6136 service, popt_get_cmdline_auth_info(),
6137 smb_encrypt, max_protocol, port,
6138 name_type, &cli);
6139 if (!NT_STATUS_IS_OK(status)) {
6140 return 1;
6143 cli_set_timeout(cli, io_timeout*1000);
6145 if (base_directory && *base_directory) {
6146 rc = do_cd(base_directory);
6147 if (rc) {
6148 cli_shutdown(cli);
6149 return rc;
6153 if (cmdstr) {
6154 rc = process_command_string(cmdstr);
6155 } else {
6156 process_stdin();
6159 cli_shutdown(cli);
6160 return rc;
6163 /****************************************************************************
6164 Handle a -L query.
6165 ****************************************************************************/
6167 static int do_host_query(const char *query_host)
6169 NTSTATUS status;
6171 status = cli_cm_open(talloc_tos(), NULL,
6172 have_ip ? dest_ss_str : query_host,
6173 "IPC$", popt_get_cmdline_auth_info(),
6174 smb_encrypt, max_protocol, port,
6175 name_type, &cli);
6176 if (!NT_STATUS_IS_OK(status)) {
6177 return 1;
6180 cli_set_timeout(cli, io_timeout*1000);
6181 browse_host(true);
6183 /* Ensure that the host can do IPv4 */
6185 if (!interpret_addr(query_host)) {
6186 struct sockaddr_storage ss;
6187 if (interpret_string_addr(&ss, query_host, 0) &&
6188 (ss.ss_family != AF_INET)) {
6189 d_printf("%s is an IPv6 address -- no workgroup available\n",
6190 query_host);
6191 return 1;
6195 if (lp_client_min_protocol() > PROTOCOL_NT1) {
6196 d_printf("SMB1 disabled -- no workgroup available\n");
6197 goto out;
6200 if (lp_disable_netbios()) {
6201 d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
6202 goto out;
6205 if (port != NBT_SMB_PORT ||
6206 smbXcli_conn_protocol(cli->conn) > PROTOCOL_NT1)
6208 int max_proto = MIN(max_protocol, PROTOCOL_NT1);
6211 * Workgroups simply don't make sense over anything
6212 * else but port 139 and SMB1.
6215 cli_shutdown(cli);
6216 d_printf("Reconnecting with SMB1 for workgroup listing.\n");
6217 status = cli_cm_open(talloc_tos(), NULL,
6218 have_ip ? dest_ss_str : query_host,
6219 "IPC$", popt_get_cmdline_auth_info(),
6220 smb_encrypt, max_proto,
6221 NBT_SMB_PORT, name_type, &cli);
6222 if (!NT_STATUS_IS_OK(status)) {
6223 d_printf("Failed to connect with SMB1 "
6224 "-- no workgroup available\n");
6225 return 0;
6229 cli_set_timeout(cli, io_timeout*1000);
6230 list_servers(lp_workgroup());
6231 out:
6232 cli_shutdown(cli);
6234 return(0);
6237 /****************************************************************************
6238 Handle a tar operation.
6239 ****************************************************************************/
6241 static int do_tar_op(const char *base_directory)
6243 struct tar *tar_ctx = tar_get_ctx();
6244 int ret = 0;
6246 /* do we already have a connection? */
6247 if (!cli) {
6248 NTSTATUS status;
6250 status = cli_cm_open(talloc_tos(), NULL,
6251 have_ip ? dest_ss_str : desthost,
6252 service, popt_get_cmdline_auth_info(),
6253 smb_encrypt, max_protocol,
6254 port, name_type, &cli);
6255 if (!NT_STATUS_IS_OK(status)) {
6256 ret = 1;
6257 goto out;
6259 cli_set_timeout(cli, io_timeout*1000);
6262 recurse = true;
6264 if (base_directory && *base_directory) {
6265 ret = do_cd(base_directory);
6266 if (ret) {
6267 goto out_cli;
6271 ret = tar_process(tar_ctx);
6273 out_cli:
6274 cli_shutdown(cli);
6275 out:
6276 return ret;
6279 /****************************************************************************
6280 Handle a message operation.
6281 ****************************************************************************/
6283 static int do_message_op(struct user_auth_info *a_info)
6285 NTSTATUS status;
6287 if (lp_disable_netbios()) {
6288 d_printf("NetBIOS over TCP disabled.\n");
6289 return 1;
6292 status = cli_connect_nb(desthost, have_ip ? &dest_ss : NULL,
6293 port ? port : NBT_SMB_PORT, name_type,
6294 lp_netbios_name(), SMB_SIGNING_DEFAULT, 0, &cli);
6295 if (!NT_STATUS_IS_OK(status)) {
6296 d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
6297 return 1;
6300 cli_set_timeout(cli, io_timeout*1000);
6301 send_message(get_cmdline_auth_info_username(a_info));
6302 cli_shutdown(cli);
6304 return 0;
6307 /****************************************************************************
6308 main program
6309 ****************************************************************************/
6311 int main(int argc,char *argv[])
6313 const char **const_argv = discard_const_p(const char *, argv);
6314 char *base_directory = NULL;
6315 int opt;
6316 char *query_host = NULL;
6317 bool message = false;
6318 static const char *new_name_resolve_order = NULL;
6319 poptContext pc;
6320 char *p;
6321 int rc = 0;
6322 bool tar_opt = false;
6323 bool service_opt = false;
6324 struct tar *tar_ctx = tar_get_ctx();
6326 struct poptOption long_options[] = {
6327 POPT_AUTOHELP
6329 { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
6330 { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
6331 { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
6332 { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
6333 { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
6334 { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
6335 { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
6336 { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
6337 { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" },
6338 { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
6339 { "timeout", 't', POPT_ARG_INT, &io_timeout, 'b', "Changes the per-operation timeout", "SECONDS" },
6340 { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
6341 { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
6342 { "quiet", 'q', POPT_ARG_NONE, NULL, 'q', "Suppress help message" },
6343 { "browse", 'B', POPT_ARG_NONE, NULL, 'B', "Browse SMB servers using DNS" },
6344 POPT_COMMON_SAMBA
6345 POPT_COMMON_CONNECTION
6346 POPT_COMMON_CREDENTIALS
6347 POPT_TABLEEND
6349 TALLOC_CTX *frame = talloc_stackframe();
6351 if (!client_set_cur_dir("\\")) {
6352 exit(ENOMEM);
6355 /* set default debug level to 1 regardless of what smb.conf sets */
6356 setup_logging( "smbclient", DEBUG_DEFAULT_STDERR );
6357 smb_init_locale();
6359 lp_set_cmdline("log level", "1");
6361 popt_common_credentials_set_ignore_missing_conf();
6362 popt_common_credentials_set_delay_post();
6364 /* skip argv(0) */
6365 pc = poptGetContext("smbclient", argc, const_argv, long_options, 0);
6366 poptSetOtherOptionHelp(pc, "service <password>");
6368 while ((opt = poptGetNextOpt(pc)) != -1) {
6370 /* if the tar option has been called previouslt, now we need to eat out the leftovers */
6371 /* I see no other way to keep things sane --SSS */
6372 if (tar_opt == true) {
6373 while (poptPeekArg(pc)) {
6374 poptGetArg(pc);
6376 tar_opt = false;
6379 /* if the service has not yet been specified lets see if it is available in the popt stack */
6380 if (!service_opt && poptPeekArg(pc)) {
6381 service = talloc_strdup(frame, poptGetArg(pc));
6382 if (!service) {
6383 exit(ENOMEM);
6385 service_opt = true;
6388 /* if the service has already been retrieved then check if we have also a password */
6389 if (service_opt
6390 && (!get_cmdline_auth_info_got_pass(
6391 popt_get_cmdline_auth_info()))
6392 && poptPeekArg(pc)) {
6393 set_cmdline_auth_info_password(
6394 popt_get_cmdline_auth_info(), poptGetArg(pc));
6398 switch (opt) {
6399 case 'M':
6400 /* Messages are sent to NetBIOS name type 0x3
6401 * (Messenger Service). Make sure we default
6402 * to port 139 instead of port 445. srl,crh
6404 name_type = 0x03;
6405 desthost = talloc_strdup(frame,poptGetOptArg(pc));
6406 if (!desthost) {
6407 exit(ENOMEM);
6409 if( !port )
6410 port = NBT_SMB_PORT;
6411 message = true;
6412 break;
6413 case 'I':
6415 if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
6416 exit(1);
6418 have_ip = true;
6419 print_sockaddr(dest_ss_str, sizeof(dest_ss_str), &dest_ss);
6421 break;
6422 case 'E':
6423 setup_logging("smbclient", DEBUG_STDERR );
6424 display_set_stderr();
6425 break;
6427 case 'L':
6428 query_host = talloc_strdup(frame, poptGetOptArg(pc));
6429 if (!query_host) {
6430 exit(ENOMEM);
6432 break;
6433 case 'm':
6434 lp_set_cmdline("client max protocol", poptGetOptArg(pc));
6435 break;
6436 case 'T':
6437 /* We must use old option processing for this. Find the
6438 * position of the -T option in the raw argv[]. */
6440 int i;
6442 for (i = 1; i < argc; i++) {
6443 if (strncmp("-T", argv[i],2)==0)
6444 break;
6446 i++;
6447 if (tar_parse_args(tar_ctx, poptGetOptArg(pc),
6448 const_argv + i, argc - i)) {
6449 poptPrintUsage(pc, stderr, 0);
6450 exit(1);
6453 /* this must be the last option, mark we have parsed it so that we know we have */
6454 tar_opt = true;
6455 break;
6456 case 'D':
6457 base_directory = talloc_strdup(frame, poptGetOptArg(pc));
6458 if (!base_directory) {
6459 exit(ENOMEM);
6461 break;
6462 case 'g':
6463 grepable=true;
6464 break;
6465 case 'q':
6466 quiet=true;
6467 break;
6468 case 'e':
6469 smb_encrypt=true;
6470 break;
6471 case 'B':
6472 return(do_smb_browse());
6477 /* We may still have some leftovers after the last popt option has been called */
6478 if (tar_opt == true) {
6479 while (poptPeekArg(pc)) {
6480 poptGetArg(pc);
6482 tar_opt = false;
6485 /* if the service has not yet been specified lets see if it is available in the popt stack */
6486 if (!service_opt && poptPeekArg(pc)) {
6487 service = talloc_strdup(frame,poptGetArg(pc));
6488 if (!service) {
6489 exit(ENOMEM);
6491 service_opt = true;
6494 /* if the service has already been retrieved then check if we have also a password */
6495 if (service_opt
6496 && !get_cmdline_auth_info_got_pass(popt_get_cmdline_auth_info())
6497 && poptPeekArg(pc)) {
6498 set_cmdline_auth_info_password(popt_get_cmdline_auth_info(),
6499 poptGetArg(pc));
6502 if (service_opt && service) {
6503 size_t len;
6505 /* Convert any '/' characters in the service name to '\' characters */
6506 string_replace(service, '/','\\');
6507 if (count_chars(service,'\\') < 3) {
6508 d_printf("\n%s: Not enough '\\' characters in service\n",service);
6509 poptPrintUsage(pc, stderr, 0);
6510 exit(1);
6512 /* Remove trailing slashes */
6513 len = strlen(service);
6514 while(len > 0 && service[len - 1] == '\\') {
6515 --len;
6516 service[len] = '\0';
6520 if (!init_names()) {
6521 fprintf(stderr, "init_names() failed\n");
6522 exit(1);
6525 if(new_name_resolve_order)
6526 lp_set_cmdline("name resolve order", new_name_resolve_order);
6528 if (!tar_to_process(tar_ctx) && !query_host && !service && !message) {
6529 poptPrintUsage(pc, stderr, 0);
6530 exit(1);
6533 poptFreeContext(pc);
6534 popt_burn_cmdline_password(argc, argv);
6536 DEBUG(3,("Client started (version %s).\n", samba_version_string()));
6538 /* Ensure we have a password (or equivalent). */
6539 popt_common_credentials_post();
6540 smb_encrypt = get_cmdline_auth_info_smb_encrypt(
6541 popt_get_cmdline_auth_info());
6543 max_protocol = lp_client_max_protocol();
6545 if (tar_to_process(tar_ctx)) {
6546 if (cmdstr)
6547 process_command_string(cmdstr);
6548 rc = do_tar_op(base_directory);
6549 } else if (query_host && *query_host) {
6550 char *qhost = query_host;
6551 char *slash;
6553 while (*qhost == '\\' || *qhost == '/')
6554 qhost++;
6556 if ((slash = strchr_m(qhost, '/'))
6557 || (slash = strchr_m(qhost, '\\'))) {
6558 *slash = 0;
6561 if ((p=strchr_m(qhost, '#'))) {
6562 *p = 0;
6563 p++;
6564 sscanf(p, "%x", &name_type);
6567 rc = do_host_query(qhost);
6568 } else if (message) {
6569 rc = do_message_op(popt_get_cmdline_auth_info());
6570 } else if (process(base_directory)) {
6571 rc = 1;
6574 popt_free_cmdline_auth_info();
6575 TALLOC_FREE(frame);
6576 return rc;