Share ndrdump implementation.
[sfrench/samba-autobuild/.git] / source3 / lib / util.c
index d635078f37bbeea4d0a01ccfd34185d60988769c..418ae41392b2d83ef1e262a064bf360f2efc5a90 100644 (file)
@@ -60,8 +60,6 @@ enum protocol_types Protocol = PROTOCOL_COREPLUS;
 /* this is used by the chaining code */
 int chain_size = 0;
 
-int trans_num = 0;
-
 static enum remote_arch_types ra_type = RA_UNKNOWN;
 
 /***********************************************************************
@@ -191,12 +189,9 @@ void gfree_all( void )
        gfree_names();
        gfree_loadparm();
        gfree_case_tables();
-       gfree_debugsyms();
        gfree_charcnv();
        gfree_interfaces();
-
-       /* release the talloc null_context memory last */
-       talloc_disable_null_tracking();
+       gfree_debugsyms();
 }
 
 const char *my_netbios_names(int i)
@@ -291,7 +286,8 @@ static struct user_auth_info cmdline_auth_info = {
        false,  /* got_pass */
        false,  /* use_kerberos */
        Undefined, /* signing state */
-       false   /* smb_encrypt */
+       false,  /* smb_encrypt */
+       false   /* use machine account */
 };
 
 const char *get_cmdline_auth_info_username(void)
@@ -352,6 +348,11 @@ int get_cmdline_auth_info_signing_state(void)
        return cmdline_auth_info.signing_state;
 }
 
+void set_cmdline_auth_info_use_kerberos(bool b)
+{
+        cmdline_auth_info.use_kerberos = b;
+}
+
 bool get_cmdline_auth_info_use_kerberos(void)
 {
        return cmdline_auth_info.use_kerberos;
@@ -370,6 +371,11 @@ void set_cmdline_auth_info_smb_encrypt(void)
        cmdline_auth_info.smb_encrypt = true;
 }
 
+void set_cmdline_auth_info_use_machine_account(void)
+{
+       cmdline_auth_info.use_machine_account = true;
+}
+
 bool get_cmdline_auth_info_got_pass(void)
 {
        return cmdline_auth_info.got_pass;
@@ -380,6 +386,11 @@ bool get_cmdline_auth_info_smb_encrypt(void)
        return cmdline_auth_info.smb_encrypt;
 }
 
+bool get_cmdline_auth_info_use_machine_account(void)
+{
+       return cmdline_auth_info.use_machine_account;
+}
+
 bool get_cmdline_auth_info_copy(struct user_auth_info *info)
 {
        *info = cmdline_auth_info;
@@ -392,6 +403,42 @@ bool get_cmdline_auth_info_copy(struct user_auth_info *info)
        return true;
 }
 
+bool set_cmdline_auth_info_machine_account_creds(void)
+{
+       char *pass = NULL;
+       char *account = NULL;
+
+       if (!get_cmdline_auth_info_use_machine_account()) {
+               return false;
+       }
+
+       if (!secrets_init()) {
+               d_printf("ERROR: Unable to open secrets database\n");
+               return false;
+       }
+
+       if (asprintf(&account, "%s$@%s", global_myname(), lp_realm()) < 0) {
+               return false;
+       }
+
+       pass = secrets_fetch_machine_password(lp_workgroup(), NULL, NULL);
+       if (!pass) {
+               d_printf("ERROR: Unable to fetch machine password for "
+                       "%s in domain %s\n",
+                       account, lp_workgroup());
+               SAFE_FREE(account);
+               return false;
+       }
+
+       set_cmdline_auth_info_username(account);
+       set_cmdline_auth_info_password(pass);
+
+       SAFE_FREE(account);
+       SAFE_FREE(pass);
+
+       return true;
+}
+
 /**************************************************************************n
  Find a suitable temporary directory. The result should be copied immediately
  as it may be overwritten by a subsequent call.
@@ -505,6 +552,19 @@ bool file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
        return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
 }
 
+/*******************************************************************
+ Check if a unix domain socket exists - call vfs_file_exist for samba files.
+********************************************************************/
+
+bool socket_exist(const char *fname)
+{
+       SMB_STRUCT_STAT st;
+       if (sys_stat(fname,&st) != 0) 
+               return(False);
+
+       return S_ISSOCK(st.st_mode);
+}
+
 /*******************************************************************
  Check a files mod time.
 ********************************************************************/
@@ -897,85 +957,6 @@ int set_blocking(int fd, bool set)
 #undef FLAG_TO_SET
 }
 
-/****************************************************************************
- Transfer some data between two fd's.
-****************************************************************************/
-
-#ifndef TRANSFER_BUF_SIZE
-#define TRANSFER_BUF_SIZE 65536
-#endif
-
-
-ssize_t transfer_file_internal(void *in_file,
-                              void *out_file,
-                              size_t n,
-                              ssize_t (*read_fn)(void *, void *, size_t),
-                              ssize_t (*write_fn)(void *, void *, size_t))
-{
-       char *buf;
-       size_t total = 0;
-       ssize_t read_ret;
-       ssize_t write_ret;
-       size_t num_to_read_thistime;
-       size_t num_written = 0;
-
-       if ((buf = SMB_MALLOC_ARRAY(char, TRANSFER_BUF_SIZE)) == NULL)
-               return -1;
-
-       while (total < n) {
-               num_to_read_thistime = MIN((n - total), TRANSFER_BUF_SIZE);
-
-               read_ret = (*read_fn)(in_file, buf, num_to_read_thistime);
-               if (read_ret == -1) {
-                       DEBUG(0,("transfer_file_internal: read failure. Error = %s\n", strerror(errno) ));
-                       SAFE_FREE(buf);
-                       return -1;
-               }
-               if (read_ret == 0)
-                       break;
-
-               num_written = 0;
-               while (num_written < read_ret) {
-                       write_ret = (*write_fn)(out_file, buf + num_written, read_ret - num_written);
-                       if (write_ret == -1) {
-                               DEBUG(0,("transfer_file_internal: write failure. Error = %s\n", strerror(errno) ));
-                               SAFE_FREE(buf);
-                               return -1;
-                       }
-                       if (write_ret == 0)
-                               return (ssize_t)total;
-                       num_written += (size_t)write_ret;
-               }
-
-               total += (size_t)read_ret;
-       }
-
-       SAFE_FREE(buf);
-       return (ssize_t)total;          
-}
-
-static ssize_t sys_read_fn(void *file, void *buf, size_t len)
-{
-       int *fd = (int *)file;
-
-       return sys_read(*fd, buf, len);
-}
-
-static ssize_t sys_write_fn(void *file, void *buf, size_t len)
-{
-       int *fd = (int *)file;
-
-       return sys_write(*fd, buf, len);
-}
-
-SMB_OFF_T transfer_file(int infd,int outfd,SMB_OFF_T n)
-{
-       return (SMB_OFF_T)transfer_file_internal(&infd, &outfd, (size_t)n, sys_read_fn, sys_write_fn);
-}
-
 /*******************************************************************
  Sleep for a specified number of milliseconds.
 ********************************************************************/
@@ -1056,6 +1037,37 @@ void become_daemon(bool Fork, bool no_process_group)
                                  attach it to the logfile */
 }
 
+bool reinit_after_fork(struct messaging_context *msg_ctx,
+                      bool parent_longlived)
+{
+       NTSTATUS status;
+
+       /* Reset the state of the random
+        * number generation system, so
+        * children do not get the same random
+        * numbers as each other */
+       set_need_random_reseed();
+
+       /* tdb needs special fork handling */
+       if (tdb_reopen_all(parent_longlived ? 1 : 0) == -1) {
+               DEBUG(0,("tdb_reopen_all failed.\n"));
+               return false;
+       }
+
+       /*
+        * For clustering, we need to re-init our ctdbd connection after the
+        * fork
+        */
+       status = messaging_reinit(msg_ctx);
+       if (!NT_STATUS_IS_OK(status)) {
+               DEBUG(0,("messaging_reinit() failed: %s\n",
+                        nt_errstr(status)));
+               return false;
+       }
+
+       return true;
+}
+
 /****************************************************************************
  Put up a yes/no prompt.
 ****************************************************************************/
@@ -1895,10 +1907,10 @@ bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensit
  if possible.
 ********************************************************************/
  
-void set_namearray(name_compare_entry **ppname_array, char *namelist)
+void set_namearray(name_compare_entry **ppname_array, const char *namelist)
 {
        char *name_end;
-       char *nameptr = namelist;
+       const char *nameptr = namelist;
        int num_entries = 0;
        int i;
 
@@ -2123,7 +2135,7 @@ void ra_lanman_string( const char *native_lanman )
        if ( strcmp( native_lanman, "Windows 2002 5.1" ) == 0 )
                set_remote_arch( RA_WINXP );
        else if ( strcmp( native_lanman, "Windows XP 5.2" ) == 0 )
-               set_remote_arch( RA_WINXP );
+               set_remote_arch( RA_WINXP64 );
        else if ( strcmp( native_lanman, "Windows Server 2003 5.2" ) == 0 )
                set_remote_arch( RA_WIN2K3 );
 }
@@ -2164,6 +2176,9 @@ void set_remote_arch(enum remote_arch_types type)
        case RA_WINXP:
                remote_arch_str = "WinXP";
                break;
+       case RA_WINXP64:
+               remote_arch_str = "WinXP64";
+               break;
        case RA_WIN2K3:
                remote_arch_str = "Win2K3";
                break;
@@ -2202,25 +2217,60 @@ void print_asc(int level, const unsigned char *buf,int len)
                DEBUG(level,("%c", isprint(buf[i])?buf[i]:'.'));
 }
 
-void dump_data(int level, const unsigned char *buf1,int len)
+/**
+ * Write dump of binary data to the log file.
+ *
+ * The data is only written if the log level is at least level.
+ */
+static void _dump_data(int level, const uint8_t *buf, int len,
+                      bool omit_zero_bytes)
 {
-       const unsigned char *buf = (const unsigned char *)buf1;
        int i=0;
+       const uint8_t empty[16];
+       bool skipped = false;
+
        if (len<=0) return;
 
        if (!DEBUGLVL(level)) return;
-       
-       DEBUGADD(level,("[%03X] ",i));
+
+       memset(&empty, '\0', 16);
+
        for (i=0;i<len;) {
+
+               if (i%16 == 0) {
+                       if ((omit_zero_bytes == true) &&
+                           (i > 0) &&
+                           (len > i+16) &&
+                           (memcmp(&buf[i], &empty, 16) == 0))
+                       {
+                               i +=16;
+                               continue;
+                       }
+
+                       if (i<len)  {
+                               DEBUGADD(level,("[%04X] ",i));
+                       }
+               }
+
                DEBUGADD(level,("%02X ",(int)buf[i]));
                i++;
-               if (i%8 == 0) DEBUGADD(level,(" "));
-               if (i%16 == 0) {      
+               if (i%8 == 0) DEBUGADD(level,("  "));
+               if (i%16 == 0) {
+
                        print_asc(level,&buf[i-16],8); DEBUGADD(level,(" "));
                        print_asc(level,&buf[i-8],8); DEBUGADD(level,("\n"));
-                       if (i<len) DEBUGADD(level,("[%03X] ",i));
+
+                       if ((omit_zero_bytes == true) &&
+                           (len > i+16) &&
+                           (memcmp(&buf[i], &empty, 16) == 0)) {
+                               if (!skipped) {
+                                       DEBUGADD(level,("skipping zero buffer bytes\n"));
+                                       skipped = true;
+                               }
+                       }
                }
        }
+
        if (i%16) {
                int n;
                n = 16 - (i%16);
@@ -2233,8 +2283,32 @@ void dump_data(int level, const unsigned char *buf1,int len)
                if (n>0) print_asc(level,&buf[i-n],n);
                DEBUGADD(level,("\n"));
        }
+
+}
+
+/**
+ * Write dump of binary data to the log file.
+ *
+ * The data is only written if the log level is at least level.
+ */
+_PUBLIC_ void dump_data(int level, const uint8_t *buf, int len)
+{
+       _dump_data(level, buf, len, false);
 }
 
+/**
+ * Write dump of binary data to the log file.
+ *
+ * The data is only written if the log level is at least level.
+ * 16 zero bytes in a row are ommited
+ */
+_PUBLIC_ void dump_data_skip_zeros(int level, const uint8_t *buf, int len)
+{
+       _dump_data(level, buf, len, true);
+}
+
+
+
 void dump_data_pw(const char *msg, const uchar * data, size_t len)
 {
 #ifdef DEBUG_PASSWORD
@@ -2248,7 +2322,7 @@ void dump_data_pw(const char *msg, const uchar * data, size_t len)
 
 const char *tab_depth(int level, int depth)
 {
-       if( DEBUGLVL(level) ) {
+       if( CHECK_DEBUGLVL(level) ) {
                dbgtext("%*s", depth*4, "");
        }
        return "";
@@ -2497,6 +2571,7 @@ char *smb_xstrndup(const char *s, size_t n)
        if (n == -1 || ! *ptr) {
                smb_panic("smb_xvasprintf: out of memory");
        }
+       va_end(ap2);
        return n;
 }
 
@@ -2586,6 +2661,19 @@ char *lib_path(const char *name)
        return talloc_asprintf(talloc_tos(), "%s/%s", get_dyn_LIBDIR(), name);
 }
 
+/**
+ * @brief Returns an absolute path to a file in the Samba modules directory.
+ *
+ * @param name File to find, relative to MODULESDIR.
+ *
+ * @retval Pointer to a string containing the full path.
+ **/
+
+char *modules_path(const char *name)
+{
+       return talloc_asprintf(talloc_tos(), "%s/%s", get_dyn_MODULESDIR(), name);
+}
+
 /**
  * @brief Returns an absolute path to a file in the Samba data directory.
  *
@@ -2961,6 +3049,32 @@ void *talloc_check_name_abort(const void *ptr, const char *name)
        return NULL;
 }
 
+/**********************************************************************
+ Append a DATA_BLOB to a talloc'ed object
+***********************************************************************/
+
+void *talloc_append_blob(TALLOC_CTX *mem_ctx, void *buf, DATA_BLOB blob)
+{
+       size_t old_size = 0;
+       char *result;
+
+       if (blob.length == 0) {
+               return buf;
+       }
+
+       if (buf != NULL) {
+               old_size = talloc_get_size(buf);
+       }
+
+       result = (char *)TALLOC_REALLOC(mem_ctx, buf, old_size + blob.length);
+       if (result == NULL) {
+               return NULL;
+       }
+
+       memcpy(result + old_size, blob.data, blob.length);
+       return result;
+}
+
 uint32 map_share_mode_to_deny_mode(uint32 share_access, uint32 private_options)
 {
        switch (share_access & ~FILE_SHARE_DELETE) {
@@ -3058,7 +3172,7 @@ struct server_id interpret_pid(const char *pid_string)
                result.pid = pid;
        }
        else if (sscanf(pid_string, "%u", &pid) == 1) {
-               result.vnn = NONCLUSTER_VNN;
+               result.vnn = get_my_vnn();
                result.pid = pid;
        }
        else {
@@ -3339,3 +3453,130 @@ void *talloc_zeronull(const void *context, size_t size, const char *name)
        return talloc_named_const(context, size, name);
 }
 #endif
+
+/* Split a path name into filename and stream name components. Canonicalise
+ * such that an implicit $DATA token is always explicit.
+ *
+ * The "specification" of this function can be found in the
+ * run_local_stream_name() function in torture.c, I've tried those
+ * combinations against a W2k3 server.
+ */
+
+NTSTATUS split_ntfs_stream_name(TALLOC_CTX *mem_ctx, const char *fname,
+                               char **pbase, char **pstream)
+{
+       char *base = NULL;
+       char *stream = NULL;
+       char *sname; /* stream name */
+       const char *stype; /* stream type */
+
+       DEBUG(10, ("split_ntfs_stream_name called for [%s]\n", fname));
+
+       sname = strchr_m(fname, ':');
+
+       if (lp_posix_pathnames() || (sname == NULL)) {
+               if (pbase != NULL) {
+                       base = talloc_strdup(mem_ctx, fname);
+                       NT_STATUS_HAVE_NO_MEMORY(base);
+               }
+               goto done;
+       }
+
+       if (pbase != NULL) {
+               base = talloc_strndup(mem_ctx, fname, PTR_DIFF(sname, fname));
+               NT_STATUS_HAVE_NO_MEMORY(base);
+       }
+
+       sname += 1;
+
+       stype = strchr_m(sname, ':');
+
+       if (stype == NULL) {
+               sname = talloc_strdup(mem_ctx, sname);
+               stype = "$DATA";
+       }
+       else {
+               if (StrCaseCmp(stype, ":$DATA") != 0) {
+                       /*
+                        * If there is an explicit stream type, so far we only
+                        * allow $DATA. Is there anything else allowed? -- vl
+                        */
+                       DEBUG(10, ("[%s] is an invalid stream type\n", stype));
+                       TALLOC_FREE(base);
+                       return NT_STATUS_OBJECT_NAME_INVALID;
+               }
+               sname = talloc_strndup(mem_ctx, sname, PTR_DIFF(stype, sname));
+               stype += 1;
+       }
+
+       if (sname == NULL) {
+               TALLOC_FREE(base);
+               return NT_STATUS_NO_MEMORY;
+       }
+
+       if (sname[0] == '\0') {
+               /*
+                * no stream name, so no stream
+                */
+               goto done;
+       }
+
+       if (pstream != NULL) {
+               stream = talloc_asprintf(mem_ctx, "%s:%s", sname, stype);
+               if (stream == NULL) {
+                       TALLOC_FREE(sname);
+                       TALLOC_FREE(base);
+                       return NT_STATUS_NO_MEMORY;
+               }
+               /*
+                * upper-case the type field
+                */
+               strupper_m(strchr_m(stream, ':')+1);
+       }
+
+ done:
+       if (pbase != NULL) {
+               *pbase = base;
+       }
+       if (pstream != NULL) {
+               *pstream = stream;
+       }
+       return NT_STATUS_OK;
+}
+
+bool is_valid_policy_hnd(const POLICY_HND *hnd)
+{
+       POLICY_HND tmp;
+       ZERO_STRUCT(tmp);
+       return (memcmp(&tmp, hnd, sizeof(tmp)) != 0);
+}
+
+bool policy_hnd_equal(const struct policy_handle *hnd1,
+                     const struct policy_handle *hnd2)
+{
+       if (!hnd1 || !hnd2) {
+               return false;
+       }
+
+       return (memcmp(hnd1, hnd2, sizeof(*hnd1)) == 0);
+}
+
+/****************************************************************
+ strip off leading '\\' from a hostname
+****************************************************************/
+
+const char *strip_hostname(const char *s)
+{
+       if (!s) {
+               return NULL;
+       }
+
+       if (strlen_m(s) < 3) {
+               return s;
+       }
+
+       if (s[0] == '\\') s++;
+       if (s[0] == '\\') s++;
+
+       return s;
+}