summaryrefslogtreecommitdiff
path: root/source3/client
diff options
context:
space:
mode:
Diffstat (limited to 'source3/client')
-rw-r--r--source3/client/cifs.upcall.c391
-rw-r--r--source3/client/cifs_spnego.h46
-rw-r--r--source3/client/client.c4977
-rw-r--r--source3/client/client_proto.h52
-rw-r--r--source3/client/clitar.c1921
-rw-r--r--source3/client/dnsbrowse.c237
-rw-r--r--source3/client/mount.cifs.c1449
-rw-r--r--source3/client/smbspool.c624
-rw-r--r--source3/client/tree.c812
-rw-r--r--source3/client/umount.cifs.c386
10 files changed, 10895 insertions, 0 deletions
diff --git a/source3/client/cifs.upcall.c b/source3/client/cifs.upcall.c
new file mode 100644
index 0000000000..4110de35fd
--- /dev/null
+++ b/source3/client/cifs.upcall.c
@@ -0,0 +1,391 @@
+/*
+* CIFS user-space helper.
+* Copyright (C) Igor Mammedov (niallain@gmail.com) 2007
+*
+* Used by /sbin/request-key for handling
+* cifs upcall for kerberos authorization of access to share and
+* cifs upcall for DFS srver name resolving (IPv4/IPv6 aware).
+* You should have keyutils installed and add something like the
+* following lines to /etc/request-key.conf file:
+
+create cifs.spnego * * /usr/local/sbin/cifs.upcall %k
+create dns_resolver * * /usr/local/sbin/cifs.upcall %k
+
+* This program is free software; you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published by
+* the Free Software Foundation; either version 2 of the License, or
+* (at your option) any later version.
+* This program is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+* GNU General Public License for more details.
+* You should have received a copy of the GNU General Public License
+* along with this program; if not, write to the Free Software
+* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+*/
+
+#include "includes.h"
+#include <keyutils.h>
+
+#include "cifs_spnego.h"
+
+const char *CIFSSPNEGO_VERSION = "1.2";
+static const char *prog = "cifs.upcall";
+typedef enum _secType {
+ NONE = 0,
+ KRB5,
+ MS_KRB5
+} secType_t;
+
+/*
+ * Prepares AP-REQ data for mechToken and gets session key
+ * Uses credentials from cache. It will not ask for password
+ * you should receive credentials for yuor name manually using
+ * kinit or whatever you wish.
+ *
+ * in:
+ * oid - string with OID/ Could be OID_KERBEROS5
+ * or OID_KERBEROS5_OLD
+ * principal - Service name.
+ * Could be "cifs/FQDN" for KRB5 OID
+ * or for MS_KRB5 OID style server principal
+ * like "pdc$@YOUR.REALM.NAME"
+ *
+ * out:
+ * secblob - pointer for spnego wrapped AP-REQ data to be stored
+ * sess_key- pointer for SessionKey data to be stored
+ *
+ * ret: 0 - success, others - failure
+*/
+static int
+handle_krb5_mech(const char *oid, const char *principal,
+ DATA_BLOB * secblob, DATA_BLOB * sess_key)
+{
+ int retval;
+ DATA_BLOB tkt, tkt_wrapped;
+
+ /* get a kerberos ticket for the service and extract the session key */
+ retval = cli_krb5_get_ticket(principal, 0,
+ &tkt, sess_key, 0, NULL, NULL);
+
+ if (retval)
+ return retval;
+
+ /* wrap that up in a nice GSS-API wrapping */
+ tkt_wrapped = spnego_gen_krb5_wrap(tkt, TOK_ID_KRB_AP_REQ);
+
+ /* and wrap that in a shiny SPNEGO wrapper */
+ *secblob = gen_negTokenInit(oid, tkt_wrapped);
+
+ data_blob_free(&tkt_wrapped);
+ data_blob_free(&tkt);
+ return retval;
+}
+
+#define DKD_HAVE_HOSTNAME 1
+#define DKD_HAVE_VERSION 2
+#define DKD_HAVE_SEC 4
+#define DKD_HAVE_IPV4 8
+#define DKD_HAVE_IPV6 16
+#define DKD_HAVE_UID 32
+#define DKD_MUSTHAVE_SET (DKD_HAVE_HOSTNAME|DKD_HAVE_VERSION|DKD_HAVE_SEC)
+
+static int
+decode_key_description(const char *desc, int *ver, secType_t * sec,
+ char **hostname, uid_t * uid)
+{
+ int retval = 0;
+ char *pos;
+ const char *tkn = desc;
+
+ do {
+ pos = index(tkn, ';');
+ if (strncmp(tkn, "host=", 5) == 0) {
+ int len;
+
+ if (pos == NULL) {
+ len = strlen(tkn);
+ } else {
+ len = pos - tkn;
+ }
+ len -= 4;
+ SAFE_FREE(*hostname);
+ *hostname = SMB_XMALLOC_ARRAY(char, len);
+ strlcpy(*hostname, tkn + 5, len);
+ retval |= DKD_HAVE_HOSTNAME;
+ } else if (strncmp(tkn, "ipv4=", 5) == 0) {
+ /* BB: do we need it if we have hostname already? */
+ } else if (strncmp(tkn, "ipv6=", 5) == 0) {
+ /* BB: do we need it if we have hostname already? */
+ } else if (strncmp(tkn, "sec=", 4) == 0) {
+ if (strncmp(tkn + 4, "krb5", 4) == 0) {
+ retval |= DKD_HAVE_SEC;
+ *sec = KRB5;
+ } else if (strncmp(tkn + 4, "mskrb5", 6) == 0) {
+ retval |= DKD_HAVE_SEC;
+ *sec = MS_KRB5;
+ }
+ } else if (strncmp(tkn, "uid=", 4) == 0) {
+ errno = 0;
+ *uid = strtol(tkn + 4, NULL, 16);
+ if (errno != 0) {
+ syslog(LOG_WARNING, "Invalid uid format: %s",
+ strerror(errno));
+ return 1;
+ } else {
+ retval |= DKD_HAVE_UID;
+ }
+ } else if (strncmp(tkn, "ver=", 4) == 0) { /* if version */
+ errno = 0;
+ *ver = strtol(tkn + 4, NULL, 16);
+ if (errno != 0) {
+ syslog(LOG_WARNING,
+ "Invalid version format: %s",
+ strerror(errno));
+ return 1;
+ } else {
+ retval |= DKD_HAVE_VERSION;
+ }
+ }
+ if (pos == NULL)
+ break;
+ tkn = pos + 1;
+ } while (tkn);
+ return retval;
+}
+
+static int
+cifs_resolver(const key_serial_t key, const char *key_descr)
+{
+ int c;
+ struct addrinfo *addr;
+ char ip[INET6_ADDRSTRLEN];
+ void *p;
+ const char *keyend = key_descr;
+ /* skip next 4 ';' delimiters to get to description */
+ for (c = 1; c <= 4; c++) {
+ keyend = index(keyend+1, ';');
+ if (!keyend) {
+ syslog(LOG_WARNING, "invalid key description: %s",
+ key_descr);
+ return 1;
+ }
+ }
+ keyend++;
+
+ /* resolve name to ip */
+ c = getaddrinfo(keyend, NULL, NULL, &addr);
+ if (c) {
+ syslog(LOG_WARNING, "unable to resolve hostname: %s [%s]",
+ keyend, gai_strerror(c));
+ return 1;
+ }
+
+ /* conver ip to string form */
+ if (addr->ai_family == AF_INET) {
+ p = &(((struct sockaddr_in *)addr->ai_addr)->sin_addr);
+ } else {
+ p = &(((struct sockaddr_in6 *)addr->ai_addr)->sin6_addr);
+ }
+ if (!inet_ntop(addr->ai_family, p, ip, sizeof(ip))) {
+ syslog(LOG_WARNING, "%s: inet_ntop: %s",
+ __FUNCTION__, strerror(errno));
+ freeaddrinfo(addr);
+ return 1;
+ }
+
+ /* setup key */
+ c = keyctl_instantiate(key, ip, strlen(ip)+1, 0);
+ if (c == -1) {
+ syslog(LOG_WARNING, "%s: keyctl_instantiate: %s",
+ __FUNCTION__, strerror(errno));
+ freeaddrinfo(addr);
+ return 1;
+ }
+
+ freeaddrinfo(addr);
+ return 0;
+}
+
+static void
+usage(void)
+{
+ syslog(LOG_WARNING, "Usage: %s [-c] [-v] key_serial", prog);
+ fprintf(stderr, "Usage: %s [-c] [-v] key_serial\n", prog);
+}
+
+int main(const int argc, char *const argv[])
+{
+ struct cifs_spnego_msg *keydata = NULL;
+ DATA_BLOB secblob = data_blob_null;
+ DATA_BLOB sess_key = data_blob_null;
+ secType_t sectype = NONE;
+ key_serial_t key = 0;
+ size_t datalen;
+ long rc = 1;
+ uid_t uid = 0;
+ int kernel_upcall_version = 0;
+ int c, use_cifs_service_prefix = 0;
+ char *buf, *hostname = NULL;
+ const char *oid;
+
+ openlog(prog, 0, LOG_DAEMON);
+
+ while ((c = getopt(argc, argv, "cv")) != -1) {
+ switch (c) {
+ case 'c':{
+ use_cifs_service_prefix = 1;
+ break;
+ }
+ case 'v':{
+ printf("version: %s\n", CIFSSPNEGO_VERSION);
+ goto out;
+ }
+ default:{
+ syslog(LOG_WARNING, "unknown option: %c", c);
+ goto out;
+ }
+ }
+ }
+
+ /* is there a key? */
+ if (argc <= optind) {
+ usage();
+ goto out;
+ }
+
+ /* get key and keyring values */
+ errno = 0;
+ key = strtol(argv[optind], NULL, 10);
+ if (errno != 0) {
+ key = 0;
+ syslog(LOG_WARNING, "Invalid key format: %s", strerror(errno));
+ goto out;
+ }
+
+ rc = keyctl_describe_alloc(key, &buf);
+ if (rc == -1) {
+ syslog(LOG_WARNING, "keyctl_describe_alloc failed: %s",
+ strerror(errno));
+ rc = 1;
+ goto out;
+ }
+
+ if ((strncmp(buf, "cifs.resolver", sizeof("cifs.resolver")-1) == 0) ||
+ (strncmp(buf, "dns_resolver", sizeof("dns_resolver")-1) == 0)) {
+ rc = cifs_resolver(key, buf);
+ goto out;
+ }
+
+ rc = decode_key_description(buf, &kernel_upcall_version, &sectype,
+ &hostname, &uid);
+ if ((rc & DKD_MUSTHAVE_SET) != DKD_MUSTHAVE_SET) {
+ syslog(LOG_WARNING,
+ "unable to get from description necessary params");
+ rc = 1;
+ SAFE_FREE(buf);
+ goto out;
+ }
+ SAFE_FREE(buf);
+
+ if (kernel_upcall_version > CIFS_SPNEGO_UPCALL_VERSION) {
+ syslog(LOG_WARNING,
+ "incompatible kernel upcall version: 0x%x",
+ kernel_upcall_version);
+ rc = 1;
+ goto out;
+ }
+
+ if (rc & DKD_HAVE_UID) {
+ rc = setuid(uid);
+ if (rc == -1) {
+ syslog(LOG_WARNING, "setuid: %s", strerror(errno));
+ goto out;
+ }
+ }
+
+ /* BB: someday upcall SPNEGO blob could be checked here to decide
+ * what mech to use */
+
+ // do mech specific authorization
+ switch (sectype) {
+ case MS_KRB5:
+ case KRB5:{
+ char *princ;
+ size_t len;
+
+ /* for "cifs/" service name + terminating 0 */
+ len = strlen(hostname) + 5 + 1;
+ princ = SMB_XMALLOC_ARRAY(char, len);
+ if (!princ) {
+ rc = 1;
+ break;
+ }
+ if (use_cifs_service_prefix) {
+ strlcpy(princ, "cifs/", len);
+ } else {
+ strlcpy(princ, "host/", len);
+ }
+ strlcpy(princ + 5, hostname, len - 5);
+
+ if (sectype == MS_KRB5)
+ oid = OID_KERBEROS5_OLD;
+ else
+ oid = OID_KERBEROS5;
+
+ rc = handle_krb5_mech(oid, princ, &secblob, &sess_key);
+ SAFE_FREE(princ);
+ break;
+ }
+ default:{
+ syslog(LOG_WARNING, "sectype: %d is not implemented",
+ sectype);
+ rc = 1;
+ break;
+ }
+ }
+
+ if (rc) {
+ goto out;
+ }
+
+ /* pack SecurityBLob and SessionKey into downcall packet */
+ datalen =
+ sizeof(struct cifs_spnego_msg) + secblob.length + sess_key.length;
+ keydata = (struct cifs_spnego_msg*)SMB_XMALLOC_ARRAY(char, datalen);
+ if (!keydata) {
+ rc = 1;
+ goto out;
+ }
+ keydata->version = kernel_upcall_version;
+ keydata->flags = 0;
+ keydata->sesskey_len = sess_key.length;
+ keydata->secblob_len = secblob.length;
+ memcpy(&(keydata->data), sess_key.data, sess_key.length);
+ memcpy(&(keydata->data) + keydata->sesskey_len,
+ secblob.data, secblob.length);
+
+ /* setup key */
+ rc = keyctl_instantiate(key, keydata, datalen, 0);
+ if (rc == -1) {
+ syslog(LOG_WARNING, "keyctl_instantiate: %s", strerror(errno));
+ goto out;
+ }
+
+ /* BB: maybe we need use timeout for key: for example no more then
+ * ticket lifietime? */
+ /* keyctl_set_timeout( key, 60); */
+out:
+ /*
+ * on error, negatively instantiate the key ourselves so that we can
+ * make sure the kernel doesn't hang it off of a searchable keyring
+ * and interfere with the next attempt to instantiate the key.
+ */
+ if (rc != 0 && key == 0)
+ keyctl_negate(key, 1, KEY_REQKEY_DEFL_DEFAULT);
+ data_blob_free(&secblob);
+ data_blob_free(&sess_key);
+ SAFE_FREE(hostname);
+ SAFE_FREE(keydata);
+ return rc;
+}
diff --git a/source3/client/cifs_spnego.h b/source3/client/cifs_spnego.h
new file mode 100644
index 0000000000..f8753a7d59
--- /dev/null
+++ b/source3/client/cifs_spnego.h
@@ -0,0 +1,46 @@
+/*
+ * fs/cifs/cifs_spnego.h -- SPNEGO upcall management for CIFS
+ *
+ * Copyright (c) 2007 Red Hat, Inc.
+ * Author(s): Jeff Layton (jlayton@redhat.com)
+ * Steve French (sfrench@us.ibm.com)
+ *
+ * This library is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU Lesser General Public License as published
+ * by the Free Software Foundation; either version 2.1 of the License, or
+ * (at your option) any later version.
+ *
+ * This library is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
+ * the GNU Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public License
+ * along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ */
+
+#ifndef _CIFS_SPNEGO_H
+#define _CIFS_SPNEGO_H
+
+#define CIFS_SPNEGO_UPCALL_VERSION 2
+
+/*
+ * The version field should always be set to CIFS_SPNEGO_UPCALL_VERSION.
+ * The flags field is for future use. The request-key callout should set
+ * sesskey_len and secblob_len, and then concatenate the SessKey+SecBlob
+ * and stuff it in the data field.
+ */
+struct cifs_spnego_msg {
+ uint32_t version;
+ uint32_t flags;
+ uint32_t sesskey_len;
+ uint32_t secblob_len;
+ uint8_t data[1];
+};
+
+#ifdef __KERNEL__
+extern struct key_type cifs_spnego_key_type;
+#endif /* KERNEL */
+
+#endif /* _CIFS_SPNEGO_H */
diff --git a/source3/client/client.c b/source3/client/client.c
new file mode 100644
index 0000000000..1c05c4035d
--- /dev/null
+++ b/source3/client/client.c
@@ -0,0 +1,4977 @@
+/*
+ Unix SMB/CIFS implementation.
+ SMB client
+ Copyright (C) Andrew Tridgell 1994-1998
+ Copyright (C) Simo Sorce 2001-2002
+ Copyright (C) Jelmer Vernooij 2003
+ Copyright (C) Gerald (Jerry) Carter 2004
+ Copyright (C) Jeremy Allison 1994-2007
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "includes.h"
+#include "client/client_proto.h"
+#include "include/rpc_client.h"
+#ifndef REGISTER
+#define REGISTER 0
+#endif
+
+extern int do_smb_browse(void); /* mDNS browsing */
+
+extern bool AllowDebugChange;
+extern bool override_logfile;
+extern char tar_type;
+
+static int port = 0;
+static char *service;
+static char *desthost;
+static char *calling_name;
+static bool grepable = false;
+static char *cmdstr = NULL;
+const char *cmd_ptr = NULL;
+
+static int io_bufsize = 524288;
+
+static int name_type = 0x20;
+extern int max_protocol;
+
+static int process_tok(char *tok);
+static int cmd_help(void);
+
+#define CREATE_ACCESS_READ READ_CONTROL_ACCESS
+
+/* 30 second timeout on most commands */
+#define CLIENT_TIMEOUT (30*1000)
+#define SHORT_TIMEOUT (5*1000)
+
+/* value for unused fid field in trans2 secondary request */
+#define FID_UNUSED (0xFFFF)
+
+time_t newer_than = 0;
+static int archive_level = 0;
+
+static bool translation = false;
+static bool have_ip;
+
+/* clitar bits insert */
+extern int blocksize;
+extern bool tar_inc;
+extern bool tar_reset;
+/* clitar bits end */
+
+static bool prompt = true;
+
+static bool recurse = false;
+static bool showacls = false;
+bool lowercase = false;
+
+static struct sockaddr_storage dest_ss;
+
+#define SEPARATORS " \t\n\r"
+
+static bool abort_mget = true;
+
+/* timing globals */
+SMB_BIG_UINT get_total_size = 0;
+unsigned int get_total_time_ms = 0;
+static SMB_BIG_UINT put_total_size = 0;
+static unsigned int put_total_time_ms = 0;
+
+/* totals globals */
+static double dir_total;
+
+/* encrypted state. */
+static bool smb_encrypt;
+
+/* root cli_state connection */
+
+struct cli_state *cli;
+
+static char CLI_DIRSEP_CHAR = '\\';
+static char CLI_DIRSEP_STR[] = { '\\', '\0' };
+
+/* Accessor functions for directory paths. */
+static char *fileselection;
+static const char *client_get_fileselection(void)
+{
+ if (fileselection) {
+ return fileselection;
+ }
+ return "";
+}
+
+static const char *client_set_fileselection(const char *new_fs)
+{
+ SAFE_FREE(fileselection);
+ if (new_fs) {
+ fileselection = SMB_STRDUP(new_fs);
+ }
+ return client_get_fileselection();
+}
+
+static char *cwd;
+static const char *client_get_cwd(void)
+{
+ if (cwd) {
+ return cwd;
+ }
+ return CLI_DIRSEP_STR;
+}
+
+static const char *client_set_cwd(const char *new_cwd)
+{
+ SAFE_FREE(cwd);
+ if (new_cwd) {
+ cwd = SMB_STRDUP(new_cwd);
+ }
+ return client_get_cwd();
+}
+
+static char *cur_dir;
+const char *client_get_cur_dir(void)
+{
+ if (cur_dir) {
+ return cur_dir;
+ }
+ return CLI_DIRSEP_STR;
+}
+
+const char *client_set_cur_dir(const char *newdir)
+{
+ SAFE_FREE(cur_dir);
+ if (newdir) {
+ cur_dir = SMB_STRDUP(newdir);
+ }
+ return client_get_cur_dir();
+}
+
+/****************************************************************************
+ Write to a local file with CR/LF->LF translation if appropriate. Return the
+ number taken from the buffer. This may not equal the number written.
+****************************************************************************/
+
+static int writefile(int f, char *b, int n)
+{
+ int i;
+
+ if (!translation) {
+ return write(f,b,n);
+ }
+
+ i = 0;
+ while (i < n) {
+ if (*b == '\r' && (i<(n-1)) && *(b+1) == '\n') {
+ b++;i++;
+ }
+ if (write(f, b, 1) != 1) {
+ break;
+ }
+ b++;
+ i++;
+ }
+
+ return(i);
+}
+
+/****************************************************************************
+ Read from a file with LF->CR/LF translation if appropriate. Return the
+ number read. read approx n bytes.
+****************************************************************************/
+
+static int readfile(char *b, int n, XFILE *f)
+{
+ int i;
+ int c;
+
+ if (!translation)
+ return x_fread(b,1,n,f);
+
+ i = 0;
+ while (i < (n - 1) && (i < BUFFER_SIZE)) {
+ if ((c = x_getc(f)) == EOF) {
+ break;
+ }
+
+ if (c == '\n') { /* change all LFs to CR/LF */
+ b[i++] = '\r';
+ }
+
+ b[i++] = c;
+ }
+
+ return(i);
+}
+
+/****************************************************************************
+ Send a message.
+****************************************************************************/
+
+static void send_message(void)
+{
+ int total_len = 0;
+ int grp_id;
+
+ if (!cli_message_start(cli, desthost,
+ get_cmdline_auth_info_username(), &grp_id)) {
+ d_printf("message start: %s\n", cli_errstr(cli));
+ return;
+ }
+
+
+ d_printf("Connected. Type your message, ending it with a Control-D\n");
+
+ while (!feof(stdin) && total_len < 1600) {
+ int maxlen = MIN(1600 - total_len,127);
+ char msg[1024];
+ int l=0;
+ int c;
+
+ ZERO_ARRAY(msg);
+
+ for (l=0;l<maxlen && (c=fgetc(stdin))!=EOF;l++) {
+ if (c == '\n')
+ msg[l++] = '\r';
+ msg[l] = c;
+ }
+
+ if ((total_len > 0) && (strlen(msg) == 0)) {
+ break;
+ }
+
+ if (!cli_message_text(cli, msg, l, grp_id)) {
+ d_printf("SMBsendtxt failed (%s)\n",cli_errstr(cli));
+ return;
+ }
+
+ total_len += l;
+ }
+
+ if (total_len >= 1600)
+ d_printf("the message was truncated to 1600 bytes\n");
+ else
+ d_printf("sent %d bytes\n",total_len);
+
+ if (!cli_message_end(cli, grp_id)) {
+ d_printf("SMBsendend failed (%s)\n",cli_errstr(cli));
+ return;
+ }
+}
+
+/****************************************************************************
+ Check the space on a device.
+****************************************************************************/
+
+static int do_dskattr(void)
+{
+ int total, bsize, avail;
+ struct cli_state *targetcli = NULL;
+ char *targetpath = NULL;
+ TALLOC_CTX *ctx = talloc_tos();
+
+ if ( !cli_resolve_path(ctx, "", cli, client_get_cur_dir(), &targetcli, &targetpath)) {
+ d_printf("Error in dskattr: %s\n", cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_dskattr(targetcli, &bsize, &total, &avail)) {
+ d_printf("Error in dskattr: %s\n",cli_errstr(targetcli));
+ return 1;
+ }
+
+ d_printf("\n\t\t%d blocks of size %d. %d blocks available\n",
+ total, bsize, avail);
+
+ return 0;
+}
+
+/****************************************************************************
+ Show cd/pwd.
+****************************************************************************/
+
+static int cmd_pwd(void)
+{
+ d_printf("Current directory is %s",service);
+ d_printf("%s\n",client_get_cur_dir());
+ return 0;
+}
+
+/****************************************************************************
+ Ensure name has correct directory separators.
+****************************************************************************/
+
+static void normalize_name(char *newdir)
+{
+ if (!(cli->posix_capabilities & CIFS_UNIX_POSIX_PATHNAMES_CAP)) {
+ string_replace(newdir,'/','\\');
+ }
+}
+
+/****************************************************************************
+ Change directory - inner section.
+****************************************************************************/
+
+static int do_cd(const char *new_dir)
+{
+ char *newdir = NULL;
+ char *saved_dir = NULL;
+ char *new_cd = NULL;
+ char *targetpath = NULL;
+ struct cli_state *targetcli = NULL;
+ SMB_STRUCT_STAT sbuf;
+ uint32 attributes;
+ int ret = 1;
+ TALLOC_CTX *ctx = talloc_stackframe();
+
+ newdir = talloc_strdup(ctx, new_dir);
+ if (!newdir) {
+ TALLOC_FREE(ctx);
+ return 1;
+ }
+
+ normalize_name(newdir);
+
+ /* Save the current directory in case the new directory is invalid */
+
+ saved_dir = talloc_strdup(ctx, client_get_cur_dir());
+ if (!saved_dir) {
+ TALLOC_FREE(ctx);
+ return 1;
+ }
+
+ if (*newdir == CLI_DIRSEP_CHAR) {
+ client_set_cur_dir(newdir);
+ new_cd = newdir;
+ } else {
+ new_cd = talloc_asprintf(ctx, "%s%s",
+ client_get_cur_dir(),
+ newdir);
+ if (!new_cd) {
+ goto out;
+ }
+ }
+
+ /* Ensure cur_dir ends in a DIRSEP */
+ if ((new_cd[0] != '\0') && (*(new_cd+strlen(new_cd)-1) != CLI_DIRSEP_CHAR)) {
+ new_cd = talloc_asprintf_append(new_cd, CLI_DIRSEP_STR);
+ if (!new_cd) {
+ goto out;
+ }
+ }
+ client_set_cur_dir(new_cd);
+
+ new_cd = clean_name(ctx, new_cd);
+ client_set_cur_dir(new_cd);
+
+ if ( !cli_resolve_path(ctx, "", cli, new_cd, &targetcli, &targetpath)) {
+ d_printf("cd %s: %s\n", new_cd, cli_errstr(cli));
+ client_set_cur_dir(saved_dir);
+ goto out;
+ }
+
+ if (strequal(targetpath,CLI_DIRSEP_STR )) {
+ TALLOC_FREE(ctx);
+ return 0;
+ }
+
+ /* Use a trans2_qpathinfo to test directories for modern servers.
+ Except Win9x doesn't support the qpathinfo_basic() call..... */
+
+ if (targetcli->protocol > PROTOCOL_LANMAN2 && !targetcli->win95) {
+ if (!cli_qpathinfo_basic( targetcli, targetpath, &sbuf, &attributes ) ) {
+ d_printf("cd %s: %s\n", new_cd, cli_errstr(targetcli));
+ client_set_cur_dir(saved_dir);
+ goto out;
+ }
+
+ if (!(attributes & FILE_ATTRIBUTE_DIRECTORY)) {
+ d_printf("cd %s: not a directory\n", new_cd);
+ client_set_cur_dir(saved_dir);
+ goto out;
+ }
+ } else {
+ targetpath = talloc_asprintf(ctx,
+ "%s%s",
+ targetpath,
+ CLI_DIRSEP_STR );
+ if (!targetpath) {
+ client_set_cur_dir(saved_dir);
+ goto out;
+ }
+ targetpath = clean_name(ctx, targetpath);
+ if (!targetpath) {
+ client_set_cur_dir(saved_dir);
+ goto out;
+ }
+
+ if (!cli_chkpath(targetcli, targetpath)) {
+ d_printf("cd %s: %s\n", new_cd, cli_errstr(targetcli));
+ client_set_cur_dir(saved_dir);
+ goto out;
+ }
+ }
+
+ ret = 0;
+
+out:
+
+ TALLOC_FREE(ctx);
+ return ret;
+}
+
+/****************************************************************************
+ Change directory.
+****************************************************************************/
+
+static int cmd_cd(void)
+{
+ char *buf = NULL;
+ int rc = 0;
+
+ if (next_token_talloc(talloc_tos(), &cmd_ptr, &buf,NULL)) {
+ rc = do_cd(buf);
+ } else {
+ d_printf("Current directory is %s\n",client_get_cur_dir());
+ }
+
+ return rc;
+}
+
+/****************************************************************************
+ Change directory.
+****************************************************************************/
+
+static int cmd_cd_oneup(void)
+{
+ return do_cd("..");
+}
+
+/*******************************************************************
+ Decide if a file should be operated on.
+********************************************************************/
+
+static bool do_this_one(file_info *finfo)
+{
+ if (!finfo->name) {
+ return false;
+ }
+
+ if (finfo->mode & aDIR) {
+ return true;
+ }
+
+ if (*client_get_fileselection() &&
+ !mask_match(finfo->name,client_get_fileselection(),false)) {
+ DEBUG(3,("mask_match %s failed\n", finfo->name));
+ return false;
+ }
+
+ if (newer_than && finfo->mtime_ts.tv_sec < newer_than) {
+ DEBUG(3,("newer_than %s failed\n", finfo->name));
+ return false;
+ }
+
+ if ((archive_level==1 || archive_level==2) && !(finfo->mode & aARCH)) {
+ DEBUG(3,("archive %s failed\n", finfo->name));
+ return false;
+ }
+
+ return true;
+}
+
+/****************************************************************************
+ Display info about a file.
+****************************************************************************/
+
+static void display_finfo(file_info *finfo, const char *dir)
+{
+ time_t t;
+ TALLOC_CTX *ctx = talloc_tos();
+
+ if (!do_this_one(finfo)) {
+ return;
+ }
+
+ t = finfo->mtime_ts.tv_sec; /* the time is assumed to be passed as GMT */
+ if (!showacls) {
+ d_printf(" %-30s%7.7s %8.0f %s",
+ finfo->name,
+ attrib_string(finfo->mode),
+ (double)finfo->size,
+ time_to_asc(t));
+ dir_total += finfo->size;
+ } else {
+ char *afname = NULL;
+ int fnum;
+
+ /* skip if this is . or .. */
+ if ( strequal(finfo->name,"..") || strequal(finfo->name,".") )
+ return;
+ /* create absolute filename for cli_nt_create() FIXME */
+ afname = talloc_asprintf(ctx,
+ "%s%s%s",
+ dir,
+ CLI_DIRSEP_STR,
+ finfo->name);
+ if (!afname) {
+ return;
+ }
+ /* print file meta date header */
+ d_printf( "FILENAME:%s\n", finfo->name);
+ d_printf( "MODE:%s\n", attrib_string(finfo->mode));
+ d_printf( "SIZE:%.0f\n", (double)finfo->size);
+ d_printf( "MTIME:%s", time_to_asc(t));
+ fnum = cli_nt_create(finfo->cli, afname, CREATE_ACCESS_READ);
+ if (fnum == -1) {
+ DEBUG( 0, ("display_finfo() Failed to open %s: %s\n",
+ afname,
+ cli_errstr( finfo->cli)));
+ } else {
+ SEC_DESC *sd = NULL;
+ sd = cli_query_secdesc(finfo->cli, fnum, ctx);
+ if (!sd) {
+ DEBUG( 0, ("display_finfo() failed to "
+ "get security descriptor: %s",
+ cli_errstr( finfo->cli)));
+ } else {
+ display_sec_desc(sd);
+ }
+ TALLOC_FREE(sd);
+ }
+ TALLOC_FREE(afname);
+ }
+}
+
+/****************************************************************************
+ Accumulate size of a file.
+****************************************************************************/
+
+static void do_du(file_info *finfo, const char *dir)
+{
+ if (do_this_one(finfo)) {
+ dir_total += finfo->size;
+ }
+}
+
+static bool do_list_recurse;
+static bool do_list_dirs;
+static char *do_list_queue = 0;
+static long do_list_queue_size = 0;
+static long do_list_queue_start = 0;
+static long do_list_queue_end = 0;
+static void (*do_list_fn)(file_info *, const char *dir);
+
+/****************************************************************************
+ Functions for do_list_queue.
+****************************************************************************/
+
+/*
+ * The do_list_queue is a NUL-separated list of strings stored in a
+ * char*. Since this is a FIFO, we keep track of the beginning and
+ * ending locations of the data in the queue. When we overflow, we
+ * double the size of the char*. When the start of the data passes
+ * the midpoint, we move everything back. This is logically more
+ * complex than a linked list, but easier from a memory management
+ * angle. In any memory error condition, do_list_queue is reset.
+ * Functions check to ensure that do_list_queue is non-NULL before
+ * accessing it.
+ */
+
+static void reset_do_list_queue(void)
+{
+ SAFE_FREE(do_list_queue);
+ do_list_queue_size = 0;
+ do_list_queue_start = 0;
+ do_list_queue_end = 0;
+}
+
+static void init_do_list_queue(void)
+{
+ reset_do_list_queue();
+ do_list_queue_size = 1024;
+ do_list_queue = (char *)SMB_MALLOC(do_list_queue_size);
+ if (do_list_queue == 0) {
+ d_printf("malloc fail for size %d\n",
+ (int)do_list_queue_size);
+ reset_do_list_queue();
+ } else {
+ memset(do_list_queue, 0, do_list_queue_size);
+ }
+}
+
+static void adjust_do_list_queue(void)
+{
+ /*
+ * If the starting point of the queue is more than half way through,
+ * move everything toward the beginning.
+ */
+
+ if (do_list_queue == NULL) {
+ DEBUG(4,("do_list_queue is empty\n"));
+ do_list_queue_start = do_list_queue_end = 0;
+ return;
+ }
+
+ if (do_list_queue_start == do_list_queue_end) {
+ DEBUG(4,("do_list_queue is empty\n"));
+ do_list_queue_start = do_list_queue_end = 0;
+ *do_list_queue = '\0';
+ } else if (do_list_queue_start > (do_list_queue_size / 2)) {
+ DEBUG(4,("sliding do_list_queue backward\n"));
+ memmove(do_list_queue,
+ do_list_queue + do_list_queue_start,
+ do_list_queue_end - do_list_queue_start);
+ do_list_queue_end -= do_list_queue_start;
+ do_list_queue_start = 0;
+ }
+}
+
+static void add_to_do_list_queue(const char *entry)
+{
+ long new_end = do_list_queue_end + ((long)strlen(entry)) + 1;
+ while (new_end > do_list_queue_size) {
+ do_list_queue_size *= 2;
+ DEBUG(4,("enlarging do_list_queue to %d\n",
+ (int)do_list_queue_size));
+ do_list_queue = (char *)SMB_REALLOC(do_list_queue, do_list_queue_size);
+ if (! do_list_queue) {
+ d_printf("failure enlarging do_list_queue to %d bytes\n",
+ (int)do_list_queue_size);
+ reset_do_list_queue();
+ } else {
+ memset(do_list_queue + do_list_queue_size / 2,
+ 0, do_list_queue_size / 2);
+ }
+ }
+ if (do_list_queue) {
+ safe_strcpy_base(do_list_queue + do_list_queue_end,
+ entry, do_list_queue, do_list_queue_size);
+ do_list_queue_end = new_end;
+ DEBUG(4,("added %s to do_list_queue (start=%d, end=%d)\n",
+ entry, (int)do_list_queue_start, (int)do_list_queue_end));
+ }
+}
+
+static char *do_list_queue_head(void)
+{
+ return do_list_queue + do_list_queue_start;
+}
+
+static void remove_do_list_queue_head(void)
+{
+ if (do_list_queue_end > do_list_queue_start) {
+ do_list_queue_start += strlen(do_list_queue_head()) + 1;
+ adjust_do_list_queue();
+ DEBUG(4,("removed head of do_list_queue (start=%d, end=%d)\n",
+ (int)do_list_queue_start, (int)do_list_queue_end));
+ }
+}
+
+static int do_list_queue_empty(void)
+{
+ return (! (do_list_queue && *do_list_queue));
+}
+
+/****************************************************************************
+ A helper for do_list.
+****************************************************************************/
+
+static void do_list_helper(const char *mntpoint, file_info *f, const char *mask, void *state)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *dir = NULL;
+ char *dir_end = NULL;
+
+ /* Work out the directory. */
+ dir = talloc_strdup(ctx, mask);
+ if (!dir) {
+ return;
+ }
+ if ((dir_end = strrchr(dir, CLI_DIRSEP_CHAR)) != NULL) {
+ *dir_end = '\0';
+ }
+
+ if (f->mode & aDIR) {
+ if (do_list_dirs && do_this_one(f)) {
+ do_list_fn(f, dir);
+ }
+ if (do_list_recurse &&
+ f->name &&
+ !strequal(f->name,".") &&
+ !strequal(f->name,"..")) {
+ char *mask2 = NULL;
+ char *p = NULL;
+
+ if (!f->name[0]) {
+ d_printf("Empty dir name returned. Possible server misconfiguration.\n");
+ TALLOC_FREE(dir);
+ return;
+ }
+
+ mask2 = talloc_asprintf(ctx,
+ "%s%s",
+ mntpoint,
+ mask);
+ if (!mask2) {
+ TALLOC_FREE(dir);
+ return;
+ }
+ p = strrchr_m(mask2,CLI_DIRSEP_CHAR);
+ if (!p) {
+ TALLOC_FREE(dir);
+ return;
+ }
+ p[1] = 0;
+ mask2 = talloc_asprintf_append(mask2,
+ "%s%s*",
+ f->name,
+ CLI_DIRSEP_STR);
+ if (!mask2) {
+ TALLOC_FREE(dir);
+ return;
+ }
+ add_to_do_list_queue(mask2);
+ TALLOC_FREE(mask2);
+ }
+ TALLOC_FREE(dir);
+ return;
+ }
+
+ if (do_this_one(f)) {
+ do_list_fn(f,dir);
+ }
+ TALLOC_FREE(dir);
+}
+
+/****************************************************************************
+ A wrapper around cli_list that adds recursion.
+****************************************************************************/
+
+void do_list(const char *mask,
+ uint16 attribute,
+ void (*fn)(file_info *, const char *dir),
+ bool rec,
+ bool dirs)
+{
+ static int in_do_list = 0;
+ TALLOC_CTX *ctx = talloc_tos();
+ struct cli_state *targetcli = NULL;
+ char *targetpath = NULL;
+
+ if (in_do_list && rec) {
+ fprintf(stderr, "INTERNAL ERROR: do_list called recursively when the recursive flag is true\n");
+ exit(1);
+ }
+
+ in_do_list = 1;
+
+ do_list_recurse = rec;
+ do_list_dirs = dirs;
+ do_list_fn = fn;
+
+ if (rec) {
+ init_do_list_queue();
+ add_to_do_list_queue(mask);
+
+ while (!do_list_queue_empty()) {
+ /*
+ * Need to copy head so that it doesn't become
+ * invalid inside the call to cli_list. This
+ * would happen if the list were expanded
+ * during the call.
+ * Fix from E. Jay Berkenbilt (ejb@ql.org)
+ */
+ char *head = talloc_strdup(ctx, do_list_queue_head());
+
+ if (!head) {
+ return;
+ }
+
+ /* check for dfs */
+
+ if ( !cli_resolve_path(ctx, "", cli, head, &targetcli, &targetpath ) ) {
+ d_printf("do_list: [%s] %s\n", head, cli_errstr(cli));
+ remove_do_list_queue_head();
+ continue;
+ }
+
+ cli_list(targetcli, targetpath, attribute, do_list_helper, NULL);
+ remove_do_list_queue_head();
+ if ((! do_list_queue_empty()) && (fn == display_finfo)) {
+ char *next_file = do_list_queue_head();
+ char *save_ch = 0;
+ if ((strlen(next_file) >= 2) &&
+ (next_file[strlen(next_file) - 1] == '*') &&
+ (next_file[strlen(next_file) - 2] == CLI_DIRSEP_CHAR)) {
+ save_ch = next_file +
+ strlen(next_file) - 2;
+ *save_ch = '\0';
+ if (showacls) {
+ /* cwd is only used if showacls is on */
+ client_set_cwd(next_file);
+ }
+ }
+ if (!showacls) /* don't disturbe the showacls output */
+ d_printf("\n%s\n",next_file);
+ if (save_ch) {
+ *save_ch = CLI_DIRSEP_CHAR;
+ }
+ }
+ TALLOC_FREE(head);
+ TALLOC_FREE(targetpath);
+ }
+ } else {
+ /* check for dfs */
+ if (cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetpath)) {
+ if (cli_list(targetcli, targetpath, attribute, do_list_helper, NULL) == -1) {
+ d_printf("%s listing %s\n",
+ cli_errstr(targetcli), targetpath);
+ }
+ TALLOC_FREE(targetpath);
+ } else {
+ d_printf("do_list: [%s] %s\n", mask, cli_errstr(cli));
+ }
+ }
+
+ in_do_list = 0;
+ reset_do_list_queue();
+}
+
+/****************************************************************************
+ Get a directory listing.
+****************************************************************************/
+
+static int cmd_dir(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
+ char *mask = NULL;
+ char *buf = NULL;
+ int rc = 1;
+
+ dir_total = 0;
+ mask = talloc_strdup(ctx, client_get_cur_dir());
+ if (!mask) {
+ return 1;
+ }
+
+ if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ normalize_name(buf);
+ if (*buf == CLI_DIRSEP_CHAR) {
+ mask = talloc_strdup(ctx, buf);
+ } else {
+ mask = talloc_asprintf_append(mask, buf);
+ }
+ } else {
+ mask = talloc_asprintf_append(mask, "*");
+ }
+ if (!mask) {
+ return 1;
+ }
+
+ if (showacls) {
+ /* cwd is only used if showacls is on */
+ client_set_cwd(client_get_cur_dir());
+ }
+
+ do_list(mask, attribute, display_finfo, recurse, true);
+
+ rc = do_dskattr();
+
+ DEBUG(3, ("Total bytes listed: %.0f\n", dir_total));
+
+ return rc;
+}
+
+/****************************************************************************
+ Get a directory listing.
+****************************************************************************/
+
+static int cmd_du(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
+ char *mask = NULL;
+ char *buf = NULL;
+ int rc = 1;
+
+ dir_total = 0;
+ mask = talloc_strdup(ctx, client_get_cur_dir());
+ if (!mask) {
+ return 1;
+ }
+ if ((mask[0] != '\0') && (mask[strlen(mask)-1]!=CLI_DIRSEP_CHAR)) {
+ mask = talloc_asprintf_append(mask, CLI_DIRSEP_STR);
+ if (!mask) {
+ return 1;
+ }
+ }
+
+ if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ normalize_name(buf);
+ if (*buf == CLI_DIRSEP_CHAR) {
+ mask = talloc_strdup(ctx, buf);
+ } else {
+ mask = talloc_asprintf_append(mask, buf);
+ }
+ } else {
+ mask = talloc_strdup(ctx, "*");
+ }
+
+ do_list(mask, attribute, do_du, recurse, true);
+
+ rc = do_dskattr();
+
+ d_printf("Total number of bytes: %.0f\n", dir_total);
+
+ return rc;
+}
+
+static int cmd_echo(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *num;
+ char *data;
+ NTSTATUS status;
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &num, NULL)
+ || !next_token_talloc(ctx, &cmd_ptr, &data, NULL)) {
+ d_printf("echo <num> <data>\n");
+ return 1;
+ }
+
+ status = cli_echo(cli, atoi(num), data_blob_const(data, strlen(data)));
+
+ if (!NT_STATUS_IS_OK(status)) {
+ d_printf("echo failed: %s\n", nt_errstr(status));
+ return 1;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Get a file from rname to lname
+****************************************************************************/
+
+static NTSTATUS writefile_sink(char *buf, size_t n, void *priv)
+{
+ int *pfd = (int *)priv;
+ if (writefile(*pfd, buf, n) == -1) {
+ return map_nt_error_from_unix(errno);
+ }
+ return NT_STATUS_OK;
+}
+
+static int do_get(const char *rname, const char *lname_in, bool reget)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ int handle = 0, fnum;
+ bool newhandle = false;
+ struct timeval tp_start;
+ uint16 attr;
+ SMB_OFF_T size;
+ off_t start = 0;
+ SMB_OFF_T nread = 0;
+ int rc = 0;
+ struct cli_state *targetcli = NULL;
+ char *targetname = NULL;
+ char *lname = NULL;
+ NTSTATUS status;
+
+ lname = talloc_strdup(ctx, lname_in);
+ if (!lname) {
+ return 1;
+ }
+
+ if (lowercase) {
+ strlower_m(lname);
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, rname, &targetcli, &targetname ) ) {
+ d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
+ return 1;
+ }
+
+ GetTimeOfDay(&tp_start);
+
+ fnum = cli_open(targetcli, targetname, O_RDONLY, DENY_NONE);
+
+ if (fnum == -1) {
+ d_printf("%s opening remote file %s\n",cli_errstr(cli),rname);
+ return 1;
+ }
+
+ if(!strcmp(lname,"-")) {
+ handle = fileno(stdout);
+ } else {
+ if (reget) {
+ handle = sys_open(lname, O_WRONLY|O_CREAT, 0644);
+ if (handle >= 0) {
+ start = sys_lseek(handle, 0, SEEK_END);
+ if (start == -1) {
+ d_printf("Error seeking local file\n");
+ return 1;
+ }
+ }
+ } else {
+ handle = sys_open(lname, O_WRONLY|O_CREAT|O_TRUNC, 0644);
+ }
+ newhandle = true;
+ }
+ if (handle < 0) {
+ d_printf("Error opening local file %s\n",lname);
+ return 1;
+ }
+
+
+ if (!cli_qfileinfo(targetcli, fnum,
+ &attr, &size, NULL, NULL, NULL, NULL, NULL) &&
+ !cli_getattrE(targetcli, fnum,
+ &attr, &size, NULL, NULL, NULL)) {
+ d_printf("getattrib: %s\n",cli_errstr(targetcli));
+ return 1;
+ }
+
+ DEBUG(1,("getting file %s of size %.0f as %s ",
+ rname, (double)size, lname));
+
+ status = cli_pull(targetcli, fnum, start, size, io_bufsize,
+ writefile_sink, (void *)&handle, &nread);
+ if (!NT_STATUS_IS_OK(status)) {
+ d_fprintf(stderr, "parallel_read returned %s\n",
+ nt_errstr(status));
+ cli_close(targetcli, fnum);
+ return 1;
+ }
+
+ if (!cli_close(targetcli, fnum)) {
+ d_printf("Error %s closing remote file\n",cli_errstr(cli));
+ rc = 1;
+ }
+
+ if (newhandle) {
+ close(handle);
+ }
+
+ if (archive_level >= 2 && (attr & aARCH)) {
+ cli_setatr(cli, rname, attr & ~(uint16)aARCH, 0);
+ }
+
+ {
+ struct timeval tp_end;
+ int this_time;
+
+ GetTimeOfDay(&tp_end);
+ this_time =
+ (tp_end.tv_sec - tp_start.tv_sec)*1000 +
+ (tp_end.tv_usec - tp_start.tv_usec)/1000;
+ get_total_time_ms += this_time;
+ get_total_size += nread;
+
+ DEBUG(1,("(%3.1f KiloBytes/sec) (average %3.1f KiloBytes/sec)\n",
+ nread / (1.024*this_time + 1.0e-4),
+ get_total_size / (1.024*get_total_time_ms)));
+ }
+
+ TALLOC_FREE(targetname);
+ return rc;
+}
+
+/****************************************************************************
+ Get a file.
+****************************************************************************/
+
+static int cmd_get(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *lname = NULL;
+ char *rname = NULL;
+ char *fname = NULL;
+
+ rname = talloc_strdup(ctx, client_get_cur_dir());
+ if (!rname) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&fname,NULL)) {
+ d_printf("get <filename> [localname]\n");
+ return 1;
+ }
+ rname = talloc_asprintf_append(rname, fname);
+ if (!rname) {
+ return 1;
+ }
+ rname = clean_name(ctx, rname);
+ if (!rname) {
+ return 1;
+ }
+
+ next_token_talloc(ctx, &cmd_ptr,&lname,NULL);
+ if (!lname) {
+ lname = fname;
+ }
+
+ return do_get(rname, lname, false);
+}
+
+/****************************************************************************
+ Do an mget operation on one file.
+****************************************************************************/
+
+static void do_mget(file_info *finfo, const char *dir)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *rname = NULL;
+ char *quest = NULL;
+ char *saved_curdir = NULL;
+ char *mget_mask = NULL;
+ char *new_cd = NULL;
+
+ if (!finfo->name) {
+ return;
+ }
+
+ if (strequal(finfo->name,".") || strequal(finfo->name,".."))
+ return;
+
+ if (abort_mget) {
+ d_printf("mget aborted\n");
+ return;
+ }
+
+ if (finfo->mode & aDIR) {
+ if (asprintf(&quest,
+ "Get directory %s? ",finfo->name) < 0) {
+ return;
+ }
+ } else {
+ if (asprintf(&quest,
+ "Get file %s? ",finfo->name) < 0) {
+ return;
+ }
+ }
+
+ if (prompt && !yesno(quest)) {
+ SAFE_FREE(quest);
+ return;
+ }
+ SAFE_FREE(quest);
+
+ if (!(finfo->mode & aDIR)) {
+ rname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ finfo->name);
+ if (!rname) {
+ return;
+ }
+ do_get(rname, finfo->name, false);
+ TALLOC_FREE(rname);
+ return;
+ }
+
+ /* handle directories */
+ saved_curdir = talloc_strdup(ctx, client_get_cur_dir());
+ if (!saved_curdir) {
+ return;
+ }
+
+ new_cd = talloc_asprintf(ctx,
+ "%s%s%s",
+ client_get_cur_dir(),
+ finfo->name,
+ CLI_DIRSEP_STR);
+ if (!new_cd) {
+ return;
+ }
+ client_set_cur_dir(new_cd);
+
+ string_replace(finfo->name,'\\','/');
+ if (lowercase) {
+ strlower_m(finfo->name);
+ }
+
+ if (!directory_exist(finfo->name,NULL) &&
+ mkdir(finfo->name,0777) != 0) {
+ d_printf("failed to create directory %s\n",finfo->name);
+ client_set_cur_dir(saved_curdir);
+ return;
+ }
+
+ if (chdir(finfo->name) != 0) {
+ d_printf("failed to chdir to directory %s\n",finfo->name);
+ client_set_cur_dir(saved_curdir);
+ return;
+ }
+
+ mget_mask = talloc_asprintf(ctx,
+ "%s*",
+ client_get_cur_dir());
+
+ if (!mget_mask) {
+ return;
+ }
+
+ do_list(mget_mask, aSYSTEM | aHIDDEN | aDIR,do_mget,false, true);
+ chdir("..");
+ client_set_cur_dir(saved_curdir);
+ TALLOC_FREE(mget_mask);
+ TALLOC_FREE(saved_curdir);
+ TALLOC_FREE(new_cd);
+}
+
+/****************************************************************************
+ View the file using the pager.
+****************************************************************************/
+
+static int cmd_more(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *rname = NULL;
+ char *fname = NULL;
+ char *lname = NULL;
+ char *pager_cmd = NULL;
+ const char *pager;
+ int fd;
+ int rc = 0;
+
+ rname = talloc_strdup(ctx, client_get_cur_dir());
+ if (!rname) {
+ return 1;
+ }
+
+ lname = talloc_asprintf(ctx, "%s/smbmore.XXXXXX",tmpdir());
+ if (!lname) {
+ return 1;
+ }
+ fd = smb_mkstemp(lname);
+ if (fd == -1) {
+ d_printf("failed to create temporary file for more\n");
+ return 1;
+ }
+ close(fd);
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&fname,NULL)) {
+ d_printf("more <filename>\n");
+ unlink(lname);
+ return 1;
+ }
+ rname = talloc_asprintf_append(rname, fname);
+ if (!rname) {
+ return 1;
+ }
+ rname = clean_name(ctx,rname);
+ if (!rname) {
+ return 1;
+ }
+
+ rc = do_get(rname, lname, false);
+
+ pager=getenv("PAGER");
+
+ pager_cmd = talloc_asprintf(ctx,
+ "%s %s",
+ (pager? pager:PAGER),
+ lname);
+ if (!pager_cmd) {
+ return 1;
+ }
+ system(pager_cmd);
+ unlink(lname);
+
+ return rc;
+}
+
+/****************************************************************************
+ Do a mget command.
+****************************************************************************/
+
+static int cmd_mget(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ uint16 attribute = aSYSTEM | aHIDDEN;
+ char *mget_mask = NULL;
+ char *buf = NULL;
+
+ if (recurse) {
+ attribute |= aDIR;
+ }
+
+ abort_mget = false;
+
+ while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ mget_mask = talloc_strdup(ctx, client_get_cur_dir());
+ if (!mget_mask) {
+ return 1;
+ }
+ if (*buf == CLI_DIRSEP_CHAR) {
+ mget_mask = talloc_strdup(ctx, buf);
+ } else {
+ mget_mask = talloc_asprintf_append(mget_mask,
+ buf);
+ }
+ if (!mget_mask) {
+ return 1;
+ }
+ do_list(mget_mask, attribute, do_mget, false, true);
+ }
+
+ if (!*mget_mask) {
+ mget_mask = talloc_asprintf(ctx,
+ "%s*",
+ client_get_cur_dir());
+ if (!mget_mask) {
+ return 1;
+ }
+ do_list(mget_mask, attribute, do_mget, false, true);
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Make a directory of name "name".
+****************************************************************************/
+
+static bool do_mkdir(const char *name)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ struct cli_state *targetcli;
+ char *targetname = NULL;
+
+ if (!cli_resolve_path(ctx, "", cli, name, &targetcli, &targetname)) {
+ d_printf("mkdir %s: %s\n", name, cli_errstr(cli));
+ return false;
+ }
+
+ if (!cli_mkdir(targetcli, targetname)) {
+ d_printf("%s making remote directory %s\n",
+ cli_errstr(targetcli),name);
+ return false;
+ }
+
+ return true;
+}
+
+/****************************************************************************
+ Show 8.3 name of a file.
+****************************************************************************/
+
+static bool do_altname(const char *name)
+{
+ fstring altname;
+
+ if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
+ d_printf("%s getting alt name for %s\n",
+ cli_errstr(cli),name);
+ return false;
+ }
+ d_printf("%s\n", altname);
+
+ return true;
+}
+
+/****************************************************************************
+ Exit client.
+****************************************************************************/
+
+static int cmd_quit(void)
+{
+ cli_cm_shutdown();
+ exit(0);
+ /* NOTREACHED */
+ return 0;
+}
+
+/****************************************************************************
+ Make a directory.
+****************************************************************************/
+
+static int cmd_mkdir(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+
+ mask = talloc_strdup(ctx, client_get_cur_dir());
+ if (!mask) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ if (!recurse) {
+ d_printf("mkdir <dirname>\n");
+ }
+ return 1;
+ }
+ mask = talloc_asprintf_append(mask, buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (recurse) {
+ char *ddir = NULL;
+ char *ddir2 = NULL;
+ struct cli_state *targetcli;
+ char *targetname = NULL;
+ char *p = NULL;
+ char *saveptr;
+
+ ddir2 = talloc_strdup(ctx, "");
+ if (!ddir2) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ return 1;
+ }
+
+ ddir = talloc_strdup(ctx, targetname);
+ if (!ddir) {
+ return 1;
+ }
+ trim_char(ddir,'.','\0');
+ p = strtok_r(ddir, "/\\", &saveptr);
+ while (p) {
+ ddir2 = talloc_asprintf_append(ddir2, p);
+ if (!ddir2) {
+ return 1;
+ }
+ if (!cli_chkpath(targetcli, ddir2)) {
+ do_mkdir(ddir2);
+ }
+ ddir2 = talloc_asprintf_append(ddir2, CLI_DIRSEP_STR);
+ if (!ddir2) {
+ return 1;
+ }
+ p = strtok_r(NULL, "/\\", &saveptr);
+ }
+ } else {
+ do_mkdir(mask);
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Show alt name.
+****************************************************************************/
+
+static int cmd_altname(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *name;
+ char *buf;
+
+ name = talloc_strdup(ctx, client_get_cur_dir());
+ if (!name) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
+ d_printf("altname <file>\n");
+ return 1;
+ }
+ name = talloc_asprintf_append(name, buf);
+ if (!name) {
+ return 1;
+ }
+ do_altname(name);
+ return 0;
+}
+
+/****************************************************************************
+ Show all info we can get
+****************************************************************************/
+
+static int do_allinfo(const char *name)
+{
+ fstring altname;
+ struct timespec b_time, a_time, m_time, c_time;
+ SMB_OFF_T size;
+ uint16_t mode;
+ SMB_INO_T ino;
+ NTTIME tmp;
+ unsigned int num_streams;
+ struct stream_struct *streams;
+ unsigned int i;
+
+ if (!NT_STATUS_IS_OK(cli_qpathinfo_alt_name(cli, name, altname))) {
+ d_printf("%s getting alt name for %s\n",
+ cli_errstr(cli),name);
+ return false;
+ }
+ d_printf("altname: %s\n", altname);
+
+ if (!cli_qpathinfo2(cli, name, &b_time, &a_time, &m_time, &c_time,
+ &size, &mode, &ino)) {
+ d_printf("%s getting pathinfo for %s\n",
+ cli_errstr(cli),name);
+ return false;
+ }
+
+ unix_timespec_to_nt_time(&tmp, b_time);
+ d_printf("create_time: %s\n", nt_time_string(talloc_tos(), tmp));
+
+ unix_timespec_to_nt_time(&tmp, a_time);
+ d_printf("access_time: %s\n", nt_time_string(talloc_tos(), tmp));
+
+ unix_timespec_to_nt_time(&tmp, m_time);
+ d_printf("write_time: %s\n", nt_time_string(talloc_tos(), tmp));
+
+ unix_timespec_to_nt_time(&tmp, c_time);
+ d_printf("change_time: %s\n", nt_time_string(talloc_tos(), tmp));
+
+ if (!cli_qpathinfo_streams(cli, name, talloc_tos(), &num_streams,
+ &streams)) {
+ d_printf("%s getting streams for %s\n",
+ cli_errstr(cli),name);
+ return false;
+ }
+
+ for (i=0; i<num_streams; i++) {
+ d_printf("stream: [%s], %lld bytes\n", streams[i].name,
+ (unsigned long long)streams[i].size);
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Show all info we can get
+****************************************************************************/
+
+static int cmd_allinfo(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *name;
+ char *buf;
+
+ name = talloc_strdup(ctx, client_get_cur_dir());
+ if (!name) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
+ d_printf("allinfo <file>\n");
+ return 1;
+ }
+ name = talloc_asprintf_append(name, buf);
+ if (!name) {
+ return 1;
+ }
+
+ do_allinfo(name);
+
+ return 0;
+}
+
+/****************************************************************************
+ Put a single file.
+****************************************************************************/
+
+static int do_put(const char *rname, const char *lname, bool reput)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ int fnum;
+ XFILE *f;
+ SMB_OFF_T start = 0;
+ off_t nread = 0;
+ char *buf = NULL;
+ int maxwrite = io_bufsize;
+ int rc = 0;
+ struct timeval tp_start;
+ struct cli_state *targetcli;
+ char *targetname = NULL;
+
+ if (!cli_resolve_path(ctx, "", cli, rname, &targetcli, &targetname)) {
+ d_printf("Failed to open %s: %s\n", rname, cli_errstr(cli));
+ return 1;
+ }
+
+ GetTimeOfDay(&tp_start);
+
+ if (reput) {
+ fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT, DENY_NONE);
+ if (fnum >= 0) {
+ if (!cli_qfileinfo(targetcli, fnum, NULL, &start, NULL, NULL, NULL, NULL, NULL) &&
+ !cli_getattrE(targetcli, fnum, NULL, &start, NULL, NULL, NULL)) {
+ d_printf("getattrib: %s\n",cli_errstr(cli));
+ return 1;
+ }
+ }
+ } else {
+ fnum = cli_open(targetcli, targetname, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE);
+ }
+
+ if (fnum == -1) {
+ d_printf("%s opening remote file %s\n",cli_errstr(targetcli),rname);
+ return 1;
+ }
+
+ /* allow files to be piped into smbclient
+ jdblair 24.jun.98
+
+ Note that in this case this function will exit(0) rather
+ than returning. */
+ if (!strcmp(lname, "-")) {
+ f = x_stdin;
+ /* size of file is not known */
+ } else {
+ f = x_fopen(lname,O_RDONLY, 0);
+ if (f && reput) {
+ if (x_tseek(f, start, SEEK_SET) == -1) {
+ d_printf("Error seeking local file\n");
+ return 1;
+ }
+ }
+ }
+
+ if (!f) {
+ d_printf("Error opening local file %s\n",lname);
+ return 1;
+ }
+
+ DEBUG(1,("putting file %s as %s ",lname,
+ rname));
+
+ buf = (char *)SMB_MALLOC(maxwrite);
+ if (!buf) {
+ d_printf("ERROR: Not enough memory!\n");
+ return 1;
+ }
+ while (!x_feof(f)) {
+ int n = maxwrite;
+ int ret;
+
+ if ((n = readfile(buf,n,f)) < 1) {
+ if((n == 0) && x_feof(f))
+ break; /* Empty local file. */
+
+ d_printf("Error reading local file: %s\n", strerror(errno));
+ rc = 1;
+ break;
+ }
+
+ ret = cli_write(targetcli, fnum, 0, buf, nread + start, n);
+
+ if (n != ret) {
+ d_printf("Error writing file: %s\n", cli_errstr(cli));
+ rc = 1;
+ break;
+ }
+
+ nread += n;
+ }
+
+ if (!cli_close(targetcli, fnum)) {
+ d_printf("%s closing remote file %s\n",cli_errstr(cli),rname);
+ x_fclose(f);
+ SAFE_FREE(buf);
+ return 1;
+ }
+
+ if (f != x_stdin) {
+ x_fclose(f);
+ }
+
+ SAFE_FREE(buf);
+
+ {
+ struct timeval tp_end;
+ int this_time;
+
+ GetTimeOfDay(&tp_end);
+ this_time =
+ (tp_end.tv_sec - tp_start.tv_sec)*1000 +
+ (tp_end.tv_usec - tp_start.tv_usec)/1000;
+ put_total_time_ms += this_time;
+ put_total_size += nread;
+
+ DEBUG(1,("(%3.1f kb/s) (average %3.1f kb/s)\n",
+ nread / (1.024*this_time + 1.0e-4),
+ put_total_size / (1.024*put_total_time_ms)));
+ }
+
+ if (f == x_stdin) {
+ cli_cm_shutdown();
+ exit(0);
+ }
+
+ return rc;
+}
+
+/****************************************************************************
+ Put a file.
+****************************************************************************/
+
+static int cmd_put(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *lname;
+ char *rname;
+ char *buf;
+
+ rname = talloc_strdup(ctx, client_get_cur_dir());
+ if (!rname) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&lname,NULL)) {
+ d_printf("put <filename>\n");
+ return 1;
+ }
+
+ if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ rname = talloc_asprintf_append(rname, buf);
+ } else {
+ rname = talloc_asprintf_append(rname, lname);
+ }
+ if (!rname) {
+ return 1;
+ }
+
+ rname = clean_name(ctx, rname);
+ if (!rname) {
+ return 1;
+ }
+
+ {
+ SMB_STRUCT_STAT st;
+ /* allow '-' to represent stdin
+ jdblair, 24.jun.98 */
+ if (!file_exist(lname,&st) &&
+ (strcmp(lname,"-"))) {
+ d_printf("%s does not exist\n",lname);
+ return 1;
+ }
+ }
+
+ return do_put(rname, lname, false);
+}
+
+/*************************************
+ File list structure.
+*************************************/
+
+static struct file_list {
+ struct file_list *prev, *next;
+ char *file_path;
+ bool isdir;
+} *file_list;
+
+/****************************************************************************
+ Free a file_list structure.
+****************************************************************************/
+
+static void free_file_list (struct file_list *list_head)
+{
+ struct file_list *list, *next;
+
+ for (list = list_head; list; list = next) {
+ next = list->next;
+ DLIST_REMOVE(list_head, list);
+ SAFE_FREE(list->file_path);
+ SAFE_FREE(list);
+ }
+}
+
+/****************************************************************************
+ Seek in a directory/file list until you get something that doesn't start with
+ the specified name.
+****************************************************************************/
+
+static bool seek_list(struct file_list *list, char *name)
+{
+ while (list) {
+ trim_string(list->file_path,"./","\n");
+ if (strncmp(list->file_path, name, strlen(name)) != 0) {
+ return true;
+ }
+ list = list->next;
+ }
+
+ return false;
+}
+
+/****************************************************************************
+ Set the file selection mask.
+****************************************************************************/
+
+static int cmd_select(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *new_fs = NULL;
+ next_token_talloc(ctx, &cmd_ptr,&new_fs,NULL)
+ ;
+ if (new_fs) {
+ client_set_fileselection(new_fs);
+ } else {
+ client_set_fileselection("");
+ }
+ return 0;
+}
+
+/****************************************************************************
+ Recursive file matching function act as find
+ match must be always set to true when calling this function
+****************************************************************************/
+
+static int file_find(struct file_list **list, const char *directory,
+ const char *expression, bool match)
+{
+ SMB_STRUCT_DIR *dir;
+ struct file_list *entry;
+ struct stat statbuf;
+ int ret;
+ char *path;
+ bool isdir;
+ const char *dname;
+
+ dir = sys_opendir(directory);
+ if (!dir)
+ return -1;
+
+ while ((dname = readdirname(dir))) {
+ if (!strcmp("..", dname))
+ continue;
+ if (!strcmp(".", dname))
+ continue;
+
+ if (asprintf(&path, "%s/%s", directory, dname) <= 0) {
+ continue;
+ }
+
+ isdir = false;
+ if (!match || !gen_fnmatch(expression, dname)) {
+ if (recurse) {
+ ret = stat(path, &statbuf);
+ if (ret == 0) {
+ if (S_ISDIR(statbuf.st_mode)) {
+ isdir = true;
+ ret = file_find(list, path, expression, false);
+ }
+ } else {
+ d_printf("file_find: cannot stat file %s\n", path);
+ }
+
+ if (ret == -1) {
+ SAFE_FREE(path);
+ sys_closedir(dir);
+ return -1;
+ }
+ }
+ entry = SMB_MALLOC_P(struct file_list);
+ if (!entry) {
+ d_printf("Out of memory in file_find\n");
+ sys_closedir(dir);
+ return -1;
+ }
+ entry->file_path = path;
+ entry->isdir = isdir;
+ DLIST_ADD(*list, entry);
+ } else {
+ SAFE_FREE(path);
+ }
+ }
+
+ sys_closedir(dir);
+ return 0;
+}
+
+/****************************************************************************
+ mput some files.
+****************************************************************************/
+
+static int cmd_mput(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *p = NULL;
+
+ while (next_token_talloc(ctx, &cmd_ptr,&p,NULL)) {
+ int ret;
+ struct file_list *temp_list;
+ char *quest, *lname, *rname;
+
+ file_list = NULL;
+
+ ret = file_find(&file_list, ".", p, true);
+ if (ret) {
+ free_file_list(file_list);
+ continue;
+ }
+
+ quest = NULL;
+ lname = NULL;
+ rname = NULL;
+
+ for (temp_list = file_list; temp_list;
+ temp_list = temp_list->next) {
+
+ SAFE_FREE(lname);
+ if (asprintf(&lname, "%s/", temp_list->file_path) <= 0) {
+ continue;
+ }
+ trim_string(lname, "./", "/");
+
+ /* check if it's a directory */
+ if (temp_list->isdir) {
+ /* if (!recurse) continue; */
+
+ SAFE_FREE(quest);
+ if (asprintf(&quest, "Put directory %s? ", lname) < 0) {
+ break;
+ }
+ if (prompt && !yesno(quest)) { /* No */
+ /* Skip the directory */
+ lname[strlen(lname)-1] = '/';
+ if (!seek_list(temp_list, lname))
+ break;
+ } else { /* Yes */
+ SAFE_FREE(rname);
+ if(asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
+ break;
+ }
+ normalize_name(rname);
+ if (!cli_chkpath(cli, rname) &&
+ !do_mkdir(rname)) {
+ DEBUG (0, ("Unable to make dir, skipping..."));
+ /* Skip the directory */
+ lname[strlen(lname)-1] = '/';
+ if (!seek_list(temp_list, lname)) {
+ break;
+ }
+ }
+ }
+ continue;
+ } else {
+ SAFE_FREE(quest);
+ if (asprintf(&quest,"Put file %s? ", lname) < 0) {
+ break;
+ }
+ if (prompt && !yesno(quest)) {
+ /* No */
+ continue;
+ }
+
+ /* Yes */
+ SAFE_FREE(rname);
+ if (asprintf(&rname, "%s%s", client_get_cur_dir(), lname) < 0) {
+ break;
+ }
+ }
+
+ normalize_name(rname);
+
+ do_put(rname, lname, false);
+ }
+ free_file_list(file_list);
+ SAFE_FREE(quest);
+ SAFE_FREE(lname);
+ SAFE_FREE(rname);
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Cancel a print job.
+****************************************************************************/
+
+static int do_cancel(int job)
+{
+ if (cli_printjob_del(cli, job)) {
+ d_printf("Job %d cancelled\n",job);
+ return 0;
+ } else {
+ d_printf("Error cancelling job %d : %s\n",job,cli_errstr(cli));
+ return 1;
+ }
+}
+
+/****************************************************************************
+ Cancel a print job.
+****************************************************************************/
+
+static int cmd_cancel(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf = NULL;
+ int job;
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &buf,NULL)) {
+ d_printf("cancel <jobid> ...\n");
+ return 1;
+ }
+ do {
+ job = atoi(buf);
+ do_cancel(job);
+ } while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL));
+
+ return 0;
+}
+
+/****************************************************************************
+ Print a file.
+****************************************************************************/
+
+static int cmd_print(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *lname = NULL;
+ char *rname = NULL;
+ char *p = NULL;
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &lname,NULL)) {
+ d_printf("print <filename>\n");
+ return 1;
+ }
+
+ rname = talloc_strdup(ctx, lname);
+ if (!rname) {
+ return 1;
+ }
+ p = strrchr_m(rname,'/');
+ if (p) {
+ rname = talloc_asprintf(ctx,
+ "%s-%d",
+ p+1,
+ (int)sys_getpid());
+ }
+ if (strequal(lname,"-")) {
+ rname = talloc_asprintf(ctx,
+ "stdin-%d",
+ (int)sys_getpid());
+ }
+ if (!rname) {
+ return 1;
+ }
+
+ return do_put(rname, lname, false);
+}
+
+/****************************************************************************
+ Show a print queue entry.
+****************************************************************************/
+
+static void queue_fn(struct print_job_info *p)
+{
+ d_printf("%-6d %-9d %s\n", (int)p->id, (int)p->size, p->name);
+}
+
+/****************************************************************************
+ Show a print queue.
+****************************************************************************/
+
+static int cmd_queue(void)
+{
+ cli_print_queue(cli, queue_fn);
+ return 0;
+}
+
+/****************************************************************************
+ Delete some files.
+****************************************************************************/
+
+static void do_del(file_info *finfo, const char *dir)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+
+ mask = talloc_asprintf(ctx,
+ "%s%c%s",
+ dir,
+ CLI_DIRSEP_CHAR,
+ finfo->name);
+ if (!mask) {
+ return;
+ }
+
+ if (finfo->mode & aDIR) {
+ TALLOC_FREE(mask);
+ return;
+ }
+
+ if (!cli_unlink(finfo->cli, mask)) {
+ d_printf("%s deleting remote file %s\n",
+ cli_errstr(finfo->cli),mask);
+ }
+ TALLOC_FREE(mask);
+}
+
+/****************************************************************************
+ Delete some files.
+****************************************************************************/
+
+static int cmd_del(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ uint16 attribute = aSYSTEM | aHIDDEN;
+
+ if (recurse) {
+ attribute |= aDIR;
+ }
+
+ mask = talloc_strdup(ctx, client_get_cur_dir());
+ if (!mask) {
+ return 1;
+ }
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("del <filename>\n");
+ return 1;
+ }
+ mask = talloc_asprintf_append(mask, buf);
+ if (!mask) {
+ return 1;
+ }
+
+ do_list(mask,attribute,do_del,false,false);
+ return 0;
+}
+
+/****************************************************************************
+ Wildcard delete some files.
+****************************************************************************/
+
+static int cmd_wdel(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ uint16 attribute;
+ struct cli_state *targetcli;
+ char *targetname = NULL;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("wdel 0x<attrib> <wcard>\n");
+ return 1;
+ }
+
+ attribute = (uint16)strtol(buf, (char **)NULL, 16);
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("wdel 0x<attrib> <wcard>\n");
+ return 1;
+ }
+
+ mask = talloc_asprintf(ctx, "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("cmd_wdel %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_unlink_full(targetcli, targetname, attribute)) {
+ d_printf("%s deleting remote files %s\n",cli_errstr(targetcli),targetname);
+ }
+ return 0;
+}
+
+/****************************************************************************
+****************************************************************************/
+
+static int cmd_open(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+ int fnum;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("open <filename>\n");
+ return 1;
+ }
+ mask = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("open %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ fnum = cli_nt_create(targetcli, targetname, FILE_READ_DATA|FILE_WRITE_DATA);
+ if (fnum == -1) {
+ fnum = cli_nt_create(targetcli, targetname, FILE_READ_DATA);
+ if (fnum != -1) {
+ d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
+ } else {
+ d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
+ }
+ } else {
+ d_printf("open file %s: for read/write fnum %d\n", targetname, fnum);
+ }
+ return 0;
+}
+
+static int cmd_posix_encrypt(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
+
+ if (cli->use_kerberos) {
+ status = cli_gss_smb_encryption_start(cli);
+ } else {
+ char *domain = NULL;
+ char *user = NULL;
+ char *password = NULL;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&domain,NULL)) {
+ d_printf("posix_encrypt domain user password\n");
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&user,NULL)) {
+ d_printf("posix_encrypt domain user password\n");
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&password,NULL)) {
+ d_printf("posix_encrypt domain user password\n");
+ return 1;
+ }
+
+ status = cli_raw_ntlm_smb_encryption_start(cli,
+ user,
+ password,
+ domain);
+ }
+
+ if (!NT_STATUS_IS_OK(status)) {
+ d_printf("posix_encrypt failed with error %s\n", nt_errstr(status));
+ } else {
+ d_printf("encryption on\n");
+ smb_encrypt = true;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+****************************************************************************/
+
+static int cmd_posix_open(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+ mode_t mode;
+ int fnum;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("posix_open <filename> 0<mode>\n");
+ return 1;
+ }
+ mask = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("posix_open <filename> 0<mode>\n");
+ return 1;
+ }
+ mode = (mode_t)strtol(buf, (char **)NULL, 8);
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("posix_open %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ fnum = cli_posix_open(targetcli, targetname, O_CREAT|O_RDWR, mode);
+ if (fnum == -1) {
+ fnum = cli_posix_open(targetcli, targetname, O_CREAT|O_RDONLY, mode);
+ if (fnum != -1) {
+ d_printf("posix_open file %s: for read/write fnum %d\n", targetname, fnum);
+ } else {
+ d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
+ }
+ } else {
+ d_printf("posix_open file %s: for read/write fnum %d\n", targetname, fnum);
+ }
+
+ return 0;
+}
+
+static int cmd_posix_mkdir(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+ mode_t mode;
+ int fnum;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("posix_mkdir <filename> 0<mode>\n");
+ return 1;
+ }
+ mask = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("posix_mkdir <filename> 0<mode>\n");
+ return 1;
+ }
+ mode = (mode_t)strtol(buf, (char **)NULL, 8);
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("posix_mkdir %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ fnum = cli_posix_mkdir(targetcli, targetname, mode);
+ if (fnum == -1) {
+ d_printf("Failed to open file %s. %s\n", targetname, cli_errstr(cli));
+ } else {
+ d_printf("posix_mkdir created directory %s\n", targetname);
+ }
+ return 0;
+}
+
+static int cmd_posix_unlink(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("posix_unlink <filename>\n");
+ return 1;
+ }
+ mask = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("posix_unlink %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_posix_unlink(targetcli, targetname)) {
+ d_printf("Failed to unlink file %s. %s\n", targetname, cli_errstr(cli));
+ } else {
+ d_printf("posix_unlink deleted file %s\n", targetname);
+ }
+
+ return 0;
+}
+
+static int cmd_posix_rmdir(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("posix_rmdir <filename>\n");
+ return 1;
+ }
+ mask = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("posix_rmdir %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_posix_rmdir(targetcli, targetname)) {
+ d_printf("Failed to unlink directory %s. %s\n", targetname, cli_errstr(cli));
+ } else {
+ d_printf("posix_rmdir deleted directory %s\n", targetname);
+ }
+
+ return 0;
+}
+
+static int cmd_close(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf = NULL;
+ int fnum;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("close <fnum>\n");
+ return 1;
+ }
+
+ fnum = atoi(buf);
+ /* We really should use the targetcli here.... */
+ if (!cli_close(cli, fnum)) {
+ d_printf("close %d: %s\n", fnum, cli_errstr(cli));
+ return 1;
+ }
+ return 0;
+}
+
+static int cmd_posix(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ uint16 major, minor;
+ uint32 caplow, caphigh;
+ char *caps;
+
+ if (!SERVER_HAS_UNIX_CIFS(cli)) {
+ d_printf("Server doesn't support UNIX CIFS extensions.\n");
+ return 1;
+ }
+
+ if (!cli_unix_extensions_version(cli, &major, &minor, &caplow, &caphigh)) {
+ d_printf("Can't get UNIX CIFS extensions version from server.\n");
+ return 1;
+ }
+
+ d_printf("Server supports CIFS extensions %u.%u\n", (unsigned int)major, (unsigned int)minor);
+
+ caps = talloc_strdup(ctx, "");
+ if (!caps) {
+ return 1;
+ }
+ if (caplow & CIFS_UNIX_FCNTL_LOCKS_CAP) {
+ caps = talloc_asprintf_append(caps, "locks ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_POSIX_ACLS_CAP) {
+ caps = talloc_asprintf_append(caps, "acls ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_XATTTR_CAP) {
+ caps = talloc_asprintf_append(caps, "eas ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
+ caps = talloc_asprintf_append(caps, "pathnames ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_POSIX_PATH_OPERATIONS_CAP) {
+ caps = talloc_asprintf_append(caps, "posix_path_operations ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_LARGE_READ_CAP) {
+ caps = talloc_asprintf_append(caps, "large_read ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_LARGE_WRITE_CAP) {
+ caps = talloc_asprintf_append(caps, "large_write ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_CAP) {
+ caps = talloc_asprintf_append(caps, "posix_encrypt ");
+ if (!caps) {
+ return 1;
+ }
+ }
+ if (caplow & CIFS_UNIX_TRANSPORT_ENCRYPTION_MANDATORY_CAP) {
+ caps = talloc_asprintf_append(caps, "mandatory_posix_encrypt ");
+ if (!caps) {
+ return 1;
+ }
+ }
+
+ if (*caps && caps[strlen(caps)-1] == ' ') {
+ caps[strlen(caps)-1] = '\0';
+ }
+
+ d_printf("Server supports CIFS capabilities %s\n", caps);
+
+ if (!cli_set_unix_extensions_capabilities(cli, major, minor, caplow, caphigh)) {
+ d_printf("Can't set UNIX CIFS extensions capabilities. %s.\n", cli_errstr(cli));
+ return 1;
+ }
+
+ if (caplow & CIFS_UNIX_POSIX_PATHNAMES_CAP) {
+ CLI_DIRSEP_CHAR = '/';
+ *CLI_DIRSEP_STR = '/';
+ client_set_cur_dir(CLI_DIRSEP_STR);
+ }
+
+ return 0;
+}
+
+static int cmd_lock(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf = NULL;
+ SMB_BIG_UINT start, len;
+ enum brl_type lock_type;
+ int fnum;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
+ return 1;
+ }
+ fnum = atoi(buf);
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
+ return 1;
+ }
+
+ if (*buf == 'r' || *buf == 'R') {
+ lock_type = READ_LOCK;
+ } else if (*buf == 'w' || *buf == 'W') {
+ lock_type = WRITE_LOCK;
+ } else {
+ d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
+ return 1;
+ }
+
+ start = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("lock <fnum> [r|w] <hex-start> <hex-len>\n");
+ return 1;
+ }
+
+ len = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
+
+ if (!cli_posix_lock(cli, fnum, start, len, true, lock_type)) {
+ d_printf("lock failed %d: %s\n", fnum, cli_errstr(cli));
+ }
+
+ return 0;
+}
+
+static int cmd_unlock(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf = NULL;
+ SMB_BIG_UINT start, len;
+ int fnum;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("unlock <fnum> <hex-start> <hex-len>\n");
+ return 1;
+ }
+ fnum = atoi(buf);
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("unlock <fnum> <hex-start> <hex-len>\n");
+ return 1;
+ }
+
+ start = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("unlock <fnum> <hex-start> <hex-len>\n");
+ return 1;
+ }
+
+ len = (SMB_BIG_UINT)strtol(buf, (char **)NULL, 16);
+
+ if (!cli_posix_unlock(cli, fnum, start, len)) {
+ d_printf("unlock failed %d: %s\n", fnum, cli_errstr(cli));
+ }
+
+ return 0;
+}
+
+
+/****************************************************************************
+ Remove a directory.
+****************************************************************************/
+
+static int cmd_rmdir(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *mask = NULL;
+ char *buf = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("rmdir <dirname>\n");
+ return 1;
+ }
+ mask = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!mask) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, mask, &targetcli, &targetname)) {
+ d_printf("rmdir %s: %s\n", mask, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_rmdir(targetcli, targetname)) {
+ d_printf("%s removing remote directory file %s\n",
+ cli_errstr(targetcli),mask);
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ UNIX hardlink.
+****************************************************************************/
+
+static int cmd_link(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *oldname = NULL;
+ char *newname = NULL;
+ char *buf = NULL;
+ char *buf2 = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
+ d_printf("link <oldname> <newname>\n");
+ return 1;
+ }
+ oldname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!oldname) {
+ return 1;
+ }
+ newname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf2);
+ if (!newname) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, oldname, &targetcli, &targetname)) {
+ d_printf("link %s: %s\n", oldname, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
+ d_printf("Server doesn't support UNIX CIFS calls.\n");
+ return 1;
+ }
+
+ if (!cli_unix_hardlink(targetcli, targetname, newname)) {
+ d_printf("%s linking files (%s -> %s)\n", cli_errstr(targetcli), newname, oldname);
+ return 1;
+ }
+ return 0;
+}
+
+/****************************************************************************
+ UNIX symlink.
+****************************************************************************/
+
+static int cmd_symlink(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *oldname = NULL;
+ char *newname = NULL;
+ char *buf = NULL;
+ char *buf2 = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
+ d_printf("symlink <oldname> <newname>\n");
+ return 1;
+ }
+ oldname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!oldname) {
+ return 1;
+ }
+ newname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf2);
+ if (!newname) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, oldname, &targetcli, &targetname)) {
+ d_printf("link %s: %s\n", oldname, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
+ d_printf("Server doesn't support UNIX CIFS calls.\n");
+ return 1;
+ }
+
+ if (!cli_unix_symlink(targetcli, targetname, newname)) {
+ d_printf("%s symlinking files (%s -> %s)\n",
+ cli_errstr(targetcli), newname, targetname);
+ return 1;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ UNIX chmod.
+****************************************************************************/
+
+static int cmd_chmod(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *src = NULL;
+ char *buf = NULL;
+ char *buf2 = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+ mode_t mode;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
+ d_printf("chmod mode file\n");
+ return 1;
+ }
+ src = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf2);
+ if (!src) {
+ return 1;
+ }
+
+ mode = (mode_t)strtol(buf, NULL, 8);
+
+ if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
+ d_printf("chmod %s: %s\n", src, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
+ d_printf("Server doesn't support UNIX CIFS calls.\n");
+ return 1;
+ }
+
+ if (!cli_unix_chmod(targetcli, targetname, mode)) {
+ d_printf("%s chmod file %s 0%o\n",
+ cli_errstr(targetcli), src, (unsigned int)mode);
+ return 1;
+ }
+
+ return 0;
+}
+
+static const char *filetype_to_str(mode_t mode)
+{
+ if (S_ISREG(mode)) {
+ return "regular file";
+ } else if (S_ISDIR(mode)) {
+ return "directory";
+ } else
+#ifdef S_ISCHR
+ if (S_ISCHR(mode)) {
+ return "character device";
+ } else
+#endif
+#ifdef S_ISBLK
+ if (S_ISBLK(mode)) {
+ return "block device";
+ } else
+#endif
+#ifdef S_ISFIFO
+ if (S_ISFIFO(mode)) {
+ return "fifo";
+ } else
+#endif
+#ifdef S_ISLNK
+ if (S_ISLNK(mode)) {
+ return "symbolic link";
+ } else
+#endif
+#ifdef S_ISSOCK
+ if (S_ISSOCK(mode)) {
+ return "socket";
+ } else
+#endif
+ return "";
+}
+
+static char rwx_to_str(mode_t m, mode_t bt, char ret)
+{
+ if (m & bt) {
+ return ret;
+ } else {
+ return '-';
+ }
+}
+
+static char *unix_mode_to_str(char *s, mode_t m)
+{
+ char *p = s;
+ const char *str = filetype_to_str(m);
+
+ switch(str[0]) {
+ case 'd':
+ *p++ = 'd';
+ break;
+ case 'c':
+ *p++ = 'c';
+ break;
+ case 'b':
+ *p++ = 'b';
+ break;
+ case 'f':
+ *p++ = 'p';
+ break;
+ case 's':
+ *p++ = str[1] == 'y' ? 'l' : 's';
+ break;
+ case 'r':
+ default:
+ *p++ = '-';
+ break;
+ }
+ *p++ = rwx_to_str(m, S_IRUSR, 'r');
+ *p++ = rwx_to_str(m, S_IWUSR, 'w');
+ *p++ = rwx_to_str(m, S_IXUSR, 'x');
+ *p++ = rwx_to_str(m, S_IRGRP, 'r');
+ *p++ = rwx_to_str(m, S_IWGRP, 'w');
+ *p++ = rwx_to_str(m, S_IXGRP, 'x');
+ *p++ = rwx_to_str(m, S_IROTH, 'r');
+ *p++ = rwx_to_str(m, S_IWOTH, 'w');
+ *p++ = rwx_to_str(m, S_IXOTH, 'x');
+ *p++ = '\0';
+ return s;
+}
+
+/****************************************************************************
+ Utility function for UNIX getfacl.
+****************************************************************************/
+
+static char *perms_to_string(fstring permstr, unsigned char perms)
+{
+ fstrcpy(permstr, "---");
+ if (perms & SMB_POSIX_ACL_READ) {
+ permstr[0] = 'r';
+ }
+ if (perms & SMB_POSIX_ACL_WRITE) {
+ permstr[1] = 'w';
+ }
+ if (perms & SMB_POSIX_ACL_EXECUTE) {
+ permstr[2] = 'x';
+ }
+ return permstr;
+}
+
+/****************************************************************************
+ UNIX getfacl.
+****************************************************************************/
+
+static int cmd_getfacl(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *src = NULL;
+ char *name = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+ uint16 major, minor;
+ uint32 caplow, caphigh;
+ char *retbuf = NULL;
+ size_t rb_size = 0;
+ SMB_STRUCT_STAT sbuf;
+ uint16 num_file_acls = 0;
+ uint16 num_dir_acls = 0;
+ uint16 i;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
+ d_printf("getfacl filename\n");
+ return 1;
+ }
+ src = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ name);
+ if (!src) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
+ d_printf("stat %s: %s\n", src, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
+ d_printf("Server doesn't support UNIX CIFS calls.\n");
+ return 1;
+ }
+
+ if (!cli_unix_extensions_version(targetcli, &major, &minor,
+ &caplow, &caphigh)) {
+ d_printf("Can't get UNIX CIFS version from server.\n");
+ return 1;
+ }
+
+ if (!(caplow & CIFS_UNIX_POSIX_ACLS_CAP)) {
+ d_printf("This server supports UNIX extensions "
+ "but doesn't support POSIX ACLs.\n");
+ return 1;
+ }
+
+ if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
+ d_printf("%s getfacl doing a stat on file %s\n",
+ cli_errstr(targetcli), src);
+ return 1;
+ }
+
+ if (!cli_unix_getfacl(targetcli, targetname, &rb_size, &retbuf)) {
+ d_printf("%s getfacl file %s\n",
+ cli_errstr(targetcli), src);
+ return 1;
+ }
+
+ /* ToDo : Print out the ACL values. */
+ if (SVAL(retbuf,0) != SMB_POSIX_ACL_VERSION || rb_size < 6) {
+ d_printf("getfacl file %s, unknown POSIX acl version %u.\n",
+ src, (unsigned int)CVAL(retbuf,0) );
+ SAFE_FREE(retbuf);
+ return 1;
+ }
+
+ num_file_acls = SVAL(retbuf,2);
+ num_dir_acls = SVAL(retbuf,4);
+ if (rb_size != SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)) {
+ d_printf("getfacl file %s, incorrect POSIX acl buffer size (should be %u, was %u).\n",
+ src,
+ (unsigned int)(SMB_POSIX_ACL_HEADER_SIZE + SMB_POSIX_ACL_ENTRY_SIZE*(num_file_acls+num_dir_acls)),
+ (unsigned int)rb_size);
+
+ SAFE_FREE(retbuf);
+ return 1;
+ }
+
+ d_printf("# file: %s\n", src);
+ d_printf("# owner: %u\n# group: %u\n", (unsigned int)sbuf.st_uid, (unsigned int)sbuf.st_gid);
+
+ if (num_file_acls == 0 && num_dir_acls == 0) {
+ d_printf("No acls found.\n");
+ }
+
+ for (i = 0; i < num_file_acls; i++) {
+ uint32 uorg;
+ fstring permstring;
+ unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE));
+ unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+1);
+
+ switch(tagtype) {
+ case SMB_POSIX_ACL_USER_OBJ:
+ d_printf("user::");
+ break;
+ case SMB_POSIX_ACL_USER:
+ uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
+ d_printf("user:%u:", uorg);
+ break;
+ case SMB_POSIX_ACL_GROUP_OBJ:
+ d_printf("group::");
+ break;
+ case SMB_POSIX_ACL_GROUP:
+ uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+(i*SMB_POSIX_ACL_ENTRY_SIZE)+2);
+ d_printf("group:%u", uorg);
+ break;
+ case SMB_POSIX_ACL_MASK:
+ d_printf("mask::");
+ break;
+ case SMB_POSIX_ACL_OTHER:
+ d_printf("other::");
+ break;
+ default:
+ d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
+ src, (unsigned int)tagtype );
+ SAFE_FREE(retbuf);
+ return 1;
+ }
+
+ d_printf("%s\n", perms_to_string(permstring, perms));
+ }
+
+ for (i = 0; i < num_dir_acls; i++) {
+ uint32 uorg;
+ fstring permstring;
+ unsigned char tagtype = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE));
+ unsigned char perms = CVAL(retbuf, SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+1);
+
+ switch(tagtype) {
+ case SMB_POSIX_ACL_USER_OBJ:
+ d_printf("default:user::");
+ break;
+ case SMB_POSIX_ACL_USER:
+ uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
+ d_printf("default:user:%u:", uorg);
+ break;
+ case SMB_POSIX_ACL_GROUP_OBJ:
+ d_printf("default:group::");
+ break;
+ case SMB_POSIX_ACL_GROUP:
+ uorg = IVAL(retbuf,SMB_POSIX_ACL_HEADER_SIZE+((i+num_file_acls)*SMB_POSIX_ACL_ENTRY_SIZE)+2);
+ d_printf("default:group:%u", uorg);
+ break;
+ case SMB_POSIX_ACL_MASK:
+ d_printf("default:mask::");
+ break;
+ case SMB_POSIX_ACL_OTHER:
+ d_printf("default:other::");
+ break;
+ default:
+ d_printf("getfacl file %s, incorrect POSIX acl tagtype (%u).\n",
+ src, (unsigned int)tagtype );
+ SAFE_FREE(retbuf);
+ return 1;
+ }
+
+ d_printf("%s\n", perms_to_string(permstring, perms));
+ }
+
+ SAFE_FREE(retbuf);
+ return 0;
+}
+
+/****************************************************************************
+ UNIX stat.
+****************************************************************************/
+
+static int cmd_stat(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *src = NULL;
+ char *name = NULL;
+ char *targetname = NULL;
+ struct cli_state *targetcli;
+ fstring mode_str;
+ SMB_STRUCT_STAT sbuf;
+ struct tm *lt;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&name,NULL)) {
+ d_printf("stat file\n");
+ return 1;
+ }
+ src = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ name);
+ if (!src) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
+ d_printf("stat %s: %s\n", src, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
+ d_printf("Server doesn't support UNIX CIFS calls.\n");
+ return 1;
+ }
+
+ if (!cli_unix_stat(targetcli, targetname, &sbuf)) {
+ d_printf("%s stat file %s\n",
+ cli_errstr(targetcli), src);
+ return 1;
+ }
+
+ /* Print out the stat values. */
+ d_printf("File: %s\n", src);
+ d_printf("Size: %-12.0f\tBlocks: %u\t%s\n",
+ (double)sbuf.st_size,
+ (unsigned int)sbuf.st_blocks,
+ filetype_to_str(sbuf.st_mode));
+
+#if defined(S_ISCHR) && defined(S_ISBLK)
+ if (S_ISCHR(sbuf.st_mode) || S_ISBLK(sbuf.st_mode)) {
+ d_printf("Inode: %.0f\tLinks: %u\tDevice type: %u,%u\n",
+ (double)sbuf.st_ino,
+ (unsigned int)sbuf.st_nlink,
+ unix_dev_major(sbuf.st_rdev),
+ unix_dev_minor(sbuf.st_rdev));
+ } else
+#endif
+ d_printf("Inode: %.0f\tLinks: %u\n",
+ (double)sbuf.st_ino,
+ (unsigned int)sbuf.st_nlink);
+
+ d_printf("Access: (0%03o/%s)\tUid: %u\tGid: %u\n",
+ ((int)sbuf.st_mode & 0777),
+ unix_mode_to_str(mode_str, sbuf.st_mode),
+ (unsigned int)sbuf.st_uid,
+ (unsigned int)sbuf.st_gid);
+
+ lt = localtime(&sbuf.st_atime);
+ if (lt) {
+ strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
+ } else {
+ fstrcpy(mode_str, "unknown");
+ }
+ d_printf("Access: %s\n", mode_str);
+
+ lt = localtime(&sbuf.st_mtime);
+ if (lt) {
+ strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
+ } else {
+ fstrcpy(mode_str, "unknown");
+ }
+ d_printf("Modify: %s\n", mode_str);
+
+ lt = localtime(&sbuf.st_ctime);
+ if (lt) {
+ strftime(mode_str, sizeof(mode_str), "%Y-%m-%d %T %z", lt);
+ } else {
+ fstrcpy(mode_str, "unknown");
+ }
+ d_printf("Change: %s\n", mode_str);
+
+ return 0;
+}
+
+
+/****************************************************************************
+ UNIX chown.
+****************************************************************************/
+
+static int cmd_chown(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *src = NULL;
+ uid_t uid;
+ gid_t gid;
+ char *buf, *buf2, *buf3;
+ struct cli_state *targetcli;
+ char *targetname = NULL;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf3,NULL)) {
+ d_printf("chown uid gid file\n");
+ return 1;
+ }
+
+ uid = (uid_t)atoi(buf);
+ gid = (gid_t)atoi(buf2);
+
+ src = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf3);
+ if (!src) {
+ return 1;
+ }
+ if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname) ) {
+ d_printf("chown %s: %s\n", src, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!SERVER_HAS_UNIX_CIFS(targetcli)) {
+ d_printf("Server doesn't support UNIX CIFS calls.\n");
+ return 1;
+ }
+
+ if (!cli_unix_chown(targetcli, targetname, uid, gid)) {
+ d_printf("%s chown file %s uid=%d, gid=%d\n",
+ cli_errstr(targetcli), src, (int)uid, (int)gid);
+ return 1;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Rename some file.
+****************************************************************************/
+
+static int cmd_rename(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *src, *dest;
+ char *buf, *buf2;
+ struct cli_state *targetcli;
+ char *targetsrc;
+ char *targetdest;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
+ d_printf("rename <src> <dest>\n");
+ return 1;
+ }
+
+ src = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!src) {
+ return 1;
+ }
+
+ dest = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf2);
+ if (!dest) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetsrc)) {
+ d_printf("rename %s: %s\n", src, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, dest, &targetcli, &targetdest)) {
+ d_printf("rename %s: %s\n", dest, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_rename(targetcli, targetsrc, targetdest)) {
+ d_printf("%s renaming files %s -> %s \n",
+ cli_errstr(targetcli),
+ targetsrc,
+ targetdest);
+ return 1;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Print the volume name.
+****************************************************************************/
+
+static int cmd_volume(void)
+{
+ fstring volname;
+ uint32 serial_num;
+ time_t create_date;
+
+ if (!cli_get_fs_volume_info(cli, volname, &serial_num, &create_date)) {
+ d_printf("Errr %s getting volume info\n",cli_errstr(cli));
+ return 1;
+ }
+
+ d_printf("Volume: |%s| serial number 0x%x\n",
+ volname, (unsigned int)serial_num);
+ return 0;
+}
+
+/****************************************************************************
+ Hard link files using the NT call.
+****************************************************************************/
+
+static int cmd_hardlink(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *src, *dest;
+ char *buf, *buf2;
+ struct cli_state *targetcli;
+ char *targetname;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL) ||
+ !next_token_talloc(ctx, &cmd_ptr,&buf2,NULL)) {
+ d_printf("hardlink <src> <dest>\n");
+ return 1;
+ }
+
+ src = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!src) {
+ return 1;
+ }
+
+ dest = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf2);
+ if (!dest) {
+ return 1;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, src, &targetcli, &targetname)) {
+ d_printf("hardlink %s: %s\n", src, cli_errstr(cli));
+ return 1;
+ }
+
+ if (!cli_nt_hardlink(targetcli, targetname, dest)) {
+ d_printf("%s doing an NT hard link of files\n",cli_errstr(targetcli));
+ return 1;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Toggle the prompt flag.
+****************************************************************************/
+
+static int cmd_prompt(void)
+{
+ prompt = !prompt;
+ DEBUG(2,("prompting is now %s\n",prompt?"on":"off"));
+ return 1;
+}
+
+/****************************************************************************
+ Set the newer than time.
+****************************************************************************/
+
+static int cmd_newer(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+ bool ok;
+ SMB_STRUCT_STAT sbuf;
+
+ ok = next_token_talloc(ctx, &cmd_ptr,&buf,NULL);
+ if (ok && (sys_stat(buf,&sbuf) == 0)) {
+ newer_than = sbuf.st_mtime;
+ DEBUG(1,("Getting files newer than %s",
+ time_to_asc(newer_than)));
+ } else {
+ newer_than = 0;
+ }
+
+ if (ok && newer_than == 0) {
+ d_printf("Error setting newer-than time\n");
+ return 1;
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Set the archive level.
+****************************************************************************/
+
+static int cmd_archive(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+
+ if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ archive_level = atoi(buf);
+ } else {
+ d_printf("Archive level is %d\n",archive_level);
+ }
+
+ return 0;
+}
+
+/****************************************************************************
+ Toggle the lowercaseflag.
+****************************************************************************/
+
+static int cmd_lowercase(void)
+{
+ lowercase = !lowercase;
+ DEBUG(2,("filename lowercasing is now %s\n",lowercase?"on":"off"));
+ return 0;
+}
+
+/****************************************************************************
+ Toggle the case sensitive flag.
+****************************************************************************/
+
+static int cmd_setcase(void)
+{
+ bool orig_case_sensitive = cli_set_case_sensitive(cli, false);
+
+ cli_set_case_sensitive(cli, !orig_case_sensitive);
+ DEBUG(2,("filename case sensitivity is now %s\n",!orig_case_sensitive ?
+ "on":"off"));
+ return 0;
+}
+
+/****************************************************************************
+ Toggle the showacls flag.
+****************************************************************************/
+
+static int cmd_showacls(void)
+{
+ showacls = !showacls;
+ DEBUG(2,("showacls is now %s\n",showacls?"on":"off"));
+ return 0;
+}
+
+
+/****************************************************************************
+ Toggle the recurse flag.
+****************************************************************************/
+
+static int cmd_recurse(void)
+{
+ recurse = !recurse;
+ DEBUG(2,("directory recursion is now %s\n",recurse?"on":"off"));
+ return 0;
+}
+
+/****************************************************************************
+ Toggle the translate flag.
+****************************************************************************/
+
+static int cmd_translate(void)
+{
+ translation = !translation;
+ DEBUG(2,("CR/LF<->LF and print text translation now %s\n",
+ translation?"on":"off"));
+ return 0;
+}
+
+/****************************************************************************
+ Do the lcd command.
+ ****************************************************************************/
+
+static int cmd_lcd(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+ char *d;
+
+ if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ chdir(buf);
+ }
+ d = TALLOC_ARRAY(ctx, char, PATH_MAX+1);
+ if (!d) {
+ return 1;
+ }
+ DEBUG(2,("the local directory is now %s\n",sys_getwd(d)));
+ return 0;
+}
+
+/****************************************************************************
+ Get a file restarting at end of local file.
+ ****************************************************************************/
+
+static int cmd_reget(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *local_name = NULL;
+ char *remote_name = NULL;
+ char *fname = NULL;
+ char *p = NULL;
+
+ remote_name = talloc_strdup(ctx, client_get_cur_dir());
+ if (!remote_name) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &fname, NULL)) {
+ d_printf("reget <filename>\n");
+ return 1;
+ }
+ remote_name = talloc_asprintf_append(remote_name, fname);
+ if (!remote_name) {
+ return 1;
+ }
+ remote_name = clean_name(ctx,remote_name);
+ if (!remote_name) {
+ return 1;
+ }
+
+ local_name = fname;
+ next_token_talloc(ctx, &cmd_ptr, &p, NULL);
+ if (p) {
+ local_name = p;
+ }
+
+ return do_get(remote_name, local_name, true);
+}
+
+/****************************************************************************
+ Put a file restarting at end of local file.
+ ****************************************************************************/
+
+static int cmd_reput(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *local_name = NULL;
+ char *remote_name = NULL;
+ char *buf;
+ SMB_STRUCT_STAT st;
+
+ remote_name = talloc_strdup(ctx, client_get_cur_dir());
+ if (!remote_name) {
+ return 1;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr, &local_name, NULL)) {
+ d_printf("reput <filename>\n");
+ return 1;
+ }
+
+ if (!file_exist(local_name, &st)) {
+ d_printf("%s does not exist\n", local_name);
+ return 1;
+ }
+
+ if (next_token_talloc(ctx, &cmd_ptr, &buf, NULL)) {
+ remote_name = talloc_asprintf_append(remote_name,
+ buf);
+ } else {
+ remote_name = talloc_asprintf_append(remote_name,
+ local_name);
+ }
+ if (!remote_name) {
+ return 1;
+ }
+
+ remote_name = clean_name(ctx, remote_name);
+ if (!remote_name) {
+ return 1;
+ }
+
+ return do_put(remote_name, local_name, true);
+}
+
+/****************************************************************************
+ List a share name.
+ ****************************************************************************/
+
+static void browse_fn(const char *name, uint32 m,
+ const char *comment, void *state)
+{
+ const char *typestr = "";
+
+ switch (m & 7) {
+ case STYPE_DISKTREE:
+ typestr = "Disk";
+ break;
+ case STYPE_PRINTQ:
+ typestr = "Printer";
+ break;
+ case STYPE_DEVICE:
+ typestr = "Device";
+ break;
+ case STYPE_IPC:
+ typestr = "IPC";
+ break;
+ }
+ /* FIXME: If the remote machine returns non-ascii characters
+ in any of these fields, they can corrupt the output. We
+ should remove them. */
+ if (!grepable) {
+ d_printf("\t%-15s %-10.10s%s\n",
+ name,typestr,comment);
+ } else {
+ d_printf ("%s|%s|%s\n",typestr,name,comment);
+ }
+}
+
+static bool browse_host_rpc(bool sort)
+{
+ NTSTATUS status;
+ struct rpc_pipe_client *pipe_hnd;
+ TALLOC_CTX *frame = talloc_stackframe();
+ WERROR werr;
+ struct srvsvc_NetShareInfoCtr info_ctr;
+ struct srvsvc_NetShareCtr1 ctr1;
+ uint32_t resume_handle = 0;
+ uint32_t total_entries = 0;
+ int i;
+
+ status = cli_rpc_pipe_open_noauth(cli, &ndr_table_srvsvc.syntax_id,
+ &pipe_hnd);
+
+ if (!NT_STATUS_IS_OK(status)) {
+ DEBUG(10, ("Could not connect to srvsvc pipe: %s\n",
+ nt_errstr(status)));
+ TALLOC_FREE(frame);
+ return false;
+ }
+
+ ZERO_STRUCT(info_ctr);
+ ZERO_STRUCT(ctr1);
+
+ info_ctr.level = 1;
+ info_ctr.ctr.ctr1 = &ctr1;
+
+ status = rpccli_srvsvc_NetShareEnumAll(pipe_hnd, frame,
+ pipe_hnd->desthost,
+ &info_ctr,
+ 0xffffffff,
+ &total_entries,
+ &resume_handle,
+ &werr);
+
+ if (!NT_STATUS_IS_OK(status) || !W_ERROR_IS_OK(werr)) {
+ TALLOC_FREE(pipe_hnd);
+ TALLOC_FREE(frame);
+ return false;
+ }
+
+ for (i=0; i < info_ctr.ctr.ctr1->count; i++) {
+ struct srvsvc_NetShareInfo1 info = info_ctr.ctr.ctr1->array[i];
+ browse_fn(info.name, info.type, info.comment, NULL);
+ }
+
+ TALLOC_FREE(pipe_hnd);
+ TALLOC_FREE(frame);
+ return true;
+}
+
+/****************************************************************************
+ Try and browse available connections on a host.
+****************************************************************************/
+
+static bool browse_host(bool sort)
+{
+ int ret;
+ if (!grepable) {
+ d_printf("\n\tSharename Type Comment\n");
+ d_printf("\t--------- ---- -------\n");
+ }
+
+ if (browse_host_rpc(sort)) {
+ return true;
+ }
+
+ if((ret = cli_RNetShareEnum(cli, browse_fn, NULL)) == -1)
+ d_printf("Error returning browse list: %s\n", cli_errstr(cli));
+
+ return (ret != -1);
+}
+
+/****************************************************************************
+ List a server name.
+****************************************************************************/
+
+static void server_fn(const char *name, uint32 m,
+ const char *comment, void *state)
+{
+
+ if (!grepable){
+ d_printf("\t%-16s %s\n", name, comment);
+ } else {
+ d_printf("%s|%s|%s\n",(char *)state, name, comment);
+ }
+}
+
+/****************************************************************************
+ Try and browse available connections on a host.
+****************************************************************************/
+
+static bool list_servers(const char *wk_grp)
+{
+ fstring state;
+
+ if (!cli->server_domain)
+ return false;
+
+ if (!grepable) {
+ d_printf("\n\tServer Comment\n");
+ d_printf("\t--------- -------\n");
+ };
+ fstrcpy( state, "Server" );
+ cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_ALL, server_fn,
+ state);
+
+ if (!grepable) {
+ d_printf("\n\tWorkgroup Master\n");
+ d_printf("\t--------- -------\n");
+ };
+
+ fstrcpy( state, "Workgroup" );
+ cli_NetServerEnum(cli, cli->server_domain, SV_TYPE_DOMAIN_ENUM,
+ server_fn, state);
+ return true;
+}
+
+/****************************************************************************
+ Print or set current VUID
+****************************************************************************/
+
+static int cmd_vuid(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ d_printf("Current VUID is %d\n", cli->vuid);
+ return 0;
+ }
+
+ cli->vuid = atoi(buf);
+ return 0;
+}
+
+/****************************************************************************
+ Setup a new VUID, by issuing a session setup
+****************************************************************************/
+
+static int cmd_logon(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *l_username, *l_password;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&l_username,NULL)) {
+ d_printf("logon <username> [<password>]\n");
+ return 0;
+ }
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&l_password,NULL)) {
+ char *pass = getpass("Password: ");
+ if (pass) {
+ l_password = talloc_strdup(ctx,pass);
+ }
+ }
+ if (!l_password) {
+ return 1;
+ }
+
+ if (!NT_STATUS_IS_OK(cli_session_setup(cli, l_username,
+ l_password, strlen(l_password),
+ l_password, strlen(l_password),
+ lp_workgroup()))) {
+ d_printf("session setup failed: %s\n", cli_errstr(cli));
+ return -1;
+ }
+
+ d_printf("Current VUID is %d\n", cli->vuid);
+ return 0;
+}
+
+
+/****************************************************************************
+ list active connections
+****************************************************************************/
+
+static int cmd_list_connect(void)
+{
+ cli_cm_display();
+ return 0;
+}
+
+/****************************************************************************
+ display the current active client connection
+****************************************************************************/
+
+static int cmd_show_connect( void )
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ struct cli_state *targetcli;
+ char *targetpath;
+
+ if (!cli_resolve_path(ctx, "", cli, client_get_cur_dir(),
+ &targetcli, &targetpath ) ) {
+ d_printf("showconnect %s: %s\n", cur_dir, cli_errstr(cli));
+ return 1;
+ }
+
+ d_printf("//%s/%s\n", targetcli->desthost, targetcli->share);
+ return 0;
+}
+
+/****************************************************************************
+ iosize command
+***************************************************************************/
+
+int cmd_iosize(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+ int iosize;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ if (!smb_encrypt) {
+ d_printf("iosize <n> or iosize 0x<n>. "
+ "Minimum is 16384 (0x4000), "
+ "max is 16776960 (0xFFFF00)\n");
+ } else {
+ d_printf("iosize <n> or iosize 0x<n>. "
+ "(Encrypted connection) ,"
+ "Minimum is 16384 (0x4000), "
+ "max is 130048 (0x1FC00)\n");
+ }
+ return 1;
+ }
+
+ iosize = strtol(buf,NULL,0);
+ if (smb_encrypt && (iosize < 0x4000 || iosize > 0xFC00)) {
+ d_printf("iosize out of range for encrypted "
+ "connection (min = 16384 (0x4000), "
+ "max = 130048 (0x1FC00)");
+ return 1;
+ } else if (!smb_encrypt && (iosize < 0x4000 || iosize > 0xFFFF00)) {
+ d_printf("iosize out of range (min = 16384 (0x4000), "
+ "max = 16776960 (0xFFFF00)");
+ return 1;
+ }
+
+ io_bufsize = iosize;
+ d_printf("iosize is now %d\n", io_bufsize);
+ return 0;
+}
+
+
+/* Some constants for completing filename arguments */
+
+#define COMPL_NONE 0 /* No completions */
+#define COMPL_REMOTE 1 /* Complete remote filename */
+#define COMPL_LOCAL 2 /* Complete local filename */
+
+/* This defines the commands supported by this client.
+ * NOTE: The "!" must be the last one in the list because it's fn pointer
+ * field is NULL, and NULL in that field is used in process_tok()
+ * (below) to indicate the end of the list. crh
+ */
+static struct {
+ const char *name;
+ int (*fn)(void);
+ const char *description;
+ char compl_args[2]; /* Completion argument info */
+} commands[] = {
+ {"?",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
+ {"allinfo",cmd_allinfo,"<file> show all available info",
+ {COMPL_NONE,COMPL_NONE}},
+ {"altname",cmd_altname,"<file> show alt name",{COMPL_NONE,COMPL_NONE}},
+ {"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}},
+ {"blocksize",cmd_block,"blocksize <number> (default 20)",{COMPL_NONE,COMPL_NONE}},
+ {"cancel",cmd_cancel,"<jobid> cancel a print queue entry",{COMPL_NONE,COMPL_NONE}},
+ {"case_sensitive",cmd_setcase,"toggle the case sensitive flag to server",{COMPL_NONE,COMPL_NONE}},
+ {"cd",cmd_cd,"[directory] change/report the remote directory",{COMPL_REMOTE,COMPL_NONE}},
+ {"chmod",cmd_chmod,"<src> <mode> chmod a file using UNIX permission",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"chown",cmd_chown,"<src> <uid> <gid> chown a file using UNIX uids and gids",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"close",cmd_close,"<fid> close a file given a fid",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"del",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
+ {"dir",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
+ {"du",cmd_du,"<mask> computes the total size of the current directory",{COMPL_REMOTE,COMPL_NONE}},
+ {"echo",cmd_echo,"ping the server",{COMPL_NONE,COMPL_NONE}},
+ {"exit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
+ {"get",cmd_get,"<remote name> [local name] get a file",{COMPL_REMOTE,COMPL_LOCAL}},
+ {"getfacl",cmd_getfacl,"<file name> get the POSIX ACL on a file (UNIX extensions only)",{COMPL_REMOTE,COMPL_LOCAL}},
+ {"hardlink",cmd_hardlink,"<src> <dest> create a Windows hard link",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"help",cmd_help,"[command] give help on a command",{COMPL_NONE,COMPL_NONE}},
+ {"history",cmd_history,"displays the command history",{COMPL_NONE,COMPL_NONE}},
+ {"iosize",cmd_iosize,"iosize <number> (default 64512)",{COMPL_NONE,COMPL_NONE}},
+ {"lcd",cmd_lcd,"[directory] change/report the local current working directory",{COMPL_LOCAL,COMPL_NONE}},
+ {"link",cmd_link,"<oldname> <newname> create a UNIX hard link",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"lock",cmd_lock,"lock <fnum> [r|w] <hex-start> <hex-len> : set a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"lowercase",cmd_lowercase,"toggle lowercasing of filenames for get",{COMPL_NONE,COMPL_NONE}},
+ {"ls",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
+ {"l",cmd_dir,"<mask> list the contents of the current directory",{COMPL_REMOTE,COMPL_NONE}},
+ {"mask",cmd_select,"<mask> mask all filenames against this",{COMPL_REMOTE,COMPL_NONE}},
+ {"md",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
+ {"mget",cmd_mget,"<mask> get all the matching files",{COMPL_REMOTE,COMPL_NONE}},
+ {"mkdir",cmd_mkdir,"<directory> make a directory",{COMPL_NONE,COMPL_NONE}},
+ {"more",cmd_more,"<remote name> view a remote file with your pager",{COMPL_REMOTE,COMPL_NONE}},
+ {"mput",cmd_mput,"<mask> put all matching files",{COMPL_REMOTE,COMPL_NONE}},
+ {"newer",cmd_newer,"<file> only mget files newer than the specified local file",{COMPL_LOCAL,COMPL_NONE}},
+ {"open",cmd_open,"<mask> open a file",{COMPL_REMOTE,COMPL_NONE}},
+ {"posix", cmd_posix, "turn on all POSIX capabilities", {COMPL_REMOTE,COMPL_NONE}},
+ {"posix_encrypt",cmd_posix_encrypt,"<domain> <user> <password> start up transport encryption",{COMPL_REMOTE,COMPL_NONE}},
+ {"posix_open",cmd_posix_open,"<name> 0<mode> open_flags mode open a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
+ {"posix_mkdir",cmd_posix_mkdir,"<name> 0<mode> creates a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
+ {"posix_rmdir",cmd_posix_rmdir,"<name> removes a directory using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
+ {"posix_unlink",cmd_posix_unlink,"<name> removes a file using POSIX interface",{COMPL_REMOTE,COMPL_NONE}},
+ {"print",cmd_print,"<file name> print a file",{COMPL_NONE,COMPL_NONE}},
+ {"prompt",cmd_prompt,"toggle prompting for filenames for mget and mput",{COMPL_NONE,COMPL_NONE}},
+ {"put",cmd_put,"<local name> [remote name] put a file",{COMPL_LOCAL,COMPL_REMOTE}},
+ {"pwd",cmd_pwd,"show current remote directory (same as 'cd' with no args)",{COMPL_NONE,COMPL_NONE}},
+ {"q",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
+ {"queue",cmd_queue,"show the print queue",{COMPL_NONE,COMPL_NONE}},
+ {"quit",cmd_quit,"logoff the server",{COMPL_NONE,COMPL_NONE}},
+ {"rd",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
+ {"recurse",cmd_recurse,"toggle directory recursion for mget and mput",{COMPL_NONE,COMPL_NONE}},
+ {"reget",cmd_reget,"<remote name> [local name] get a file restarting at end of local file",{COMPL_REMOTE,COMPL_LOCAL}},
+ {"rename",cmd_rename,"<src> <dest> rename some files",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"reput",cmd_reput,"<local name> [remote name] put a file restarting at end of remote file",{COMPL_LOCAL,COMPL_REMOTE}},
+ {"rm",cmd_del,"<mask> delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
+ {"rmdir",cmd_rmdir,"<directory> remove a directory",{COMPL_NONE,COMPL_NONE}},
+ {"showacls",cmd_showacls,"toggle if ACLs are shown or not",{COMPL_NONE,COMPL_NONE}},
+ {"setmode",cmd_setmode,"filename <setmode string> change modes of file",{COMPL_REMOTE,COMPL_NONE}},
+ {"stat",cmd_stat,"filename Do a UNIX extensions stat call on a file",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"symlink",cmd_symlink,"<oldname> <newname> create a UNIX symlink",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"tar",cmd_tar,"tar <c|x>[IXFqbgNan] current directory to/from <file name>",{COMPL_NONE,COMPL_NONE}},
+ {"tarmode",cmd_tarmode,"<full|inc|reset|noreset> tar's behaviour towards archive bits",{COMPL_NONE,COMPL_NONE}},
+ {"translate",cmd_translate,"toggle text translation for printing",{COMPL_NONE,COMPL_NONE}},
+ {"unlock",cmd_unlock,"unlock <fnum> <hex-start> <hex-len> : remove a POSIX lock",{COMPL_REMOTE,COMPL_REMOTE}},
+ {"volume",cmd_volume,"print the volume name",{COMPL_NONE,COMPL_NONE}},
+ {"vuid",cmd_vuid,"change current vuid",{COMPL_NONE,COMPL_NONE}},
+ {"wdel",cmd_wdel,"<attrib> <mask> wildcard delete all matching files",{COMPL_REMOTE,COMPL_NONE}},
+ {"logon",cmd_logon,"establish new logon",{COMPL_NONE,COMPL_NONE}},
+ {"listconnect",cmd_list_connect,"list open connections",{COMPL_NONE,COMPL_NONE}},
+ {"showconnect",cmd_show_connect,"display the current active connection",{COMPL_NONE,COMPL_NONE}},
+ {"..",cmd_cd_oneup,"change the remote directory (up one level)",{COMPL_REMOTE,COMPL_NONE}},
+
+ /* Yes, this must be here, see crh's comment above. */
+ {"!",NULL,"run a shell command on the local system",{COMPL_NONE,COMPL_NONE}},
+ {NULL,NULL,NULL,{COMPL_NONE,COMPL_NONE}}
+};
+
+/*******************************************************************
+ Lookup a command string in the list of commands, including
+ abbreviations.
+******************************************************************/
+
+static int process_tok(char *tok)
+{
+ int i = 0, matches = 0;
+ int cmd=0;
+ int tok_len = strlen(tok);
+
+ while (commands[i].fn != NULL) {
+ if (strequal(commands[i].name,tok)) {
+ matches = 1;
+ cmd = i;
+ break;
+ } else if (strnequal(commands[i].name, tok, tok_len)) {
+ matches++;
+ cmd = i;
+ }
+ i++;
+ }
+
+ if (matches == 0)
+ return(-1);
+ else if (matches == 1)
+ return(cmd);
+ else
+ return(-2);
+}
+
+/****************************************************************************
+ Help.
+****************************************************************************/
+
+static int cmd_help(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ int i=0,j;
+ char *buf;
+
+ if (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ if ((i = process_tok(buf)) >= 0)
+ d_printf("HELP %s:\n\t%s\n\n",
+ commands[i].name,commands[i].description);
+ } else {
+ while (commands[i].description) {
+ for (j=0; commands[i].description && (j<5); j++) {
+ d_printf("%-15s",commands[i].name);
+ i++;
+ }
+ d_printf("\n");
+ }
+ }
+ return 0;
+}
+
+/****************************************************************************
+ Process a -c command string.
+****************************************************************************/
+
+static int process_command_string(const char *cmd_in)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *cmd = talloc_strdup(ctx, cmd_in);
+ int rc = 0;
+
+ if (!cmd) {
+ return 1;
+ }
+ /* establish the connection if not already */
+
+ if (!cli) {
+ cli = cli_cm_open(talloc_tos(), NULL, desthost,
+ service, true, smb_encrypt);
+ if (!cli) {
+ return 1;
+ }
+ }
+
+ while (cmd[0] != '\0') {
+ char *line;
+ char *p;
+ char *tok;
+ int i;
+
+ if ((p = strchr_m(cmd, ';')) == 0) {
+ line = cmd;
+ cmd += strlen(cmd);
+ } else {
+ *p = '\0';
+ line = cmd;
+ cmd = p + 1;
+ }
+
+ /* and get the first part of the command */
+ cmd_ptr = line;
+ if (!next_token_talloc(ctx, &cmd_ptr,&tok,NULL)) {
+ continue;
+ }
+
+ if ((i = process_tok(tok)) >= 0) {
+ rc = commands[i].fn();
+ } else if (i == -2) {
+ d_printf("%s: command abbreviation ambiguous\n",tok);
+ } else {
+ d_printf("%s: command not found\n",tok);
+ }
+ }
+
+ return rc;
+}
+
+#define MAX_COMPLETIONS 100
+
+typedef struct {
+ char *dirmask;
+ char **matches;
+ int count, samelen;
+ const char *text;
+ int len;
+} completion_remote_t;
+
+static void completion_remote_filter(const char *mnt,
+ file_info *f,
+ const char *mask,
+ void *state)
+{
+ completion_remote_t *info = (completion_remote_t *)state;
+
+ if ((info->count < MAX_COMPLETIONS - 1) &&
+ (strncmp(info->text, f->name, info->len) == 0) &&
+ (strcmp(f->name, ".") != 0) &&
+ (strcmp(f->name, "..") != 0)) {
+ if ((info->dirmask[0] == 0) && !(f->mode & aDIR))
+ info->matches[info->count] = SMB_STRDUP(f->name);
+ else {
+ TALLOC_CTX *ctx = talloc_stackframe();
+ char *tmp;
+
+ tmp = talloc_strdup(ctx,info->dirmask);
+ if (!tmp) {
+ TALLOC_FREE(ctx);
+ return;
+ }
+ tmp = talloc_asprintf_append(tmp, f->name);
+ if (!tmp) {
+ TALLOC_FREE(ctx);
+ return;
+ }
+ if (f->mode & aDIR) {
+ tmp = talloc_asprintf_append(tmp, CLI_DIRSEP_STR);
+ }
+ if (!tmp) {
+ TALLOC_FREE(ctx);
+ return;
+ }
+ info->matches[info->count] = SMB_STRDUP(tmp);
+ TALLOC_FREE(ctx);
+ }
+ if (info->matches[info->count] == NULL) {
+ return;
+ }
+ if (f->mode & aDIR) {
+ smb_readline_ca_char(0);
+ }
+ if (info->count == 1) {
+ info->samelen = strlen(info->matches[info->count]);
+ } else {
+ while (strncmp(info->matches[info->count],
+ info->matches[info->count-1],
+ info->samelen) != 0) {
+ info->samelen--;
+ }
+ }
+ info->count++;
+ }
+}
+
+static char **remote_completion(const char *text, int len)
+{
+ TALLOC_CTX *ctx = talloc_stackframe();
+ char *dirmask = NULL;
+ char *targetpath = NULL;
+ struct cli_state *targetcli = NULL;
+ int i;
+ completion_remote_t info = { NULL, NULL, 1, 0, NULL, 0 };
+
+ /* can't have non-static intialisation on Sun CC, so do it
+ at run time here */
+ info.samelen = len;
+ info.text = text;
+ info.len = len;
+
+ info.matches = SMB_MALLOC_ARRAY(char *,MAX_COMPLETIONS);
+ if (!info.matches) {
+ TALLOC_FREE(ctx);
+ return NULL;
+ }
+
+ /*
+ * We're leaving matches[0] free to fill it later with the text to
+ * display: Either the one single match or the longest common subset
+ * of the matches.
+ */
+ info.matches[0] = NULL;
+ info.count = 1;
+
+ for (i = len-1; i >= 0; i--) {
+ if ((text[i] == '/') || (text[i] == CLI_DIRSEP_CHAR)) {
+ break;
+ }
+ }
+
+ info.text = text+i+1;
+ info.samelen = info.len = len-i-1;
+
+ if (i > 0) {
+ info.dirmask = SMB_MALLOC_ARRAY(char, i+2);
+ if (!info.dirmask) {
+ goto cleanup;
+ }
+ strncpy(info.dirmask, text, i+1);
+ info.dirmask[i+1] = 0;
+ dirmask = talloc_asprintf(ctx,
+ "%s%*s*",
+ client_get_cur_dir(),
+ i-1,
+ text);
+ } else {
+ info.dirmask = SMB_STRDUP("");
+ if (!info.dirmask) {
+ goto cleanup;
+ }
+ dirmask = talloc_asprintf(ctx,
+ "%s*",
+ client_get_cur_dir());
+ }
+ if (!dirmask) {
+ goto cleanup;
+ }
+
+ if (!cli_resolve_path(ctx, "", cli, dirmask, &targetcli, &targetpath)) {
+ goto cleanup;
+ }
+ if (cli_list(targetcli, targetpath, aDIR | aSYSTEM | aHIDDEN,
+ completion_remote_filter, (void *)&info) < 0) {
+ goto cleanup;
+ }
+
+ if (info.count == 1) {
+ /*
+ * No matches at all, NULL indicates there is nothing
+ */
+ SAFE_FREE(info.matches[0]);
+ SAFE_FREE(info.matches);
+ TALLOC_FREE(ctx);
+ return NULL;
+ }
+
+ if (info.count == 2) {
+ /*
+ * Exactly one match in matches[1], indicate this is the one
+ * in matches[0].
+ */
+ info.matches[0] = info.matches[1];
+ info.matches[1] = NULL;
+ info.count -= 1;
+ TALLOC_FREE(ctx);
+ return info.matches;
+ }
+
+ /*
+ * We got more than one possible match, set the result to the maximum
+ * common subset
+ */
+
+ info.matches[0] = SMB_STRNDUP(info.matches[1], info.samelen);
+ info.matches[info.count] = NULL;
+ return info.matches;
+
+cleanup:
+ for (i = 0; i < info.count; i++) {
+ SAFE_FREE(info.matches[i]);
+ }
+ SAFE_FREE(info.matches);
+ SAFE_FREE(info.dirmask);
+ TALLOC_FREE(ctx);
+ return NULL;
+}
+
+static char **completion_fn(const char *text, int start, int end)
+{
+ smb_readline_ca_char(' ');
+
+ if (start) {
+ const char *buf, *sp;
+ int i;
+ char compl_type;
+
+ buf = smb_readline_get_line_buffer();
+ if (buf == NULL)
+ return NULL;
+
+ sp = strchr(buf, ' ');
+ if (sp == NULL)
+ return NULL;
+
+ for (i = 0; commands[i].name; i++) {
+ if ((strncmp(commands[i].name, buf, sp - buf) == 0) &&
+ (commands[i].name[sp - buf] == 0)) {
+ break;
+ }
+ }
+ if (commands[i].name == NULL)
+ return NULL;
+
+ while (*sp == ' ')
+ sp++;
+
+ if (sp == (buf + start))
+ compl_type = commands[i].compl_args[0];
+ else
+ compl_type = commands[i].compl_args[1];
+
+ if (compl_type == COMPL_REMOTE)
+ return remote_completion(text, end - start);
+ else /* fall back to local filename completion */
+ return NULL;
+ } else {
+ char **matches;
+ int i, len, samelen = 0, count=1;
+
+ matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
+ if (!matches) {
+ return NULL;
+ }
+ matches[0] = NULL;
+
+ len = strlen(text);
+ for (i=0;commands[i].fn && count < MAX_COMPLETIONS-1;i++) {
+ if (strncmp(text, commands[i].name, len) == 0) {
+ matches[count] = SMB_STRDUP(commands[i].name);
+ if (!matches[count])
+ goto cleanup;
+ if (count == 1)
+ samelen = strlen(matches[count]);
+ else
+ while (strncmp(matches[count], matches[count-1], samelen) != 0)
+ samelen--;
+ count++;
+ }
+ }
+
+ switch (count) {
+ case 0: /* should never happen */
+ case 1:
+ goto cleanup;
+ case 2:
+ matches[0] = SMB_STRDUP(matches[1]);
+ break;
+ default:
+ matches[0] = (char *)SMB_MALLOC(samelen+1);
+ if (!matches[0])
+ goto cleanup;
+ strncpy(matches[0], matches[1], samelen);
+ matches[0][samelen] = 0;
+ }
+ matches[count] = NULL;
+ return matches;
+
+cleanup:
+ for (i = 0; i < count; i++)
+ free(matches[i]);
+
+ free(matches);
+ return NULL;
+ }
+}
+
+/****************************************************************************
+ Make sure we swallow keepalives during idle time.
+****************************************************************************/
+
+static void readline_callback(void)
+{
+ fd_set fds;
+ struct timeval timeout;
+ static time_t last_t;
+ time_t t;
+
+ t = time(NULL);
+
+ if (t - last_t < 5)
+ return;
+
+ last_t = t;
+
+ again:
+
+ if (cli->fd == -1)
+ return;
+
+ FD_ZERO(&fds);
+ FD_SET(cli->fd,&fds);
+
+ timeout.tv_sec = 0;
+ timeout.tv_usec = 0;
+ sys_select_intr(cli->fd+1,&fds,NULL,NULL,&timeout);
+
+ /* We deliberately use receive_smb_raw instead of
+ client_receive_smb as we want to receive
+ session keepalives and then drop them here.
+ */
+ if (FD_ISSET(cli->fd,&fds)) {
+ NTSTATUS status;
+ size_t len;
+
+ set_smb_read_error(&cli->smb_rw_error, SMB_READ_OK);
+
+ status = receive_smb_raw(cli->fd, cli->inbuf, cli->bufsize, 0, 0, &len);
+
+ if (!NT_STATUS_IS_OK(status)) {
+ DEBUG(0, ("Read from server failed, maybe it closed "
+ "the connection\n"));
+
+ if (NT_STATUS_EQUAL(status, NT_STATUS_END_OF_FILE)) {
+ set_smb_read_error(&cli->smb_rw_error,
+ SMB_READ_EOF);
+ return;
+ }
+
+ if (NT_STATUS_EQUAL(status, NT_STATUS_IO_TIMEOUT)) {
+ set_smb_read_error(&cli->smb_rw_error,
+ SMB_READ_TIMEOUT);
+ return;
+ }
+
+ set_smb_read_error(&cli->smb_rw_error, SMB_READ_ERROR);
+ return;
+ }
+ if(CVAL(cli->inbuf,0) != SMBkeepalive) {
+ DEBUG(0, ("Read from server "
+ "returned unexpected packet!\n"));
+ return;
+ }
+
+ goto again;
+ }
+
+ /* Ping the server to keep the connection alive using SMBecho. */
+ {
+ unsigned char garbage[16];
+ memset(garbage, 0xf0, sizeof(garbage));
+ cli_echo(cli, 1, data_blob_const(garbage, sizeof(garbage)));
+ }
+}
+
+/****************************************************************************
+ Process commands on stdin.
+****************************************************************************/
+
+static int process_stdin(void)
+{
+ int rc = 0;
+
+ while (1) {
+ TALLOC_CTX *frame = talloc_stackframe();
+ char *tok = NULL;
+ char *the_prompt = NULL;
+ char *line = NULL;
+ int i;
+
+ /* display a prompt */
+ if (asprintf(&the_prompt, "smb: %s> ", client_get_cur_dir()) < 0) {
+ TALLOC_FREE(frame);
+ break;
+ }
+ line = smb_readline(the_prompt, readline_callback, completion_fn);
+ SAFE_FREE(the_prompt);
+ if (!line) {
+ TALLOC_FREE(frame);
+ break;
+ }
+
+ /* special case - first char is ! */
+ if (*line == '!') {
+ system(line + 1);
+ SAFE_FREE(line);
+ TALLOC_FREE(frame);
+ continue;
+ }
+
+ /* and get the first part of the command */
+ cmd_ptr = line;
+ if (!next_token_talloc(frame, &cmd_ptr,&tok,NULL)) {
+ TALLOC_FREE(frame);
+ SAFE_FREE(line);
+ continue;
+ }
+
+ if ((i = process_tok(tok)) >= 0) {
+ rc = commands[i].fn();
+ } else if (i == -2) {
+ d_printf("%s: command abbreviation ambiguous\n",tok);
+ } else {
+ d_printf("%s: command not found\n",tok);
+ }
+ SAFE_FREE(line);
+ TALLOC_FREE(frame);
+ }
+ return rc;
+}
+
+/****************************************************************************
+ Process commands from the client.
+****************************************************************************/
+
+static int process(const char *base_directory)
+{
+ int rc = 0;
+
+ cli = cli_cm_open(talloc_tos(), NULL,
+ desthost, service, true, smb_encrypt);
+ if (!cli) {
+ return 1;
+ }
+
+ if (base_directory && *base_directory) {
+ rc = do_cd(base_directory);
+ if (rc) {
+ cli_cm_shutdown();
+ return rc;
+ }
+ }
+
+ if (cmdstr) {
+ rc = process_command_string(cmdstr);
+ } else {
+ process_stdin();
+ }
+
+ cli_cm_shutdown();
+ return rc;
+}
+
+/****************************************************************************
+ Handle a -L query.
+****************************************************************************/
+
+static int do_host_query(const char *query_host)
+{
+ struct sockaddr_storage ss;
+
+ cli = cli_cm_open(talloc_tos(), NULL,
+ query_host, "IPC$", true, smb_encrypt);
+ if (!cli)
+ return 1;
+
+ browse_host(true);
+
+ if (interpret_string_addr(&ss, query_host, 0) && (ss.ss_family != AF_INET)) {
+ d_printf("%s is an IPv6 address -- no workgroup available\n",
+ query_host);
+ return 1;
+ }
+
+ if (port != 139) {
+
+ /* Workgroups simply don't make sense over anything
+ else but port 139... */
+
+ cli_cm_shutdown();
+ cli_cm_set_port( 139 );
+ cli = cli_cm_open(talloc_tos(), NULL,
+ query_host, "IPC$", true, smb_encrypt);
+ }
+
+ if (cli == NULL) {
+ d_printf("NetBIOS over TCP disabled -- no workgroup available\n");
+ return 1;
+ }
+
+ list_servers(lp_workgroup());
+
+ cli_cm_shutdown();
+
+ return(0);
+}
+
+/****************************************************************************
+ Handle a tar operation.
+****************************************************************************/
+
+static int do_tar_op(const char *base_directory)
+{
+ int ret;
+
+ /* do we already have a connection? */
+ if (!cli) {
+ cli = cli_cm_open(talloc_tos(), NULL,
+ desthost, service, true, smb_encrypt);
+ if (!cli)
+ return 1;
+ }
+
+ recurse=true;
+
+ if (base_directory && *base_directory) {
+ ret = do_cd(base_directory);
+ if (ret) {
+ cli_cm_shutdown();
+ return ret;
+ }
+ }
+
+ ret=process_tar();
+
+ cli_cm_shutdown();
+
+ return(ret);
+}
+
+/****************************************************************************
+ Handle a message operation.
+****************************************************************************/
+
+static int do_message_op(void)
+{
+ struct sockaddr_storage ss;
+ struct nmb_name called, calling;
+ fstring server_name;
+ char name_type_hex[10];
+ int msg_port;
+ NTSTATUS status;
+
+ make_nmb_name(&calling, calling_name, 0x0);
+ make_nmb_name(&called , desthost, name_type);
+
+ fstrcpy(server_name, desthost);
+ snprintf(name_type_hex, sizeof(name_type_hex), "#%X", name_type);
+ fstrcat(server_name, name_type_hex);
+
+ zero_addr(&ss);
+ if (have_ip)
+ ss = dest_ss;
+
+ /* we can only do messages over port 139 (to windows clients at least) */
+
+ msg_port = port ? port : 139;
+
+ if (!(cli=cli_initialise()) || (cli_set_port(cli, msg_port) != msg_port)) {
+ d_printf("Connection to %s failed\n", desthost);
+ return 1;
+ }
+
+ status = cli_connect(cli, server_name, &ss);
+ if (!NT_STATUS_IS_OK(status)) {
+ d_printf("Connection to %s failed. Error %s\n", desthost, nt_errstr(status));
+ return 1;
+ }
+
+ if (!cli_session_request(cli, &calling, &called)) {
+ d_printf("session request failed\n");
+ cli_cm_shutdown();
+ return 1;
+ }
+
+ send_message();
+ cli_cm_shutdown();
+
+ return 0;
+}
+
+/****************************************************************************
+ main program
+****************************************************************************/
+
+ int main(int argc,char *argv[])
+{
+ char *base_directory = NULL;
+ int opt;
+ char *query_host = NULL;
+ bool message = false;
+ char *term_code = NULL;
+ static const char *new_name_resolve_order = NULL;
+ poptContext pc;
+ char *p;
+ int rc = 0;
+ fstring new_workgroup;
+ bool tar_opt = false;
+ bool service_opt = false;
+ struct poptOption long_options[] = {
+ POPT_AUTOHELP
+
+ { "name-resolve", 'R', POPT_ARG_STRING, &new_name_resolve_order, 'R', "Use these name resolution services only", "NAME-RESOLVE-ORDER" },
+ { "message", 'M', POPT_ARG_STRING, NULL, 'M', "Send message", "HOST" },
+ { "ip-address", 'I', POPT_ARG_STRING, NULL, 'I', "Use this IP to connect to", "IP" },
+ { "stderr", 'E', POPT_ARG_NONE, NULL, 'E', "Write messages to stderr instead of stdout" },
+ { "list", 'L', POPT_ARG_STRING, NULL, 'L', "Get a list of shares available on a host", "HOST" },
+ { "terminal", 't', POPT_ARG_STRING, NULL, 't', "Terminal I/O code {sjis|euc|jis7|jis8|junet|hex}", "CODE" },
+ { "max-protocol", 'm', POPT_ARG_STRING, NULL, 'm', "Set the max protocol level", "LEVEL" },
+ { "tar", 'T', POPT_ARG_STRING, NULL, 'T', "Command line tar", "<c|x>IXFqgbNan" },
+ { "directory", 'D', POPT_ARG_STRING, NULL, 'D', "Start from directory", "DIR" },
+ { "command", 'c', POPT_ARG_STRING, &cmdstr, 'c', "Execute semicolon separated commands" },
+ { "send-buffer", 'b', POPT_ARG_INT, &io_bufsize, 'b', "Changes the transmit/send buffer", "BYTES" },
+ { "port", 'p', POPT_ARG_INT, &port, 'p', "Port to connect to", "PORT" },
+ { "grepable", 'g', POPT_ARG_NONE, NULL, 'g', "Produce grepable output" },
+ { "browse", 'B', POPT_ARG_NONE, NULL, 'B', "Browse SMB servers using DNS" },
+ POPT_COMMON_SAMBA
+ POPT_COMMON_CONNECTION
+ POPT_COMMON_CREDENTIALS
+ POPT_TABLEEND
+ };
+ TALLOC_CTX *frame = talloc_stackframe();
+
+ if (!client_set_cur_dir("\\")) {
+ exit(ENOMEM);
+ }
+
+#ifdef KANJI
+ term_code = talloc_strdup(frame,KANJI);
+#else /* KANJI */
+ term_code = talloc_strdup(frame,"");
+#endif /* KANJI */
+ if (!term_code) {
+ exit(ENOMEM);
+ }
+
+ /* initialize the workgroup name so we can determine whether or
+ not it was set by a command line option */
+
+ set_global_myworkgroup( "" );
+ set_global_myname( "" );
+
+ /* set default debug level to 1 regardless of what smb.conf sets */
+ setup_logging( "smbclient", true );
+ DEBUGLEVEL_CLASS[DBGC_ALL] = 1;
+ if ((dbf = x_fdup(x_stderr))) {
+ x_setbuf( dbf, NULL );
+ }
+
+ load_case_tables();
+
+ /* skip argv(0) */
+ pc = poptGetContext("smbclient", argc, (const char **) argv, long_options, 0);
+ poptSetOtherOptionHelp(pc, "service <password>");
+
+ lp_set_in_client(true); /* Make sure that we tell lp_load we are */
+
+ while ((opt = poptGetNextOpt(pc)) != -1) {
+
+ /* if the tar option has been called previouslt, now we need to eat out the leftovers */
+ /* I see no other way to keep things sane --SSS */
+ if (tar_opt == true) {
+ while (poptPeekArg(pc)) {
+ poptGetArg(pc);
+ }
+ tar_opt = false;
+ }
+
+ /* if the service has not yet been specified lets see if it is available in the popt stack */
+ if (!service_opt && poptPeekArg(pc)) {
+ service = talloc_strdup(frame, poptGetArg(pc));
+ if (!service) {
+ exit(ENOMEM);
+ }
+ service_opt = true;
+ }
+
+ /* if the service has already been retrieved then check if we have also a password */
+ if (service_opt && (!get_cmdline_auth_info_got_pass()) && poptPeekArg(pc)) {
+ set_cmdline_auth_info_password(poptGetArg(pc));
+ }
+
+ switch (opt) {
+ case 'M':
+ /* Messages are sent to NetBIOS name type 0x3
+ * (Messenger Service). Make sure we default
+ * to port 139 instead of port 445. srl,crh
+ */
+ name_type = 0x03;
+ cli_cm_set_dest_name_type( name_type );
+ desthost = talloc_strdup(frame,poptGetOptArg(pc));
+ if (!desthost) {
+ exit(ENOMEM);
+ }
+ if( !port )
+ cli_cm_set_port( 139 );
+ message = true;
+ break;
+ case 'I':
+ {
+ if (!interpret_string_addr(&dest_ss, poptGetOptArg(pc), 0)) {
+ exit(1);
+ }
+ have_ip = true;
+
+ cli_cm_set_dest_ss(&dest_ss);
+ }
+ break;
+ case 'E':
+ if (dbf) {
+ x_fclose(dbf);
+ }
+ dbf = x_stderr;
+ display_set_stderr();
+ break;
+
+ case 'L':
+ query_host = talloc_strdup(frame, poptGetOptArg(pc));
+ if (!query_host) {
+ exit(ENOMEM);
+ }
+ break;
+ case 't':
+ term_code = talloc_strdup(frame,poptGetOptArg(pc));
+ if (!term_code) {
+ exit(ENOMEM);
+ }
+ break;
+ case 'm':
+ max_protocol = interpret_protocol(poptGetOptArg(pc), max_protocol);
+ break;
+ case 'T':
+ /* We must use old option processing for this. Find the
+ * position of the -T option in the raw argv[]. */
+ {
+ int i;
+ for (i = 1; i < argc; i++) {
+ if (strncmp("-T", argv[i],2)==0)
+ break;
+ }
+ i++;
+ if (!tar_parseargs(argc, argv, poptGetOptArg(pc), i)) {
+ poptPrintUsage(pc, stderr, 0);
+ exit(1);
+ }
+ }
+ /* this must be the last option, mark we have parsed it so that we know we have */
+ tar_opt = true;
+ break;
+ case 'D':
+ base_directory = talloc_strdup(frame, poptGetOptArg(pc));
+ if (!base_directory) {
+ exit(ENOMEM);
+ }
+ break;
+ case 'g':
+ grepable=true;
+ break;
+ case 'e':
+ smb_encrypt=true;
+ break;
+ case 'B':
+ return(do_smb_browse());
+
+ }
+ }
+
+ /* We may still have some leftovers after the last popt option has been called */
+ if (tar_opt == true) {
+ while (poptPeekArg(pc)) {
+ poptGetArg(pc);
+ }
+ tar_opt = false;
+ }
+
+ /* if the service has not yet been specified lets see if it is available in the popt stack */
+ if (!service_opt && poptPeekArg(pc)) {
+ service = talloc_strdup(frame,poptGetArg(pc));
+ if (!service) {
+ exit(ENOMEM);
+ }
+ service_opt = true;
+ }
+
+ /* if the service has already been retrieved then check if we have also a password */
+ if (service_opt && !get_cmdline_auth_info_got_pass() && poptPeekArg(pc)) {
+ set_cmdline_auth_info_password(poptGetArg(pc));
+ }
+
+ /* check for the -P option */
+
+ if ( port != 0 )
+ cli_cm_set_port( port );
+
+ /*
+ * Don't load debug level from smb.conf. It should be
+ * set by cmdline arg or remain default (0)
+ */
+ AllowDebugChange = false;
+
+ /* save the workgroup...
+
+ FIXME!! do we need to do this for other options as well
+ (or maybe a generic way to keep lp_load() from overwriting
+ everything)? */
+
+ fstrcpy( new_workgroup, lp_workgroup() );
+ calling_name = talloc_strdup(frame, global_myname() );
+ if (!calling_name) {
+ exit(ENOMEM);
+ }
+
+ if ( override_logfile )
+ setup_logging( lp_logfile(), false );
+
+ if (!lp_load(get_dyn_CONFIGFILE(),true,false,false,true)) {
+ fprintf(stderr, "%s: Can't load %s - run testparm to debug it\n",
+ argv[0], get_dyn_CONFIGFILE());
+ }
+
+ if (get_cmdline_auth_info_use_machine_account() &&
+ !set_cmdline_auth_info_machine_account_creds()) {
+ exit(-1);
+ }
+
+ load_interfaces();
+
+ if (service_opt && service) {
+ size_t len;
+
+ /* Convert any '/' characters in the service name to '\' characters */
+ string_replace(service, '/','\\');
+ if (count_chars(service,'\\') < 3) {
+ d_printf("\n%s: Not enough '\\' characters in service\n",service);
+ poptPrintUsage(pc, stderr, 0);
+ exit(1);
+ }
+ /* Remove trailing slashes */
+ len = strlen(service);
+ while(len > 0 && service[len - 1] == '\\') {
+ --len;
+ service[len] = '\0';
+ }
+ }
+
+ if ( strlen(new_workgroup) != 0 ) {
+ set_global_myworkgroup( new_workgroup );
+ }
+
+ if ( strlen(calling_name) != 0 ) {
+ set_global_myname( calling_name );
+ } else {
+ TALLOC_FREE(calling_name);
+ calling_name = talloc_strdup(frame, global_myname() );
+ }
+
+ smb_encrypt = get_cmdline_auth_info_smb_encrypt();
+ if (!init_names()) {
+ fprintf(stderr, "init_names() failed\n");
+ exit(1);
+ }
+
+ if(new_name_resolve_order)
+ lp_set_name_resolve_order(new_name_resolve_order);
+
+ if (!tar_type && !query_host && !service && !message) {
+ poptPrintUsage(pc, stderr, 0);
+ exit(1);
+ }
+
+ poptFreeContext(pc);
+
+ /* Store the username and password for dfs support */
+
+ cli_cm_set_credentials();
+
+ DEBUG(3,("Client started (version %s).\n", SAMBA_VERSION_STRING));
+
+ if (tar_type) {
+ if (cmdstr)
+ process_command_string(cmdstr);
+ return do_tar_op(base_directory);
+ }
+
+ if (query_host && *query_host) {
+ char *qhost = query_host;
+ char *slash;
+
+ while (*qhost == '\\' || *qhost == '/')
+ qhost++;
+
+ if ((slash = strchr_m(qhost, '/'))
+ || (slash = strchr_m(qhost, '\\'))) {
+ *slash = 0;
+ }
+
+ if ((p=strchr_m(qhost, '#'))) {
+ *p = 0;
+ p++;
+ sscanf(p, "%x", &name_type);
+ cli_cm_set_dest_name_type( name_type );
+ }
+
+ return do_host_query(qhost);
+ }
+
+ if (message) {
+ return do_message_op();
+ }
+
+ if (process(base_directory)) {
+ return 1;
+ }
+
+ TALLOC_FREE(frame);
+ return rc;
+}
diff --git a/source3/client/client_proto.h b/source3/client/client_proto.h
new file mode 100644
index 0000000000..aa3eb0e8af
--- /dev/null
+++ b/source3/client/client_proto.h
@@ -0,0 +1,52 @@
+/*
+ * Unix SMB/CIFS implementation.
+ * collected prototypes header
+ *
+ * frozen from "make proto" in May 2008
+ *
+ * Copyright (C) Michael Adam 2008
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 3 of the License, or
+ * (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * GNU General Public License for more details.
+ *
+ * You should have received a copy of the GNU General Public License
+ * along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifndef _CLIENT_PROTO_H_
+#define _CLIENT_PROTO_H_
+
+
+/* The following definitions come from client/client.c */
+
+const char *client_get_cur_dir(void);
+const char *client_set_cur_dir(const char *newdir);
+void do_list(const char *mask,
+ uint16 attribute,
+ void (*fn)(file_info *, const char *dir),
+ bool rec,
+ bool dirs);
+int cmd_iosize(void);
+
+/* The following definitions come from client/clitar.c */
+
+int cmd_block(void);
+int cmd_tarmode(void);
+int cmd_setmode(void);
+int cmd_tar(void);
+int process_tar(void);
+int tar_parseargs(int argc, char *argv[], const char *Optarg, int Optind);
+
+/* The following definitions come from client/dnsbrowse.c */
+
+int do_smb_browse(void);
+int do_smb_browse(void);
+
+#endif /* _CLIENT_PROTO_H_ */
diff --git a/source3/client/clitar.c b/source3/client/clitar.c
new file mode 100644
index 0000000000..084f87e399
--- /dev/null
+++ b/source3/client/clitar.c
@@ -0,0 +1,1921 @@
+/*
+ Unix SMB/CIFS implementation.
+ Tar Extensions
+ Copyright (C) Ricky Poulten 1995-1998
+ Copyright (C) Richard Sharpe 1998
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+/* The following changes developed by Richard Sharpe for Canon Information
+ Systems Research Australia (CISRA)
+
+ 1. Restore can now restore files with long file names
+ 2. Save now saves directory information so that we can restore
+ directory creation times
+ 3. tar now accepts both UNIX path names and DOS path names. I prefer
+ those lovely /'s to those UGLY \'s :-)
+ 4. the files to exclude can be specified as a regular expression by adding
+ an r flag to the other tar flags. Eg:
+
+ -TcrX file.tar "*.(obj|exe)"
+
+ will skip all .obj and .exe files
+*/
+
+
+#include "includes.h"
+#include "clitar.h"
+#include "client/client_proto.h"
+
+static int clipfind(char **aret, int ret, char *tok);
+
+typedef struct file_info_struct file_info2;
+
+struct file_info_struct {
+ SMB_OFF_T size;
+ uint16 mode;
+ uid_t uid;
+ gid_t gid;
+ /* These times are normally kept in GMT */
+ struct timespec mtime_ts;
+ struct timespec atime_ts;
+ struct timespec ctime_ts;
+ char *name; /* This is dynamically allocated */
+ file_info2 *next, *prev; /* Used in the stack ... */
+};
+
+typedef struct {
+ file_info2 *top;
+ int items;
+} stack;
+
+#define SEPARATORS " \t\n\r"
+extern time_t newer_than;
+extern struct cli_state *cli;
+
+/* These defines are for the do_setrattr routine, to indicate
+ * setting and reseting of file attributes in the function call */
+#define ATTRSET 1
+#define ATTRRESET 0
+
+static uint16 attribute = aDIR | aSYSTEM | aHIDDEN;
+
+#ifndef CLIENT_TIMEOUT
+#define CLIENT_TIMEOUT (30*1000)
+#endif
+
+static char *tarbuf, *buffer_p;
+static int tp, ntarf, tbufsiz;
+static double ttarf;
+/* Incremental mode */
+static bool tar_inc=False;
+/* Reset archive bit */
+static bool tar_reset=False;
+/* Include / exclude mode (true=include, false=exclude) */
+static bool tar_excl=True;
+/* use regular expressions for search on file names */
+static bool tar_re_search=False;
+/* Do not dump anything, just calculate sizes */
+static bool dry_run=False;
+/* Dump files with System attribute */
+static bool tar_system=True;
+/* Dump files with Hidden attribute */
+static bool tar_hidden=True;
+/* Be noisy - make a catalogue */
+static bool tar_noisy=True;
+static bool tar_real_noisy=False; /* Don't want to be really noisy by default */
+
+char tar_type='\0';
+static char **cliplist=NULL;
+static int clipn=0;
+static bool must_free_cliplist = False;
+extern const char *cmd_ptr;
+
+extern bool lowercase;
+extern uint16 cnum;
+extern bool readbraw_supported;
+extern int max_xmit;
+extern int get_total_time_ms;
+extern int get_total_size;
+
+static int blocksize=20;
+static int tarhandle;
+
+static void writetarheader(int f, const char *aname, SMB_BIG_UINT size, time_t mtime,
+ const char *amode, unsigned char ftype);
+static void do_atar(const char *rname_in,char *lname,file_info *finfo1);
+static void do_tar(file_info *finfo, const char *dir);
+static void oct_it(SMB_BIG_UINT value, int ndgs, char *p);
+static void fixtarname(char *tptr, const char *fp, size_t l);
+static int dotarbuf(int f, char *b, int n);
+static void dozerobuf(int f, int n);
+static void dotareof(int f);
+static void initarbuf(void);
+
+/* restore functions */
+static long readtarheader(union hblock *hb, file_info2 *finfo, const char *prefix);
+static long unoct(char *p, int ndgs);
+static void do_tarput(void);
+static void unfixtarname(char *tptr, char *fp, int l, bool first);
+
+/*
+ * tar specific utitlities
+ */
+
+/*******************************************************************
+Create a string of size size+1 (for the null)
+*******************************************************************/
+
+static char *string_create_s(int size)
+{
+ char *tmp;
+
+ tmp = (char *)SMB_MALLOC(size+1);
+
+ if (tmp == NULL) {
+ DEBUG(0, ("Out of memory in string_create_s\n"));
+ }
+
+ return(tmp);
+}
+
+/****************************************************************************
+Write a tar header to buffer
+****************************************************************************/
+
+static void writetarheader(int f, const char *aname, SMB_BIG_UINT size, time_t mtime,
+ const char *amode, unsigned char ftype)
+{
+ union hblock hb;
+ int i, chk, l;
+ char *jp;
+
+ DEBUG(5, ("WriteTarHdr, Type = %c, Size= %.0f, Name = %s\n", ftype, (double)size, aname));
+
+ memset(hb.dummy, 0, sizeof(hb.dummy));
+
+ l=strlen(aname);
+ /* We will be prepending a '.' in fixtarheader so use +2 to
+ * take care of the . and terminating zero. JRA.
+ */
+ if (l+2 >= NAMSIZ) {
+ /* write a GNU tar style long header */
+ char *b;
+ b = (char *)SMB_MALLOC(l+TBLOCK+100);
+ if (!b) {
+ DEBUG(0,("out of memory\n"));
+ exit(1);
+ }
+ writetarheader(f, "/./@LongLink", l+2, 0, " 0 \0", 'L');
+ memset(b, 0, l+TBLOCK+100);
+ fixtarname(b, aname, l+2);
+ i = strlen(b)+1;
+ DEBUG(5, ("File name in tar file: %s, size=%d, \n", b, (int)strlen(b)));
+ dotarbuf(f, b, TBLOCK*(((i-1)/TBLOCK)+1));
+ SAFE_FREE(b);
+ }
+
+ fixtarname(hb.dbuf.name, aname, (l+2 >= NAMSIZ) ? NAMSIZ : l + 2);
+
+ if (lowercase)
+ strlower_m(hb.dbuf.name);
+
+ /* write out a "standard" tar format header */
+
+ hb.dbuf.name[NAMSIZ-1]='\0';
+ safe_strcpy(hb.dbuf.mode, amode, sizeof(hb.dbuf.mode)-1);
+ oct_it((SMB_BIG_UINT)0, 8, hb.dbuf.uid);
+ oct_it((SMB_BIG_UINT)0, 8, hb.dbuf.gid);
+ oct_it((SMB_BIG_UINT) size, 13, hb.dbuf.size);
+ if (size > (SMB_BIG_UINT)077777777777LL) {
+ /* This is a non-POSIX compatible extention to store files
+ greater than 8GB. */
+
+ memset(hb.dbuf.size, 0, 4);
+ hb.dbuf.size[0]=128;
+ for (i = 8, jp=(char*)&size; i; i--)
+ hb.dbuf.size[i+3] = *(jp++);
+ }
+ oct_it((SMB_BIG_UINT) mtime, 13, hb.dbuf.mtime);
+ memcpy(hb.dbuf.chksum, " ", sizeof(hb.dbuf.chksum));
+ memset(hb.dbuf.linkname, 0, NAMSIZ);
+ hb.dbuf.linkflag=ftype;
+
+ for (chk=0, i=sizeof(hb.dummy), jp=hb.dummy; --i>=0;)
+ chk+=(0xFF & *jp++);
+
+ oct_it((SMB_BIG_UINT) chk, 8, hb.dbuf.chksum);
+ hb.dbuf.chksum[6] = '\0';
+
+ (void) dotarbuf(f, hb.dummy, sizeof(hb.dummy));
+}
+
+/****************************************************************************
+Read a tar header into a hblock structure, and validate
+***************************************************************************/
+
+static long readtarheader(union hblock *hb, file_info2 *finfo, const char *prefix)
+{
+ long chk, fchk;
+ int i;
+ char *jp;
+
+ /*
+ * read in a "standard" tar format header - we're not that interested
+ * in that many fields, though
+ */
+
+ /* check the checksum */
+ for (chk=0, i=sizeof(hb->dummy), jp=hb->dummy; --i>=0;)
+ chk+=(0xFF & *jp++);
+
+ if (chk == 0)
+ return chk;
+
+ /* compensate for blanks in chksum header */
+ for (i=sizeof(hb->dbuf.chksum), jp=hb->dbuf.chksum; --i>=0;)
+ chk-=(0xFF & *jp++);
+
+ chk += ' ' * sizeof(hb->dbuf.chksum);
+
+ fchk=unoct(hb->dbuf.chksum, sizeof(hb->dbuf.chksum));
+
+ DEBUG(5, ("checksum totals chk=%ld fchk=%ld chksum=%s\n",
+ chk, fchk, hb->dbuf.chksum));
+
+ if (fchk != chk) {
+ DEBUG(0, ("checksums don't match %ld %ld\n", fchk, chk));
+ dump_data(5, (uint8 *)hb - TBLOCK, TBLOCK *3);
+ return -1;
+ }
+
+ if ((finfo->name = string_create_s(strlen(prefix) + strlen(hb -> dbuf.name) + 3)) == NULL) {
+ DEBUG(0, ("Out of space creating file_info2 for %s\n", hb -> dbuf.name));
+ return(-1);
+ }
+
+ safe_strcpy(finfo->name, prefix, strlen(prefix) + strlen(hb -> dbuf.name) + 3);
+
+ /* use l + 1 to do the null too; do prefix - prefcnt to zap leading slash */
+ unfixtarname(finfo->name + strlen(prefix), hb->dbuf.name,
+ strlen(hb->dbuf.name) + 1, True);
+
+ /* can't handle some links at present */
+ if ((hb->dbuf.linkflag != '0') && (hb -> dbuf.linkflag != '5')) {
+ if (hb->dbuf.linkflag == 0) {
+ DEBUG(6, ("Warning: NULL link flag (gnu tar archive ?) %s\n",
+ finfo->name));
+ } else {
+ if (hb -> dbuf.linkflag == 'L') { /* We have a longlink */
+ /* Do nothing here at the moment. do_tarput will handle this
+ as long as the longlink gets back to it, as it has to advance
+ the buffer pointer, etc */
+ } else {
+ DEBUG(0, ("this tar file appears to contain some kind \
+of link other than a GNUtar Longlink - ignoring\n"));
+ return -2;
+ }
+ }
+ }
+
+ if ((unoct(hb->dbuf.mode, sizeof(hb->dbuf.mode)) & S_IFDIR) ||
+ (*(finfo->name+strlen(finfo->name)-1) == '\\')) {
+ finfo->mode=aDIR;
+ } else {
+ finfo->mode=0; /* we don't care about mode at the moment, we'll
+ * just make it a regular file */
+ }
+
+ /*
+ * Bug fix by richard@sj.co.uk
+ *
+ * REC: restore times correctly (as does tar)
+ * We only get the modification time of the file; set the creation time
+ * from the mod. time, and the access time to current time
+ */
+ finfo->mtime_ts = finfo->ctime_ts =
+ convert_time_t_to_timespec((time_t)strtol(hb->dbuf.mtime, NULL, 8));
+ finfo->atime_ts = convert_time_t_to_timespec(time(NULL));
+ finfo->size = unoct(hb->dbuf.size, sizeof(hb->dbuf.size));
+
+ return True;
+}
+
+/****************************************************************************
+Write out the tar buffer to tape or wherever
+****************************************************************************/
+
+static int dotarbuf(int f, char *b, int n)
+{
+ int fail=1, writ=n;
+
+ if (dry_run) {
+ return writ;
+ }
+ /* This routine and the next one should be the only ones that do write()s */
+ if (tp + n >= tbufsiz) {
+ int diff;
+
+ diff=tbufsiz-tp;
+ memcpy(tarbuf + tp, b, diff);
+ fail=fail && (1+write(f, tarbuf, tbufsiz));
+ n-=diff;
+ b+=diff;
+ tp=0;
+
+ while (n >= tbufsiz) {
+ fail=fail && (1 + write(f, b, tbufsiz));
+ n-=tbufsiz;
+ b+=tbufsiz;
+ }
+ }
+
+ if (n>0) {
+ memcpy(tarbuf+tp, b, n);
+ tp+=n;
+ }
+
+ return(fail ? writ : 0);
+}
+
+/****************************************************************************
+Write zeros to buffer / tape
+****************************************************************************/
+
+static void dozerobuf(int f, int n)
+{
+ /* short routine just to write out n zeros to buffer -
+ * used to round files to nearest block
+ * and to do tar EOFs */
+
+ if (dry_run)
+ return;
+
+ if (n+tp >= tbufsiz) {
+ memset(tarbuf+tp, 0, tbufsiz-tp);
+ write(f, tarbuf, tbufsiz);
+ memset(tarbuf, 0, (tp+=n-tbufsiz));
+ } else {
+ memset(tarbuf+tp, 0, n);
+ tp+=n;
+ }
+}
+
+/****************************************************************************
+Malloc tape buffer
+****************************************************************************/
+
+static void initarbuf(void)
+{
+ /* initialize tar buffer */
+ tbufsiz=blocksize*TBLOCK;
+ tarbuf=(char *)SMB_MALLOC(tbufsiz); /* FIXME: We might not get the buffer */
+
+ /* reset tar buffer pointer and tar file counter and total dumped */
+ tp=0; ntarf=0; ttarf=0;
+}
+
+/****************************************************************************
+Write two zero blocks at end of file
+****************************************************************************/
+
+static void dotareof(int f)
+{
+ SMB_STRUCT_STAT stbuf;
+ /* Two zero blocks at end of file, write out full buffer */
+
+ if (dry_run)
+ return;
+
+ (void) dozerobuf(f, TBLOCK);
+ (void) dozerobuf(f, TBLOCK);
+
+ if (sys_fstat(f, &stbuf) == -1) {
+ DEBUG(0, ("Couldn't stat file handle\n"));
+ return;
+ }
+
+ /* Could be a pipe, in which case S_ISREG should fail,
+ * and we should write out at full size */
+ if (tp > 0)
+ write(f, tarbuf, S_ISREG(stbuf.st_mode) ? tp : tbufsiz);
+}
+
+/****************************************************************************
+(Un)mangle DOS pathname, make nonabsolute
+****************************************************************************/
+
+static void fixtarname(char *tptr, const char *fp, size_t l)
+{
+ /* add a '.' to start of file name, convert from ugly dos \'s in path
+ * to lovely unix /'s :-} */
+ *tptr++='.';
+ l--;
+
+ StrnCpy(tptr, fp, l-1);
+ string_replace(tptr, '\\', '/');
+}
+
+/****************************************************************************
+Convert from decimal to octal string
+****************************************************************************/
+
+static void oct_it (SMB_BIG_UINT value, int ndgs, char *p)
+{
+ /* Converts long to octal string, pads with leading zeros */
+
+ /* skip final null, but do final space */
+ --ndgs;
+ p[--ndgs] = ' ';
+
+ /* Loop does at least one digit */
+ do {
+ p[--ndgs] = '0' + (char) (value & 7);
+ value >>= 3;
+ } while (ndgs > 0 && value != 0);
+
+ /* Do leading zeros */
+ while (ndgs > 0)
+ p[--ndgs] = '0';
+}
+
+/****************************************************************************
+Convert from octal string to long
+***************************************************************************/
+
+static long unoct(char *p, int ndgs)
+{
+ long value=0;
+ /* Converts octal string to long, ignoring any non-digit */
+
+ while (--ndgs) {
+ if (isdigit((int)*p))
+ value = (value << 3) | (long) (*p - '0');
+
+ p++;
+ }
+
+ return value;
+}
+
+/****************************************************************************
+Compare two strings in a slash insensitive way, allowing s1 to match s2
+if s1 is an "initial" string (up to directory marker). Thus, if s2 is
+a file in any subdirectory of s1, declare a match.
+***************************************************************************/
+
+static int strslashcmp(char *s1, char *s2)
+{
+ char *s1_0=s1;
+
+ while(*s1 && *s2 && (*s1 == *s2 || tolower_ascii(*s1) == tolower_ascii(*s2) ||
+ (*s1 == '\\' && *s2=='/') || (*s1 == '/' && *s2=='\\'))) {
+ s1++; s2++;
+ }
+
+ /* if s1 has a trailing slash, it compared equal, so s1 is an "initial"
+ string of s2.
+ */
+ if (!*s1 && s1 != s1_0 && (*(s1-1) == '/' || *(s1-1) == '\\'))
+ return 0;
+
+ /* ignore trailing slash on s1 */
+ if (!*s2 && (*s1 == '/' || *s1 == '\\') && !*(s1+1))
+ return 0;
+
+ /* check for s1 is an "initial" string of s2 */
+ if ((*s2 == '/' || *s2 == '\\') && !*s1)
+ return 0;
+
+ return *s1-*s2;
+}
+
+/****************************************************************************
+Ensure a remote path exists (make if necessary)
+***************************************************************************/
+
+static bool ensurepath(const char *fname)
+{
+ /* *must* be called with buffer ready malloc'ed */
+ /* ensures path exists */
+
+ char *partpath, *ffname;
+ const char *p=fname;
+ char *basehack;
+ char *saveptr;
+
+ DEBUG(5, ( "Ensurepath called with: %s\n", fname));
+
+ partpath = string_create_s(strlen(fname));
+ ffname = string_create_s(strlen(fname));
+
+ if ((partpath == NULL) || (ffname == NULL)){
+ DEBUG(0, ("Out of memory in ensurepath: %s\n", fname));
+ SAFE_FREE(partpath);
+ SAFE_FREE(ffname);
+ return(False);
+ }
+
+ *partpath = 0;
+
+ /* fname copied to ffname so can strtok_r */
+
+ safe_strcpy(ffname, fname, strlen(fname));
+
+ /* do a `basename' on ffname, so don't try and make file name directory */
+ if ((basehack=strrchr_m(ffname, '\\')) == NULL) {
+ SAFE_FREE(partpath);
+ SAFE_FREE(ffname);
+ return True;
+ } else {
+ *basehack='\0';
+ }
+
+ p=strtok_r(ffname, "\\", &saveptr);
+
+ while (p) {
+ safe_strcat(partpath, p, strlen(fname) + 1);
+
+ if (!cli_chkpath(cli, partpath)) {
+ if (!cli_mkdir(cli, partpath)) {
+ SAFE_FREE(partpath);
+ SAFE_FREE(ffname);
+ DEBUG(0, ("Error mkdir %s\n", cli_errstr(cli)));
+ return False;
+ } else {
+ DEBUG(3, ("mkdirhiering %s\n", partpath));
+ }
+ }
+
+ safe_strcat(partpath, "\\", strlen(fname) + 1);
+ p = strtok_r(NULL, "/\\", &saveptr);
+ }
+
+ SAFE_FREE(partpath);
+ SAFE_FREE(ffname);
+ return True;
+}
+
+static int padit(char *buf, SMB_BIG_UINT bufsize, SMB_BIG_UINT padsize)
+{
+ int berr= 0;
+ int bytestowrite;
+
+ DEBUG(5, ("Padding with %0.f zeros\n", (double)padsize));
+ memset(buf, 0, (size_t)bufsize);
+ while( !berr && padsize > 0 ) {
+ bytestowrite= (int)MIN(bufsize, padsize);
+ berr = dotarbuf(tarhandle, buf, bytestowrite) != bytestowrite;
+ padsize -= bytestowrite;
+ }
+
+ return berr;
+}
+
+static void do_setrattr(char *name, uint16 attr, int set)
+{
+ uint16 oldattr;
+
+ if (!cli_getatr(cli, name, &oldattr, NULL, NULL)) return;
+
+ if (set == ATTRSET) {
+ attr |= oldattr;
+ } else {
+ attr = oldattr & ~attr;
+ }
+
+ if (!cli_setatr(cli, name, attr, 0)) {
+ DEBUG(1,("setatr failed: %s\n", cli_errstr(cli)));
+ }
+}
+
+/****************************************************************************
+append one remote file to the tar file
+***************************************************************************/
+
+static void do_atar(const char *rname_in,char *lname,file_info *finfo1)
+{
+ int fnum = -1;
+ SMB_BIG_UINT nread=0;
+ char ftype;
+ file_info2 finfo;
+ bool shallitime=True;
+ char *data = NULL;
+ int read_size = 65520;
+ int datalen=0;
+ char *rname = NULL;
+ TALLOC_CTX *ctx = talloc_stackframe();
+
+ struct timeval tp_start;
+
+ GetTimeOfDay(&tp_start);
+
+ data = SMB_MALLOC_ARRAY(char, read_size);
+ if (!data) {
+ DEBUG(0,("do_atar: out of memory.\n"));
+ goto cleanup;
+ }
+
+ ftype = '0'; /* An ordinary file ... */
+
+ ZERO_STRUCT(finfo);
+
+ finfo.size = finfo1 -> size;
+ finfo.mode = finfo1 -> mode;
+ finfo.uid = finfo1 -> uid;
+ finfo.gid = finfo1 -> gid;
+ finfo.mtime_ts = finfo1 -> mtime_ts;
+ finfo.atime_ts = finfo1 -> atime_ts;
+ finfo.ctime_ts = finfo1 -> ctime_ts;
+
+ if (dry_run) {
+ DEBUG(3,("skipping file %s of size %12.0f bytes\n", finfo1->name,
+ (double)finfo.size));
+ shallitime=0;
+ ttarf+=finfo.size + TBLOCK - (finfo.size % TBLOCK);
+ ntarf++;
+ goto cleanup;
+ }
+
+ rname = clean_name(ctx, rname_in);
+ if (!rname) {
+ goto cleanup;
+ }
+
+ fnum = cli_open(cli, rname, O_RDONLY, DENY_NONE);
+
+ if (fnum == -1) {
+ DEBUG(0,("%s opening remote file %s (%s)\n",
+ cli_errstr(cli),rname, client_get_cur_dir()));
+ goto cleanup;
+ }
+
+ finfo.name = string_create_s(strlen(rname));
+ if (finfo.name == NULL) {
+ DEBUG(0, ("Unable to allocate space for finfo.name in do_atar\n"));
+ goto cleanup;
+ }
+
+ safe_strcpy(finfo.name,rname, strlen(rname));
+
+ DEBUG(3,("file %s attrib 0x%X\n",finfo.name,finfo.mode));
+
+ if (tar_inc && !(finfo.mode & aARCH)) {
+ DEBUG(4, ("skipping %s - archive bit not set\n", finfo.name));
+ shallitime=0;
+ } else if (!tar_system && (finfo.mode & aSYSTEM)) {
+ DEBUG(4, ("skipping %s - system bit is set\n", finfo.name));
+ shallitime=0;
+ } else if (!tar_hidden && (finfo.mode & aHIDDEN)) {
+ DEBUG(4, ("skipping %s - hidden bit is set\n", finfo.name));
+ shallitime=0;
+ } else {
+ bool wrote_tar_header = False;
+
+ DEBUG(3,("getting file %s of size %.0f bytes as a tar file %s",
+ finfo.name, (double)finfo.size, lname));
+
+ do {
+
+ DEBUG(3,("nread=%.0f\n",(double)nread));
+
+ datalen = cli_read(cli, fnum, data, nread, read_size);
+
+ if (datalen == -1) {
+ DEBUG(0,("Error reading file %s : %s\n", rname, cli_errstr(cli)));
+ break;
+ }
+
+ nread += datalen;
+
+ /* Only if the first read succeeds, write out the tar header. */
+ if (!wrote_tar_header) {
+ /* write a tar header, don't bother with mode - just set to 100644 */
+ writetarheader(tarhandle, rname, finfo.size,
+ finfo.mtime_ts.tv_sec, "100644 \0", ftype);
+ wrote_tar_header = True;
+ }
+
+ /* if file size has increased since we made file size query, truncate
+ read so tar header for this file will be correct.
+ */
+
+ if (nread > finfo.size) {
+ datalen -= nread - finfo.size;
+ DEBUG(0,("File size change - truncating %s to %.0f bytes\n",
+ finfo.name, (double)finfo.size));
+ }
+
+ /* add received bits of file to buffer - dotarbuf will
+ * write out in 512 byte intervals */
+
+ if (dotarbuf(tarhandle,data,datalen) != datalen) {
+ DEBUG(0,("Error writing to tar file - %s\n", strerror(errno)));
+ break;
+ }
+
+ if ( (datalen == 0) && (finfo.size != 0) ) {
+ DEBUG(0,("Error reading file %s. Got 0 bytes\n", rname));
+ break;
+ }
+
+ datalen=0;
+ } while ( nread < finfo.size );
+
+ if (wrote_tar_header) {
+ /* pad tar file with zero's if we couldn't get entire file */
+ if (nread < finfo.size) {
+ DEBUG(0, ("Didn't get entire file. size=%.0f, nread=%d\n",
+ (double)finfo.size, (int)nread));
+ if (padit(data, (SMB_BIG_UINT)sizeof(data), finfo.size - nread))
+ DEBUG(0,("Error writing tar file - %s\n", strerror(errno)));
+ }
+
+ /* round tar file to nearest block */
+ if (finfo.size % TBLOCK)
+ dozerobuf(tarhandle, TBLOCK - (finfo.size % TBLOCK));
+
+ ttarf+=finfo.size + TBLOCK - (finfo.size % TBLOCK);
+ ntarf++;
+ } else {
+ DEBUG(4, ("skipping %s - initial read failed (file was locked ?)\n", finfo.name));
+ shallitime=0;
+ }
+ }
+
+ cli_close(cli, fnum);
+ fnum = -1;
+
+ if (shallitime) {
+ struct timeval tp_end;
+ int this_time;
+
+ /* if shallitime is true then we didn't skip */
+ if (tar_reset && !dry_run)
+ (void) do_setrattr(finfo.name, aARCH, ATTRRESET);
+
+ GetTimeOfDay(&tp_end);
+ this_time = (tp_end.tv_sec - tp_start.tv_sec)*1000 + (tp_end.tv_usec - tp_start.tv_usec)/1000;
+ get_total_time_ms += this_time;
+ get_total_size += finfo.size;
+
+ if (tar_noisy) {
+ DEBUG(0, ("%12.0f (%7.1f kb/s) %s\n",
+ (double)finfo.size, finfo.size / MAX(0.001, (1.024*this_time)),
+ finfo.name));
+ }
+
+ /* Thanks to Carel-Jan Engel (ease@mail.wirehub.nl) for this one */
+ DEBUG(3,("(%g kb/s) (average %g kb/s)\n",
+ finfo.size / MAX(0.001, (1.024*this_time)),
+ get_total_size / MAX(0.001, (1.024*get_total_time_ms))));
+ }
+
+ cleanup:
+
+ if (fnum != -1) {
+ cli_close(cli, fnum);
+ fnum = -1;
+ }
+ TALLOC_FREE(ctx);
+ SAFE_FREE(data);
+}
+
+/****************************************************************************
+Append single file to tar file (or not)
+***************************************************************************/
+
+static void do_tar(file_info *finfo, const char *dir)
+{
+ TALLOC_CTX *ctx = talloc_stackframe();
+
+ if (strequal(finfo->name,"..") || strequal(finfo->name,"."))
+ return;
+
+ /* Is it on the exclude list ? */
+ if (!tar_excl && clipn) {
+ char *exclaim;
+
+ DEBUG(5, ("Excl: strlen(cur_dir) = %d\n", (int)strlen(client_get_cur_dir())));
+
+ exclaim = talloc_asprintf(ctx,
+ "%s\\%s",
+ client_get_cur_dir(),
+ finfo->name);
+ if (!exclaim) {
+ return;
+ }
+
+ DEBUG(5, ("...tar_re_search: %d\n", tar_re_search));
+
+ if ((!tar_re_search && clipfind(cliplist, clipn, exclaim)) ||
+ (tar_re_search && mask_match_list(exclaim, cliplist, clipn, True))) {
+ DEBUG(3,("Skipping file %s\n", exclaim));
+ TALLOC_FREE(exclaim);
+ return;
+ }
+ TALLOC_FREE(exclaim);
+ }
+
+ if (finfo->mode & aDIR) {
+ char *saved_curdir = NULL;
+ char *new_cd = NULL;
+ char *mtar_mask = NULL;
+
+ saved_curdir = talloc_strdup(ctx, client_get_cur_dir());
+ if (!saved_curdir) {
+ return;
+ }
+
+ DEBUG(5, ("strlen(cur_dir)=%d, \
+strlen(finfo->name)=%d\nname=%s,cur_dir=%s\n",
+ (int)strlen(saved_curdir),
+ (int)strlen(finfo->name), finfo->name, saved_curdir));
+
+ new_cd = talloc_asprintf(ctx,
+ "%s%s\\",
+ client_get_cur_dir(),
+ finfo->name);
+ if (!new_cd) {
+ return;
+ }
+ client_set_cur_dir(new_cd);
+
+ DEBUG(5, ("Writing a dir, Name = %s\n", client_get_cur_dir()));
+
+ /* write a tar directory, don't bother with mode - just
+ * set it to 40755 */
+ writetarheader(tarhandle, client_get_cur_dir(), 0,
+ finfo->mtime_ts.tv_sec, "040755 \0", '5');
+ if (tar_noisy) {
+ DEBUG(0,(" directory %s\n",
+ client_get_cur_dir()));
+ }
+ ntarf++; /* Make sure we have a file on there */
+ mtar_mask = talloc_asprintf(ctx,
+ "%s*",
+ client_get_cur_dir());
+ if (!mtar_mask) {
+ return;
+ }
+ DEBUG(5, ("Doing list with mtar_mask: %s\n", mtar_mask));
+ do_list(mtar_mask, attribute, do_tar, False, True);
+ client_set_cur_dir(saved_curdir);
+ TALLOC_FREE(saved_curdir);
+ TALLOC_FREE(new_cd);
+ TALLOC_FREE(mtar_mask);
+ } else {
+ char *rname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ finfo->name);
+ if (!rname) {
+ return;
+ }
+ do_atar(rname,finfo->name,finfo);
+ TALLOC_FREE(rname);
+ }
+}
+
+/****************************************************************************
+Convert from UNIX to DOS file names
+***************************************************************************/
+
+static void unfixtarname(char *tptr, char *fp, int l, bool first)
+{
+ /* remove '.' from start of file name, convert from unix /'s to
+ * dos \'s in path. Kill any absolute path names. But only if first!
+ */
+
+ DEBUG(5, ("firstb=%lX, secondb=%lX, len=%i\n", (long)tptr, (long)fp, l));
+
+ if (first) {
+ if (*fp == '.') {
+ fp++;
+ l--;
+ }
+ if (*fp == '\\' || *fp == '/') {
+ fp++;
+ l--;
+ }
+ }
+
+ safe_strcpy(tptr, fp, l);
+ string_replace(tptr, '/', '\\');
+}
+
+/****************************************************************************
+Move to the next block in the buffer, which may mean read in another set of
+blocks. FIXME, we should allow more than one block to be skipped.
+****************************************************************************/
+
+static int next_block(char *ltarbuf, char **bufferp, int bufsiz)
+{
+ int bufread, total = 0;
+
+ DEBUG(5, ("Advancing to next block: %0lx\n", (unsigned long)*bufferp));
+ *bufferp += TBLOCK;
+ total = TBLOCK;
+
+ if (*bufferp >= (ltarbuf + bufsiz)) {
+
+ DEBUG(5, ("Reading more data into ltarbuf ...\n"));
+
+ /*
+ * Bugfix from Bob Boehmer <boehmer@worldnet.att.net>
+ * Fixes bug where read can return short if coming from
+ * a pipe.
+ */
+
+ bufread = read(tarhandle, ltarbuf, bufsiz);
+ total = bufread;
+
+ while (total < bufsiz) {
+ if (bufread < 0) { /* An error, return false */
+ return (total > 0 ? -2 : bufread);
+ }
+ if (bufread == 0) {
+ if (total <= 0) {
+ return -2;
+ }
+ break;
+ }
+ bufread = read(tarhandle, &ltarbuf[total], bufsiz - total);
+ total += bufread;
+ }
+
+ DEBUG(5, ("Total bytes read ... %i\n", total));
+
+ *bufferp = ltarbuf;
+ }
+
+ return(total);
+}
+
+/* Skip a file, even if it includes a long file name? */
+static int skip_file(int skipsize)
+{
+ int dsize = skipsize;
+
+ DEBUG(5, ("Skiping file. Size = %i\n", skipsize));
+
+ /* FIXME, we should skip more than one block at a time */
+
+ while (dsize > 0) {
+ if (next_block(tarbuf, &buffer_p, tbufsiz) <= 0) {
+ DEBUG(0, ("Empty file, short tar file, or read error: %s\n", strerror(errno)));
+ return(False);
+ }
+ dsize -= TBLOCK;
+ }
+
+ return(True);
+}
+
+/*************************************************************
+ Get a file from the tar file and store it.
+ When this is called, tarbuf already contains the first
+ file block. This is a bit broken & needs fixing.
+**************************************************************/
+
+static int get_file(file_info2 finfo)
+{
+ int fnum = -1, pos = 0, dsize = 0, bpos = 0;
+ SMB_BIG_UINT rsize = 0;
+
+ DEBUG(5, ("get_file: file: %s, size %.0f\n", finfo.name, (double)finfo.size));
+
+ if (ensurepath(finfo.name) &&
+ (fnum=cli_open(cli, finfo.name, O_RDWR|O_CREAT|O_TRUNC, DENY_NONE)) == -1) {
+ DEBUG(0, ("abandoning restore\n"));
+ return(False);
+ }
+
+ /* read the blocks from the tar file and write to the remote file */
+
+ rsize = finfo.size; /* This is how much to write */
+
+ while (rsize > 0) {
+
+ /* We can only write up to the end of the buffer */
+ dsize = MIN(tbufsiz - (buffer_p - tarbuf) - bpos, 65520); /* Calculate the size to write */
+ dsize = MIN(dsize, rsize); /* Should be only what is left */
+ DEBUG(5, ("writing %i bytes, bpos = %i ...\n", dsize, bpos));
+
+ if (cli_write(cli, fnum, 0, buffer_p + bpos, pos, dsize) != dsize) {
+ DEBUG(0, ("Error writing remote file\n"));
+ return 0;
+ }
+
+ rsize -= dsize;
+ pos += dsize;
+
+ /* Now figure out how much to move in the buffer */
+
+ /* FIXME, we should skip more than one block at a time */
+
+ /* First, skip any initial part of the part written that is left over */
+ /* from the end of the first TBLOCK */
+
+ if ((bpos) && ((bpos + dsize) >= TBLOCK)) {
+ dsize -= (TBLOCK - bpos); /* Get rid of the end of the first block */
+ bpos = 0;
+
+ if (next_block(tarbuf, &buffer_p, tbufsiz) <=0) { /* and skip the block */
+ DEBUG(0, ("Empty file, short tar file, or read error: %s\n", strerror(errno)));
+ return False;
+ }
+ }
+
+ /*
+ * Bugfix from Bob Boehmer <boehmer@worldnet.att.net>.
+ * If the file being extracted is an exact multiple of
+ * TBLOCK bytes then we don't want to extract the next
+ * block from the tarfile here, as it will be done in
+ * the caller of get_file().
+ */
+
+ while (((rsize != 0) && (dsize >= TBLOCK)) ||
+ ((rsize == 0) && (dsize > TBLOCK))) {
+
+ if (next_block(tarbuf, &buffer_p, tbufsiz) <=0) {
+ DEBUG(0, ("Empty file, short tar file, or read error: %s\n", strerror(errno)));
+ return False;
+ }
+
+ dsize -= TBLOCK;
+ }
+ bpos = dsize;
+ }
+
+ /* Now close the file ... */
+
+ if (!cli_close(cli, fnum)) {
+ DEBUG(0, ("Error closing remote file\n"));
+ return(False);
+ }
+
+ /* Now we update the creation date ... */
+ DEBUG(5, ("Updating creation date on %s\n", finfo.name));
+
+ if (!cli_setatr(cli, finfo.name, finfo.mode, finfo.mtime_ts.tv_sec)) {
+ if (tar_real_noisy) {
+ DEBUG(0, ("Could not set time on file: %s\n", finfo.name));
+ /*return(False); */ /* Ignore, as Win95 does not allow changes */
+ }
+ }
+
+ ntarf++;
+ DEBUG(0, ("restore tar file %s of size %.0f bytes\n", finfo.name, (double)finfo.size));
+ return(True);
+}
+
+/* Create a directory. We just ensure that the path exists and return as there
+ is no file associated with a directory
+*/
+static int get_dir(file_info2 finfo)
+{
+ DEBUG(0, ("restore directory %s\n", finfo.name));
+
+ if (!ensurepath(finfo.name)) {
+ DEBUG(0, ("Problems creating directory\n"));
+ return(False);
+ }
+ ntarf++;
+ return(True);
+}
+
+/* Get a file with a long file name ... first file has file name, next file
+ has the data. We only want the long file name, as the loop in do_tarput
+ will deal with the rest.
+*/
+static char *get_longfilename(file_info2 finfo)
+{
+ /* finfo.size here is the length of the filename as written by the "/./@LongLink" name
+ * header call. */
+ int namesize = finfo.size + strlen(client_get_cur_dir()) + 2;
+ char *longname = (char *)SMB_MALLOC(namesize);
+ int offset = 0, left = finfo.size;
+ bool first = True;
+
+ DEBUG(5, ("Restoring a long file name: %s\n", finfo.name));
+ DEBUG(5, ("Len = %.0f\n", (double)finfo.size));
+
+ if (longname == NULL) {
+ DEBUG(0, ("could not allocate buffer of size %d for longname\n", namesize));
+ return(NULL);
+ }
+
+ /* First, add cur_dir to the long file name */
+
+ if (strlen(client_get_cur_dir()) > 0) {
+ strncpy(longname, client_get_cur_dir(), namesize);
+ offset = strlen(client_get_cur_dir());
+ }
+
+ /* Loop through the blocks picking up the name */
+
+ while (left > 0) {
+ if (next_block(tarbuf, &buffer_p, tbufsiz) <= 0) {
+ DEBUG(0, ("Empty file, short tar file, or read error: %s\n", strerror(errno)));
+ SAFE_FREE(longname);
+ return(NULL);
+ }
+
+ unfixtarname(longname + offset, buffer_p, MIN(TBLOCK, finfo.size), first--);
+ DEBUG(5, ("UnfixedName: %s, buffer: %s\n", longname, buffer_p));
+
+ offset += TBLOCK;
+ left -= TBLOCK;
+ }
+
+ return(longname);
+}
+
+static void do_tarput(void)
+{
+ file_info2 finfo;
+ struct timeval tp_start;
+ char *longfilename = NULL, linkflag;
+ int skip = False;
+
+ ZERO_STRUCT(finfo);
+
+ GetTimeOfDay(&tp_start);
+ DEBUG(5, ("RJS do_tarput called ...\n"));
+
+ buffer_p = tarbuf + tbufsiz; /* init this to force first read */
+
+ /* Now read through those files ... */
+ while (True) {
+ /* Get us to the next block, or the first block first time around */
+ if (next_block(tarbuf, &buffer_p, tbufsiz) <= 0) {
+ DEBUG(0, ("Empty file, short tar file, or read error: %s\n", strerror(errno)));
+ SAFE_FREE(longfilename);
+ return;
+ }
+
+ DEBUG(5, ("Reading the next header ...\n"));
+
+ switch (readtarheader((union hblock *) buffer_p,
+ &finfo, client_get_cur_dir())) {
+ case -2: /* Hmm, not good, but not fatal */
+ DEBUG(0, ("Skipping %s...\n", finfo.name));
+ if ((next_block(tarbuf, &buffer_p, tbufsiz) <= 0) && !skip_file(finfo.size)) {
+ DEBUG(0, ("Short file, bailing out...\n"));
+ return;
+ }
+ break;
+
+ case -1:
+ DEBUG(0, ("abandoning restore, -1 from read tar header\n"));
+ return;
+
+ case 0: /* chksum is zero - looks like an EOF */
+ DEBUG(0, ("tar: restored %d files and directories\n", ntarf));
+ return; /* Hmmm, bad here ... */
+
+ default:
+ /* No action */
+ break;
+ }
+
+ /* Now, do we have a long file name? */
+ if (longfilename != NULL) {
+ SAFE_FREE(finfo.name); /* Free the space already allocated */
+ finfo.name = longfilename;
+ longfilename = NULL;
+ }
+
+ /* Well, now we have a header, process the file ... */
+ /* Should we skip the file? We have the long name as well here */
+ skip = clipn && ((!tar_re_search && clipfind(cliplist, clipn, finfo.name) ^ tar_excl) ||
+ (tar_re_search && mask_match_list(finfo.name, cliplist, clipn, True)));
+
+ DEBUG(5, ("Skip = %i, cliplist=%s, file=%s\n", skip, (cliplist?cliplist[0]:NULL), finfo.name));
+ if (skip) {
+ skip_file(finfo.size);
+ continue;
+ }
+
+ /* We only get this far if we should process the file */
+ linkflag = ((union hblock *)buffer_p) -> dbuf.linkflag;
+ switch (linkflag) {
+ case '0': /* Should use symbolic names--FIXME */
+ /*
+ * Skip to the next block first, so we can get the file, FIXME, should
+ * be in get_file ...
+ * The 'finfo.size != 0' fix is from Bob Boehmer <boehmer@worldnet.att.net>
+ * Fixes bug where file size in tarfile is zero.
+ */
+ if ((finfo.size != 0) && next_block(tarbuf, &buffer_p, tbufsiz) <=0) {
+ DEBUG(0, ("Short file, bailing out...\n"));
+ return;
+ }
+ if (!get_file(finfo)) {
+ DEBUG(0, ("Abandoning restore\n"));
+ return;
+ }
+ break;
+ case '5':
+ if (!get_dir(finfo)) {
+ DEBUG(0, ("Abandoning restore \n"));
+ return;
+ }
+ break;
+ case 'L':
+ SAFE_FREE(longfilename);
+ longfilename = get_longfilename(finfo);
+ if (!longfilename) {
+ DEBUG(0, ("abandoning restore\n"));
+ return;
+ }
+ DEBUG(5, ("Long file name: %s\n", longfilename));
+ break;
+
+ default:
+ skip_file(finfo.size); /* Don't handle these yet */
+ break;
+ }
+ }
+}
+
+/*
+ * samba interactive commands
+ */
+
+/****************************************************************************
+Blocksize command
+***************************************************************************/
+
+int cmd_block(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+ int block;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ DEBUG(0, ("blocksize <n>\n"));
+ return 1;
+ }
+
+ block=atoi(buf);
+ if (block < 0 || block > 65535) {
+ DEBUG(0, ("blocksize out of range"));
+ return 1;
+ }
+
+ blocksize=block;
+ DEBUG(2,("blocksize is now %d\n", blocksize));
+ return 0;
+}
+
+/****************************************************************************
+command to set incremental / reset mode
+***************************************************************************/
+
+int cmd_tarmode(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+
+ while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ if (strequal(buf, "full"))
+ tar_inc=False;
+ else if (strequal(buf, "inc"))
+ tar_inc=True;
+ else if (strequal(buf, "reset"))
+ tar_reset=True;
+ else if (strequal(buf, "noreset"))
+ tar_reset=False;
+ else if (strequal(buf, "system"))
+ tar_system=True;
+ else if (strequal(buf, "nosystem"))
+ tar_system=False;
+ else if (strequal(buf, "hidden"))
+ tar_hidden=True;
+ else if (strequal(buf, "nohidden"))
+ tar_hidden=False;
+ else if (strequal(buf, "verbose") || strequal(buf, "noquiet"))
+ tar_noisy=True;
+ else if (strequal(buf, "quiet") || strequal(buf, "noverbose"))
+ tar_noisy=False;
+ else
+ DEBUG(0, ("tarmode: unrecognised option %s\n", buf));
+ TALLOC_FREE(buf);
+ }
+
+ DEBUG(0, ("tarmode is now %s, %s, %s, %s, %s\n",
+ tar_inc ? "incremental" : "full",
+ tar_system ? "system" : "nosystem",
+ tar_hidden ? "hidden" : "nohidden",
+ tar_reset ? "reset" : "noreset",
+ tar_noisy ? "verbose" : "quiet"));
+ return 0;
+}
+
+/****************************************************************************
+Feeble attrib command
+***************************************************************************/
+
+int cmd_setmode(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *q;
+ char *buf;
+ char *fname = NULL;
+ uint16 attra[2];
+ int direct=1;
+
+ attra[0] = attra[1] = 0;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ DEBUG(0, ("setmode <filename> <[+|-]rsha>\n"));
+ return 1;
+ }
+
+ fname = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ buf);
+ if (!fname) {
+ return 1;
+ }
+
+ while (next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ q=buf;
+
+ while(*q) {
+ switch (*q++) {
+ case '+':
+ direct=1;
+ break;
+ case '-':
+ direct=0;
+ break;
+ case 'r':
+ attra[direct]|=aRONLY;
+ break;
+ case 'h':
+ attra[direct]|=aHIDDEN;
+ break;
+ case 's':
+ attra[direct]|=aSYSTEM;
+ break;
+ case 'a':
+ attra[direct]|=aARCH;
+ break;
+ default:
+ DEBUG(0, ("setmode <filename> <perm=[+|-]rsha>\n"));
+ return 1;
+ }
+ }
+ }
+
+ if (attra[ATTRSET]==0 && attra[ATTRRESET]==0) {
+ DEBUG(0, ("setmode <filename> <[+|-]rsha>\n"));
+ return 1;
+ }
+
+ DEBUG(2, ("\nperm set %d %d\n", attra[ATTRSET], attra[ATTRRESET]));
+ do_setrattr(fname, attra[ATTRSET], ATTRSET);
+ do_setrattr(fname, attra[ATTRRESET], ATTRRESET);
+ return 0;
+}
+
+/**
+ Convert list of tokens to array; dependent on above routine.
+ Uses the global cmd_ptr from above - bit of a hack.
+**/
+
+static char **toktocliplist(int *ctok, const char *sep)
+{
+ char *s=(char *)cmd_ptr;
+ int ictok=0;
+ char **ret, **iret;
+
+ if (!sep)
+ sep = " \t\n\r";
+
+ while(*s && strchr_m(sep,*s))
+ s++;
+
+ /* nothing left? */
+ if (!*s)
+ return(NULL);
+
+ do {
+ ictok++;
+ while(*s && (!strchr_m(sep,*s)))
+ s++;
+ while(*s && strchr_m(sep,*s))
+ *s++=0;
+ } while(*s);
+
+ *ctok=ictok;
+ s=(char *)cmd_ptr;
+
+ if (!(ret=iret=SMB_MALLOC_ARRAY(char *,ictok+1)))
+ return NULL;
+
+ while(ictok--) {
+ *iret++=s;
+ if (ictok > 0) {
+ while(*s++)
+ ;
+ while(!*s)
+ s++;
+ }
+ }
+
+ ret[*ctok] = NULL;
+ return ret;
+}
+
+/****************************************************************************
+Principal command for creating / extracting
+***************************************************************************/
+
+int cmd_tar(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ char *buf;
+ char **argl = NULL;
+ int argcl = 0;
+ int ret;
+
+ if (!next_token_talloc(ctx, &cmd_ptr,&buf,NULL)) {
+ DEBUG(0,("tar <c|x>[IXbgan] <filename>\n"));
+ return 1;
+ }
+
+ argl=toktocliplist(&argcl, NULL);
+ if (!tar_parseargs(argcl, argl, buf, 0)) {
+ SAFE_FREE(argl);
+ return 1;
+ }
+
+ ret = process_tar();
+ SAFE_FREE(argl);
+ return ret;
+}
+
+/****************************************************************************
+Command line (option) version
+***************************************************************************/
+
+int process_tar(void)
+{
+ TALLOC_CTX *ctx = talloc_tos();
+ int rc = 0;
+ initarbuf();
+ switch(tar_type) {
+ case 'x':
+
+#if 0
+ do_tarput2();
+#else
+ do_tarput();
+#endif
+ SAFE_FREE(tarbuf);
+ close(tarhandle);
+ break;
+ case 'r':
+ case 'c':
+ if (clipn && tar_excl) {
+ int i;
+ char *tarmac = NULL;
+
+ for (i=0; i<clipn; i++) {
+ DEBUG(5,("arg %d = %s\n", i, cliplist[i]));
+
+ if (*(cliplist[i]+strlen(cliplist[i])-1)=='\\') {
+ *(cliplist[i]+strlen(cliplist[i])-1)='\0';
+ }
+
+ if (strrchr_m(cliplist[i], '\\')) {
+ char *p;
+ char *saved_dir = talloc_strdup(ctx,
+ client_get_cur_dir());
+ if (!saved_dir) {
+ return 1;
+ }
+
+ if (*cliplist[i]=='\\') {
+ tarmac = talloc_strdup(ctx,
+ cliplist[i]);
+ } else {
+ tarmac = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ cliplist[i]);
+ }
+ if (!tarmac) {
+ return 1;
+ }
+ p = strrchr_m(tarmac, '\\');
+ if (!p) {
+ return 1;
+ }
+ p[1] = '\0';
+ client_set_cur_dir(tarmac);
+
+ DEBUG(5, ("process_tar, do_list with tarmac: %s\n", tarmac));
+ do_list(tarmac,attribute,do_tar, False, True);
+
+ client_set_cur_dir(saved_dir);
+
+ TALLOC_FREE(saved_dir);
+ TALLOC_FREE(tarmac);
+ } else {
+ tarmac = talloc_asprintf(ctx,
+ "%s%s",
+ client_get_cur_dir(),
+ cliplist[i]);
+ if (!tarmac) {
+ return 1;
+ }
+ DEBUG(5, ("process_tar, do_list with tarmac: %s\n", tarmac));
+ do_list(tarmac,attribute,do_tar, False, True);
+ TALLOC_FREE(tarmac);
+ }
+ }
+ } else {
+ char *mask = talloc_asprintf(ctx,
+ "%s\\*",
+ client_get_cur_dir());
+ if (!mask) {
+ return 1;
+ }
+ DEBUG(5, ("process_tar, do_list with mask: %s\n", mask));
+ do_list(mask,attribute,do_tar,False, True);
+ TALLOC_FREE(mask);
+ }
+
+ if (ntarf) {
+ dotareof(tarhandle);
+ }
+ close(tarhandle);
+ SAFE_FREE(tarbuf);
+
+ DEBUG(0, ("tar: dumped %d files and directories\n", ntarf));
+ DEBUG(0, ("Total bytes written: %.0f\n", (double)ttarf));
+ break;
+ }
+
+ if (must_free_cliplist) {
+ int i;
+ for (i = 0; i < clipn; ++i) {
+ SAFE_FREE(cliplist[i]);
+ }
+ SAFE_FREE(cliplist);
+ cliplist = NULL;
+ clipn = 0;
+ must_free_cliplist = False;
+ }
+ return rc;
+}
+
+/****************************************************************************
+Find a token (filename) in a clip list
+***************************************************************************/
+
+static int clipfind(char **aret, int ret, char *tok)
+{
+ if (aret==NULL)
+ return 0;
+
+ /* ignore leading slashes or dots in token */
+ while(strchr_m("/\\.", *tok))
+ tok++;
+
+ while(ret--) {
+ char *pkey=*aret++;
+
+ /* ignore leading slashes or dots in list */
+ while(strchr_m("/\\.", *pkey))
+ pkey++;
+
+ if (!strslashcmp(pkey, tok))
+ return 1;
+ }
+ return 0;
+}
+
+/****************************************************************************
+Read list of files to include from the file and initialize cliplist
+accordingly.
+***************************************************************************/
+
+static int read_inclusion_file(char *filename)
+{
+ XFILE *inclusion = NULL;
+ char buf[PATH_MAX + 1];
+ char *inclusion_buffer = NULL;
+ int inclusion_buffer_size = 0;
+ int inclusion_buffer_sofar = 0;
+ char *p;
+ char *tmpstr;
+ int i;
+ int error = 0;
+
+ clipn = 0;
+ buf[PATH_MAX] = '\0'; /* guarantee null-termination */
+ if ((inclusion = x_fopen(filename, O_RDONLY, 0)) == NULL) {
+ /* XXX It would be better to include a reason for failure, but without
+ * autoconf, it's hard to use strerror, sys_errlist, etc.
+ */
+ DEBUG(0,("Unable to open inclusion file %s\n", filename));
+ return 0;
+ }
+
+ while ((! error) && (x_fgets(buf, sizeof(buf)-1, inclusion))) {
+ if (inclusion_buffer == NULL) {
+ inclusion_buffer_size = 1024;
+ if ((inclusion_buffer = (char *)SMB_MALLOC(inclusion_buffer_size)) == NULL) {
+ DEBUG(0,("failure allocating buffer to read inclusion file\n"));
+ error = 1;
+ break;
+ }
+ }
+
+ if (buf[strlen(buf)-1] == '\n') {
+ buf[strlen(buf)-1] = '\0';
+ }
+
+ if ((strlen(buf) + 1 + inclusion_buffer_sofar) >= inclusion_buffer_size) {
+ inclusion_buffer_size *= 2;
+ inclusion_buffer = (char *)SMB_REALLOC(inclusion_buffer,inclusion_buffer_size);
+ if (!inclusion_buffer) {
+ DEBUG(0,("failure enlarging inclusion buffer to %d bytes\n",
+ inclusion_buffer_size));
+ error = 1;
+ break;
+ }
+ }
+
+ safe_strcpy(inclusion_buffer + inclusion_buffer_sofar, buf, inclusion_buffer_size - inclusion_buffer_sofar);
+ inclusion_buffer_sofar += strlen(buf) + 1;
+ clipn++;
+ }
+ x_fclose(inclusion);
+
+ if (! error) {
+ /* Allocate an array of clipn + 1 char*'s for cliplist */
+ cliplist = SMB_MALLOC_ARRAY(char *, clipn + 1);
+ if (cliplist == NULL) {
+ DEBUG(0,("failure allocating memory for cliplist\n"));
+ error = 1;
+ } else {
+ cliplist[clipn] = NULL;
+ p = inclusion_buffer;
+ for (i = 0; (! error) && (i < clipn); i++) {
+ /* set current item to NULL so array will be null-terminated even if
+ * malloc fails below. */
+ cliplist[i] = NULL;
+ if ((tmpstr = (char *)SMB_MALLOC(strlen(p)+1)) == NULL) {
+ DEBUG(0, ("Could not allocate space for a cliplist item, # %i\n", i));
+ error = 1;
+ } else {
+ unfixtarname(tmpstr, p, strlen(p) + 1, True);
+ cliplist[i] = tmpstr;
+ if ((p = strchr_m(p, '\000')) == NULL) {
+ DEBUG(0,("INTERNAL ERROR: inclusion_buffer is of unexpected contents.\n"));
+ abort();
+ }
+ }
+ ++p;
+ }
+ must_free_cliplist = True;
+ }
+ }
+
+ SAFE_FREE(inclusion_buffer);
+ if (error) {
+ if (cliplist) {
+ char **pp;
+ /* We know cliplist is always null-terminated */
+ for (pp = cliplist; *pp; ++pp) {
+ SAFE_FREE(*pp);
+ }
+ SAFE_FREE(cliplist);
+ cliplist = NULL;
+ must_free_cliplist = False;
+ }
+ return 0;
+ }
+
+ /* cliplist and its elements are freed at the end of process_tar. */
+ return 1;
+}
+
+/****************************************************************************
+Parse tar arguments. Sets tar_type, tar_excl, etc.
+***************************************************************************/
+
+int tar_parseargs(int argc, char *argv[], const char *Optarg, int Optind)
+{
+ int newOptind = Optind;
+ char tar_clipfl='\0';
+
+ /* Reset back to defaults - could be from interactive version
+ * reset mode and archive mode left as they are though
+ */
+ tar_type='\0';
+ tar_excl=True;
+ dry_run=False;
+
+ while (*Optarg) {
+ switch(*Optarg++) {
+ case 'c':
+ tar_type='c';
+ break;
+ case 'x':
+ if (tar_type=='c') {
+ printf("Tar must be followed by only one of c or x.\n");
+ return 0;
+ }
+ tar_type='x';
+ break;
+ case 'b':
+ if (Optind>=argc || !(blocksize=atoi(argv[Optind]))) {
+ DEBUG(0,("Option b must be followed by valid blocksize\n"));
+ return 0;
+ } else {
+ Optind++;
+ newOptind++;
+ }
+ break;
+ case 'g':
+ tar_inc=True;
+ break;
+ case 'N':
+ if (Optind>=argc) {
+ DEBUG(0,("Option N must be followed by valid file name\n"));
+ return 0;
+ } else {
+ SMB_STRUCT_STAT stbuf;
+
+ if (sys_stat(argv[Optind], &stbuf) == 0) {
+ newer_than = stbuf.st_mtime;
+ DEBUG(1,("Getting files newer than %s",
+ time_to_asc(newer_than)));
+ newOptind++;
+ Optind++;
+ } else {
+ DEBUG(0,("Error setting newer-than time\n"));
+ return 0;
+ }
+ }
+ break;
+ case 'a':
+ tar_reset=True;
+ break;
+ case 'q':
+ tar_noisy=False;
+ break;
+ case 'I':
+ if (tar_clipfl) {
+ DEBUG(0,("Only one of I,X,F must be specified\n"));
+ return 0;
+ }
+ tar_clipfl='I';
+ break;
+ case 'X':
+ if (tar_clipfl) {
+ DEBUG(0,("Only one of I,X,F must be specified\n"));
+ return 0;
+ }
+ tar_clipfl='X';
+ break;
+ case 'F':
+ if (tar_clipfl) {
+ DEBUG(0,("Only one of I,X,F must be specified\n"));
+ return 0;
+ }
+ tar_clipfl='F';
+ break;
+ case 'r':
+ DEBUG(0, ("tar_re_search set\n"));
+ tar_re_search = True;
+ break;
+ case 'n':
+ if (tar_type == 'c') {
+ DEBUG(0, ("dry_run set\n"));
+ dry_run = True;
+ } else {
+ DEBUG(0, ("n is only meaningful when creating a tar-file\n"));
+ return 0;
+ }
+ break;
+ default:
+ DEBUG(0,("Unknown tar option\n"));
+ return 0;
+ }
+ }
+
+ if (!tar_type) {
+ printf("Option T must be followed by one of c or x.\n");
+ return 0;
+ }
+
+ /* tar_excl is true if cliplist lists files to be included.
+ * Both 'I' and 'F' mean include. */
+ tar_excl=tar_clipfl!='X';
+
+ if (tar_clipfl=='F') {
+ if (argc-Optind-1 != 1) {
+ DEBUG(0,("Option F must be followed by exactly one filename.\n"));
+ return 0;
+ }
+ newOptind++;
+ /* Optind points at the tar output file, Optind+1 at the inclusion file. */
+ if (! read_inclusion_file(argv[Optind+1])) {
+ return 0;
+ }
+ } else if (Optind+1<argc && !tar_re_search) { /* For backwards compatibility */
+ char *tmpstr;
+ char **tmplist;
+ int clipcount;
+
+ cliplist=argv+Optind+1;
+ clipn=argc-Optind-1;
+ clipcount = clipn;
+
+ if ((tmplist=SMB_MALLOC_ARRAY(char *,clipn)) == NULL) {
+ DEBUG(0, ("Could not allocate space to process cliplist, count = %i\n", clipn));
+ return 0;
+ }
+
+ for (clipcount = 0; clipcount < clipn; clipcount++) {
+
+ DEBUG(5, ("Processing an item, %s\n", cliplist[clipcount]));
+
+ if ((tmpstr = (char *)SMB_MALLOC(strlen(cliplist[clipcount])+1)) == NULL) {
+ DEBUG(0, ("Could not allocate space for a cliplist item, # %i\n", clipcount));
+ SAFE_FREE(tmplist);
+ return 0;
+ }
+
+ unfixtarname(tmpstr, cliplist[clipcount], strlen(cliplist[clipcount]) + 1, True);
+ tmplist[clipcount] = tmpstr;
+ DEBUG(5, ("Processed an item, %s\n", tmpstr));
+
+ DEBUG(5, ("Cliplist is: %s\n", cliplist[0]));
+ }
+
+ cliplist = tmplist;
+ must_free_cliplist = True;
+
+ newOptind += clipn;
+ }
+
+ if (Optind+1<argc && tar_re_search && tar_clipfl != 'F') {
+ /* Doing regular expression seaches not from an inclusion file. */
+ clipn=argc-Optind-1;
+ cliplist=argv+Optind+1;
+ newOptind += clipn;
+ }
+
+ if (Optind>=argc || !strcmp(argv[Optind], "-")) {
+ /* Sets tar handle to either 0 or 1, as appropriate */
+ tarhandle=(tar_type=='c');
+ /*
+ * Make sure that dbf points to stderr if we are using stdout for
+ * tar output
+ */
+ if (tarhandle == 1) {
+ dbf = x_stderr;
+ }
+ if (!argv[Optind]) {
+ DEBUG(0,("Must specify tar filename\n"));
+ return 0;
+ }
+ if (!strcmp(argv[Optind], "-")) {
+ newOptind++;
+ }
+
+ } else {
+ if (tar_type=='c' && dry_run) {
+ tarhandle=-1;
+ } else if ((tar_type=='x' && (tarhandle = sys_open(argv[Optind], O_RDONLY, 0)) == -1)
+ || (tar_type=='c' && (tarhandle=sys_creat(argv[Optind], 0644)) < 0)) {
+ DEBUG(0,("Error opening local file %s - %s\n", argv[Optind], strerror(errno)));
+ return(0);
+ }
+ newOptind++;
+ }
+
+ return newOptind;
+}
diff --git a/source3/client/dnsbrowse.c b/source3/client/dnsbrowse.c
new file mode 100644
index 0000000000..5e3a4de9cf
--- /dev/null
+++ b/source3/client/dnsbrowse.c
@@ -0,0 +1,237 @@
+/*
+ Unix SMB/CIFS implementation.
+ DNS-SD browse client
+ Copyright (C) Rishi Srivatsavai 2007
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "includes.h"
+#include "client/client_proto.h"
+
+#ifdef WITH_DNSSD_SUPPORT
+
+#include <dns_sd.h>
+
+/* Holds service instances found during DNS browse */
+struct mdns_smbsrv_result
+{
+ char *serviceName;
+ char *regType;
+ char *domain;
+ uint32_t ifIndex;
+ struct mdns_smbsrv_result *nextResult;
+};
+
+/* Maintains state during DNS browse */
+struct mdns_browse_state
+{
+ struct mdns_smbsrv_result *listhead; /* Browse result list head */
+ int browseDone;
+
+};
+
+
+static void
+do_smb_resolve_reply (DNSServiceRef sdRef, DNSServiceFlags flags,
+ uint32_t interfaceIndex, DNSServiceErrorType errorCode,
+ const char *fullname, const char *hosttarget, uint16_t port,
+ uint16_t txtLen, const unsigned char *txtRecord, void *context)
+{
+ printf("SMB service available on %s port %u\n",
+ hosttarget, ntohs(port));
+}
+
+
+static void do_smb_resolve(struct mdns_smbsrv_result *browsesrv)
+{
+ DNSServiceRef mdns_conn_sdref = NULL;
+ int mdnsfd;
+ int fdsetsz;
+ int ret;
+ fd_set *fdset = NULL;
+ struct timeval tv;
+ DNSServiceErrorType err;
+
+ TALLOC_CTX * ctx = talloc_tos();
+
+ err = DNSServiceResolve(&mdns_conn_sdref, 0 /* flags */,
+ browsesrv->ifIndex,
+ browsesrv->serviceName, browsesrv->regType, browsesrv->domain,
+ do_smb_resolve_reply, NULL);
+
+ if (err != kDNSServiceErr_NoError) {
+ return;
+ }
+
+ mdnsfd = DNSServiceRefSockFD(mdns_conn_sdref);
+ for (;;) {
+ if (fdset != NULL) {
+ TALLOC_FREE(fdset);
+ }
+
+ fdsetsz = howmany(mdnsfd + 1, NFDBITS) * sizeof(fd_mask);
+ fdset = TALLOC_ZERO(ctx, fdsetsz);
+ FD_SET(mdnsfd, fdset);
+
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+
+ /* Wait until response received from mDNS daemon */
+ ret = sys_select(mdnsfd + 1, fdset, NULL, NULL, &tv);
+ if (ret <= 0 && errno != EINTR) {
+ break;
+ }
+
+ if (FD_ISSET(mdnsfd, fdset)) {
+ /* Invoke callback function */
+ DNSServiceProcessResult(mdns_conn_sdref);
+ break;
+ }
+ }
+
+ TALLOC_FREE(fdset);
+ DNSServiceRefDeallocate(mdns_conn_sdref);
+}
+
+
+static void
+do_smb_browse_reply(DNSServiceRef sdRef, DNSServiceFlags flags,
+ uint32_t interfaceIndex, DNSServiceErrorType errorCode,
+ const char *serviceName, const char *regtype,
+ const char *replyDomain, void *context)
+{
+ struct mdns_browse_state *bstatep = (struct mdns_browse_state *)context;
+ struct mdns_smbsrv_result *bresult;
+
+ if (bstatep == NULL) {
+ return;
+ }
+
+ if (errorCode != kDNSServiceErr_NoError) {
+ bstatep->browseDone = 1;
+ return;
+ }
+
+ if (flags & kDNSServiceFlagsMoreComing) {
+ bstatep->browseDone = 0;
+ } else {
+ bstatep->browseDone = 1;
+ }
+
+ if (!(flags & kDNSServiceFlagsAdd)) {
+ return;
+ }
+
+ bresult = TALLOC_ARRAY(talloc_tos(), struct mdns_smbsrv_result, 1);
+ if (bresult == NULL) {
+ return;
+ }
+
+ if (bstatep->listhead != NULL) {
+ bresult->nextResult = bstatep->listhead;
+ }
+
+ bresult->serviceName = talloc_strdup(talloc_tos(), serviceName);
+ bresult->regType = talloc_strdup(talloc_tos(), regtype);
+ bresult->domain = talloc_strdup(talloc_tos(), replyDomain);
+ bresult->ifIndex = interfaceIndex;
+ bstatep->listhead = bresult;
+}
+
+int do_smb_browse(void)
+{
+ int mdnsfd;
+ int fdsetsz;
+ int ret;
+ fd_set *fdset = NULL;
+ struct mdns_browse_state bstate;
+ struct mdns_smbsrv_result *resptr;
+ struct timeval tv;
+ DNSServiceRef mdns_conn_sdref = NULL;
+ DNSServiceErrorType err;
+
+ TALLOC_CTX * ctx = talloc_stackframe();
+
+ ZERO_STRUCT(bstate);
+
+ err = DNSServiceBrowse(&mdns_conn_sdref, 0, 0, "_smb._tcp", "",
+ do_smb_browse_reply, &bstate);
+
+ if (err != kDNSServiceErr_NoError) {
+ d_printf("Error connecting to the Multicast DNS daemon\n");
+ TALLOC_FREE(ctx);
+ return 1;
+ }
+
+ mdnsfd = DNSServiceRefSockFD(mdns_conn_sdref);
+ for (;;) {
+ if (fdset != NULL) {
+ TALLOC_FREE(fdset);
+ }
+
+ fdsetsz = howmany(mdnsfd + 1, NFDBITS) * sizeof(fd_mask);
+ fdset = TALLOC_ZERO(ctx, fdsetsz);
+ FD_SET(mdnsfd, fdset);
+
+ tv.tv_sec = 1;
+ tv.tv_usec = 0;
+
+ /* Wait until response received from mDNS daemon */
+ ret = sys_select(mdnsfd + 1, fdset, NULL, NULL, &tv);
+ if (ret <= 0 && errno != EINTR) {
+ break;
+ }
+
+ if (FD_ISSET(mdnsfd, fdset)) {
+ /* Invoke callback function */
+ if (DNSServiceProcessResult(mdns_conn_sdref)) {
+ break;
+ }
+ if (bstate.browseDone) {
+ break;
+ }
+ }
+ }
+
+ DNSServiceRefDeallocate(mdns_conn_sdref);
+
+ if (bstate.listhead != NULL) {
+ resptr = bstate.listhead;
+ while (resptr != NULL) {
+ struct mdns_smbsrv_result *oldresptr;
+ oldresptr = resptr;
+
+ /* Resolve smb service instance */
+ do_smb_resolve(resptr);
+
+ resptr = resptr->nextResult;
+ }
+ }
+
+ TALLOC_FREE(ctx);
+ return 0;
+}
+
+#else /* WITH_DNSSD_SUPPORT */
+
+int do_smb_browse(void)
+{
+ d_printf("DNS-SD browsing is not supported on this platform\n");
+ return 1;
+}
+
+#endif /* WITH_DNSSD_SUPPORT */
+
+
diff --git a/source3/client/mount.cifs.c b/source3/client/mount.cifs.c
new file mode 100644
index 0000000000..3b56e5f861
--- /dev/null
+++ b/source3/client/mount.cifs.c
@@ -0,0 +1,1449 @@
+/*
+ Mount helper utility for Linux CIFS VFS (virtual filesystem) client
+ Copyright (C) 2003,2008 Steve French (sfrench@us.ibm.com)
+ Copyright (C) 2008 Jeremy Allison (jra@samba.org)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <pwd.h>
+#include <grp.h>
+#include <ctype.h>
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <sys/stat.h>
+#include <sys/utsname.h>
+#include <sys/socket.h>
+#include <arpa/inet.h>
+#include <getopt.h>
+#include <errno.h>
+#include <netdb.h>
+#include <string.h>
+#include <mntent.h>
+#include <fcntl.h>
+#include <limits.h>
+
+#define MOUNT_CIFS_VERSION_MAJOR "1"
+#define MOUNT_CIFS_VERSION_MINOR "11"
+
+#ifndef MOUNT_CIFS_VENDOR_SUFFIX
+ #ifdef _SAMBA_BUILD_
+ #include "include/version.h"
+ #ifdef SAMBA_VERSION_VENDOR_SUFFIX
+ #define MOUNT_CIFS_VENDOR_SUFFIX "-"SAMBA_VERSION_OFFICIAL_STRING"-"SAMBA_VERSION_VENDOR_SUFFIX
+ #else
+ #define MOUNT_CIFS_VENDOR_SUFFIX "-"SAMBA_VERSION_OFFICIAL_STRING
+ #endif /* SAMBA_VERSION_OFFICIAL_STRING and SAMBA_VERSION_VENDOR_SUFFIX */
+ #else
+ #define MOUNT_CIFS_VENDOR_SUFFIX ""
+ #endif /* _SAMBA_BUILD_ */
+#endif /* MOUNT_CIFS_VENDOR_SUFFIX */
+
+#ifndef MS_MOVE
+#define MS_MOVE 8192
+#endif
+
+#ifndef MS_BIND
+#define MS_BIND 4096
+#endif
+
+#define MAX_UNC_LEN 1024
+
+#define CONST_DISCARD(type, ptr) ((type) ((void *) (ptr)))
+
+#ifndef SAFE_FREE
+#define SAFE_FREE(x) do { if ((x) != NULL) {free(x); x=NULL;} } while(0)
+#endif
+
+#define MOUNT_PASSWD_SIZE 64
+#define DOMAIN_SIZE 64
+
+const char *thisprogram;
+int verboseflag = 0;
+static int got_password = 0;
+static int got_user = 0;
+static int got_domain = 0;
+static int got_ip = 0;
+static int got_unc = 0;
+static int got_uid = 0;
+static int got_gid = 0;
+static char * user_name = NULL;
+static char * mountpassword = NULL;
+char * domain_name = NULL;
+char * prefixpath = NULL;
+
+/* glibc doesn't have strlcpy, strlcat. Ensure we do. JRA. We
+ * don't link to libreplace so need them here. */
+
+/* like strncpy but does not 0 fill the buffer and always null
+ * terminates. bufsize is the size of the destination buffer */
+static size_t strlcpy(char *d, const char *s, size_t bufsize)
+{
+ size_t len = strlen(s);
+ size_t ret = len;
+ if (bufsize <= 0) return 0;
+ if (len >= bufsize) len = bufsize-1;
+ memcpy(d, s, len);
+ d[len] = 0;
+ return ret;
+}
+
+/* like strncat but does not 0 fill the buffer and always null
+ * terminates. bufsize is the length of the buffer, which should
+ * be one more than the maximum resulting string length */
+static size_t strlcat(char *d, const char *s, size_t bufsize)
+{
+ size_t len1 = strlen(d);
+ size_t len2 = strlen(s);
+ size_t ret = len1 + len2;
+
+ if (len1+len2 >= bufsize) {
+ if (bufsize < (len1+1)) {
+ return ret;
+ }
+ len2 = bufsize - (len1+1);
+ }
+ if (len2 > 0) {
+ memcpy(d+len1, s, len2);
+ d[len1+len2] = 0;
+ }
+ return ret;
+}
+
+/* BB finish BB
+
+ cifs_umount
+ open nofollow - avoid symlink exposure?
+ get owner of dir see if matches self or if root
+ call system(umount argv) etc.
+
+BB end finish BB */
+
+static char * check_for_domain(char **);
+
+
+static void mount_cifs_usage(void)
+{
+ printf("\nUsage: %s <remotetarget> <dir> -o <options>\n", thisprogram);
+ printf("\nMount the remote target, specified as a UNC name,");
+ printf(" to a local directory.\n\nOptions:\n");
+ printf("\tuser=<arg>\n\tpass=<arg>\n\tdom=<arg>\n");
+ printf("\nLess commonly used options:");
+ printf("\n\tcredentials=<filename>,guest,perm,noperm,setuids,nosetuids,rw,ro,");
+ printf("\n\tsep=<char>,iocharset=<codepage>,suid,nosuid,exec,noexec,serverino,");
+ printf("\n\tmapchars,nomapchars,nolock,servernetbiosname=<SRV_RFC1001NAME>");
+ printf("\n\tdirectio,nounix,cifsacl,sec=<authentication mechanism>,sign");
+ printf("\n\nOptions not needed for servers supporting CIFS Unix extensions");
+ printf("\n\t(e.g. unneeded for mounts to most Samba versions):");
+ printf("\n\tuid=<uid>,gid=<gid>,dir_mode=<mode>,file_mode=<mode>,sfu");
+ printf("\n\nRarely used options:");
+ printf("\n\tport=<tcpport>,rsize=<size>,wsize=<size>,unc=<unc_name>,ip=<ip_address>,");
+ printf("\n\tdev,nodev,nouser_xattr,netbiosname=<OUR_RFC1001NAME>,hard,soft,intr,");
+ printf("\n\tnointr,ignorecase,noposixpaths,noacl,prefixpath=<path>,nobrl");
+ printf("\n\tin6_addr");
+ printf("\n\nOptions are described in more detail in the manual page");
+ printf("\n\tman 8 mount.cifs\n");
+ printf("\nTo display the version number of the mount helper:");
+ printf("\n\t%s -V\n",thisprogram);
+
+ SAFE_FREE(mountpassword);
+ exit(1);
+}
+
+/* caller frees username if necessary */
+static char * getusername(void) {
+ char *username = NULL;
+ struct passwd *password = getpwuid(getuid());
+
+ if (password) {
+ username = password->pw_name;
+ }
+ return username;
+}
+
+static char * parse_cifs_url(char * unc_name)
+{
+ printf("\nMounting cifs URL not implemented yet. Attempt to mount %s\n",unc_name);
+ return NULL;
+}
+
+static int open_cred_file(char * file_name)
+{
+ char * line_buf;
+ char * temp_val;
+ FILE * fs;
+ int i, length;
+ fs = fopen(file_name,"r");
+ if(fs == NULL)
+ return errno;
+ line_buf = (char *)malloc(4096);
+ if(line_buf == NULL) {
+ fclose(fs);
+ return ENOMEM;
+ }
+
+ while(fgets(line_buf,4096,fs)) {
+ /* parse line from credential file */
+
+ /* eat leading white space */
+ for(i=0;i<4086;i++) {
+ if((line_buf[i] != ' ') && (line_buf[i] != '\t'))
+ break;
+ /* if whitespace - skip past it */
+ }
+ if (strncasecmp("username",line_buf+i,8) == 0) {
+ temp_val = strchr(line_buf + i,'=');
+ if(temp_val) {
+ /* go past equals sign */
+ temp_val++;
+ for(length = 0;length<4087;length++) {
+ if ((temp_val[length] == '\n')
+ || (temp_val[length] == '\0')) {
+ temp_val[length] = '\0';
+ break;
+ }
+ }
+ if(length > 4086) {
+ printf("mount.cifs failed due to malformed username in credentials file");
+ memset(line_buf,0,4096);
+ exit(1);
+ } else {
+ got_user = 1;
+ user_name = (char *)calloc(1 + length,1);
+ /* BB adding free of user_name string before exit,
+ not really necessary but would be cleaner */
+ strlcpy(user_name,temp_val, length+1);
+ }
+ }
+ } else if (strncasecmp("password",line_buf+i,8) == 0) {
+ temp_val = strchr(line_buf+i,'=');
+ if(temp_val) {
+ /* go past equals sign */
+ temp_val++;
+ for(length = 0;length<MOUNT_PASSWD_SIZE+1;length++) {
+ if ((temp_val[length] == '\n')
+ || (temp_val[length] == '\0')) {
+ temp_val[length] = '\0';
+ break;
+ }
+ }
+ if(length > MOUNT_PASSWD_SIZE) {
+ printf("mount.cifs failed: password in credentials file too long\n");
+ memset(line_buf,0, 4096);
+ exit(1);
+ } else {
+ if(mountpassword == NULL) {
+ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
+ } else
+ memset(mountpassword,0,MOUNT_PASSWD_SIZE);
+ if(mountpassword) {
+ strlcpy(mountpassword,temp_val,MOUNT_PASSWD_SIZE+1);
+ got_password = 1;
+ }
+ }
+ }
+ } else if (strncasecmp("domain",line_buf+i,6) == 0) {
+ temp_val = strchr(line_buf+i,'=');
+ if(temp_val) {
+ /* go past equals sign */
+ temp_val++;
+ if(verboseflag)
+ printf("\nDomain %s\n",temp_val);
+ for(length = 0;length<DOMAIN_SIZE+1;length++) {
+ if ((temp_val[length] == '\n')
+ || (temp_val[length] == '\0')) {
+ temp_val[length] = '\0';
+ break;
+ }
+ }
+ if(length > DOMAIN_SIZE) {
+ printf("mount.cifs failed: domain in credentials file too long\n");
+ exit(1);
+ } else {
+ if(domain_name == NULL) {
+ domain_name = (char *)calloc(DOMAIN_SIZE+1,1);
+ } else
+ memset(domain_name,0,DOMAIN_SIZE);
+ if(domain_name) {
+ strlcpy(domain_name,temp_val,DOMAIN_SIZE+1);
+ got_domain = 1;
+ }
+ }
+ }
+ }
+
+ }
+ fclose(fs);
+ SAFE_FREE(line_buf);
+ return 0;
+}
+
+static int get_password_from_file(int file_descript, char * filename)
+{
+ int rc = 0;
+ int i;
+ char c;
+
+ if(mountpassword == NULL)
+ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
+ else
+ memset(mountpassword, 0, MOUNT_PASSWD_SIZE);
+
+ if (mountpassword == NULL) {
+ printf("malloc failed\n");
+ exit(1);
+ }
+
+ if(filename != NULL) {
+ file_descript = open(filename, O_RDONLY);
+ if(file_descript < 0) {
+ printf("mount.cifs failed. %s attempting to open password file %s\n",
+ strerror(errno),filename);
+ exit(1);
+ }
+ }
+ /* else file already open and fd provided */
+
+ for(i=0;i<MOUNT_PASSWD_SIZE;i++) {
+ rc = read(file_descript,&c,1);
+ if(rc < 0) {
+ printf("mount.cifs failed. Error %s reading password file\n",strerror(errno));
+ if(filename != NULL)
+ close(file_descript);
+ exit(1);
+ } else if(rc == 0) {
+ if(mountpassword[0] == 0) {
+ if(verboseflag)
+ printf("\nWarning: null password used since cifs password file empty");
+ }
+ break;
+ } else /* read valid character */ {
+ if((c == 0) || (c == '\n')) {
+ mountpassword[i] = '\0';
+ break;
+ } else
+ mountpassword[i] = c;
+ }
+ }
+ if((i == MOUNT_PASSWD_SIZE) && (verboseflag)) {
+ printf("\nWarning: password longer than %d characters specified in cifs password file",
+ MOUNT_PASSWD_SIZE);
+ }
+ got_password = 1;
+ if(filename != NULL) {
+ close(file_descript);
+ }
+
+ return rc;
+}
+
+static int parse_options(char ** optionsp, int * filesys_flags)
+{
+ const char * data;
+ char * percent_char = NULL;
+ char * value = NULL;
+ char * next_keyword = NULL;
+ char * out = NULL;
+ int out_len = 0;
+ int word_len;
+ int rc = 0;
+ char user[32];
+ char group[32];
+
+ if (!optionsp || !*optionsp)
+ return 1;
+ data = *optionsp;
+
+ if(verboseflag)
+ printf("parsing options: %s\n", data);
+
+ /* BB fixme check for separator override BB */
+
+ if (getuid()) {
+ got_uid = 1;
+ snprintf(user,sizeof(user),"%u",getuid());
+ got_gid = 1;
+ snprintf(group,sizeof(group),"%u",getgid());
+ }
+
+/* while ((data = strsep(&options, ",")) != NULL) { */
+ while(data != NULL) {
+ /* check if ends with trailing comma */
+ if(*data == 0)
+ break;
+
+ /* format is keyword=value,keyword2=value2,keyword3=value3 etc.) */
+ /* data = next keyword */
+ /* value = next value ie stuff after equal sign */
+
+ next_keyword = strchr(data,','); /* BB handle sep= */
+
+ /* temporarily null terminate end of keyword=value pair */
+ if(next_keyword)
+ *next_keyword++ = 0;
+
+ /* temporarily null terminate keyword to make keyword and value distinct */
+ if ((value = strchr(data, '=')) != NULL) {
+ *value = '\0';
+ value++;
+ }
+
+ if (strncmp(data, "users",5) == 0) {
+ if(!value || !*value) {
+ goto nocopy;
+ }
+ } else if (strncmp(data, "user_xattr",10) == 0) {
+ /* do nothing - need to skip so not parsed as user name */
+ } else if (strncmp(data, "user", 4) == 0) {
+
+ if (!value || !*value) {
+ if(data[4] == '\0') {
+ if(verboseflag)
+ printf("\nskipping empty user mount parameter\n");
+ /* remove the parm since it would otherwise be confusing
+ to the kernel code which would think it was a real username */
+ goto nocopy;
+ } else {
+ printf("username specified with no parameter\n");
+ return 1; /* needs_arg; */
+ }
+ } else {
+ if (strnlen(value, 260) < 260) {
+ got_user=1;
+ percent_char = strchr(value,'%');
+ if(percent_char) {
+ *percent_char = ',';
+ if(mountpassword == NULL)
+ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
+ if(mountpassword) {
+ if(got_password)
+ printf("\nmount.cifs warning - password specified twice\n");
+ got_password = 1;
+ percent_char++;
+ strlcpy(mountpassword, percent_char,MOUNT_PASSWD_SIZE+1);
+ /* remove password from username */
+ while(*percent_char != 0) {
+ *percent_char = ',';
+ percent_char++;
+ }
+ }
+ }
+ /* this is only case in which the user
+ name buf is not malloc - so we have to
+ check for domain name embedded within
+ the user name here since the later
+ call to check_for_domain will not be
+ invoked */
+ domain_name = check_for_domain(&value);
+ } else {
+ printf("username too long\n");
+ return 1;
+ }
+ }
+ } else if (strncmp(data, "pass", 4) == 0) {
+ if (!value || !*value) {
+ if(got_password) {
+ printf("\npassword specified twice, ignoring second\n");
+ } else
+ got_password = 1;
+ } else if (strnlen(value, 17) < 17) {
+ if(got_password)
+ printf("\nmount.cifs warning - password specified twice\n");
+ got_password = 1;
+ } else {
+ printf("password too long\n");
+ return 1;
+ }
+ } else if (strncmp(data, "sec", 3) == 0) {
+ if (value) {
+ if (!strncmp(value, "none", 4) ||
+ !strncmp(value, "krb5", 4))
+ got_password = 1;
+ }
+ } else if (strncmp(data, "ip", 2) == 0) {
+ if (!value || !*value) {
+ printf("target ip address argument missing");
+ } else if (strnlen(value, 35) < 35) {
+ if(verboseflag)
+ printf("ip address %s override specified\n",value);
+ got_ip = 1;
+ } else {
+ printf("ip address too long\n");
+ return 1;
+ }
+ } else if ((strncmp(data, "unc", 3) == 0)
+ || (strncmp(data, "target", 6) == 0)
+ || (strncmp(data, "path", 4) == 0)) {
+ if (!value || !*value) {
+ printf("invalid path to network resource\n");
+ return 1; /* needs_arg; */
+ } else if(strnlen(value,5) < 5) {
+ printf("UNC name too short");
+ }
+
+ if (strnlen(value, 300) < 300) {
+ got_unc = 1;
+ if (strncmp(value, "//", 2) == 0) {
+ if(got_unc)
+ printf("unc name specified twice, ignoring second\n");
+ else
+ got_unc = 1;
+ } else if (strncmp(value, "\\\\", 2) != 0) {
+ printf("UNC Path does not begin with // or \\\\ \n");
+ return 1;
+ } else {
+ if(got_unc)
+ printf("unc name specified twice, ignoring second\n");
+ else
+ got_unc = 1;
+ }
+ } else {
+ printf("CIFS: UNC name too long\n");
+ return 1;
+ }
+ } else if ((strncmp(data, "dom" /* domain */, 3) == 0)
+ || (strncmp(data, "workg", 5) == 0)) {
+ /* note this allows for synonyms of "domain"
+ such as "DOM" and "dom" and "workgroup"
+ and "WORKGRP" etc. */
+ if (!value || !*value) {
+ printf("CIFS: invalid domain name\n");
+ return 1; /* needs_arg; */
+ }
+ if (strnlen(value, DOMAIN_SIZE+1) < DOMAIN_SIZE+1) {
+ got_domain = 1;
+ } else {
+ printf("domain name too long\n");
+ return 1;
+ }
+ } else if (strncmp(data, "cred", 4) == 0) {
+ if (value && *value) {
+ rc = open_cred_file(value);
+ if(rc) {
+ printf("error %d (%s) opening credential file %s\n",
+ rc, strerror(rc), value);
+ return 1;
+ }
+ } else {
+ printf("invalid credential file name specified\n");
+ return 1;
+ }
+ } else if (strncmp(data, "uid", 3) == 0) {
+ if (value && *value) {
+ got_uid = 1;
+ if (!isdigit(*value)) {
+ struct passwd *pw;
+
+ if (!(pw = getpwnam(value))) {
+ printf("bad user name \"%s\"\n", value);
+ exit(1);
+ }
+ snprintf(user, sizeof(user), "%u", pw->pw_uid);
+ } else {
+ strlcpy(user,value,sizeof(user));
+ }
+ }
+ goto nocopy;
+ } else if (strncmp(data, "gid", 3) == 0) {
+ if (value && *value) {
+ got_gid = 1;
+ if (!isdigit(*value)) {
+ struct group *gr;
+
+ if (!(gr = getgrnam(value))) {
+ printf("bad group name \"%s\"\n", value);
+ exit(1);
+ }
+ snprintf(group, sizeof(group), "%u", gr->gr_gid);
+ } else {
+ strlcpy(group,value,sizeof(group));
+ }
+ }
+ goto nocopy;
+ /* fmask and dmask synonyms for people used to smbfs syntax */
+ } else if (strcmp(data, "file_mode") == 0 || strcmp(data, "fmask")==0) {
+ if (!value || !*value) {
+ printf ("Option '%s' requires a numerical argument\n", data);
+ return 1;
+ }
+
+ if (value[0] != '0') {
+ printf ("WARNING: '%s' not expressed in octal.\n", data);
+ }
+
+ if (strcmp (data, "fmask") == 0) {
+ printf ("WARNING: CIFS mount option 'fmask' is deprecated. Use 'file_mode' instead.\n");
+ data = "file_mode"; /* BB fix this */
+ }
+ } else if (strcmp(data, "dir_mode") == 0 || strcmp(data, "dmask")==0) {
+ if (!value || !*value) {
+ printf ("Option '%s' requires a numerical argument\n", data);
+ return 1;
+ }
+
+ if (value[0] != '0') {
+ printf ("WARNING: '%s' not expressed in octal.\n", data);
+ }
+
+ if (strcmp (data, "dmask") == 0) {
+ printf ("WARNING: CIFS mount option 'dmask' is deprecated. Use 'dir_mode' instead.\n");
+ data = "dir_mode";
+ }
+ /* the following eight mount options should be
+ stripped out from what is passed into the kernel
+ since these eight options are best passed as the
+ mount flags rather than redundantly to the kernel
+ and could generate spurious warnings depending on the
+ level of the corresponding cifs vfs kernel code */
+ } else if (strncmp(data, "nosuid", 6) == 0) {
+ *filesys_flags |= MS_NOSUID;
+ } else if (strncmp(data, "suid", 4) == 0) {
+ *filesys_flags &= ~MS_NOSUID;
+ } else if (strncmp(data, "nodev", 5) == 0) {
+ *filesys_flags |= MS_NODEV;
+ } else if ((strncmp(data, "nobrl", 5) == 0) ||
+ (strncmp(data, "nolock", 6) == 0)) {
+ *filesys_flags &= ~MS_MANDLOCK;
+ } else if (strncmp(data, "dev", 3) == 0) {
+ *filesys_flags &= ~MS_NODEV;
+ } else if (strncmp(data, "noexec", 6) == 0) {
+ *filesys_flags |= MS_NOEXEC;
+ } else if (strncmp(data, "exec", 4) == 0) {
+ *filesys_flags &= ~MS_NOEXEC;
+ } else if (strncmp(data, "guest", 5) == 0) {
+ got_password=1;
+ } else if (strncmp(data, "ro", 2) == 0) {
+ *filesys_flags |= MS_RDONLY;
+ } else if (strncmp(data, "rw", 2) == 0) {
+ *filesys_flags &= ~MS_RDONLY;
+ } else if (strncmp(data, "remount", 7) == 0) {
+ *filesys_flags |= MS_REMOUNT;
+ } /* else if (strnicmp(data, "port", 4) == 0) {
+ if (value && *value) {
+ vol->port =
+ simple_strtoul(value, &value, 0);
+ }
+ } else if (strnicmp(data, "rsize", 5) == 0) {
+ if (value && *value) {
+ vol->rsize =
+ simple_strtoul(value, &value, 0);
+ }
+ } else if (strnicmp(data, "wsize", 5) == 0) {
+ if (value && *value) {
+ vol->wsize =
+ simple_strtoul(value, &value, 0);
+ }
+ } else if (strnicmp(data, "version", 3) == 0) {
+ } else {
+ printf("CIFS: Unknown mount option %s\n",data);
+ } */ /* nothing to do on those four mount options above.
+ Just pass to kernel and ignore them here */
+
+ /* Copy (possibly modified) option to out */
+ word_len = strlen(data);
+ if (value)
+ word_len += 1 + strlen(value);
+
+ out = (char *)realloc(out, out_len + word_len + 2);
+ if (out == NULL) {
+ perror("malloc");
+ exit(1);
+ }
+
+ if (out_len) {
+ strlcat(out, ",", out_len + word_len + 2);
+ out_len++;
+ }
+
+ if (value)
+ snprintf(out + out_len, word_len + 1, "%s=%s", data, value);
+ else
+ snprintf(out + out_len, word_len + 1, "%s", data);
+ out_len = strlen(out);
+
+nocopy:
+ data = next_keyword;
+ }
+
+ /* special-case the uid and gid */
+ if (got_uid) {
+ word_len = strlen(user);
+
+ out = (char *)realloc(out, out_len + word_len + 6);
+ if (out == NULL) {
+ perror("malloc");
+ exit(1);
+ }
+
+ if (out_len) {
+ strlcat(out, ",", out_len + word_len + 6);
+ out_len++;
+ }
+ snprintf(out + out_len, word_len + 5, "uid=%s", user);
+ out_len = strlen(out);
+ }
+ if (got_gid) {
+ word_len = strlen(group);
+
+ out = (char *)realloc(out, out_len + 1 + word_len + 6);
+ if (out == NULL) {
+ perror("malloc");
+ exit(1);
+ }
+
+ if (out_len) {
+ strlcat(out, ",", out_len + word_len + 6);
+ out_len++;
+ }
+ snprintf(out + out_len, word_len + 5, "gid=%s", group);
+ out_len = strlen(out);
+ }
+
+ SAFE_FREE(*optionsp);
+ *optionsp = out;
+ return 0;
+}
+
+/* replace all (one or more) commas with double commas */
+static void check_for_comma(char ** ppasswrd)
+{
+ char *new_pass_buf;
+ char *pass;
+ int i,j;
+ int number_of_commas = 0;
+ int len;
+
+ if(ppasswrd == NULL)
+ return;
+ else
+ (pass = *ppasswrd);
+
+ len = strlen(pass);
+
+ for(i=0;i<len;i++) {
+ if(pass[i] == ',')
+ number_of_commas++;
+ }
+
+ if(number_of_commas == 0)
+ return;
+ if(number_of_commas > MOUNT_PASSWD_SIZE) {
+ /* would otherwise overflow the mount options buffer */
+ printf("\nInvalid password. Password contains too many commas.\n");
+ return;
+ }
+
+ new_pass_buf = (char *)malloc(len+number_of_commas+1);
+ if(new_pass_buf == NULL)
+ return;
+
+ for(i=0,j=0;i<len;i++,j++) {
+ new_pass_buf[j] = pass[i];
+ if(pass[i] == ',') {
+ j++;
+ new_pass_buf[j] = pass[i];
+ }
+ }
+ new_pass_buf[len+number_of_commas] = 0;
+
+ SAFE_FREE(*ppasswrd);
+ *ppasswrd = new_pass_buf;
+
+ return;
+}
+
+/* Usernames can not have backslash in them and we use
+ [BB check if usernames can have forward slash in them BB]
+ backslash as domain\user separator character
+*/
+static char * check_for_domain(char **ppuser)
+{
+ char * original_string;
+ char * usernm;
+ char * domainnm;
+ int original_len;
+ int len;
+ int i;
+
+ if(ppuser == NULL)
+ return NULL;
+
+ original_string = *ppuser;
+
+ if (original_string == NULL)
+ return NULL;
+
+ original_len = strlen(original_string);
+
+ usernm = strchr(*ppuser,'/');
+ if (usernm == NULL) {
+ usernm = strchr(*ppuser,'\\');
+ if (usernm == NULL)
+ return NULL;
+ }
+
+ if(got_domain) {
+ printf("Domain name specified twice. Username probably malformed\n");
+ return NULL;
+ }
+
+ usernm[0] = 0;
+ domainnm = *ppuser;
+ if (domainnm[0] != 0) {
+ got_domain = 1;
+ } else {
+ printf("null domain\n");
+ }
+ len = strlen(domainnm);
+ /* reset domainm to new buffer, and copy
+ domain name into it */
+ domainnm = (char *)malloc(len+1);
+ if(domainnm == NULL)
+ return NULL;
+
+ strlcpy(domainnm,*ppuser,len+1);
+
+/* move_string(*ppuser, usernm+1) */
+ len = strlen(usernm+1);
+
+ if(len >= original_len) {
+ /* should not happen */
+ return domainnm;
+ }
+
+ for(i=0;i<original_len;i++) {
+ if(i<len)
+ original_string[i] = usernm[i+1];
+ else /* stuff with commas to remove last parm */
+ original_string[i] = ',';
+ }
+
+ /* BB add check for more than one slash?
+ strchr(*ppuser,'/');
+ strchr(*ppuser,'\\')
+ */
+
+ return domainnm;
+}
+
+/* replace all occurances of "from" in a string with "to" */
+static void replace_char(char *string, char from, char to, int maxlen)
+{
+ char *lastchar = string + maxlen;
+ while (string) {
+ string = strchr(string, from);
+ if (string) {
+ *string = to;
+ if (string >= lastchar)
+ return;
+ }
+ }
+}
+
+/* Note that caller frees the returned buffer if necessary */
+static char * parse_server(char ** punc_name)
+{
+ char * unc_name = *punc_name;
+ int length = strnlen(unc_name, MAX_UNC_LEN);
+ char * share;
+ char * ipaddress_string = NULL;
+ struct hostent * host_entry = NULL;
+ struct in_addr server_ipaddr;
+
+ if(length > (MAX_UNC_LEN - 1)) {
+ printf("mount error: UNC name too long");
+ return NULL;
+ }
+ if (strncasecmp("cifs://",unc_name,7) == 0)
+ return parse_cifs_url(unc_name+7);
+ if (strncasecmp("smb://",unc_name,6) == 0) {
+ return parse_cifs_url(unc_name+6);
+ }
+
+ if(length < 3) {
+ /* BB add code to find DFS root here */
+ printf("\nMounting the DFS root for domain not implemented yet\n");
+ return NULL;
+ } else {
+ if(strncmp(unc_name,"//",2) && strncmp(unc_name,"\\\\",2)) {
+ /* check for nfs syntax ie server:share */
+ share = strchr(unc_name,':');
+ if(share) {
+ *punc_name = (char *)malloc(length+3);
+ if(*punc_name == NULL) {
+ /* put the original string back if
+ no memory left */
+ *punc_name = unc_name;
+ return NULL;
+ }
+ *share = '/';
+ strlcpy((*punc_name)+2,unc_name,length+1);
+ SAFE_FREE(unc_name);
+ unc_name = *punc_name;
+ unc_name[length+2] = 0;
+ goto continue_unc_parsing;
+ } else {
+ printf("mount error: improperly formatted UNC name.");
+ printf(" %s does not begin with \\\\ or //\n",unc_name);
+ return NULL;
+ }
+ } else {
+continue_unc_parsing:
+ unc_name[0] = '/';
+ unc_name[1] = '/';
+ unc_name += 2;
+
+ /* allow for either delimiter between host and sharename */
+ if ((share = strpbrk(unc_name, "/\\"))) {
+ *share = 0; /* temporarily terminate the string */
+ share += 1;
+ if(got_ip == 0) {
+ host_entry = gethostbyname(unc_name);
+ }
+ *(share - 1) = '/'; /* put delimiter back */
+
+ /* we don't convert the prefixpath delimiters since '\\' is a valid char in posix paths */
+ if ((prefixpath = strpbrk(share, "/\\"))) {
+ *prefixpath = 0; /* permanently terminate the string */
+ if (!strlen(++prefixpath))
+ prefixpath = NULL; /* this needs to be done explicitly */
+ }
+ if(got_ip) {
+ if(verboseflag)
+ printf("ip address specified explicitly\n");
+ return NULL;
+ }
+ if(host_entry == NULL) {
+ printf("mount error: could not find target server. TCP name %s not found\n", unc_name);
+ return NULL;
+ } else {
+ /* BB should we pass an alternate version of the share name as Unicode */
+ /* BB what about ipv6? BB */
+ /* BB add retries with alternate servers in list */
+
+ memcpy(&server_ipaddr.s_addr, host_entry->h_addr, 4);
+
+ ipaddress_string = inet_ntoa(server_ipaddr);
+ if(ipaddress_string == NULL) {
+ printf("mount error: could not get valid ip address for target server\n");
+ return NULL;
+ }
+ return ipaddress_string;
+ }
+ } else {
+ /* BB add code to find DFS root (send null path on get DFS Referral to specified server here */
+ printf("Mounting the DFS root for a particular server not implemented yet\n");
+ return NULL;
+ }
+ }
+ }
+}
+
+static struct option longopts[] = {
+ { "all", 0, NULL, 'a' },
+ { "help",0, NULL, 'h' },
+ { "move",0, NULL, 'm' },
+ { "bind",0, NULL, 'b' },
+ { "read-only", 0, NULL, 'r' },
+ { "ro", 0, NULL, 'r' },
+ { "verbose", 0, NULL, 'v' },
+ { "version", 0, NULL, 'V' },
+ { "read-write", 0, NULL, 'w' },
+ { "rw", 0, NULL, 'w' },
+ { "options", 1, NULL, 'o' },
+ { "type", 1, NULL, 't' },
+ { "rsize",1, NULL, 'R' },
+ { "wsize",1, NULL, 'W' },
+ { "uid", 1, NULL, '1'},
+ { "gid", 1, NULL, '2'},
+ { "user",1,NULL,'u'},
+ { "username",1,NULL,'u'},
+ { "dom",1,NULL,'d'},
+ { "domain",1,NULL,'d'},
+ { "password",1,NULL,'p'},
+ { "pass",1,NULL,'p'},
+ { "credentials",1,NULL,'c'},
+ { "port",1,NULL,'P'},
+ /* { "uuid",1,NULL,'U'}, */ /* BB unimplemented */
+ { NULL, 0, NULL, 0 }
+};
+
+/* convert a string to uppercase. return false if the string
+ * wasn't ASCII or was a NULL ptr */
+static int
+uppercase_string(char *string)
+{
+ if (!string)
+ return 0;
+
+ while (*string) {
+ /* check for unicode */
+ if ((unsigned char) string[0] & 0x80)
+ return 0;
+ *string = toupper((unsigned char) *string);
+ string++;
+ }
+
+ return 1;
+}
+
+int main(int argc, char ** argv)
+{
+ int c;
+ int flags = MS_MANDLOCK; /* no need to set legacy MS_MGC_VAL */
+ char * orgoptions = NULL;
+ char * share_name = NULL;
+ char * ipaddr = NULL;
+ char * uuid = NULL;
+ char * mountpoint = NULL;
+ char * options = NULL;
+ char * resolved_path = NULL;
+ char * temp;
+ char * dev_name;
+ int rc;
+ int rsize = 0;
+ int wsize = 0;
+ int nomtab = 0;
+ int uid = 0;
+ int gid = 0;
+ int optlen = 0;
+ int orgoptlen = 0;
+ size_t options_size = 0;
+ int retry = 0; /* set when we have to retry mount with uppercase */
+ struct stat statbuf;
+ struct utsname sysinfo;
+ struct mntent mountent;
+ FILE * pmntfile;
+
+ /* setlocale(LC_ALL, "");
+ bindtextdomain(PACKAGE, LOCALEDIR);
+ textdomain(PACKAGE); */
+
+ if(argc && argv) {
+ thisprogram = argv[0];
+ } else {
+ mount_cifs_usage();
+ exit(1);
+ }
+
+ if(thisprogram == NULL)
+ thisprogram = "mount.cifs";
+
+ uname(&sysinfo);
+ /* BB add workstation name and domain and pass down */
+
+/* #ifdef _GNU_SOURCE
+ printf(" node: %s machine: %s sysname %s domain %s\n", sysinfo.nodename,sysinfo.machine,sysinfo.sysname,sysinfo.domainname);
+#endif */
+ if(argc > 2) {
+ dev_name = argv[1];
+ share_name = strndup(argv[1], MAX_UNC_LEN);
+ if (share_name == NULL) {
+ fprintf(stderr, "%s: %s", argv[0], strerror(ENOMEM));
+ exit(1);
+ }
+ mountpoint = argv[2];
+ } else {
+ mount_cifs_usage();
+ exit(1);
+ }
+
+ /* add sharename in opts string as unc= parm */
+
+ while ((c = getopt_long (argc, argv, "afFhilL:no:O:rsSU:vVwt:",
+ longopts, NULL)) != -1) {
+ switch (c) {
+/* No code to do the following options yet */
+/* case 'l':
+ list_with_volumelabel = 1;
+ break;
+ case 'L':
+ volumelabel = optarg;
+ break; */
+/* case 'a':
+ ++mount_all;
+ break; */
+
+ case '?':
+ case 'h': /* help */
+ mount_cifs_usage ();
+ exit(1);
+ case 'n':
+ ++nomtab;
+ break;
+ case 'b':
+#ifdef MS_BIND
+ flags |= MS_BIND;
+#else
+ fprintf(stderr,
+ "option 'b' (MS_BIND) not supported\n");
+#endif
+ break;
+ case 'm':
+#ifdef MS_MOVE
+ flags |= MS_MOVE;
+#else
+ fprintf(stderr,
+ "option 'm' (MS_MOVE) not supported\n");
+#endif
+ break;
+ case 'o':
+ orgoptions = strdup(optarg);
+ break;
+ case 'r': /* mount readonly */
+ flags |= MS_RDONLY;
+ break;
+ case 'U':
+ uuid = optarg;
+ break;
+ case 'v':
+ ++verboseflag;
+ break;
+ case 'V':
+ printf ("mount.cifs version: %s.%s%s\n",
+ MOUNT_CIFS_VERSION_MAJOR,
+ MOUNT_CIFS_VERSION_MINOR,
+ MOUNT_CIFS_VENDOR_SUFFIX);
+ exit (0);
+ case 'w':
+ flags &= ~MS_RDONLY;
+ break;
+ case 'R':
+ rsize = atoi(optarg) ;
+ break;
+ case 'W':
+ wsize = atoi(optarg);
+ break;
+ case '1':
+ if (isdigit(*optarg)) {
+ char *ep;
+
+ uid = strtoul(optarg, &ep, 10);
+ if (*ep) {
+ printf("bad uid value \"%s\"\n", optarg);
+ exit(1);
+ }
+ } else {
+ struct passwd *pw;
+
+ if (!(pw = getpwnam(optarg))) {
+ printf("bad user name \"%s\"\n", optarg);
+ exit(1);
+ }
+ uid = pw->pw_uid;
+ endpwent();
+ }
+ break;
+ case '2':
+ if (isdigit(*optarg)) {
+ char *ep;
+
+ gid = strtoul(optarg, &ep, 10);
+ if (*ep) {
+ printf("bad gid value \"%s\"\n", optarg);
+ exit(1);
+ }
+ } else {
+ struct group *gr;
+
+ if (!(gr = getgrnam(optarg))) {
+ printf("bad user name \"%s\"\n", optarg);
+ exit(1);
+ }
+ gid = gr->gr_gid;
+ endpwent();
+ }
+ break;
+ case 'u':
+ got_user = 1;
+ user_name = optarg;
+ break;
+ case 'd':
+ domain_name = optarg; /* BB fix this - currently ignored */
+ got_domain = 1;
+ break;
+ case 'p':
+ if(mountpassword == NULL)
+ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
+ if(mountpassword) {
+ got_password = 1;
+ strlcpy(mountpassword,optarg,MOUNT_PASSWD_SIZE+1);
+ }
+ break;
+ case 'S':
+ get_password_from_file(0 /* stdin */,NULL);
+ break;
+ case 't':
+ break;
+ default:
+ printf("unknown mount option %c\n",c);
+ mount_cifs_usage();
+ exit(1);
+ }
+ }
+
+ if((argc < 3) || (dev_name == NULL) || (mountpoint == NULL)) {
+ mount_cifs_usage();
+ exit(1);
+ }
+
+ if (getenv("PASSWD")) {
+ if(mountpassword == NULL)
+ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
+ if(mountpassword) {
+ strlcpy(mountpassword,getenv("PASSWD"),MOUNT_PASSWD_SIZE+1);
+ got_password = 1;
+ }
+ } else if (getenv("PASSWD_FD")) {
+ get_password_from_file(atoi(getenv("PASSWD_FD")),NULL);
+ } else if (getenv("PASSWD_FILE")) {
+ get_password_from_file(0, getenv("PASSWD_FILE"));
+ }
+
+ if (orgoptions && parse_options(&orgoptions, &flags)) {
+ rc = -1;
+ goto mount_exit;
+ }
+ ipaddr = parse_server(&share_name);
+ if((ipaddr == NULL) && (got_ip == 0)) {
+ printf("No ip address specified and hostname not found\n");
+ rc = -1;
+ goto mount_exit;
+ }
+
+ /* BB save off path and pop after mount returns? */
+ resolved_path = (char *)malloc(PATH_MAX+1);
+ if(resolved_path) {
+ /* Note that if we can not canonicalize the name, we get
+ another chance to see if it is valid when we chdir to it */
+ if (realpath(mountpoint, resolved_path)) {
+ mountpoint = resolved_path;
+ }
+ }
+ if(chdir(mountpoint)) {
+ printf("mount error: can not change directory into mount target %s\n",mountpoint);
+ rc = -1;
+ goto mount_exit;
+ }
+
+ if(stat (".", &statbuf)) {
+ printf("mount error: mount point %s does not exist\n",mountpoint);
+ rc = -1;
+ goto mount_exit;
+ }
+
+ if (S_ISDIR(statbuf.st_mode) == 0) {
+ printf("mount error: mount point %s is not a directory\n",mountpoint);
+ rc = -1;
+ goto mount_exit;
+ }
+
+ if((getuid() != 0) && (geteuid() == 0)) {
+ if((statbuf.st_uid == getuid()) && (S_IRWXU == (statbuf.st_mode & S_IRWXU))) {
+#ifndef CIFS_ALLOW_USR_SUID
+ /* Do not allow user mounts to control suid flag
+ for mount unless explicitly built that way */
+ flags |= MS_NOSUID | MS_NODEV;
+#endif
+ } else {
+ printf("mount error: permission denied or not superuser and mount.cifs not installed SUID\n");
+ return -1;
+ }
+ }
+
+ if(got_user == 0) {
+ user_name = getusername();
+ got_user = 1;
+ }
+
+ if(got_password == 0) {
+ char *tmp_pass = getpass("Password: "); /* BB obsolete sys call but
+ no good replacement yet. */
+ mountpassword = (char *)calloc(MOUNT_PASSWD_SIZE+1,1);
+ if (!tmp_pass || !mountpassword) {
+ printf("Password not entered, exiting\n");
+ return -1;
+ }
+ strlcpy(mountpassword, tmp_pass, MOUNT_PASSWD_SIZE+1);
+ got_password = 1;
+ }
+ /* FIXME launch daemon (handles dfs name resolution and credential change)
+ remember to clear parms and overwrite password field before launching */
+mount_retry:
+ if(orgoptions) {
+ optlen = strlen(orgoptions);
+ orgoptlen = optlen;
+ } else
+ optlen = 0;
+ if(share_name)
+ optlen += strlen(share_name) + 4;
+ else {
+ printf("No server share name specified\n");
+ printf("\nMounting the DFS root for server not implemented yet\n");
+ exit(1);
+ }
+ if(user_name)
+ optlen += strlen(user_name) + 6;
+ if(ipaddr)
+ optlen += strlen(ipaddr) + 4;
+ if(mountpassword)
+ optlen += strlen(mountpassword) + 6;
+ SAFE_FREE(options);
+ options_size = optlen + 10 + DOMAIN_SIZE;
+ options = (char *)malloc(options_size /* space for commas in password */ + 8 /* space for domain= , domain name itself was counted as part of the length username string above */);
+
+ if(options == NULL) {
+ printf("Could not allocate memory for mount options\n");
+ return -1;
+ }
+
+ options[0] = 0;
+ strlcpy(options,"unc=",options_size);
+ strlcat(options,share_name,options_size);
+ /* scan backwards and reverse direction of slash */
+ temp = strrchr(options, '/');
+ if(temp > options + 6)
+ *temp = '\\';
+ if(ipaddr) {
+ strlcat(options,",ip=",options_size);
+ strlcat(options,ipaddr,options_size);
+ }
+
+ if(user_name) {
+ /* check for syntax like user=domain\user */
+ if(got_domain == 0)
+ domain_name = check_for_domain(&user_name);
+ strlcat(options,",user=",options_size);
+ strlcat(options,user_name,options_size);
+ }
+ if(retry == 0) {
+ if(domain_name) {
+ /* extra length accounted for in option string above */
+ strlcat(options,",domain=",options_size);
+ strlcat(options,domain_name,options_size);
+ }
+ }
+ if(mountpassword) {
+ /* Commas have to be doubled, or else they will
+ look like the parameter separator */
+/* if(sep is not set)*/
+ if(retry == 0)
+ check_for_comma(&mountpassword);
+ strlcat(options,",pass=",options_size);
+ strlcat(options,mountpassword,options_size);
+ }
+
+ strlcat(options,",ver=",options_size);
+ strlcat(options,MOUNT_CIFS_VERSION_MAJOR,options_size);
+
+ if(orgoptions) {
+ strlcat(options,",",options_size);
+ strlcat(options,orgoptions,options_size);
+ }
+ if(prefixpath) {
+ strlcat(options,",prefixpath=",options_size);
+ strlcat(options,prefixpath,options_size); /* no need to cat the / */
+ }
+ if(verboseflag)
+ printf("\nmount.cifs kernel mount options %s \n",options);
+
+ /* convert all '\\' to '/' in share portion so that /proc/mounts looks pretty */
+ replace_char(dev_name, '\\', '/', strlen(share_name));
+
+ if(mount(dev_name, mountpoint, "cifs", flags, options)) {
+ /* remember to kill daemon on error */
+ switch (errno) {
+ case 0:
+ printf("mount failed but no error number set\n");
+ break;
+ case ENODEV:
+ printf("mount error: cifs filesystem not supported by the system\n");
+ break;
+ case ENXIO:
+ if(retry == 0) {
+ retry = 1;
+ if (uppercase_string(dev_name) &&
+ uppercase_string(share_name) &&
+ uppercase_string(prefixpath)) {
+ printf("retrying with upper case share name\n");
+ goto mount_retry;
+ }
+ }
+ default:
+ printf("mount error %d = %s\n",errno,strerror(errno));
+ }
+ printf("Refer to the mount.cifs(8) manual page (e.g.man mount.cifs)\n");
+ rc = -1;
+ goto mount_exit;
+ } else {
+ pmntfile = setmntent(MOUNTED, "a+");
+ if(pmntfile) {
+ mountent.mnt_fsname = dev_name;
+ mountent.mnt_dir = mountpoint;
+ mountent.mnt_type = CONST_DISCARD(char *,"cifs");
+ mountent.mnt_opts = (char *)malloc(220);
+ if(mountent.mnt_opts) {
+ char * mount_user = getusername();
+ memset(mountent.mnt_opts,0,200);
+ if(flags & MS_RDONLY)
+ strlcat(mountent.mnt_opts,"ro",220);
+ else
+ strlcat(mountent.mnt_opts,"rw",220);
+ if(flags & MS_MANDLOCK)
+ strlcat(mountent.mnt_opts,",mand",220);
+ if(flags & MS_NOEXEC)
+ strlcat(mountent.mnt_opts,",noexec",220);
+ if(flags & MS_NOSUID)
+ strlcat(mountent.mnt_opts,",nosuid",220);
+ if(flags & MS_NODEV)
+ strlcat(mountent.mnt_opts,",nodev",220);
+ if(flags & MS_SYNCHRONOUS)
+ strlcat(mountent.mnt_opts,",synch",220);
+ if(mount_user) {
+ if(getuid() != 0) {
+ strlcat(mountent.mnt_opts,",user=",220);
+ strlcat(mountent.mnt_opts,mount_user,220);
+ }
+ /* free(mount_user); do not free static mem */
+ }
+ }
+ mountent.mnt_freq = 0;
+ mountent.mnt_passno = 0;
+ rc = addmntent(pmntfile,&mountent);
+ endmntent(pmntfile);
+ SAFE_FREE(mountent.mnt_opts);
+ } else {
+ printf("could not update mount table\n");
+ }
+ }
+ rc = 0;
+mount_exit:
+ if(mountpassword) {
+ int len = strlen(mountpassword);
+ memset(mountpassword,0,len);
+ SAFE_FREE(mountpassword);
+ }
+
+ SAFE_FREE(options);
+ SAFE_FREE(orgoptions);
+ SAFE_FREE(resolved_path);
+ SAFE_FREE(share_name);
+ return rc;
+}
diff --git a/source3/client/smbspool.c b/source3/client/smbspool.c
new file mode 100644
index 0000000000..4a173714fe
--- /dev/null
+++ b/source3/client/smbspool.c
@@ -0,0 +1,624 @@
+/*
+ Unix SMB/CIFS implementation.
+ SMB backend for the Common UNIX Printing System ("CUPS")
+
+ Copyright (C) Michael R Sweet 1999
+ Copyright (C) Andrew Tridgell 1994-1998
+ Copyright (C) Andrew Bartlett 2002
+ Copyright (C) Rodrigo Fernandez-Vizarra 2005
+ Copyright (C) James Peach 2008
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+#include "includes.h"
+
+/*
+ * Starting with CUPS 1.3, Kerberos support is provided by cupsd including
+ * the forwarding of user credentials via the authenticated session between
+ * user and server and the KRB5CCNAME environment variable which will point
+ * to a temporary file or an in-memory representation depending on the version
+ * of Kerberos you use. As a result, all of the ticket code that used to
+ * live here has been removed, and we depend on the user session (if you
+ * run smbspool by hand) or cupsd to provide the necessary Kerberos info.
+ *
+ * Also, the AUTH_USERNAME and AUTH_PASSWORD environment variables provide
+ * for per-job authentication for non-Kerberized printing. We use those
+ * if there is no username and password specified in the device URI.
+ *
+ * Finally, if we have an authentication failure we return exit code 2
+ * which tells CUPS to hold the job for authentication and bug the user
+ * to get the necessary credentials.
+ */
+
+#define MAX_RETRY_CONNECT 3
+
+
+/*
+ * Globals...
+ */
+
+
+
+/*
+ * Local functions...
+ */
+
+static int get_exit_code(struct cli_state * cli, NTSTATUS nt_status);
+static void list_devices(void);
+static struct cli_state *smb_complete_connection(const char *, const char *,
+ int, const char *, const char *, const char *, const char *, int, bool *need_auth);
+static struct cli_state *smb_connect(const char *, const char *, int, const
+ char *, const char *, const char *, const char *, bool *need_auth);
+static int smb_print(struct cli_state *, char *, FILE *);
+static char *uri_unescape_alloc(const char *);
+#if 0
+static bool smb_encrypt;
+#endif
+
+/*
+ * 'main()' - Main entry for SMB backend.
+ */
+
+int /* O - Exit status */
+main(int argc, /* I - Number of command-line arguments */
+ char *argv[])
+{ /* I - Command-line arguments */
+ int i; /* Looping var */
+ int copies; /* Number of copies */
+ int port; /* Port number */
+ char uri[1024], /* URI */
+ *sep, /* Pointer to separator */
+ *tmp, *tmp2, /* Temp pointers to do escaping */
+ *password; /* Password */
+ char *username, /* Username */
+ *server, /* Server name */
+ *printer;/* Printer name */
+ const char *workgroup; /* Workgroup */
+ FILE *fp; /* File to print */
+ int status = 1; /* Status of LPD job */
+ struct cli_state *cli; /* SMB interface */
+ char null_str[1];
+ int tries = 0;
+ bool need_auth = true;
+ const char *dev_uri;
+ TALLOC_CTX *frame = talloc_stackframe();
+
+ null_str[0] = '\0';
+
+ /*
+ * we expect the URI in argv[0]. Detect the case where it is in
+ * argv[1] and cope
+ */
+ if (argc > 2 && strncmp(argv[0], "smb://", 6) &&
+ strncmp(argv[1], "smb://", 6) == 0) {
+ argv++;
+ argc--;
+ }
+
+ if (argc == 1) {
+ /*
+ * NEW! In CUPS 1.1 the backends are run with no arguments
+ * to list the available devices. These can be devices
+ * served by this backend or any other backends (i.e. you
+ * can have an SNMP backend that is only used to enumerate
+ * the available network printers... :)
+ */
+
+ list_devices();
+ status = 0;
+ goto done;
+ }
+
+ if (argc < 6 || argc > 7) {
+ fprintf(stderr,
+"Usage: %s [DEVICE_URI] job-id user title copies options [file]\n"
+" The DEVICE_URI environment variable can also contain the\n"
+" destination printer:\n"
+"\n"
+" smb://[username:password@][workgroup/]server[:port]/printer\n",
+ argv[0]);
+ goto done;
+ }
+
+ /*
+ * If we have 7 arguments, print the file named on the command-line.
+ * Otherwise, print data from stdin...
+ */
+
+ if (argc == 6) {
+ /*
+ * Print from Copy stdin to a temporary file...
+ */
+
+ fp = stdin;
+ copies = 1;
+ } else if ((fp = fopen(argv[6], "rb")) == NULL) {
+ perror("ERROR: Unable to open print file");
+ goto done;
+ } else {
+ copies = atoi(argv[4]);
+ }
+
+ /*
+ * Find the URI...
+ */
+
+ dev_uri = getenv("DEVICE_URI");
+ if (dev_uri) {
+ strncpy(uri, dev_uri, sizeof(uri) - 1);
+ } else if (strncmp(argv[0], "smb://", 6) == 0) {
+ strncpy(uri, argv[0], sizeof(uri) - 1);
+ } else {
+ fputs("ERROR: No device URI found in DEVICE_URI environment variable or argv[0] !\n", stderr);
+ goto done;
+ }
+
+ uri[sizeof(uri) - 1] = '\0';
+
+ /*
+ * Extract the destination from the URI...
+ */
+
+ if ((sep = strrchr_m(uri, '@')) != NULL) {
+ tmp = uri + 6;
+ *sep++ = '\0';
+
+ /* username is in tmp */
+
+ server = sep;
+
+ /*
+ * Extract password as needed...
+ */
+
+ if ((tmp2 = strchr_m(tmp, ':')) != NULL) {
+ *tmp2++ = '\0';
+ password = uri_unescape_alloc(tmp2);
+ } else {
+ password = null_str;
+ }
+ username = uri_unescape_alloc(tmp);
+ } else {
+ if ((username = getenv("AUTH_USERNAME")) == NULL) {
+ username = null_str;
+ }
+
+ if ((password = getenv("AUTH_PASSWORD")) == NULL) {
+ password = null_str;
+ }
+
+ server = uri + 6;
+ }
+
+ tmp = server;
+
+ if ((sep = strchr_m(tmp, '/')) == NULL) {
+ fputs("ERROR: Bad URI - need printer name!\n", stderr);
+ goto done;
+ }
+
+ *sep++ = '\0';
+ tmp2 = sep;
+
+ if ((sep = strchr_m(tmp2, '/')) != NULL) {
+ /*
+ * Convert to smb://[username:password@]workgroup/server/printer...
+ */
+
+ *sep++ = '\0';
+
+ workgroup = uri_unescape_alloc(tmp);
+ server = uri_unescape_alloc(tmp2);
+ printer = uri_unescape_alloc(sep);
+ } else {
+ workgroup = NULL;
+ server = uri_unescape_alloc(tmp);
+ printer = uri_unescape_alloc(tmp2);
+ }
+
+ if ((sep = strrchr_m(server, ':')) != NULL) {
+ *sep++ = '\0';
+
+ port = atoi(sep);
+ } else {
+ port = 0;
+ }
+
+ /*
+ * Setup the SAMBA server state...
+ */
+
+ setup_logging("smbspool", True);
+
+ lp_set_in_client(True); /* Make sure that we tell lp_load we are */
+
+ load_case_tables();
+
+ if (!lp_load(get_dyn_CONFIGFILE(), True, False, False, True)) {
+ fprintf(stderr, "ERROR: Can't load %s - run testparm to debug it\n", get_dyn_CONFIGFILE());
+ goto done;
+ }
+
+ if (workgroup == NULL) {
+ workgroup = lp_workgroup();
+ }
+
+ load_interfaces();
+
+ do {
+ cli = smb_connect(workgroup, server, port, printer,
+ username, password, argv[2], &need_auth);
+ if (cli == NULL) {
+ if (need_auth) {
+ exit(2);
+ } else if (getenv("CLASS") == NULL) {
+ fprintf(stderr, "ERROR: Unable to connect to CIFS host, will retry in 60 seconds...\n");
+ sleep(60);
+ tries++;
+ } else {
+ fprintf(stderr, "ERROR: Unable to connect to CIFS host, trying next printer...\n");
+ goto done;
+ }
+ }
+ } while ((cli == NULL) && (tries < MAX_RETRY_CONNECT));
+
+ if (cli == NULL) {
+ fprintf(stderr, "ERROR: Unable to connect to CIFS host after (tried %d times)\n", tries);
+ goto done;
+ }
+
+ /*
+ * Now that we are connected to the server, ignore SIGTERM so that we
+ * can finish out any page data the driver sends (e.g. to eject the
+ * current page... Only ignore SIGTERM if we are printing data from
+ * stdin (otherwise you can't cancel raw jobs...)
+ */
+
+ if (argc < 7) {
+ CatchSignal(SIGTERM, SIG_IGN);
+ }
+
+ /*
+ * Queue the job...
+ */
+
+ for (i = 0; i < copies; i++) {
+ status = smb_print(cli, argv[3] /* title */ , fp);
+ if (status != 0) {
+ break;
+ }
+ }
+
+ cli_shutdown(cli);
+
+ /*
+ * Return the queue status...
+ */
+
+done:
+
+ TALLOC_FREE(frame);
+ return (status);
+}
+
+
+/*
+ * 'get_exit_code()' - Get the backend exit code based on the current error.
+ */
+
+static int
+get_exit_code(struct cli_state * cli,
+ NTSTATUS nt_status)
+{
+ int i;
+
+ /* List of NTSTATUS errors that are considered
+ * authentication errors
+ */
+ static const NTSTATUS auth_errors[] =
+ {
+ NT_STATUS_ACCESS_DENIED, NT_STATUS_ACCESS_VIOLATION,
+ NT_STATUS_SHARING_VIOLATION, NT_STATUS_PRIVILEGE_NOT_HELD,
+ NT_STATUS_INVALID_ACCOUNT_NAME, NT_STATUS_NO_SUCH_USER,
+ NT_STATUS_WRONG_PASSWORD, NT_STATUS_LOGON_FAILURE,
+ NT_STATUS_ACCOUNT_RESTRICTION, NT_STATUS_INVALID_LOGON_HOURS,
+ NT_STATUS_PASSWORD_EXPIRED, NT_STATUS_ACCOUNT_DISABLED
+ };
+
+
+ fprintf(stderr, "DEBUG: get_exit_code(cli=%p, nt_status=%x)\n",
+ cli, NT_STATUS_V(nt_status));
+
+ for (i = 0; i < ARRAY_SIZE(auth_errors); i++) {
+ if (!NT_STATUS_EQUAL(nt_status, auth_errors[i])) {
+ continue;
+ }
+
+ if (cli) {
+ if (cli->use_kerberos && cli->got_kerberos_mechanism)
+ fputs("ATTR: auth-info-required=negotiate\n", stderr);
+ else
+ fputs("ATTR: auth-info-required=username,password\n", stderr);
+ }
+
+ /*
+ * 2 = authentication required...
+ */
+
+ return (2);
+
+ }
+
+ /*
+ * 1 = fail
+ */
+
+ return (1);
+}
+
+
+/*
+ * 'list_devices()' - List the available printers seen on the network...
+ */
+
+static void
+list_devices(void)
+{
+ /*
+ * Eventually, search the local workgroup for available hosts and printers.
+ */
+
+ puts("network smb \"Unknown\" \"Windows Printer via SAMBA\"");
+}
+
+
+static struct cli_state *
+smb_complete_connection(const char *myname,
+ const char *server,
+ int port,
+ const char *username,
+ const char *password,
+ const char *workgroup,
+ const char *share,
+ int flags,
+ bool *need_auth)
+{
+ struct cli_state *cli; /* New connection */
+ NTSTATUS nt_status;
+
+ /* Start the SMB connection */
+ *need_auth = false;
+ nt_status = cli_start_connection(&cli, myname, server, NULL, port,
+ Undefined, flags, NULL);
+ if (!NT_STATUS_IS_OK(nt_status)) {
+ fprintf(stderr, "ERROR: Connection failed: %s\n", nt_errstr(nt_status));
+ return NULL;
+ }
+
+ /*
+ * We pretty much guarantee password must be valid or a pointer to a
+ * 0 char.
+ */
+ if (!password) {
+ *need_auth = true;
+ return NULL;
+ }
+
+ nt_status = cli_session_setup(cli, username,
+ password, strlen(password) + 1,
+ password, strlen(password) + 1,
+ workgroup);
+ if (!NT_STATUS_IS_OK(nt_status)) {
+ fprintf(stderr, "ERROR: Session setup failed: %s\n", nt_errstr(nt_status));
+
+ if (get_exit_code(cli, nt_status) == 2) {
+ *need_auth = true;
+ }
+
+ cli_shutdown(cli);
+
+ return NULL;
+ }
+
+ if (!cli_send_tconX(cli, share, "?????", password, strlen(password) + 1)) {
+ fprintf(stderr, "ERROR: Tree connect failed (%s)\n", cli_errstr(cli));
+
+ if (get_exit_code(cli, cli_nt_error(cli)) == 2) {
+ *need_auth = true;
+ }
+
+ cli_shutdown(cli);
+
+ return NULL;
+ }
+#if 0
+ /* Need to work out how to specify this on the URL. */
+ if (smb_encrypt) {
+ if (!cli_cm_force_encryption(cli,
+ username,
+ password,
+ workgroup,
+ share)) {
+ fprintf(stderr, "ERROR: encryption setup failed\n");
+ cli_shutdown(cli);
+ return NULL;
+ }
+ }
+#endif
+
+ return cli;
+}
+
+/*
+ * 'smb_connect()' - Return a connection to a server.
+ */
+
+static struct cli_state * /* O - SMB connection */
+smb_connect(const char *workgroup, /* I - Workgroup */
+ const char *server, /* I - Server */
+ const int port, /* I - Port */
+ const char *share, /* I - Printer */
+ const char *username, /* I - Username */
+ const char *password, /* I - Password */
+ const char *jobusername, /* I - User who issued the print job */
+ bool *need_auth)
+{ /* O - Need authentication? */
+ struct cli_state *cli; /* New connection */
+ char *myname = NULL; /* Client name */
+ struct passwd *pwd;
+
+ /*
+ * Get the names and addresses of the client and server...
+ */
+ myname = get_myname(talloc_tos());
+ if (!myname) {
+ return NULL;
+ }
+
+ /*
+ * See if we have a username first. This is for backwards compatible
+ * behavior with 3.0.14a
+ */
+
+ if (username && *username && !getenv("KRB5CCNAME")) {
+ cli = smb_complete_connection(myname, server, port, username,
+ password, workgroup, share, 0, need_auth);
+ if (cli) {
+ fputs("DEBUG: Connected with username/password...\n", stderr);
+ return (cli);
+ }
+ }
+
+ /*
+ * Try to use the user kerberos credentials (if any) to authenticate
+ */
+ cli = smb_complete_connection(myname, server, port, jobusername, "",
+ workgroup, share,
+ CLI_FULL_CONNECTION_USE_KERBEROS, need_auth);
+
+ if (cli) {
+ fputs("DEBUG: Connected using Kerberos...\n", stderr);
+ return (cli);
+ }
+
+ /* give a chance for a passwordless NTLMSSP session setup */
+ pwd = getpwuid(geteuid());
+ if (pwd == NULL) {
+ return NULL;
+ }
+
+ cli = smb_complete_connection(myname, server, port, pwd->pw_name, "",
+ workgroup, share, 0, need_auth);
+
+ if (cli) {
+ fputs("DEBUG: Connected with NTLMSSP...\n", stderr);
+ return (cli);
+ }
+
+ /*
+ * last try. Use anonymous authentication
+ */
+
+ cli = smb_complete_connection(myname, server, port, "", "",
+ workgroup, share, 0, need_auth);
+ /*
+ * Return the new connection...
+ */
+
+ return (cli);
+}
+
+
+/*
+ * 'smb_print()' - Queue a job for printing using the SMB protocol.
+ */
+
+static int /* O - 0 = success, non-0 = failure */
+smb_print(struct cli_state * cli, /* I - SMB connection */
+ char *title, /* I - Title/job name */
+ FILE * fp)
+{ /* I - File to print */
+ int fnum; /* File number */
+ int nbytes, /* Number of bytes read */
+ tbytes; /* Total bytes read */
+ char buffer[8192], /* Buffer for copy */
+ *ptr; /* Pointer into title */
+
+
+ /*
+ * Sanitize the title...
+ */
+
+ for (ptr = title; *ptr; ptr++) {
+ if (!isalnum((int) *ptr) && !isspace((int) *ptr)) {
+ *ptr = '_';
+ }
+ }
+
+ /*
+ * Open the printer device...
+ */
+
+ fnum = cli_open(cli, title, O_RDWR | O_CREAT | O_TRUNC, DENY_NONE);
+ if (fnum == -1) {
+ fprintf(stderr, "ERROR: %s opening remote spool %s\n",
+ cli_errstr(cli), title);
+ return (get_exit_code(cli, cli_nt_error(cli)));
+ }
+
+ /*
+ * Copy the file to the printer...
+ */
+
+ if (fp != stdin)
+ rewind(fp);
+
+ tbytes = 0;
+
+ while ((nbytes = fread(buffer, 1, sizeof(buffer), fp)) > 0) {
+ if (cli_write(cli, fnum, 0, buffer, tbytes, nbytes) != nbytes) {
+ int status = get_exit_code(cli, cli_nt_error(cli));
+
+ fprintf(stderr, "ERROR: Error writing spool: %s\n", cli_errstr(cli));
+ fprintf(stderr, "DEBUG: Returning status %d...\n", status);
+ cli_close(cli, fnum);
+
+ return (status);
+ }
+ tbytes += nbytes;
+ }
+
+ if (!cli_close(cli, fnum)) {
+ fprintf(stderr, "ERROR: %s closing remote spool %s\n",
+ cli_errstr(cli), title);
+ return (get_exit_code(cli, cli_nt_error(cli)));
+ } else {
+ return (0);
+ }
+}
+
+static char *
+uri_unescape_alloc(const char *uritok)
+{
+ char *ret;
+
+ ret = (char *) SMB_STRDUP(uritok);
+ if (!ret) {
+ return NULL;
+ }
+
+ rfc1738_unescape(ret);
+ return ret;
+}
diff --git a/source3/client/tree.c b/source3/client/tree.c
new file mode 100644
index 0000000000..e0b8c91949
--- /dev/null
+++ b/source3/client/tree.c
@@ -0,0 +1,812 @@
+/*
+ Unix SMB/CIFS implementation.
+ SMB client GTK+ tree-based application
+ Copyright (C) Andrew Tridgell 1998
+ Copyright (C) Richard Sharpe 2001
+ Copyright (C) John Terpstra 2001
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>.
+*/
+
+/* example-gtk+ application, ripped off from the gtk+ tree.c sample */
+
+#include <stdio.h>
+#include <errno.h>
+#include <gtk/gtk.h>
+#include "libsmbclient.h"
+
+static GtkWidget *clist;
+
+struct tree_data {
+
+ guint32 type; /* Type of tree item, an SMBC_TYPE */
+ char name[256]; /* May need to change this later */
+
+};
+
+static void tree_error_message(gchar *message) {
+
+ GtkWidget *dialog, *label, *okay_button;
+
+ /* Create the widgets */
+
+ dialog = gtk_dialog_new();
+ gtk_window_set_modal(GTK_WINDOW(dialog), True);
+ label = gtk_label_new (message);
+ okay_button = gtk_button_new_with_label("Okay");
+
+ /* Ensure that the dialog box is destroyed when the user clicks ok. */
+
+ gtk_signal_connect_object (GTK_OBJECT (okay_button), "clicked",
+ GTK_SIGNAL_FUNC (gtk_widget_destroy), dialog);
+ gtk_container_add (GTK_CONTAINER (GTK_DIALOG(dialog)->action_area),
+ okay_button);
+
+ /* Add the label, and show everything we've added to the dialog. */
+
+ gtk_container_add (GTK_CONTAINER (GTK_DIALOG(dialog)->vbox),
+ label);
+ gtk_widget_show_all (dialog);
+}
+
+/*
+ * We are given a widget, and we want to retrieve its URL so we
+ * can do a directory listing.
+ *
+ * We walk back up the tree, picking up pieces until we hit a server or
+ * workgroup type and return a path from there
+ */
+
+static char *path_string;
+
+char *get_path(TALLOC_CTX *ctx, GtkWidget *item)
+{
+ GtkWidget *p = item;
+ struct tree_data *pd;
+ char *comps[1024]; /* We keep pointers to the components here */
+ int i = 0, j, level,type;
+
+ /* Walk back up the tree, getting the private data */
+
+ level = GTK_TREE(item->parent)->level;
+
+ /* Pick up this item's component info */
+
+ pd = (struct tree_data *)gtk_object_get_user_data(GTK_OBJECT(item));
+
+ comps[i++] = pd->name;
+ type = pd->type;
+
+ while (level > 0 && type != SMBC_SERVER && type != SMBC_WORKGROUP) {
+
+ /* Find the parent and extract the data etc ... */
+
+ p = GTK_WIDGET(p->parent);
+ p = GTK_WIDGET(GTK_TREE(p)->tree_owner);
+
+ pd = (struct tree_data *)gtk_object_get_user_data(GTK_OBJECT(p));
+
+ level = GTK_TREE(item->parent)->level;
+
+ comps[i++] = pd->name;
+ type = pd->type;
+
+ }
+
+ /*
+ * Got a list of comps now, should check that we did not hit a workgroup
+ * when we got other things as well ... Later
+ *
+ * Now, build the path
+ */
+
+ TALLOC_FREE(path_string);
+ path_string = talloc_strdup(ctx, "smb:/");
+
+ if (path_string) {
+ for (j = i - 1; j >= 0; j--) {
+ path_string = talloc_asprintf_append(path_string, "/%s", comps[j]);
+ }
+ }
+
+ if (path_string) {
+ fprintf(stdout, "Path string = %s\n", path_string);
+ }
+
+ return path_string;
+
+}
+
+struct tree_data *make_tree_data(guint32 type, const char *name)
+{
+ struct tree_data *p = SMB_MALLOC_P(struct tree_data);
+
+ if (p) {
+
+ p->type = type;
+ strncpy(p->name, name, sizeof(p->name));
+
+ }
+
+ return p;
+
+}
+
+/* Note that this is called every time the user clicks on an item,
+ whether it is already selected or not. */
+static void cb_select_child (GtkWidget *root_tree, GtkWidget *child,
+ GtkWidget *subtree)
+{
+ gint dh, err, dirlen;
+ char dirbuf[512];
+ struct smbc_dirent *dirp;
+ struct stat st1;
+ char *path;
+ TALLOC_CTX *ctx = talloc_stackframe();
+
+ g_print ("select_child called for root tree %p, subtree %p, child %p\n",
+ root_tree, subtree, child);
+
+ /* Now, figure out what it is, and display it in the clist ... */
+
+ gtk_clist_clear(GTK_CLIST(clist)); /* Clear the CLIST */
+
+ /* Now, get the private data for the subtree */
+
+ path = get_path(ctx, child);
+ if (!path) {
+ gtk_main_quit();
+ TALLOC_FREE(ctx);
+ return;
+ }
+
+ if ((dh = smbc_opendir(path)) < 0) { /* Handle error */
+ g_print("cb_select_child: Could not open dir %s, %s\n", path,
+ strerror(errno));
+ gtk_main_quit();
+ TALLOC_FREE(ctx);
+ return;
+ }
+
+ while ((err = smbc_getdents(dh, (struct smbc_dirent *)dirbuf,
+ sizeof(dirbuf))) != 0) {
+ if (err < 0) {
+ g_print("cb_select_child: Could not read dir %s, %s\n", path,
+ strerror(errno));
+ gtk_main_quit();
+ TALLOC_FREE(ctx);
+ return;
+ }
+
+ dirp = (struct smbc_dirent *)dirbuf;
+
+ while (err > 0) {
+ gchar col1[128], col2[128], col3[128], col4[128];
+ gchar *rowdata[4] = {col1, col2, col3, col4};
+
+ dirlen = dirp->dirlen;
+
+ /* Format each of the items ... */
+
+ strncpy(col1, dirp->name, 128);
+
+ col2[0] = col3[0] = col4[0] = (char)0;
+
+ switch (dirp->smbc_type) {
+
+ case SMBC_WORKGROUP:
+
+ break;
+
+ case SMBC_SERVER:
+
+ strncpy(col2, (dirp->comment?dirp->comment:""), 128);
+
+ break;
+
+ case SMBC_FILE_SHARE:
+
+ strncpy(col2, (dirp->comment?dirp->comment:""), 128);
+
+ break;
+
+ case SMBC_PRINTER_SHARE:
+
+ strncpy(col2, (dirp->comment?dirp->comment:""), 128);
+ break;
+
+ case SMBC_COMMS_SHARE:
+
+ break;
+
+ case SMBC_IPC_SHARE:
+
+ break;
+
+ case SMBC_DIR:
+ case SMBC_FILE:
+
+ /* Get stats on the file/dir and see what we have */
+
+ if ((strcmp(dirp->name, ".") != 0) &&
+ (strcmp(dirp->name, "..") != 0)) {
+ char *path1;
+
+ path1 = talloc_asprintf(ctx,
+ "%s/%s",
+ path,
+ dirp->name);
+ if (!path1) {
+ gtk_main_quit();
+ TALLOC_FREE(ctx);
+ return;
+ }
+
+ if (smbc_stat(path1, &st1) < 0) {
+ if (errno != EBUSY) {
+ g_print("cb_select_child: Could not stat file %s, %s\n", path1,
+ strerror(errno));
+ gtk_main_quit();
+ TALLOC_FREE(ctx);
+ return;
+ } else {
+ strncpy(col2, "Device or resource busy", sizeof(col2));
+ }
+ }
+ else {
+ /* Now format each of the relevant things ... */
+
+ snprintf(col2, sizeof(col2), "%c%c%c%c%c%c%c%c%c(%0X)",
+ (st1.st_mode&S_IRUSR?'r':'-'),
+ (st1.st_mode&S_IWUSR?'w':'-'),
+ (st1.st_mode&S_IXUSR?'x':'-'),
+ (st1.st_mode&S_IRGRP?'r':'-'),
+ (st1.st_mode&S_IWGRP?'w':'-'),
+ (st1.st_mode&S_IXGRP?'x':'-'),
+ (st1.st_mode&S_IROTH?'r':'-'),
+ (st1.st_mode&S_IWOTH?'w':'-'),
+ (st1.st_mode&S_IXOTH?'x':'-'),
+ st1.st_mode);
+ snprintf(col3, sizeof(col3), "%u", st1.st_size);
+ snprintf(col4, sizeof(col4), "%s", ctime(&st1.st_mtime));
+ }
+ }
+
+ break;
+
+ default:
+
+ break;
+ }
+
+ gtk_clist_append(GTK_CLIST(clist), rowdata);
+
+ (char *)dirp += dirlen;
+ err -= dirlen;
+
+ }
+ }
+ TALLOC_FREE(ctx);
+}
+
+/* Note that this is never called */
+static void cb_unselect_child( GtkWidget *root_tree,
+ GtkWidget *child,
+ GtkWidget *subtree )
+{
+ g_print ("unselect_child called for root tree %p, subtree %p, child %p\n",
+ root_tree, subtree, child);
+}
+
+/* for all the GtkItem:: and GtkTreeItem:: signals */
+static void cb_itemsignal( GtkWidget *item,
+ gchar *signame )
+{
+ GtkWidget *real_tree, *aitem, *subtree;
+ gchar *name;
+ GtkLabel *label;
+ gint dh, err, dirlen, level;
+ char dirbuf[512];
+ struct smbc_dirent *dirp;
+
+ label = GTK_LABEL (GTK_BIN (item)->child);
+ /* Get the text of the label */
+ gtk_label_get (label, &name);
+
+ level = GTK_TREE(item->parent)->level;
+
+ /* Get the level of the tree which the item is in */
+ g_print ("%s called for item %s->%p, level %d\n", signame, name,
+ item, GTK_TREE (item->parent)->level);
+
+ real_tree = GTK_TREE_ITEM_SUBTREE(item); /* Get the subtree */
+
+ if (strncmp(signame, "expand", 6) == 0) { /* Expand called */
+ char server[128];
+
+ if ((dh = smbc_opendir(get_path(item))) < 0) { /* Handle error */
+ gchar errmsg[256];
+
+ g_print("cb_itemsignal: Could not open dir %s, %s\n", get_path(item),
+ strerror(errno));
+
+ slprintf(errmsg, sizeof(errmsg), "cb_itemsignal: Could not open dir %s, %s\n", get_path(item), strerror(errno));
+
+ tree_error_message(errmsg);
+
+ /* gtk_main_quit();*/
+
+ return;
+
+ }
+
+ while ((err = smbc_getdents(dh, (struct smbc_dirent *)dirbuf,
+ sizeof(dirbuf))) != 0) {
+
+ if (err < 0) { /* An error, report it */
+ gchar errmsg[256];
+
+ g_print("cb_itemsignal: Could not read dir smbc://, %s\n",
+ strerror(errno));
+
+ slprintf(errmsg, sizeof(errmsg), "cb_itemsignal: Could not read dir smbc://, %s\n", strerror(errno));
+
+ tree_error_message(errmsg);
+
+ /* gtk_main_quit();*/
+
+ return;
+
+ }
+
+ dirp = (struct smbc_dirent *)dirbuf;
+
+ while (err > 0) {
+ struct tree_data *my_data;
+
+ dirlen = dirp->dirlen;
+
+ my_data = make_tree_data(dirp->smbc_type, dirp->name);
+
+ if (!my_data) {
+
+ g_print("Could not allocate space for tree_data: %s\n",
+ dirp->name);
+
+ gtk_main_quit();
+ return;
+
+ }
+
+ aitem = gtk_tree_item_new_with_label(dirp->name);
+
+ /* Connect all GtkItem:: and GtkTreeItem:: signals */
+ gtk_signal_connect (GTK_OBJECT(aitem), "select",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "select");
+ gtk_signal_connect (GTK_OBJECT(aitem), "deselect",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "deselect");
+ gtk_signal_connect (GTK_OBJECT(aitem), "toggle",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "toggle");
+ gtk_signal_connect (GTK_OBJECT(aitem), "expand",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "expand");
+ gtk_signal_connect (GTK_OBJECT(aitem), "collapse",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "collapse");
+ /* Add it to the parent tree */
+ gtk_tree_append (GTK_TREE(real_tree), aitem);
+
+ gtk_widget_show (aitem);
+
+ gtk_object_set_user_data(GTK_OBJECT(aitem), (gpointer)my_data);
+
+ fprintf(stdout, "Added: %s, len: %u\n", dirp->name, dirlen);
+
+ if (dirp->smbc_type != SMBC_FILE &&
+ dirp->smbc_type != SMBC_IPC_SHARE &&
+ (strcmp(dirp->name, ".") != 0) &&
+ (strcmp(dirp->name, "..") !=0)){
+
+ subtree = gtk_tree_new();
+ gtk_tree_item_set_subtree(GTK_TREE_ITEM(aitem), subtree);
+
+ gtk_signal_connect(GTK_OBJECT(subtree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), real_tree);
+ gtk_signal_connect(GTK_OBJECT(subtree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), real_tree);
+
+ }
+
+ (char *)dirp += dirlen;
+ err -= dirlen;
+
+ }
+
+ }
+
+ smbc_closedir(dh);
+
+ }
+ else if (strncmp(signame, "collapse", 8) == 0) {
+ GtkWidget *subtree = gtk_tree_new();
+
+ gtk_tree_remove_items(GTK_TREE(real_tree), GTK_TREE(real_tree)->children);
+
+ gtk_tree_item_set_subtree(GTK_TREE_ITEM(item), subtree);
+
+ gtk_signal_connect (GTK_OBJECT(subtree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), real_tree);
+ gtk_signal_connect (GTK_OBJECT(subtree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), real_tree);
+
+ }
+
+}
+
+static void cb_selection_changed( GtkWidget *tree )
+{
+ GList *i;
+
+ g_print ("selection_change called for tree %p\n", tree);
+ g_print ("selected objects are:\n");
+
+ i = GTK_TREE_SELECTION(tree);
+ while (i){
+ gchar *name;
+ GtkLabel *label;
+ GtkWidget *item;
+
+ /* Get a GtkWidget pointer from the list node */
+ item = GTK_WIDGET (i->data);
+ label = GTK_LABEL (GTK_BIN (item)->child);
+ gtk_label_get (label, &name);
+ g_print ("\t%s on level %d\n", name, GTK_TREE
+ (item->parent)->level);
+ i = i->next;
+ }
+}
+
+/*
+ * Expand or collapse the whole network ...
+ */
+static void cb_wholenet(GtkWidget *item, gchar *signame)
+{
+ GtkWidget *real_tree, *aitem, *subtree;
+ gchar *name;
+ GtkLabel *label;
+ gint dh, err, dirlen;
+ char dirbuf[512];
+ struct smbc_dirent *dirp;
+
+ label = GTK_LABEL (GTK_BIN (item)->child);
+ gtk_label_get (label, &name);
+ g_print ("%s called for item %s->%p, level %d\n", signame, name,
+ item, GTK_TREE (item->parent)->level);
+
+ real_tree = GTK_TREE_ITEM_SUBTREE(item); /* Get the subtree */
+
+ if (strncmp(signame, "expand", 6) == 0) { /* Expand called */
+
+ if ((dh = smbc_opendir("smb://")) < 0) { /* Handle error */
+
+ g_print("cb_wholenet: Could not open dir smbc://, %s\n",
+ strerror(errno));
+
+ gtk_main_quit();
+
+ return;
+
+ }
+
+ while ((err = smbc_getdents(dh, (struct smbc_dirent *)dirbuf,
+ sizeof(dirbuf))) != 0) {
+
+ if (err < 0) { /* An error, report it */
+
+ g_print("cb_wholenet: Could not read dir smbc://, %s\n",
+ strerror(errno));
+
+ gtk_main_quit();
+
+ return;
+
+ }
+
+ dirp = (struct smbc_dirent *)dirbuf;
+
+ while (err > 0) {
+ struct tree_data *my_data;
+
+ dirlen = dirp->dirlen;
+
+ my_data = make_tree_data(dirp->smbc_type, dirp->name);
+
+ aitem = gtk_tree_item_new_with_label(dirp->name);
+
+ /* Connect all GtkItem:: and GtkTreeItem:: signals */
+ gtk_signal_connect (GTK_OBJECT(aitem), "select",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "select");
+ gtk_signal_connect (GTK_OBJECT(aitem), "deselect",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "deselect");
+ gtk_signal_connect (GTK_OBJECT(aitem), "toggle",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "toggle");
+ gtk_signal_connect (GTK_OBJECT(aitem), "expand",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "expand");
+ gtk_signal_connect (GTK_OBJECT(aitem), "collapse",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "collapse");
+
+ gtk_tree_append (GTK_TREE(real_tree), aitem);
+ /* Show it - this can be done at any time */
+ gtk_widget_show (aitem);
+
+ gtk_object_set_user_data(GTK_OBJECT(aitem), (gpointer)my_data);
+
+ fprintf(stdout, "Added: %s, len: %u\n", dirp->name, dirlen);
+
+ subtree = gtk_tree_new();
+
+ gtk_tree_item_set_subtree(GTK_TREE_ITEM(aitem), subtree);
+
+ gtk_signal_connect(GTK_OBJECT(subtree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), real_tree);
+ gtk_signal_connect(GTK_OBJECT(subtree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), real_tree);
+
+ (char *)dirp += dirlen;
+ err -= dirlen;
+
+ }
+
+ }
+
+ smbc_closedir(dh);
+
+ }
+ else { /* Must be collapse ... FIXME ... */
+ GtkWidget *subtree = gtk_tree_new();
+
+ gtk_tree_remove_items(GTK_TREE(real_tree), GTK_TREE(real_tree)->children);
+
+ gtk_tree_item_set_subtree(GTK_TREE_ITEM(item), subtree);
+
+ gtk_signal_connect (GTK_OBJECT(subtree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), real_tree);
+ gtk_signal_connect (GTK_OBJECT(subtree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), real_tree);
+
+
+ }
+
+}
+
+/* Should put up a dialog box to ask the user for username and password */
+
+static void
+auth_fn(const char *server, const char *share,
+ char *workgroup, int wgmaxlen, char *username, int unmaxlen,
+ char *password, int pwmaxlen)
+{
+
+ strncpy(username, "test", unmaxlen);
+ strncpy(password, "test", pwmaxlen);
+
+}
+
+static char *col_titles[] = {
+ "Name", "Attributes", "Size", "Modification Date",
+};
+
+int main( int argc,
+ char *argv[] )
+{
+ GtkWidget *window, *scrolled_win, *scrolled_win2, *tree;
+ GtkWidget *subtree, *item, *main_hbox, *r_pane, *l_pane;
+ gint err, dh;
+ gint i;
+ char dirbuf[512];
+ struct smbc_dirent *dirp;
+ TALLOC_CTX *frame = talloc_stackframe();
+
+ gtk_init (&argc, &argv);
+
+ /* Init the smbclient library */
+
+ err = smbc_init(auth_fn, 10);
+
+ /* Print an error response ... */
+
+ if (err < 0) {
+
+ fprintf(stderr, "smbc_init returned %s (%i)\nDo you have a ~/.smb/smb.conf file?\n", strerror(errno), errno);
+ exit(1);
+
+ }
+
+ /* a generic toplevel window */
+ window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
+ gtk_widget_set_name(window, "main browser window");
+ gtk_signal_connect (GTK_OBJECT(window), "delete_event",
+ GTK_SIGNAL_FUNC (gtk_main_quit), NULL);
+ gtk_window_set_title(GTK_WINDOW(window), "The Linux Windows Network Browser");
+ gtk_widget_set_usize(GTK_WIDGET(window), 750, -1);
+ gtk_container_set_border_width (GTK_CONTAINER(window), 5);
+
+ gtk_widget_show (window);
+
+ /* A container for the two panes ... */
+
+ main_hbox = gtk_hbox_new(FALSE, 1);
+ gtk_container_border_width(GTK_CONTAINER(main_hbox), 1);
+ gtk_container_add(GTK_CONTAINER(window), main_hbox);
+
+ gtk_widget_show(main_hbox);
+
+ l_pane = gtk_hpaned_new();
+ gtk_paned_gutter_size(GTK_PANED(l_pane), (GTK_PANED(l_pane))->handle_size);
+ r_pane = gtk_hpaned_new();
+ gtk_paned_gutter_size(GTK_PANED(r_pane), (GTK_PANED(r_pane))->handle_size);
+ gtk_container_add(GTK_CONTAINER(main_hbox), l_pane);
+ gtk_widget_show(l_pane);
+
+ /* A generic scrolled window */
+ scrolled_win = gtk_scrolled_window_new (NULL, NULL);
+ gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win),
+ GTK_POLICY_AUTOMATIC,
+ GTK_POLICY_AUTOMATIC);
+ gtk_widget_set_usize (scrolled_win, 150, 200);
+ gtk_container_add (GTK_CONTAINER(l_pane), scrolled_win);
+ gtk_widget_show (scrolled_win);
+
+ /* Another generic scrolled window */
+ scrolled_win2 = gtk_scrolled_window_new (NULL, NULL);
+ gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_win2),
+ GTK_POLICY_AUTOMATIC,
+ GTK_POLICY_AUTOMATIC);
+ gtk_widget_set_usize (scrolled_win2, 150, 200);
+ gtk_paned_add2 (GTK_PANED(l_pane), scrolled_win2);
+ gtk_widget_show (scrolled_win2);
+
+ /* Create the root tree */
+ tree = gtk_tree_new();
+ g_print ("root tree is %p\n", tree);
+ /* connect all GtkTree:: signals */
+ gtk_signal_connect (GTK_OBJECT(tree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), tree);
+ gtk_signal_connect (GTK_OBJECT(tree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), tree);
+ gtk_signal_connect (GTK_OBJECT(tree), "selection_changed",
+ GTK_SIGNAL_FUNC(cb_selection_changed), tree);
+ /* Add it to the scrolled window */
+ gtk_scrolled_window_add_with_viewport (GTK_SCROLLED_WINDOW(scrolled_win),
+ tree);
+ /* Set the selection mode */
+ gtk_tree_set_selection_mode (GTK_TREE(tree),
+ GTK_SELECTION_MULTIPLE);
+ /* Show it */
+ gtk_widget_show (tree);
+
+ /* Now, create a clist and attach it to the second pane */
+
+ clist = gtk_clist_new_with_titles(4, col_titles);
+
+ gtk_container_add (GTK_CONTAINER(scrolled_win2), clist);
+
+ gtk_widget_show(clist);
+
+ /* Now, build the top level display ... */
+
+ if ((dh = smbc_opendir("smb:///")) < 0) {
+
+ fprintf(stderr, "Could not list default workgroup: smb:///: %s\n",
+ strerror(errno));
+
+ exit(1);
+
+ }
+
+ /* Create a tree item for Whole Network */
+
+ item = gtk_tree_item_new_with_label ("Whole Network");
+ /* Connect all GtkItem:: and GtkTreeItem:: signals */
+ gtk_signal_connect (GTK_OBJECT(item), "select",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "select");
+ gtk_signal_connect (GTK_OBJECT(item), "deselect",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "deselect");
+ gtk_signal_connect (GTK_OBJECT(item), "toggle",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "toggle");
+ gtk_signal_connect (GTK_OBJECT(item), "expand",
+ GTK_SIGNAL_FUNC(cb_wholenet), "expand");
+ gtk_signal_connect (GTK_OBJECT(item), "collapse",
+ GTK_SIGNAL_FUNC(cb_wholenet), "collapse");
+ /* Add it to the parent tree */
+ gtk_tree_append (GTK_TREE(tree), item);
+ /* Show it - this can be done at any time */
+ gtk_widget_show (item);
+
+ subtree = gtk_tree_new(); /* A subtree for Whole Network */
+
+ gtk_tree_item_set_subtree(GTK_TREE_ITEM(item), subtree);
+
+ gtk_signal_connect (GTK_OBJECT(subtree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), tree);
+ gtk_signal_connect (GTK_OBJECT(subtree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), tree);
+
+ /* Now, get the items in smb:/// and add them to the tree */
+
+ dirp = (struct smbc_dirent *)dirbuf;
+
+ while ((err = smbc_getdents(dh, (struct smbc_dirent *)dirbuf,
+ sizeof(dirbuf))) != 0) {
+
+ if (err < 0) { /* Handle the error */
+
+ fprintf(stderr, "Could not read directory for smbc:///: %s\n",
+ strerror(errno));
+
+ exit(1);
+
+ }
+
+ fprintf(stdout, "Dir len: %u\n", err);
+
+ while (err > 0) { /* Extract each entry and make a sub-tree */
+ struct tree_data *my_data;
+ int dirlen = dirp->dirlen;
+
+ my_data = make_tree_data(dirp->smbc_type, dirp->name);
+
+ item = gtk_tree_item_new_with_label(dirp->name);
+ /* Connect all GtkItem:: and GtkTreeItem:: signals */
+ gtk_signal_connect (GTK_OBJECT(item), "select",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "select");
+ gtk_signal_connect (GTK_OBJECT(item), "deselect",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "deselect");
+ gtk_signal_connect (GTK_OBJECT(item), "toggle",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "toggle");
+ gtk_signal_connect (GTK_OBJECT(item), "expand",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "expand");
+ gtk_signal_connect (GTK_OBJECT(item), "collapse",
+ GTK_SIGNAL_FUNC(cb_itemsignal), "collapse");
+ /* Add it to the parent tree */
+ gtk_tree_append (GTK_TREE(tree), item);
+ /* Show it - this can be done at any time */
+ gtk_widget_show (item);
+
+ gtk_object_set_user_data(GTK_OBJECT(item), (gpointer)my_data);
+
+ fprintf(stdout, "Added: %s, len: %u\n", dirp->name, dirlen);
+
+ subtree = gtk_tree_new();
+
+ gtk_tree_item_set_subtree(GTK_TREE_ITEM(item), subtree);
+
+ gtk_signal_connect (GTK_OBJECT(subtree), "select_child",
+ GTK_SIGNAL_FUNC(cb_select_child), tree);
+ gtk_signal_connect (GTK_OBJECT(subtree), "unselect_child",
+ GTK_SIGNAL_FUNC(cb_unselect_child), tree);
+
+ (char *)dirp += dirlen;
+ err -= dirlen;
+
+ }
+
+ }
+
+ smbc_closedir(dh); /* FIXME, check for error :-) */
+
+ /* Show the window and loop endlessly */
+ gtk_main();
+ TALLOC_FREE(frame);
+ return 0;
+}
+/* example-end */
diff --git a/source3/client/umount.cifs.c b/source3/client/umount.cifs.c
new file mode 100644
index 0000000000..3e2415ad00
--- /dev/null
+++ b/source3/client/umount.cifs.c
@@ -0,0 +1,386 @@
+/*
+ Unmount utility program for Linux CIFS VFS (virtual filesystem) client
+ Copyright (C) 2005 Steve French (sfrench@us.ibm.com)
+
+ This program is free software; you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see <http://www.gnu.org/licenses/>. */
+
+#ifndef _GNU_SOURCE
+#define _GNU_SOURCE
+#endif
+
+#include <stdlib.h>
+#include <stdio.h>
+#include <unistd.h>
+#include <ctype.h>
+#include <sys/types.h>
+#include <sys/mount.h>
+#include <sys/ioctl.h>
+#include <sys/stat.h>
+#include <sys/vfs.h>
+#include <fcntl.h>
+#include <getopt.h>
+#include <errno.h>
+#include <string.h>
+#include <mntent.h>
+
+#define UNMOUNT_CIFS_VERSION_MAJOR "0"
+#define UNMOUNT_CIFS_VERSION_MINOR "5"
+
+#ifndef UNMOUNT_CIFS_VENDOR_SUFFIX
+ #ifdef _SAMBA_BUILD_
+ #include "include/version.h"
+ #ifdef SAMBA_VERSION_VENDOR_SUFFIX
+ #define UNMOUNT_CIFS_VENDOR_SUFFIX "-"SAMBA_VERSION_OFFICIAL_STRING"-"SAMBA_VERSION_VENDOR_SUFFIX
+ #else
+ #define UNMOUNT_CIFS_VENDOR_SUFFIX "-"SAMBA_VERSION_OFFICIAL_STRING
+ #endif /* SAMBA_VERSION_OFFICIAL_STRING and SAMBA_VERSION_VENDOR_SUFFIX */
+ #else
+ #define UNMOUNT_CIFS_VENDOR_SUFFIX ""
+ #endif /* _SAMBA_BUILD_ */
+#endif /* UNMOUNT_CIFS_VENDOR_SUFFIX */
+
+#ifndef MNT_DETACH
+#define MNT_DETACH 0x02
+#endif
+
+#ifndef MNT_EXPIRE
+#define MNT_EXPIRE 0x04
+#endif
+
+#ifndef MOUNTED_LOCK
+#define MOUNTED_LOCK "/etc/mtab~"
+#endif
+#ifndef MOUNTED_TEMP
+#define MOUNTED_TEMP "/etc/mtab.tmp"
+#endif
+
+#define CIFS_IOC_CHECKUMOUNT _IO(0xCF, 2)
+#define CIFS_MAGIC_NUMBER 0xFF534D42 /* the first four bytes of SMB PDU */
+
+static struct option longopts[] = {
+ { "all", 0, NULL, 'a' },
+ { "help",0, NULL, 'h' },
+ { "read-only", 0, NULL, 'r' },
+ { "ro", 0, NULL, 'r' },
+ { "verbose", 0, NULL, 'v' },
+ { "version", 0, NULL, 'V' },
+ { "expire", 0, NULL, 'e' },
+ { "force", 0, 0, 'f' },
+ { "lazy", 0, 0, 'l' },
+ { "no-mtab", 0, 0, 'n' },
+ { NULL, 0, NULL, 0 }
+};
+
+const char * thisprogram;
+int verboseflg = 0;
+
+static void umount_cifs_usage(void)
+{
+ printf("\nUsage: %s <remotetarget> <dir>\n", thisprogram);
+ printf("\nUnmount the specified directory\n");
+ printf("\nLess commonly used options:");
+ printf("\n\t-r\tIf mount fails, retry with readonly remount.");
+ printf("\n\t-n\tDo not write to mtab.");
+ printf("\n\t-f\tAttempt a forced unmount, even if the fs is busy.");
+ printf("\n\t-l\tAttempt lazy unmount, Unmount now, cleanup later.");
+ printf("\n\t-v\tEnable verbose mode (may be useful for debugging).");
+ printf("\n\t-h\tDisplay this help.");
+ printf("\n\nOptions are described in more detail in the manual page");
+ printf("\n\tman 8 umount.cifs\n");
+ printf("\nTo display the version number of the cifs umount utility:");
+ printf("\n\t%s -V\n",thisprogram);
+ printf("\nInvoking the umount utility on cifs mounts, can execute");
+ printf(" /sbin/umount.cifs (if present and umount -i is not specified.\n");
+}
+
+static int umount_check_perm(char * dir)
+{
+ int fileid;
+ int rc;
+
+ /* allow root to unmount, no matter what */
+ if(getuid() == 0)
+ return 0;
+
+ /* presumably can not chdir into the target as we do on mount */
+ fileid = open(dir, O_RDONLY | O_DIRECTORY | O_NOFOLLOW, 0);
+ if(fileid == -1) {
+ if(verboseflg)
+ printf("error opening mountpoint %d %s",errno,strerror(errno));
+ return errno;
+ }
+
+ rc = ioctl(fileid, CIFS_IOC_CHECKUMOUNT, NULL);
+
+ if(verboseflg)
+ printf("ioctl returned %d with errno %d %s\n",rc,errno,strerror(errno));
+
+ if(rc == ENOTTY) {
+ printf("user unmounting via %s is an optional feature of",thisprogram);
+ printf(" the cifs filesystem driver (cifs.ko)");
+ printf("\n\tand requires cifs.ko version 1.32 or later\n");
+ } else if (rc != 0)
+ printf("user unmount of %s failed with %d %s\n",dir,errno,strerror(errno));
+ close(fileid);
+
+ return rc;
+}
+
+static int lock_mtab(void)
+{
+ int rc;
+
+ rc = mknod(MOUNTED_LOCK , 0600, 0);
+ if(rc == -1)
+ printf("\ngetting lock file %s failed with %s\n",MOUNTED_LOCK,
+ strerror(errno));
+
+ return rc;
+
+}
+
+static void unlock_mtab(void)
+{
+ unlink(MOUNTED_LOCK);
+}
+
+static int remove_from_mtab(char * mountpoint)
+{
+ int rc;
+ int num_matches;
+ FILE * org_fd;
+ FILE * new_fd;
+ struct mntent * mount_entry;
+
+ /* Do we need to check if it is a symlink to e.g. /proc/mounts
+ in which case we probably do not want to update it? */
+
+ /* Do we first need to check if it is writable? */
+
+ if (lock_mtab()) {
+ printf("Mount table locked\n");
+ return -EACCES;
+ }
+
+ if(verboseflg)
+ printf("attempting to remove from mtab\n");
+
+ org_fd = setmntent(MOUNTED, "r");
+
+ if(org_fd == NULL) {
+ printf("Can not open %s\n",MOUNTED);
+ unlock_mtab();
+ return -EIO;
+ }
+
+ new_fd = setmntent(MOUNTED_TEMP,"w");
+ if(new_fd == NULL) {
+ printf("Can not open temp file %s", MOUNTED_TEMP);
+ endmntent(org_fd);
+ unlock_mtab();
+ return -EIO;
+ }
+
+ /* BB fix so we only remove the last entry that matches BB */
+ num_matches = 0;
+ while((mount_entry = getmntent(org_fd)) != NULL) {
+ if(strcmp(mount_entry->mnt_dir, mountpoint) == 0) {
+ num_matches++;
+ }
+ }
+ if(verboseflg)
+ printf("%d matching entries in mount table\n", num_matches);
+
+ /* Is there a better way to seek back to the first entry in mtab? */
+ endmntent(org_fd);
+ org_fd = setmntent(MOUNTED, "r");
+
+ if(org_fd == NULL) {
+ printf("Can not open %s\n",MOUNTED);
+ unlock_mtab();
+ return -EIO;
+ }
+
+ while((mount_entry = getmntent(org_fd)) != NULL) {
+ if(strcmp(mount_entry->mnt_dir, mountpoint) != 0) {
+ addmntent(new_fd, mount_entry);
+ } else {
+ if(num_matches != 1) {
+ addmntent(new_fd, mount_entry);
+ num_matches--;
+ } else if(verboseflg)
+ printf("entry not copied (ie entry is removed)\n");
+ }
+ }
+
+ if(verboseflg)
+ printf("done updating tmp file\n");
+ rc = fchmod (fileno (new_fd), S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH);
+ if(rc < 0) {
+ printf("error %s changing mode of %s\n", strerror(errno),
+ MOUNTED_TEMP);
+ }
+ endmntent(new_fd);
+
+ rc = rename(MOUNTED_TEMP, MOUNTED);
+
+ if(rc < 0) {
+ printf("failure %s renaming %s to %s\n",strerror(errno),
+ MOUNTED_TEMP, MOUNTED);
+ unlock_mtab();
+ return -EIO;
+ }
+
+ unlock_mtab();
+
+ return rc;
+}
+
+int main(int argc, char ** argv)
+{
+ int c;
+ int rc;
+ int flags = 0;
+ int nomtab = 0;
+ int retry_remount = 0;
+ struct statfs statbuf;
+ char * mountpoint;
+
+ if(argc && argv) {
+ thisprogram = argv[0];
+ } else {
+ umount_cifs_usage();
+ return -EINVAL;
+ }
+
+ if(argc < 2) {
+ umount_cifs_usage();
+ return -EINVAL;
+ }
+
+ if(thisprogram == NULL)
+ thisprogram = "umount.cifs";
+
+ /* add sharename in opts string as unc= parm */
+
+ while ((c = getopt_long (argc, argv, "afhilnrvV",
+ longopts, NULL)) != -1) {
+ switch (c) {
+/* No code to do the following option yet */
+/* case 'a':
+ ++umount_all;
+ break; */
+ case '?':
+ case 'h': /* help */
+ umount_cifs_usage();
+ exit(1);
+ case 'n':
+ ++nomtab;
+ break;
+ case 'f':
+ flags |= MNT_FORCE;
+ break;
+ case 'l':
+ flags |= MNT_DETACH; /* lazy unmount */
+ break;
+ case 'e':
+ flags |= MNT_EXPIRE; /* gradually timeout */
+ break;
+ case 'r':
+ ++retry_remount;
+ break;
+ case 'v':
+ ++verboseflg;
+ break;
+ case 'V':
+ printf ("umount.cifs version: %s.%s%s\n",
+ UNMOUNT_CIFS_VERSION_MAJOR,
+ UNMOUNT_CIFS_VERSION_MINOR,
+ UNMOUNT_CIFS_VENDOR_SUFFIX);
+ exit (0);
+ default:
+ printf("unknown unmount option %c\n",c);
+ umount_cifs_usage();
+ exit(1);
+ }
+ }
+
+ /* move past the umount options */
+ argv += optind;
+ argc -= optind;
+
+ mountpoint = argv[0];
+
+ if((argc < 1) || (argv[0] == NULL)) {
+ printf("\nMissing name of unmount directory\n");
+ umount_cifs_usage();
+ return -EINVAL;
+ }
+
+ if(verboseflg)
+ printf("optind %d unmount dir %s\n",optind, mountpoint);
+
+ /* check if running effectively root */
+ if(geteuid() != 0) {
+ printf("Trying to unmount when %s not installed suid\n",thisprogram);
+ if(verboseflg)
+ printf("euid = %d\n",geteuid());
+ return -EACCES;
+ }
+
+ /* fixup path if needed */
+
+ /* Trim any trailing slashes */
+ while ((strlen(mountpoint) > 1) &&
+ (mountpoint[strlen(mountpoint)-1] == '/'))
+ {
+ mountpoint[strlen(mountpoint)-1] = '\0';
+ }
+
+ /* make sure that this is a cifs filesystem */
+ rc = statfs(mountpoint, &statbuf);
+
+ if(rc || (statbuf.f_type != CIFS_MAGIC_NUMBER)) {
+ printf("This utility only unmounts cifs filesystems.\n");
+ return -EINVAL;
+ }
+
+ /* check if our uid was the one who mounted */
+ rc = umount_check_perm(mountpoint);
+ if (rc) {
+ printf("Not permitted to unmount\n");
+ return rc;
+ }
+
+ if(umount2(mountpoint, flags)) {
+ /* remember to kill daemon on error */
+ switch (errno) {
+ case 0:
+ printf("unmount failed but no error number set\n");
+ break;
+ default:
+ printf("unmount error %d = %s\n",errno,strerror(errno));
+ }
+ printf("Refer to the umount.cifs(8) manual page (man 8 umount.cifs)\n");
+ return -1;
+ } else {
+ if(verboseflg)
+ printf("umount2 succeeded\n");
+ if(nomtab == 0)
+ remove_from_mtab(mountpoint);
+ }
+
+ return 0;
+}
+