Share ndrdump implementation.
[sfrench/samba-autobuild/.git] / source3 / lib / util.c
index b25190b2f778e2f7a8d12d7dbe56860a5ea3fadd..418ae41392b2d83ef1e262a064bf360f2efc5a90 100644 (file)
@@ -2,7 +2,7 @@
    Unix SMB/CIFS implementation.
    Samba utility functions
    Copyright (C) Andrew Tridgell 1992-1998
-   Copyright (C) Jeremy Allison 2001-2002
+   Copyright (C) Jeremy Allison 2001-2007
    Copyright (C) Simo Sorce 2001
    Copyright (C) Jim McDonough <jmcd@us.ibm.com> 2003
    Copyright (C) James Peach 2006
 
 #include "includes.h"
 
-extern fstring local_machine;
 extern char *global_clobber_region_function;
 extern unsigned int global_clobber_region_line;
-extern fstring remote_arch;
 
 /* Max allowable allococation - 256mb - 0x10000000 */
 #define MAX_ALLOC_SIZE (1024*1024*256)
@@ -59,16 +57,10 @@ extern fstring remote_arch;
 
 enum protocol_types Protocol = PROTOCOL_COREPLUS;
 
-/* a default finfo structure to ensure all fields are sensible */
-file_info def_finfo;
-
 /* this is used by the chaining code */
 int chain_size = 0;
 
-int trans_num = 0;
-
 static enum remote_arch_types ra_type = RA_UNKNOWN;
-pstring user_socket_options=DEFAULT_SOCKET_OPTIONS;   
 
 /***********************************************************************
  Definitions for all names.
@@ -84,7 +76,7 @@ static char **smb_my_netbios_names;
  Allocate and set myname. Ensure upper case.
 ***********************************************************************/
 
-BOOL set_global_myname(const char *myname)
+bool set_global_myname(const char *myname)
 {
        SAFE_FREE(smb_myname);
        smb_myname = SMB_STRDUP(myname);
@@ -103,7 +95,7 @@ const char *global_myname(void)
  Allocate and set myworkgroup. Ensure upper case.
 ***********************************************************************/
 
-BOOL set_global_myworkgroup(const char *myworkgroup)
+bool set_global_myworkgroup(const char *myworkgroup)
 {
        SAFE_FREE(smb_myworkgroup);
        smb_myworkgroup = SMB_STRDUP(myworkgroup);
@@ -122,7 +114,7 @@ const char *lp_workgroup(void)
  Allocate and set scope. Ensure upper case.
 ***********************************************************************/
 
-BOOL set_global_scope(const char *scope)
+bool set_global_scope(const char *scope)
 {
        SAFE_FREE(smb_scope);
        smb_scope = SMB_STRDUP(scope);
@@ -154,7 +146,7 @@ static void free_netbios_names_array(void)
        smb_num_netbios_names = 0;
 }
 
-static BOOL allocate_my_netbios_names_array(size_t number)
+static bool allocate_my_netbios_names_array(size_t number)
 {
        free_netbios_names_array();
 
@@ -168,7 +160,7 @@ static BOOL allocate_my_netbios_names_array(size_t number)
        return True;
 }
 
-static BOOL set_my_netbios_names(const char *name, int i)
+static bool set_my_netbios_names(const char *name, int i)
 {
        SAFE_FREE(smb_my_netbios_names[i]);
 
@@ -189,19 +181,17 @@ void gfree_names(void)
        SAFE_FREE( smb_myworkgroup );
        SAFE_FREE( smb_scope );
        free_netbios_names_array();
+       free_local_machine_name();
 }
 
 void gfree_all( void )
 {
-       gfree_names();  
+       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)
@@ -209,7 +199,7 @@ const char *my_netbios_names(int i)
        return smb_my_netbios_names[i];
 }
 
-BOOL set_netbios_aliases(const char **str_array)
+bool set_netbios_aliases(const char **str_array)
 {
        size_t namecount;
 
@@ -235,7 +225,7 @@ BOOL set_netbios_aliases(const char **str_array)
                size_t i;
                for ( i = 0; str_array[i] != NULL; i++) {
                        size_t n;
-                       BOOL duplicate = False;
+                       bool duplicate = False;
 
                        /* Look for duplicates */
                        for( n=0; n<namecount; n++ ) {
@@ -258,9 +248,8 @@ BOOL set_netbios_aliases(const char **str_array)
   Common name initialization code.
 ****************************************************************************/
 
-BOOL init_names(void)
+bool init_names(void)
 {
-       char *p;
        int n;
 
        if (global_myname() == NULL || *global_myname() == '\0') {
@@ -273,22 +262,183 @@ BOOL init_names(void)
        if (!set_netbios_aliases(lp_netbios_aliases())) {
                DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
                return False;
-       }                       
+       }
 
-       fstrcpy( local_machine, global_myname() );
-       trim_char( local_machine, ' ', ' ' );
-       p = strchr( local_machine, ' ' );
-       if (p)
-               *p = 0;
-       strlower_m( local_machine );
+       set_local_machine_name(global_myname(),false);
 
        DEBUG( 5, ("Netbios name list:-\n") );
-       for( n=0; my_netbios_names(n); n++ )
-               DEBUGADD( 5, ( "my_netbios_names[%d]=\"%s\"\n", n, my_netbios_names(n) ) );
+       for( n=0; my_netbios_names(n); n++ ) {
+               DEBUGADD( 5, ("my_netbios_names[%d]=\"%s\"\n",
+                                       n, my_netbios_names(n) ) );
+       }
 
        return( True );
 }
 
+/**************************************************************************n
+  Code to cope with username/password auth options from the commandline.
+  Used mainly in client tools.
+****************************************************************************/
+
+static struct user_auth_info cmdline_auth_info = {
+       NULL,   /* username */
+       NULL,   /* password */
+       false,  /* got_pass */
+       false,  /* use_kerberos */
+       Undefined, /* signing state */
+       false,  /* smb_encrypt */
+       false   /* use machine account */
+};
+
+const char *get_cmdline_auth_info_username(void)
+{
+       if (!cmdline_auth_info.username) {
+               return "";
+       }
+       return cmdline_auth_info.username;
+}
+
+void set_cmdline_auth_info_username(const char *username)
+{
+       SAFE_FREE(cmdline_auth_info.username);
+       cmdline_auth_info.username = SMB_STRDUP(username);
+       if (!cmdline_auth_info.username) {
+               exit(ENOMEM);
+       }
+}
+
+const char *get_cmdline_auth_info_password(void)
+{
+       if (!cmdline_auth_info.password) {
+               return "";
+       }
+       return cmdline_auth_info.password;
+}
+
+void set_cmdline_auth_info_password(const char *password)
+{
+       SAFE_FREE(cmdline_auth_info.password);
+       cmdline_auth_info.password = SMB_STRDUP(password);
+       if (!cmdline_auth_info.password) {
+               exit(ENOMEM);
+       }
+       cmdline_auth_info.got_pass = true;
+}
+
+bool set_cmdline_auth_info_signing_state(const char *arg)
+{
+       cmdline_auth_info.signing_state = -1;
+       if (strequal(arg, "off") || strequal(arg, "no") ||
+                       strequal(arg, "false")) {
+               cmdline_auth_info.signing_state = false;
+       } else if (strequal(arg, "on") || strequal(arg, "yes") ||
+                       strequal(arg, "true") || strequal(arg, "auto")) {
+               cmdline_auth_info.signing_state = true;
+       } else if (strequal(arg, "force") || strequal(arg, "required") ||
+                       strequal(arg, "forced")) {
+               cmdline_auth_info.signing_state = Required;
+       } else {
+               return false;
+       }
+       return true;
+}
+
+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;
+}
+
+/* This should only be used by lib/popt_common.c JRA */
+void set_cmdline_auth_info_use_krb5_ticket(void)
+{
+       cmdline_auth_info.use_kerberos = true;
+       cmdline_auth_info.got_pass = true;
+}
+
+/* This should only be used by lib/popt_common.c JRA */
+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;
+}
+
+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;
+       /* Now re-alloc the strings. */
+       info->username = SMB_STRDUP(get_cmdline_auth_info_username());
+       info->password = SMB_STRDUP(get_cmdline_auth_info_password());
+       if (!info->username || !info->password) {
+               return false;
+       }
+       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.
@@ -306,7 +456,7 @@ const char *tmpdir(void)
  Add a gid to an array of gids if it's not already there.
 ****************************************************************************/
 
-BOOL add_gid_to_array_unique(TALLOC_CTX *mem_ctx, gid_t gid,
+bool add_gid_to_array_unique(TALLOC_CTX *mem_ctx, gid_t gid,
                             gid_t **gids, size_t *num_gids)
 {
        int i;
@@ -390,7 +540,7 @@ const char *get_numlist(const char *p, uint32 **num, int *count)
  Check if a file exists - call vfs_file_exist for samba files.
 ********************************************************************/
 
-BOOL file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
+bool file_exist(const char *fname,SMB_STRUCT_STAT *sbuf)
 {
        SMB_STRUCT_STAT st;
        if (!sbuf)
@@ -402,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.
 ********************************************************************/
@@ -420,10 +583,10 @@ time_t file_modtime(const char *fname)
  Check if a directory exists.
 ********************************************************************/
 
-BOOL directory_exist(char *dname,SMB_STRUCT_STAT *st)
+bool directory_exist(char *dname,SMB_STRUCT_STAT *st)
 {
        SMB_STRUCT_STAT st2;
-       BOOL ret;
+       bool ret;
 
        if (!st)
                st = &st2;
@@ -515,32 +678,30 @@ void show_msg(char *buf)
 }
 
 /*******************************************************************
- Set the length and marker of an smb packet.
+ Set the length and marker of an encrypted smb packet.
 ********************************************************************/
 
-void smb_setlen(char *buf,int len)
+void smb_set_enclen(char *buf,int len,uint16 enc_ctx_num)
 {
        _smb_setlen(buf,len);
 
        SCVAL(buf,4,0xFF);
-       SCVAL(buf,5,'S');
-       SCVAL(buf,6,'M');
-       SCVAL(buf,7,'B');
+       SCVAL(buf,5,'E');
+       SSVAL(buf,6,enc_ctx_num);
 }
 
 /*******************************************************************
- Setup the word count and byte count for a smb message.
+ Set the length and marker of an smb packet.
 ********************************************************************/
 
-int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
+void smb_setlen(char *buf,int len)
 {
-       if (zero && (num_words || num_bytes)) {
-               memset(buf + smb_size,'\0',num_words*2 + num_bytes);
-       }
-       SCVAL(buf,smb_wct,num_words);
-       SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
-       smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
-       return (smb_size + num_words*2 + num_bytes);
+       _smb_setlen(buf,len);
+
+       SCVAL(buf,4,0xFF);
+       SCVAL(buf,5,'S');
+       SCVAL(buf,6,'M');
+       SCVAL(buf,7,'B');
 }
 
 /*******************************************************************
@@ -550,21 +711,11 @@ int set_message(char *buf,int num_words,int num_bytes,BOOL zero)
 int set_message_bcc(char *buf,int num_bytes)
 {
        int num_words = CVAL(buf,smb_wct);
-       SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);  
-       smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
+       SSVAL(buf,smb_vwv + num_words*SIZEOFWORD,num_bytes);
+       _smb_setlen(buf,smb_size + num_words*2 + num_bytes - 4);
        return (smb_size + num_words*2 + num_bytes);
 }
 
-/*******************************************************************
- Setup only the byte count for a smb message, using the end of the
- message as a marker.
-********************************************************************/
-
-int set_message_end(void *outbuf,void *end_ptr)
-{
-       return set_message_bcc((char *)outbuf,PTR_DIFF(end_ptr,smb_buf((char *)outbuf)));
-}
-
 /*******************************************************************
  Add a data blob to the end of a smb_buf, adjusting bcc and smb_len.
  Return the bytes added
@@ -590,94 +741,127 @@ ssize_t message_push_blob(uint8 **outbuf, DATA_BLOB blob)
  Reduce a file name, removing .. elements.
 ********************************************************************/
 
-void dos_clean_name(char *s)
+static char *dos_clean_name(TALLOC_CTX *ctx, const char *s)
 {
-       char *p=NULL;
+       char *p = NULL;
+       char *str = NULL;
 
        DEBUG(3,("dos_clean_name [%s]\n",s));
 
        /* remove any double slashes */
-       all_string_sub(s, "\\\\", "\\", 0);
+       str = talloc_all_string_sub(ctx, s, "\\\\", "\\");
+       if (!str) {
+               return NULL;
+       }
 
        /* Remove leading .\\ characters */
-       if(strncmp(s, ".\\", 2) == 0) {
-               trim_string(s, ".\\", NULL);
-               if(*s == 0)
-                       pstrcpy(s,".\\");
+       if(strncmp(str, ".\\", 2) == 0) {
+               trim_string(str, ".\\", NULL);
+               if(*str == 0) {
+                       str = talloc_strdup(ctx, ".\\");
+                       if (!str) {
+                               return NULL;
+                       }
+               }
        }
 
-       while ((p = strstr_m(s,"\\..\\")) != NULL) {
-               pstring s1;
+       while ((p = strstr_m(str,"\\..\\")) != NULL) {
+               char *s1;
 
                *p = 0;
-               pstrcpy(s1,p+3);
+               s1 = p+3;
 
-               if ((p=strrchr_m(s,'\\')) != NULL)
+               if ((p=strrchr_m(str,'\\')) != NULL) {
                        *p = 0;
-               else
-                       *s = 0;
-               pstrcat(s,s1);
-       }  
+               } else {
+                       *str = 0;
+               }
+               str = talloc_asprintf(ctx,
+                               "%s%s",
+                               str,
+                               s1);
+               if (!str) {
+                       return NULL;
+               }
+       }
 
-       trim_string(s,NULL,"\\..");
-       all_string_sub(s, "\\.\\", "\\", 0);
+       trim_string(str,NULL,"\\..");
+       return talloc_all_string_sub(ctx, str, "\\.\\", "\\");
 }
 
 /*******************************************************************
- Reduce a file name, removing .. elements. 
+ Reduce a file name, removing .. elements.
 ********************************************************************/
 
-void unix_clean_name(char *s)
+char *unix_clean_name(TALLOC_CTX *ctx, const char *s)
 {
-       char *p=NULL;
+       char *p = NULL;
+       char *str = NULL;
 
        DEBUG(3,("unix_clean_name [%s]\n",s));
 
        /* remove any double slashes */
-       all_string_sub(s, "//","/", 0);
+       str = talloc_all_string_sub(ctx, s, "//","/");
+       if (!str) {
+               return NULL;
+       }
 
        /* Remove leading ./ characters */
-       if(strncmp(s, "./", 2) == 0) {
-               trim_string(s, "./", NULL);
-               if(*s == 0)
-                       pstrcpy(s,"./");
+       if(strncmp(str, "./", 2) == 0) {
+               trim_string(str, "./", NULL);
+               if(*str == 0) {
+                       str = talloc_strdup(ctx, "./");
+                       if (!str) {
+                               return NULL;
+                       }
+               }
        }
 
-       while ((p = strstr_m(s,"/../")) != NULL) {
-               pstring s1;
+       while ((p = strstr_m(str,"/../")) != NULL) {
+               char *s1;
 
                *p = 0;
-               pstrcpy(s1,p+3);
+               s1 = p+3;
 
-               if ((p=strrchr_m(s,'/')) != NULL)
+               if ((p=strrchr_m(str,'/')) != NULL) {
                        *p = 0;
-               else
-                       *s = 0;
-               pstrcat(s,s1);
-       }  
+               } else {
+                       *str = 0;
+               }
+               str = talloc_asprintf(ctx,
+                               "%s%s",
+                               str,
+                               s1);
+               if (!str) {
+                       return NULL;
+               }
+       }
 
-       trim_string(s,NULL,"/..");
-       all_string_sub(s, "/./", "/", 0);
+       trim_string(str,NULL,"/..");
+       return talloc_all_string_sub(ctx, str, "/./", "/");
 }
 
-void clean_name(char *s)
+char *clean_name(TALLOC_CTX *ctx, const char *s)
 {
-       dos_clean_name(s);
-       unix_clean_name(s);
+       char *str = dos_clean_name(ctx, s);
+       if (!str) {
+               return NULL;
+       }
+       return unix_clean_name(ctx, str);
 }
 
 /*******************************************************************
  Close the low 3 fd's and open dev/null in their place.
 ********************************************************************/
 
-void close_low_fds(BOOL stderr_too)
+void close_low_fds(bool stderr_too)
 {
 #ifndef VALGRIND
        int fd;
        int i;
 
        close(0);
-       close(1); 
+       close(1);
 
        if (stderr_too)
                close(2);
@@ -750,7 +934,7 @@ ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, SMB_OFF_T pos
   if BSD use FNDELAY
 ****************************************************************************/
 
-int set_blocking(int fd, BOOL set)
+int set_blocking(int fd, bool set)
 {
        int val;
 #ifdef O_NONBLOCK
@@ -773,67 +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(int infd, int outfd, size_t n, ssize_t (*read_fn)(int, void *, size_t),
-                                               ssize_t (*write_fn)(int, const 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)(infd, 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)(outfd,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;          
-}
-
-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, sys_write);
-}
-
 /*******************************************************************
  Sleep for a specified number of milliseconds.
 ********************************************************************/
@@ -888,7 +1011,7 @@ void smb_msleep(unsigned int t)
  Become a daemon, discarding the controlling terminal.
 ****************************************************************************/
 
-void become_daemon(BOOL Fork, BOOL no_process_group)
+void become_daemon(bool Fork, bool no_process_group)
 {
        if (Fork) {
                if (sys_fork()) {
@@ -914,13 +1037,44 @@ 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.
 ****************************************************************************/
 
-BOOL yesno(char *p)
+bool yesno(const char *p)
 {
-       pstring ans;
+       char ans[20];
        printf("%s",p);
 
        if (!fgets(ans,sizeof(ans)-1,stdin))
@@ -1059,7 +1213,7 @@ void *calloc_array(size_t size, size_t nmemb)
  Changes were instigated by Coverity error checking. JRA.
 ****************************************************************************/
 
-void *Realloc(void *p, size_t size, BOOL free_old_on_error)
+void *Realloc(void *p, size_t size, bool free_old_on_error)
 {
        void *ret=NULL;
 
@@ -1099,7 +1253,7 @@ void *Realloc(void *p, size_t size, BOOL free_old_on_error)
  Type-safe realloc.
 ****************************************************************************/
 
-void *realloc_array(void *p, size_t el_size, unsigned int count, BOOL free_old_on_error)
+void *realloc_array(void *p, size_t el_size, unsigned int count, bool free_old_on_error)
 {
        if (count >= MAX_ALLOC_SIZE/el_size) {
                if (free_old_on_error) {
@@ -1180,9 +1334,10 @@ void safe_free(void *p)
  Get my own name and IP.
 ****************************************************************************/
 
-BOOL get_myname(char *my_name)
+char *get_myname(TALLOC_CTX *ctx)
 {
-       fstring hostname;
+       char *p;
+       char hostname[HOST_NAME_MAX];
 
        *hostname = 0;
 
@@ -1195,40 +1350,36 @@ BOOL get_myname(char *my_name)
        /* Ensure null termination. */
        hostname[sizeof(hostname)-1] = '\0';
 
-       if (my_name) {
-               /* split off any parts after an initial . */
-               char *p = strchr_m(hostname,'.');
-
-               if (p)
-                       *p = 0;
-
-               fstrcpy(my_name,hostname);
+       /* split off any parts after an initial . */
+       p = strchr_m(hostname,'.');
+       if (p) {
+               *p = 0;
        }
 
-       return(True);
+       return talloc_strdup(ctx, hostname);
 }
 
 /****************************************************************************
- Get my own domain name.
+ Get my own domain name, or "" if we have none.
 ****************************************************************************/
 
-BOOL get_mydnsdomname(fstring my_domname)
+char *get_mydnsdomname(TALLOC_CTX *ctx)
 {
-       fstring domname;
+       const char *domname;
        char *p;
 
-       *my_domname = '\0';
-       if (!get_mydnsfullname(domname)) {
-               return False;
-       }       
+       domname = get_mydnsfullname();
+       if (!domname) {
+               return NULL;
+       }
+
        p = strchr_m(domname, '.');
        if (p) {
                p++;
-               fstrcpy(my_domname, p);
-               return True;
+               return talloc_strdup(ctx, p);
+       } else {
+               return talloc_strdup(ctx, "");
        }
-
-       return False;
 }
 
 /****************************************************************************
@@ -1260,80 +1411,83 @@ int interpret_protocol(const char *str,int def)
 /******************************************************************
  Remove any mount options such as -rsize=2048,wsize=2048 etc.
  Based on a fix from <Thomas.Hepper@icem.de>.
+ Returns a malloc'ed string.
 *******************************************************************/
 
-static void strip_mount_options( pstring *str)
+static char *strip_mount_options(TALLOC_CTX *ctx, const char *str)
 {
-       if (**str == '-') { 
-               char *p = *str;
+       if (*str == '-') {
+               const char *p = str;
                while(*p && !isspace(*p))
                        p++;
                while(*p && isspace(*p))
                        p++;
                if(*p) {
-                       pstring tmp_str;
-
-                       pstrcpy(tmp_str, p);
-                       pstrcpy(*str, tmp_str);
+                       return talloc_strdup(ctx, p);
                }
        }
+       return NULL;
 }
 
 /*******************************************************************
  Patch from jkf@soton.ac.uk
  Split Luke's automount_server into YP lookup and string splitter
- so can easily implement automount_path(). 
- As we may end up doing both, cache the last YP result. 
+ so can easily implement automount_path().
+ Returns a malloc'ed string.
 *******************************************************************/
 
 #ifdef WITH_NISPLUS_HOME
-char *automount_lookup(const char *user_name)
+char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
 {
-       static fstring last_key = "";
-       static pstring last_value = "";
+       char *value = NULL;
+
        char *nis_map = (char *)lp_nis_home_map_name();
+
        char buffer[NIS_MAXATTRVAL + 1];
        nis_result *result;
        nis_object *object;
        entry_obj  *entry;
-       if (strcmp(user_name, last_key)) {
-               slprintf(buffer, sizeof(buffer)-1, "[key=%s],%s", user_name, nis_map);
-               DEBUG(5, ("NIS+ querystring: %s\n", buffer));
-               if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
-                       if (result->status != NIS_SUCCESS) {
-                               DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
-                               fstrcpy(last_key, ""); pstrcpy(last_value, "");
-                       } else {
-                               object = result->objects.objects_val;
-                               if (object->zo_data.zo_type == ENTRY_OBJ) {
-                                       entry = &object->zo_data.objdata_u.en_data;
-                                       DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
-                                       DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
-                                       pstrcpy(last_value, entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
-                                       pstring_sub(last_value, "&", user_name);
-                                       fstrcpy(last_key, user_name);
+
+       snprintf(buffer, sizeof(buffer), "[key=%s],%s", user_name, nis_map);
+       DEBUG(5, ("NIS+ querystring: %s\n", buffer));
+
+       if (result = nis_list(buffer, FOLLOW_PATH|EXPAND_NAME|HARD_LOOKUP, NULL, NULL)) {
+               if (result->status != NIS_SUCCESS) {
+                       DEBUG(3, ("NIS+ query failed: %s\n", nis_sperrno(result->status)));
+               } else {
+                       object = result->objects.objects_val;
+                       if (object->zo_data.zo_type == ENTRY_OBJ) {
+                               entry = &object->zo_data.objdata_u.en_data;
+                               DEBUG(5, ("NIS+ entry type: %s\n", entry->en_type));
+                               DEBUG(3, ("NIS+ result: %s\n", entry->en_cols.en_cols_val[1].ec_value.ec_value_val));
+
+                               value = talloc_strdup(ctx,
+                                               entry->en_cols.en_cols_val[1].ec_value.ec_value_val);
+                               if (!value) {
+                                       nis_freeresult(result);
+                                       return NULL;
                                }
+                               value = talloc_string_sub(ctx,
+                                               value,
+                                               "&",
+                                               user_name);
                        }
                }
-               nis_freeresult(result);
        }
+       nis_freeresult(result);
 
-       strip_mount_options(&last_value);
-
-       DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n", user_name, last_value));
-       return last_value;
+       if (value) {
+               value = strip_mount_options(ctx, value);
+               DEBUG(4, ("NIS+ Lookup: %s resulted in %s\n",
+                                       user_name, value));
+       }
+       return value;
 }
 #else /* WITH_NISPLUS_HOME */
 
-char *automount_lookup(const char *user_name)
+char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
 {
-       static fstring last_key = "";
-       static pstring last_value = "";
+       char *value = NULL;
 
        int nis_error;        /* returned by yp all functions */
        char *nis_result;     /* yp_match inits this */
@@ -1343,38 +1497,32 @@ char *automount_lookup(const char *user_name)
 
        if ((nis_error = yp_get_default_domain(&nis_domain)) != 0) {
                DEBUG(3, ("YP Error: %s\n", yperr_string(nis_error)));
-               return last_value;
+               return NULL;
        }
 
        DEBUG(5, ("NIS Domain: %s\n", nis_domain));
 
-       if (!strcmp(user_name, last_key)) {
-               nis_result = last_value;
-               nis_result_len = strlen(last_value);
-               nis_error = 0;
-       } else {
-               if ((nis_error = yp_match(nis_domain, nis_map, user_name, strlen(user_name),
-                               &nis_result, &nis_result_len)) == 0) {
-                       fstrcpy(last_key, user_name);
-                       pstrcpy(last_value, nis_result);
-                       strip_mount_options(&last_value);
-
-               } else if(nis_error == YPERR_KEY) {
-
-                       /* If Key lookup fails user home server is not in nis_map 
-                               use default information for server, and home directory */
-                       last_value[0] = 0;
-                       DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
-                                       user_name, nis_map));
-                       DEBUG(3, ("using defaults for server and home directory\n"));
-               } else {
-                       DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
-                                       yperr_string(nis_error), user_name, nis_map));
+       if ((nis_error = yp_match(nis_domain, nis_map, user_name,
+                                       strlen(user_name), &nis_result,
+                                       &nis_result_len)) == 0) {
+               value = talloc_strdup(ctx, nis_result);
+               if (!value) {
+                       return NULL;
                }
+               value = strip_mount_options(ctx, value);
+       } else if(nis_error == YPERR_KEY) {
+               DEBUG(3, ("YP Key not found:  while looking up \"%s\" in map \"%s\"\n", 
+                               user_name, nis_map));
+               DEBUG(3, ("using defaults for server and home directory\n"));
+       } else {
+               DEBUG(3, ("YP Error: \"%s\" while looking up \"%s\" in map \"%s\"\n", 
+                               yperr_string(nis_error), user_name, nis_map));
        }
 
-       DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, last_value));
-       return last_value;
+       if (value) {
+               DEBUG(4, ("YP Lookup: %s resulted in %s\n", user_name, value));
+       }
+       return value;
 }
 #endif /* WITH_NISPLUS_HOME */
 #endif
@@ -1383,7 +1531,7 @@ char *automount_lookup(const char *user_name)
  Check if a process exists. Does this work on all unixes?
 ****************************************************************************/
 
-BOOL process_exists(const struct server_id pid)
+bool process_exists(const struct server_id pid)
 {
        if (procid_is_me(&pid)) {
                return True;
@@ -1401,7 +1549,7 @@ BOOL process_exists(const struct server_id pid)
 #endif
 }
 
-BOOL process_exists_by_pid(pid_t pid)
+bool process_exists_by_pid(pid_t pid)
 {
        /* Doing kill with a non-positive pid causes messages to be
         * sent to places we don't want. */
@@ -1437,21 +1585,21 @@ const char *uidtoname(uid_t uid)
 
 char *gidtoname(gid_t gid)
 {
-       fstring name;
        struct group *grp;
 
        grp = getgrgid(gid);
        if (grp) {
-               fstrcpy(name, grp->gr_name);
+               return talloc_strdup(talloc_tos(), grp->gr_name);
        }
        else {
-               slprintf(name,sizeof(name) - 1, "%d",(int)gid);
+               return talloc_asprintf(talloc_tos(),
+                                       "%d",
+                                       (int)gid);
        }
-       return talloc_strdup(talloc_tos(), name);
 }
 
 /*******************************************************************
- Convert a user name into a uid. 
+ Convert a user name into a uid.
 ********************************************************************/
 
 uid_t nametouid(const char *name)
@@ -1709,7 +1857,7 @@ const char *readdirname(SMB_STRUCT_DIR *p)
  of a path matches a (possibly wildcarded) entry in a namelist.
 ********************************************************************/
 
-BOOL is_in_path(const char *name, name_compare_entry *namelist, BOOL case_sensitive)
+bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensitive)
 {
        const char *last_component;
 
@@ -1759,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;
 
@@ -1860,7 +2008,7 @@ void free_namearray(name_compare_entry *name_array)
  Returns True if the lock was granted, False otherwise.
 ****************************************************************************/
 
-BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
+bool fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
 {
        SMB_STRUCT_FLOCK lock;
        int ret;
@@ -1897,7 +2045,7 @@ BOOL fcntl_lock(int fd, int op, SMB_OFF_T offset, SMB_OFF_T count, int type)
  F_UNLCK in *ptype if the region is unlocked). False if the call failed.
 ****************************************************************************/
 
-BOOL fcntl_getlock(int fd, SMB_OFF_T *poffset, SMB_OFF_T *pcount, int *ptype, pid_t *ppid)
+bool fcntl_getlock(int fd, SMB_OFF_T *poffset, SMB_OFF_T *pcount, int *ptype, pid_t *ppid)
 {
        SMB_STRUCT_FLOCK lock;
        int ret;
@@ -1939,10 +2087,10 @@ BOOL fcntl_getlock(int fd, SMB_OFF_T *poffset, SMB_OFF_T *pcount, int *ptype, pi
  Returns true if it is equal, false otherwise.
 ********************************************************************/
 
-BOOL is_myname(const char *s)
+bool is_myname(const char *s)
 {
        int n;
-       BOOL ret = False;
+       bool ret = False;
 
        for (n=0; my_netbios_names(n); n++) {
                if (strequal(my_netbios_names(n), s)) {
@@ -1959,9 +2107,9 @@ BOOL is_myname(const char *s)
  Returns true if it is equal, false otherwise.
 ********************************************************************/
 
-BOOL is_myworkgroup(const char *s)
+bool is_myworkgroup(const char *s)
 {
-       BOOL ret = False;
+       bool ret = False;
 
        if (strequal(s, lp_workgroup())) {
                ret=True;
@@ -1987,11 +2135,21 @@ 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 );
 }
 
+static const char *remote_arch_str;
+
+const char *get_remote_arch_str(void)
+{
+       if (!remote_arch_str) {
+               return "UNKNOWN";
+       }
+       return remote_arch_str;
+}
+
 /*******************************************************************
  Set the horrid remote_arch string based on an enum.
 ********************************************************************/
@@ -2001,42 +2159,46 @@ void set_remote_arch(enum remote_arch_types type)
        ra_type = type;
        switch( type ) {
        case RA_WFWG:
-               fstrcpy(remote_arch, "WfWg");
+               remote_arch_str = "WfWg";
                break;
        case RA_OS2:
-               fstrcpy(remote_arch, "OS2");
+               remote_arch_str = "OS2";
                break;
        case RA_WIN95:
-               fstrcpy(remote_arch, "Win95");
+               remote_arch_str = "Win95";
                break;
        case RA_WINNT:
-               fstrcpy(remote_arch, "WinNT");
+               remote_arch_str = "WinNT";
                break;
        case RA_WIN2K:
-               fstrcpy(remote_arch, "Win2K");
+               remote_arch_str = "Win2K";
                break;
        case RA_WINXP:
-               fstrcpy(remote_arch, "WinXP");
+               remote_arch_str = "WinXP";
+               break;
+       case RA_WINXP64:
+               remote_arch_str = "WinXP64";
                break;
        case RA_WIN2K3:
-               fstrcpy(remote_arch, "Win2K3");
+               remote_arch_str = "Win2K3";
                break;
        case RA_VISTA:
-               fstrcpy(remote_arch, "Vista");
+               remote_arch_str = "Vista";
                break;
        case RA_SAMBA:
-               fstrcpy(remote_arch,"Samba");
+               remote_arch_str = "Samba";
                break;
        case RA_CIFSFS:
-               fstrcpy(remote_arch,"CIFSFS");
+               remote_arch_str = "CIFSFS";
                break;
        default:
                ra_type = RA_UNKNOWN;
-               fstrcpy(remote_arch, "UNKNOWN");
+               remote_arch_str = "UNKNOWN";
                break;
        }
 
-       DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n", remote_arch));
+       DEBUG(10,("set_remote_arch: Client arch is \'%s\'\n",
+                               remote_arch_str));
 }
 
 /*******************************************************************
@@ -2055,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);
@@ -2083,11 +2280,35 @@ void dump_data(int level, const unsigned char *buf1,int len)
                n = MIN(8,i%16);
                print_asc(level,&buf[i-(i%16)],n); DEBUGADD(level,( " " ));
                n = (i%16) - n;
-               if (n>0) print_asc(level,&buf[i-n],n); 
-               DEBUGADD(level,("\n"));    
-       }       
+               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
@@ -2099,12 +2320,12 @@ void dump_data_pw(const char *msg, const uchar * data, size_t len)
 #endif
 }
 
-char *tab_depth(int depth)
+const char *tab_depth(int level, int depth)
 {
-       static pstring spaces;
-       memset(spaces, ' ', depth * 4);
-       spaces[depth * 4] = 0;
-       return spaces;
+       if( CHECK_DEBUGLVL(level) ) {
+               dbgtext("%*s", depth*4, "");
+       }
+       return "";
 }
 
 /*****************************************************************************
@@ -2121,7 +2342,7 @@ int str_checksum(const char *s)
        int res = 0;
        int c;
        int i=0;
-       
+
        while(*s) {
                c = *s;
                res ^= (c << (i % 15)) ^ (c >> (15-(i%15)));
@@ -2350,12 +2571,13 @@ 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;
 }
 
 /*****************************************************************
  Like strdup but for memory.
-*****************************************************************/  
+*****************************************************************/
 
 void *memdup(const void *p, size_t size)
 {
@@ -2371,34 +2593,50 @@ void *memdup(const void *p, size_t size)
 
 /*****************************************************************
  Get local hostname and cache result.
-*****************************************************************/  
+*****************************************************************/
 
 char *myhostname(void)
 {
-       static pstring ret;
-       if (ret[0] == 0)
-               get_myname(ret);
+       static char *ret;
+       if (ret == NULL) {
+               /* This is cached forever so
+                * use NULL talloc ctx. */
+               ret = get_myname(NULL);
+       }
        return ret;
 }
 
 /*****************************************************************
- A useful function for returning a path in the Samba lock directory.
-*****************************************************************/  
+ A useful function for returning a path in the Samba pid directory.
+*****************************************************************/
 
-char *lock_path(const char *name)
+static char *xx_path(const char *name, const char *rootpath)
 {
-       pstring fname;
+       char *fname = NULL;
 
-       pstrcpy(fname,lp_lockdir());
-       trim_char(fname,'\0','/');
-       
-       if (!directory_exist(fname,NULL))
+       fname = talloc_strdup(talloc_tos(), rootpath);
+       if (!fname) {
+               return NULL;
+       }
+       trim_string(fname,"","/");
+
+       if (!directory_exist(fname,NULL)) {
                mkdir(fname,0755);
-       
-       pstrcat(fname,"/");
-       pstrcat(fname,name);
+       }
+
+       return talloc_asprintf(talloc_tos(),
+                               "%s/%s",
+                               fname,
+                               name);
+}
+
+/*****************************************************************
+ A useful function for returning a path in the Samba lock directory.
+*****************************************************************/
 
-       return talloc_strdup(talloc_tos(), fname);
+char *lock_path(const char *name)
+{
+       return xx_path(name, lp_lockdir());
 }
 
 /*****************************************************************
@@ -2407,42 +2645,66 @@ char *lock_path(const char *name)
 
 char *pid_path(const char *name)
 {
-       pstring fname;
+       return xx_path(name, lp_piddir());
+}
 
-       pstrcpy(fname,lp_piddir());
-       trim_char(fname,'\0','/');
+/**
+ * @brief Returns an absolute path to a file in the Samba lib directory.
+ *
+ * @param name File to find, relative to LIBDIR.
+ *
+ * @retval Pointer to a string containing the full path.
+ **/
 
-       if (!directory_exist(fname,NULL))
-               mkdir(fname,0755);
+char *lib_path(const char *name)
+{
+       return talloc_asprintf(talloc_tos(), "%s/%s", get_dyn_LIBDIR(), name);
+}
 
-       pstrcat(fname,"/");
-       pstrcat(fname,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.
+ **/
 
-       return talloc_strdup(talloc_tos(), fname);
+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 lib directory.
+ * @brief Returns an absolute path to a file in the Samba data directory.
  *
- * @param name File to find, relative to LIBDIR.
+ * @param name File to find, relative to CODEPAGEDIR.
  *
- * @retval Pointer to a static #pstring containing the full path.
+ * @retval Pointer to a talloc'ed string containing the full path.
  **/
 
-char *lib_path(const char *name)
+char *data_path(const char *name)
+{
+       return talloc_asprintf(talloc_tos(), "%s/%s", get_dyn_CODEPAGEDIR(), name);
+}
+
+/*****************************************************************
+a useful function for returning a path in the Samba state directory
+ *****************************************************************/
+
+char *state_path(const char *name)
 {
-       return talloc_asprintf(talloc_tos(), "%s/%s", dyn_LIBDIR, name);
+       return xx_path(name, get_dyn_STATEDIR());
 }
 
 /**
  * @brief Returns the platform specific shared library extension.
  *
- * @retval Pointer to a static #fstring containing the extension.
+ * @retval Pointer to a const char * containing the extension.
  **/
 
 const char *shlib_ext(void)
 {
-  return dyn_SHLIBEXT;
+       return get_dyn_SHLIBEXT();
 }
 
 /*******************************************************************
@@ -2462,7 +2724,7 @@ char *parent_dirname(const char *path)
        return parent;
 }
 
-BOOL parent_dirname_talloc(TALLOC_CTX *mem_ctx, const char *dir,
+bool parent_dirname_talloc(TALLOC_CTX *mem_ctx, const char *dir,
                           char **parent, const char **name)
 {
        char *p;
@@ -2498,7 +2760,7 @@ BOOL parent_dirname_talloc(TALLOC_CTX *mem_ctx, const char *dir,
  Determine if a pattern contains any Microsoft wildcard characters.
 *******************************************************************/
 
-BOOL ms_has_wild(const char *s)
+bool ms_has_wild(const char *s)
 {
        char c;
 
@@ -2520,7 +2782,7 @@ BOOL ms_has_wild(const char *s)
        return False;
 }
 
-BOOL ms_has_wild_w(const smb_ucs2_t *s)
+bool ms_has_wild_w(const smb_ucs2_t *s)
 {
        smb_ucs2_t c;
        if (!s) return False;
@@ -2542,7 +2804,7 @@ BOOL ms_has_wild_w(const smb_ucs2_t *s)
  of the ".." name.
 *******************************************************************/
 
-BOOL mask_match(const char *string, const char *pattern, BOOL is_case_sensitive)
+bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
 {
        if (strcmp(string,"..") == 0)
                string = ".";
@@ -2558,7 +2820,7 @@ BOOL mask_match(const char *string, const char *pattern, BOOL is_case_sensitive)
  pattern translation.
 *******************************************************************/
 
-BOOL mask_match_search(const char *string, const char *pattern, BOOL is_case_sensitive)
+bool mask_match_search(const char *string, const char *pattern, bool is_case_sensitive)
 {
        if (strcmp(string,"..") == 0)
                string = ".";
@@ -2573,7 +2835,7 @@ BOOL mask_match_search(const char *string, const char *pattern, BOOL is_case_sen
  on each.  Returns True if any of the patterns match.
 *******************************************************************/
 
-BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_sensitive)
+bool mask_match_list(const char *string, char **list, int listLen, bool is_case_sensitive)
 {
        while (listLen-- > 0) {
                if (mask_match(string, *list++, is_case_sensitive))
@@ -2586,7 +2848,7 @@ BOOL mask_match_list(const char *string, char **list, int listLen, BOOL is_case_
  Recursive routine that is called by unix_wild_match.
 *********************************************************/
 
-static BOOL unix_do_match(const char *regexp, const char *str)
+static bool unix_do_match(const char *regexp, const char *str)
 {
        const char *p;
 
@@ -2606,7 +2868,7 @@ static BOOL unix_do_match(const char *regexp, const char *str)
                                 */
                                p++;
                                if(!*p)
-                                       return True; /* Automatic match */
+                                       return true; /* Automatic match */
                                while(*str) {
 
                                        while(*str && (*p != *str))
@@ -2641,24 +2903,24 @@ static BOOL unix_do_match(const char *regexp, const char *str)
                                                }
 
                                                if ( matchcount <= 0 )
-                                                       return False;
+                                                       return false;
                                        }
 
                                        str--; /* We've eaten the match char after the '*' */
 
                                        if(unix_do_match(p, str))
-                                               return True;
+                                               return true;
 
                                        if(!*str)
-                                               return False;
+                                               return false;
                                        else
                                                str++;
                                }
-                               return False;
+                               return false;
 
                        default:
                                if(*str != *p)
-                                       return False;
+                                       return false;
                                str++;
                                p++;
                                break;
@@ -2666,11 +2928,11 @@ static BOOL unix_do_match(const char *regexp, const char *str)
        }
 
        if(!*p && !*str)
-               return True;
+               return true;
 
        if (!*p && str[0] == '.' && str[1] == 0)
-               return(True);
-  
+               return true;
+
        if (!*str && *p == '?') {
                while (*p == '?')
                        p++;
@@ -2678,9 +2940,9 @@ static BOOL unix_do_match(const char *regexp, const char *str)
        }
 
        if(!*str && (*p == '*' && p[1] == '\0'))
-               return True;
+               return true;
 
-       return False;
+       return false;
 }
 
 /*******************************************************************
@@ -2688,25 +2950,38 @@ static BOOL unix_do_match(const char *regexp, const char *str)
  Returns True if match, False if not.
 *******************************************************************/
 
-BOOL unix_wild_match(const char *pattern, const char *string)
+bool unix_wild_match(const char *pattern, const char *string)
 {
-       pstring p2, s2;
+       TALLOC_CTX *ctx = talloc_stackframe();
+       char *p2;
+       char *s2;
        char *p;
+       bool ret = false;
 
-       pstrcpy(p2, pattern);
-       pstrcpy(s2, string);
+       p2 = talloc_strdup(ctx,pattern);
+       s2 = talloc_strdup(ctx,string);
+       if (!p2 || !s2) {
+               TALLOC_FREE(ctx);
+               return false;
+       }
        strlower_m(p2);
        strlower_m(s2);
 
        /* Remove any *? and ** from the pattern as they are meaningless */
-       for(p = p2; *p; p++)
-               while( *p == '*' && (p[1] == '?' ||p[1] == '*'))
-                       pstrcpy( &p[1], &p[2]);
-       if (strequal(p2,"*"))
-               return True;
+       for(p = p2; *p; p++) {
+               while( *p == '*' && (p[1] == '?' ||p[1] == '*')) {
+                       memmove(&p[1], &p[2], strlen(&p[2])+1);
+               }
+       }
 
-       return unix_do_match(p2, s2);
+       if (strequal(p2,"*")) {
+               TALLOC_FREE(ctx);
+               return true;
+       }
+
+       ret = unix_do_match(p2, s2);
+       TALLOC_FREE(ctx);
+       return ret;
 }
 
 /**********************************************************************
@@ -2774,45 +3049,31 @@ void *talloc_check_name_abort(const void *ptr, const char *name)
        return NULL;
 }
 
+/**********************************************************************
+ Append a DATA_BLOB to a talloc'ed object
+***********************************************************************/
 
-#ifdef __INSURE__
-
-/*******************************************************************
-This routine is a trick to immediately catch errors when debugging
-with insure. A xterm with a gdb is popped up when insure catches
-a error. It is Linux specific.
-********************************************************************/
-
-int _Insure_trap_error(int a1, int a2, int a3, int a4, int a5, int a6)
+void *talloc_append_blob(TALLOC_CTX *mem_ctx, void *buf, DATA_BLOB blob)
 {
-       static int (*fn)();
-       int ret;
-       char pidstr[10];
-       /* you can get /usr/bin/backtrace from 
-           http://samba.org/ftp/unpacked/junkcode/backtrace */
-       pstring cmd = "/usr/bin/backtrace %d";
-
-       slprintf(pidstr, sizeof(pidstr)-1, "%d", sys_getpid());
-       pstring_sub(cmd, "%d", pidstr);
+       size_t old_size = 0;
+       char *result;
 
-       if (!fn) {
-               static void *h;
-               h = dlopen("/usr/local/parasoft/insure++lite/lib.linux2/libinsure.so", RTLD_LAZY);
-               fn = dlsym(h, "_Insure_trap_error");
-
-               if (!h || h == _Insure_trap_error) {
-                       h = dlopen("/usr/local/parasoft/lib.linux2/libinsure.so", RTLD_LAZY);
-                       fn = dlsym(h, "_Insure_trap_error");
-               }               
+       if (blob.length == 0) {
+               return buf;
        }
 
-       ret = fn(a1, a2, a3, a4, a5, a6);
+       if (buf != NULL) {
+               old_size = talloc_get_size(buf);
+       }
 
-       system(cmd);
+       result = (char *)TALLOC_REALLOC(mem_ctx, buf, old_size + blob.length);
+       if (result == NULL) {
+               return NULL;
+       }
 
-       return ret;
+       memcpy(result + old_size, blob.data, blob.length);
+       return result;
 }
-#endif
 
 uint32 map_share_mode_to_deny_mode(uint32 share_access, uint32 private_options)
 {
@@ -2873,7 +3134,7 @@ struct server_id server_id_self(void)
        return procid_self();
 }
 
-BOOL procid_equal(const struct server_id *p1, const struct server_id *p2)
+bool procid_equal(const struct server_id *p1, const struct server_id *p2)
 {
        if (p1->pid != p2->pid)
                return False;
@@ -2884,13 +3145,13 @@ BOOL procid_equal(const struct server_id *p1, const struct server_id *p2)
        return True;
 }
 
-BOOL cluster_id_equal(const struct server_id *id1,
+bool cluster_id_equal(const struct server_id *id1,
                      const struct server_id *id2)
 {
        return procid_equal(id1, id2);
 }
 
-BOOL procid_is_me(const struct server_id *pid)
+bool procid_is_me(const struct server_id *pid)
 {
        if (pid->pid != sys_getpid())
                return False;
@@ -2911,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 {
@@ -2926,18 +3187,23 @@ struct server_id interpret_pid(const char *pid_string)
 
 char *procid_str(TALLOC_CTX *mem_ctx, const struct server_id *pid)
 {
-       fstring str;
 #ifdef CLUSTER_SUPPORT
        if (pid->vnn == NONCLUSTER_VNN) {
-               fstr_sprintf(str, "%d", (int)pid->pid);
+               return talloc_asprintf(mem_ctx,
+                               "%d",
+                               (int)pid->pid);
        }
        else {
-               fstr_sprintf(str, "%u:%d", (unsigned)pid->vnn, (int)pid->pid);
+               return talloc_asprintf(mem_ctx,
+                                       "%u:%d",
+                                       (unsigned)pid->vnn,
+                                       (int)pid->pid);
        }
 #else
-       fstr_sprintf(str, "%d", (int)pid->pid);
+       return talloc_asprintf(mem_ctx,
+                       "%d",
+                       (int)pid->pid);
 #endif
-       return talloc_strdup(mem_ctx, str);
 }
 
 char *procid_str_static(const struct server_id *pid)
@@ -2945,12 +3211,12 @@ char *procid_str_static(const struct server_id *pid)
        return procid_str(talloc_tos(), pid);
 }
 
-BOOL procid_valid(const struct server_id *pid)
+bool procid_valid(const struct server_id *pid)
 {
        return (pid->pid != -1);
 }
 
-BOOL procid_is_local(const struct server_id *pid)
+bool procid_is_local(const struct server_id *pid)
 {
 #ifdef CLUSTER_SUPPORT
        return pid->vnn == my_vnn;
@@ -2982,7 +3248,7 @@ int this_is_smp(void)
  pointer ptr+off.
 ****************************************************************/
 
-BOOL is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
+bool is_offset_safe(const char *buf_base, size_t buf_len, char *ptr, size_t off)
 {
        const char *end_base = buf_base + buf_len;
        char *end_ptr = ptr + off;
@@ -3059,6 +3325,30 @@ int get_safe_IVAL(const char *buf_base, size_t buf_len, char *ptr, size_t off, i
        return IVAL(ptr,off);
 }
 
+/****************************************************************
+ Split DOM\user into DOM and user. Do not mix with winbind variants of that
+ call (they take care of winbind separator and other winbind specific settings).
+****************************************************************/
+
+void split_domain_user(TALLOC_CTX *mem_ctx,
+                      const char *full_name,
+                      char **domain,
+                      char **user)
+{
+       const char *p = NULL;
+
+       p = strchr_m(full_name, '\\');
+
+       if (p != NULL) {
+               *domain = talloc_strndup(mem_ctx, full_name,
+                                        PTR_DIFF(p, full_name));
+               *user = talloc_strdup(mem_ctx, p+1);
+       } else {
+               *domain = talloc_strdup(mem_ctx, "");
+               *user = talloc_strdup(mem_ctx, full_name);
+       }
+}
+
 #if 0
 
 Disable these now we have checked all code paths and ensured
@@ -3163,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;
+}