s3-lib Move source3-specific malloc replacements into a seperate file
[amitay/samba.git] / source3 / lib / util.c
index 75fd82709a881a3b98983f50d708ef88093e9036..173e9067cc24da3ea2f3d2d6e79666e8b662503b 100644 (file)
    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"
-
-extern char *global_clobber_region_function;
-extern unsigned int global_clobber_region_line;
+#include "system/passwd.h"
+#include "system/filesys.h"
+#include "util_tdb.h"
+#include "ctdbd_conn.h"
+#include "../lib/util/util_pw.h"
+#include "messages.h"
 
 /* Max allowable allococation - 256mb - 0x10000000 */
 #define MAX_ALLOC_SIZE (1024*1024*256)
@@ -55,493 +58,44 @@ extern unsigned int global_clobber_region_line;
 #endif /* WITH_NISPLUS_HOME */
 #endif /* HAVE_NETGROUP && WITH_AUTOMOUNT */
 
-enum protocol_types Protocol = PROTOCOL_COREPLUS;
-
-static enum remote_arch_types ra_type = RA_UNKNOWN;
-
-/***********************************************************************
- Definitions for all names.
-***********************************************************************/
-
-static char *smb_myname;
-static char *smb_myworkgroup;
-static char *smb_scope;
-static int smb_num_netbios_names;
-static char **smb_my_netbios_names;
-
-/***********************************************************************
- Allocate and set myname. Ensure upper case.
-***********************************************************************/
-
-bool set_global_myname(const char *myname)
-{
-       SAFE_FREE(smb_myname);
-       smb_myname = SMB_STRDUP(myname);
-       if (!smb_myname)
-               return False;
-       strupper_m(smb_myname);
-       return True;
-}
-
-const char *global_myname(void)
-{
-       return smb_myname;
-}
-
-/***********************************************************************
- Allocate and set myworkgroup. Ensure upper case.
-***********************************************************************/
-
-bool set_global_myworkgroup(const char *myworkgroup)
-{
-       SAFE_FREE(smb_myworkgroup);
-       smb_myworkgroup = SMB_STRDUP(myworkgroup);
-       if (!smb_myworkgroup)
-               return False;
-       strupper_m(smb_myworkgroup);
-       return True;
-}
-
-const char *lp_workgroup(void)
-{
-       return smb_myworkgroup;
-}
-
-/***********************************************************************
- Allocate and set scope. Ensure upper case.
-***********************************************************************/
-
-bool set_global_scope(const char *scope)
-{
-       SAFE_FREE(smb_scope);
-       smb_scope = SMB_STRDUP(scope);
-       if (!smb_scope)
-               return False;
-       strupper_m(smb_scope);
-       return True;
-}
-
-/*********************************************************************
- Ensure scope is never null string.
-*********************************************************************/
-
-const char *global_scope(void)
-{
-       if (!smb_scope)
-               set_global_scope("");
-       return smb_scope;
-}
-
-static void free_netbios_names_array(void)
-{
-       int i;
-
-       for (i = 0; i < smb_num_netbios_names; i++)
-               SAFE_FREE(smb_my_netbios_names[i]);
-
-       SAFE_FREE(smb_my_netbios_names);
-       smb_num_netbios_names = 0;
-}
+static enum protocol_types Protocol = PROTOCOL_COREPLUS;
 
-static bool allocate_my_netbios_names_array(size_t number)
+enum protocol_types get_Protocol(void)
 {
-       free_netbios_names_array();
-
-       smb_num_netbios_names = number + 1;
-       smb_my_netbios_names = SMB_MALLOC_ARRAY( char *, smb_num_netbios_names );
-
-       if (!smb_my_netbios_names)
-               return False;
-
-       memset(smb_my_netbios_names, '\0', sizeof(char *) * smb_num_netbios_names);
-       return True;
+       return Protocol;
 }
 
-static bool set_my_netbios_names(const char *name, int i)
+void set_Protocol(enum protocol_types  p)
 {
-       SAFE_FREE(smb_my_netbios_names[i]);
-
-       smb_my_netbios_names[i] = SMB_STRDUP(name);
-       if (!smb_my_netbios_names[i])
-               return False;
-       strupper_m(smb_my_netbios_names[i]);
-       return True;
+       Protocol = p;
 }
 
-/***********************************************************************
- Free memory allocated to global objects
-***********************************************************************/
-
-void gfree_names(void)
-{
-       SAFE_FREE( smb_myname );
-       SAFE_FREE( smb_myworkgroup );
-       SAFE_FREE( smb_scope );
-       free_netbios_names_array();
-       free_local_machine_name();
-}
+static enum remote_arch_types ra_type = RA_UNKNOWN;
 
 void gfree_all( void )
 {
        gfree_names();
        gfree_loadparm();
-       gfree_case_tables();
        gfree_charcnv();
        gfree_interfaces();
        gfree_debugsyms();
 }
 
-const char *my_netbios_names(int i)
-{
-       return smb_my_netbios_names[i];
-}
-
-bool set_netbios_aliases(const char **str_array)
-{
-       size_t namecount;
-
-       /* Work out the max number of netbios aliases that we have */
-       for( namecount=0; str_array && (str_array[namecount] != NULL); namecount++ )
-               ;
-
-       if ( global_myname() && *global_myname())
-               namecount++;
-
-       /* Allocate space for the netbios aliases */
-       if (!allocate_my_netbios_names_array(namecount))
-               return False;
-
-       /* Use the global_myname string first */
-       namecount=0;
-       if ( global_myname() && *global_myname()) {
-               set_my_netbios_names( global_myname(), namecount );
-               namecount++;
-       }
-
-       if (str_array) {
-               size_t i;
-               for ( i = 0; str_array[i] != NULL; i++) {
-                       size_t n;
-                       bool duplicate = False;
-
-                       /* Look for duplicates */
-                       for( n=0; n<namecount; n++ ) {
-                               if( strequal( str_array[i], my_netbios_names(n) ) ) {
-                                       duplicate = True;
-                                       break;
-                               }
-                       }
-                       if (!duplicate) {
-                               if (!set_my_netbios_names(str_array[i], namecount))
-                                       return False;
-                               namecount++;
-                       }
-               }
-       }
-       return True;
-}
-
-/****************************************************************************
-  Common name initialization code.
-****************************************************************************/
-
-bool init_names(void)
-{
-       int n;
-
-       if (global_myname() == NULL || *global_myname() == '\0') {
-               if (!set_global_myname(myhostname())) {
-                       DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
-                       return False;
-               }
-       }
-
-       if (!set_netbios_aliases(lp_netbios_aliases())) {
-               DEBUG( 0, ( "init_structs: malloc fail.\n" ) );
-               return False;
-       }
-
-       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) ) );
-       }
-
-       return( True );
-}
-
-/**************************************************************************n
-  Code to cope with username/password auth options from the commandline.
-  Used mainly in client tools.
-****************************************************************************/
-
-struct user_auth_info *user_auth_info_init(TALLOC_CTX *mem_ctx)
-{
-       struct user_auth_info *result;
-
-       result = TALLOC_ZERO_P(mem_ctx, struct user_auth_info);
-       if (result == NULL) {
-               return NULL;
-       }
-
-       result->signing_state = Undefined;
-       return result;
-}
-
-const char *get_cmdline_auth_info_username(const struct user_auth_info *auth_info)
-{
-       if (!auth_info->username) {
-               return "";
-       }
-       return auth_info->username;
-}
-
-void set_cmdline_auth_info_username(struct user_auth_info *auth_info,
-                                   const char *username)
-{
-       TALLOC_FREE(auth_info->username);
-       auth_info->username = talloc_strdup(auth_info, username);
-       if (!auth_info->username) {
-               exit(ENOMEM);
-       }
-}
-
-const char *get_cmdline_auth_info_password(const struct user_auth_info *auth_info)
-{
-       if (!auth_info->password) {
-               return "";
-       }
-       return auth_info->password;
-}
-
-void set_cmdline_auth_info_password(struct user_auth_info *auth_info,
-                                   const char *password)
-{
-       TALLOC_FREE(auth_info->password);
-       if (password == NULL) {
-               password = "";
-       }
-       auth_info->password = talloc_strdup(auth_info, password);
-       if (!auth_info->password) {
-               exit(ENOMEM);
-       }
-       auth_info->got_pass = true;
-}
-
-bool set_cmdline_auth_info_signing_state(struct user_auth_info *auth_info,
-                                        const char *arg)
-{
-       auth_info->signing_state = -1;
-       if (strequal(arg, "off") || strequal(arg, "no") ||
-                       strequal(arg, "false")) {
-               auth_info->signing_state = false;
-       } else if (strequal(arg, "on") || strequal(arg, "yes") ||
-                       strequal(arg, "true") || strequal(arg, "auto")) {
-               auth_info->signing_state = true;
-       } else if (strequal(arg, "force") || strequal(arg, "required") ||
-                       strequal(arg, "forced")) {
-               auth_info->signing_state = Required;
-       } else {
-               return false;
-       }
-       return true;
-}
-
-int get_cmdline_auth_info_signing_state(const struct user_auth_info *auth_info)
-{
-       return auth_info->signing_state;
-}
-
-void set_cmdline_auth_info_use_kerberos(struct user_auth_info *auth_info,
-                                       bool b)
-{
-        auth_info->use_kerberos = b;
-}
-
-bool get_cmdline_auth_info_use_kerberos(const struct user_auth_info *auth_info)
-{
-       return auth_info->use_kerberos;
-}
-
-void set_cmdline_auth_info_fallback_after_kerberos(struct user_auth_info *auth_info,
-                                       bool b)
-{
-       auth_info->fallback_after_kerberos = b;
-}
-
-bool get_cmdline_auth_info_fallback_after_kerberos(const struct user_auth_info *auth_info)
-{
-       return auth_info->fallback_after_kerberos;
-}
-
-/* This should only be used by lib/popt_common.c JRA */
-void set_cmdline_auth_info_use_krb5_ticket(struct user_auth_info *auth_info)
-{
-       auth_info->use_kerberos = true;
-       auth_info->got_pass = true;
-}
-
-/* This should only be used by lib/popt_common.c JRA */
-void set_cmdline_auth_info_smb_encrypt(struct user_auth_info *auth_info)
-{
-       auth_info->smb_encrypt = true;
-}
-
-void set_cmdline_auth_info_use_machine_account(struct user_auth_info *auth_info)
-{
-       auth_info->use_machine_account = true;
-}
-
-bool get_cmdline_auth_info_got_pass(const struct user_auth_info *auth_info)
-{
-       return auth_info->got_pass;
-}
-
-bool get_cmdline_auth_info_smb_encrypt(const struct user_auth_info *auth_info)
-{
-       return auth_info->smb_encrypt;
-}
-
-bool get_cmdline_auth_info_use_machine_account(const struct user_auth_info *auth_info)
-{
-       return auth_info->use_machine_account;
-}
-
-struct user_auth_info *get_cmdline_auth_info_copy(TALLOC_CTX *mem_ctx,
-                                                 const struct user_auth_info *src)
-{
-       struct user_auth_info *result;
-
-       result = user_auth_info_init(mem_ctx);
-       if (result == NULL) {
-               return NULL;
-       }
-
-       *result = *src;
-
-       result->username = talloc_strdup(
-               result, get_cmdline_auth_info_username(src));
-       result->password = talloc_strdup(
-               result, get_cmdline_auth_info_password(src));
-       if ((result->username == NULL) || (result->password == NULL)) {
-               TALLOC_FREE(result);
-               return NULL;
-       }
-
-       return result;
-}
-
-bool set_cmdline_auth_info_machine_account_creds(struct user_auth_info *auth_info)
-{
-       char *pass = NULL;
-       char *account = NULL;
-
-       if (!get_cmdline_auth_info_use_machine_account(auth_info)) {
-               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(auth_info, account);
-       set_cmdline_auth_info_password(auth_info, pass);
-
-       SAFE_FREE(account);
-       SAFE_FREE(pass);
-
-       return true;
-}
-
-/****************************************************************************
- Ensure we have a password if one not given.
-****************************************************************************/
-
-void set_cmdline_auth_info_getpass(struct user_auth_info *auth_info)
-{
-       char *label = NULL;
-       char *pass;
-       TALLOC_CTX *frame;
-
-       if (get_cmdline_auth_info_got_pass(auth_info) ||
-                       get_cmdline_auth_info_use_kerberos(auth_info)) {
-               /* Already got one... */
-               return;
-       }
-
-       frame = talloc_stackframe();
-       label = talloc_asprintf(frame, "Enter %s's password: ",
-                       get_cmdline_auth_info_username(auth_info));
-       pass = getpass(label);
-       if (pass) {
-               set_cmdline_auth_info_password(auth_info, pass);
-       }
-       TALLOC_FREE(frame);
-}
-
-/****************************************************************************
- 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,
-                            gid_t **gids, size_t *num_gids)
-{
-       int i;
-
-       if ((*num_gids != 0) && (*gids == NULL)) {
-               /*
-                * A former call to this routine has failed to allocate memory
-                */
-               return False;
-       }
-
-       for (i=0; i<*num_gids; i++) {
-               if ((*gids)[i] == gid) {
-                       return True;
-               }
-       }
-
-       *gids = TALLOC_REALLOC_ARRAY(mem_ctx, *gids, gid_t, *num_gids+1);
-       if (*gids == NULL) {
-               *num_gids = 0;
-               return False;
-       }
-
-       (*gids)[*num_gids] = gid;
-       *num_gids += 1;
-       return True;
-}
-
 /*******************************************************************
  Check if a file exists - call vfs_file_exist for samba files.
 ********************************************************************/
 
-bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf)
+bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf,
+                    bool fake_dir_create_times)
 {
        SMB_STRUCT_STAT st;
        if (!sbuf)
                sbuf = &st;
-  
-       if (sys_stat(fname,sbuf) != 0) 
+
+       if (sys_stat(fname, sbuf, fake_dir_create_times) != 0)
                return(False);
 
-       return((S_ISREG(sbuf->st_mode)) || (S_ISFIFO(sbuf->st_mode)));
+       return((S_ISREG(sbuf->st_ex_mode)) || (S_ISFIFO(sbuf->st_ex_mode)));
 }
 
 /*******************************************************************
@@ -551,31 +105,10 @@ bool file_exist_stat(const char *fname,SMB_STRUCT_STAT *sbuf)
 bool socket_exist(const char *fname)
 {
        SMB_STRUCT_STAT st;
-       if (sys_stat(fname,&st) != 0) 
+       if (sys_stat(fname, &st, false) != 0)
                return(False);
 
-       return S_ISSOCK(st.st_mode);
-}
-
-/*******************************************************************
- Check if a directory exists.
-********************************************************************/
-
-bool directory_exist_stat(char *dname,SMB_STRUCT_STAT *st)
-{
-       SMB_STRUCT_STAT st2;
-       bool ret;
-
-       if (!st)
-               st = &st2;
-
-       if (sys_stat(dname,st) != 0) 
-               return(False);
-
-       ret = S_ISDIR(st->st_mode);
-       if(!ret)
-               errno = ENOTDIR;
-       return ret;
+       return S_ISSOCK(st.st_ex_mode);
 }
 
 /*******************************************************************
@@ -584,7 +117,7 @@ bool directory_exist_stat(char *dname,SMB_STRUCT_STAT *st)
 
 uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
 {
-       return sbuf->st_size;
+       return sbuf->st_ex_size;
 }
 
 /*******************************************************************
@@ -594,44 +127,24 @@ uint64_t get_file_size_stat(const SMB_STRUCT_STAT *sbuf)
 SMB_OFF_T get_file_size(char *file_name)
 {
        SMB_STRUCT_STAT buf;
-       buf.st_size = 0;
-       if(sys_stat(file_name,&buf) != 0)
+       buf.st_ex_size = 0;
+       if (sys_stat(file_name, &buf, false) != 0)
                return (SMB_OFF_T)-1;
        return get_file_size_stat(&buf);
 }
 
-/*******************************************************************
- Return a string representing an attribute for a file.
-********************************************************************/
-
-char *attrib_string(uint16 mode)
-{
-       fstring attrstr;
-
-       attrstr[0] = 0;
-
-       if (mode & aVOLID) fstrcat(attrstr,"V");
-       if (mode & aDIR) fstrcat(attrstr,"D");
-       if (mode & aARCH) fstrcat(attrstr,"A");
-       if (mode & aHIDDEN) fstrcat(attrstr,"H");
-       if (mode & aSYSTEM) fstrcat(attrstr,"S");
-       if (mode & aRONLY) fstrcat(attrstr,"R");          
-
-       return talloc_strdup(talloc_tos(), attrstr);
-}
-
 /*******************************************************************
  Show a smb message structure.
 ********************************************************************/
 
-void show_msg(char *buf)
+void show_msg(const char *buf)
 {
        int i;
        int bcc=0;
 
        if (!DEBUGLVL(5))
                return;
-       
+
        DEBUG(5,("size=%d\nsmb_com=0x%x\nsmb_rcls=%d\nsmb_reh=%d\nsmb_err=%d\nsmb_flg=%d\nsmb_flg2=%d\n",
                        smb_len(buf),
                        (int)CVAL(buf,smb_com),
@@ -650,7 +163,7 @@ void show_msg(char *buf)
        for (i=0;i<(int)CVAL(buf,smb_wct);i++)
                DEBUGADD(5,("smb_vwv[%2d]=%5d (0x%X)\n",i,
                        SVAL(buf,smb_vwv+2*i),SVAL(buf,smb_vwv+2*i)));
-       
+
        bcc = (int)SVAL(buf,smb_vwv+2*(CVAL(buf,smb_wct)));
 
        DEBUGADD(5,("smb_bcc=%d\n",bcc));
@@ -661,7 +174,7 @@ void show_msg(char *buf)
        if (DEBUGLEVEL < 50)
                bcc = MIN(bcc, 512);
 
-       dump_data(10, (uint8 *)smb_buf(buf), bcc);      
+       dump_data(10, (const uint8 *)smb_buf_const(buf), bcc);
 }
 
 /*******************************************************************
@@ -877,61 +390,13 @@ ssize_t write_data_at_offset(int fd, const char *buffer, size_t N, SMB_OFF_T pos
 #endif
 }
 
-/*******************************************************************
- Sleep for a specified number of milliseconds.
-********************************************************************/
 
-void smb_msleep(unsigned int t)
+NTSTATUS reinit_after_fork(struct messaging_context *msg_ctx,
+                          struct event_context *ev_ctx,
+                          struct server_id id,
+                          bool parent_longlived)
 {
-#if defined(HAVE_NANOSLEEP)
-       struct timespec tval;
-       int ret;
-
-       tval.tv_sec = t/1000;
-       tval.tv_nsec = 1000000*(t%1000);
-
-       do {
-               errno = 0;
-               ret = nanosleep(&tval, &tval);
-       } while (ret < 0 && errno == EINTR && (tval.tv_sec > 0 || tval.tv_nsec > 0));
-#else
-       unsigned int tdiff=0;
-       struct timeval tval,t1,t2;  
-       fd_set fds;
-
-       GetTimeOfDay(&t1);
-       t2 = t1;
-  
-       while (tdiff < t) {
-               tval.tv_sec = (t-tdiff)/1000;
-               tval.tv_usec = 1000*((t-tdiff)%1000);
-
-               /* Never wait for more than 1 sec. */
-               if (tval.tv_sec > 1) {
-                       tval.tv_sec = 1; 
-                       tval.tv_usec = 0;
-               }
-
-               FD_ZERO(&fds);
-               errno = 0;
-               sys_select_intr(0,&fds,NULL,NULL,&tval);
-
-               GetTimeOfDay(&t2);
-               if (t2.tv_sec < t1.tv_sec) {
-                       /* Someone adjusted time... */
-                       t1 = t2;
-               }
-
-               tdiff = TvalDiff(&t1,&t2);
-       }
-#endif
-}
-
-bool reinit_after_fork(struct messaging_context *msg_ctx,
-                      struct event_context *ev_ctx,
-                      bool parent_longlived)
-{
-       NTSTATUS status;
+       NTSTATUS status = NT_STATUS_OK;
 
        /* Reset the state of the random
         * number generation system, so
@@ -942,11 +407,12 @@ bool reinit_after_fork(struct messaging_context *msg_ctx,
        /* tdb needs special fork handling */
        if (tdb_reopen_all(parent_longlived ? 1 : 0) == -1) {
                DEBUG(0,("tdb_reopen_all failed.\n"));
-               return false;
+               status = NT_STATUS_OPEN_FAILED;
+               goto done;
        }
 
-       if (ev_ctx) {
-               event_context_reinit(ev_ctx);
+       if (ev_ctx && tevent_re_initialise(ev_ctx) != 0) {
+               smb_panic(__location__ ": Failed to re-initialise event context");
        }
 
        if (msg_ctx) {
@@ -954,176 +420,14 @@ bool reinit_after_fork(struct messaging_context *msg_ctx,
                 * For clustering, we need to re-init our ctdbd connection after the
                 * fork
                 */
-               status = messaging_reinit(msg_ctx);
+               status = messaging_reinit(msg_ctx, id);
                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(const char *p)
-{
-       char ans[20];
-       printf("%s",p);
-
-       if (!fgets(ans,sizeof(ans)-1,stdin))
-               return(False);
-
-       if (*ans == 'y' || *ans == 'Y')
-               return(True);
-
-       return(False);
-}
-
-#if defined(PARANOID_MALLOC_CHECKER)
-
-/****************************************************************************
- Internal malloc wrapper. Externally visible.
-****************************************************************************/
-
-void *malloc_(size_t size)
-{
-       if (size == 0) {
-               return NULL;
-       }
-#undef malloc
-       return malloc(size);
-#define malloc(s) __ERROR_DONT_USE_MALLOC_DIRECTLY
-}
-
-/****************************************************************************
- Internal calloc wrapper. Not externally visible.
-****************************************************************************/
-
-static void *calloc_(size_t count, size_t size)
-{
-       if (size == 0 || count == 0) {
-               return NULL;
-       }
-#undef calloc
-       return calloc(count, size);
-#define calloc(n,s) __ERROR_DONT_USE_CALLOC_DIRECTLY
-}
-
-/****************************************************************************
- Internal realloc wrapper. Not externally visible.
-****************************************************************************/
-
-static void *realloc_(void *ptr, size_t size)
-{
-#undef realloc
-       return realloc(ptr, size);
-#define realloc(p,s) __ERROR_DONT_USE_RELLOC_DIRECTLY
-}
-
-#endif /* PARANOID_MALLOC_CHECKER */
-
-/****************************************************************************
- Type-safe memalign
-****************************************************************************/
-
-void *memalign_array(size_t el_size, size_t align, unsigned int count)
-{
-       if (count >= MAX_ALLOC_SIZE/el_size) {
-               return NULL;
-       }
-
-       return sys_memalign(align, el_size*count);
-}
-
-/****************************************************************************
- Type-safe calloc.
-****************************************************************************/
-
-void *calloc_array(size_t size, size_t nmemb)
-{
-       if (nmemb >= MAX_ALLOC_SIZE/size) {
-               return NULL;
-       }
-       if (size == 0 || nmemb == 0) {
-               return NULL;
-       }
-#if defined(PARANOID_MALLOC_CHECKER)
-       return calloc_(nmemb, size);
-#else
-       return calloc(nmemb, size);
-#endif
-}
-
-/****************************************************************************
- Expand a pointer to be a particular size.
- Note that this version of Realloc has an extra parameter that decides
- whether to free the passed in storage on allocation failure or if the
- new size is zero.
-
- This is designed for use in the typical idiom of :
-
- p = SMB_REALLOC(p, size)
- if (!p) {
-    return error;
- }
-
- and not to have to keep track of the old 'p' contents to free later, nor
- to worry if the size parameter was zero. In the case where NULL is returned
- we guarentee that p has been freed.
-
- If free later semantics are desired, then pass 'free_old_on_error' as False which
- guarentees that the old contents are not freed on error, even if size == 0. To use
- this idiom use :
-
- tmp = SMB_REALLOC_KEEP_OLD_ON_ERROR(p, size);
- if (!tmp) {
-    SAFE_FREE(p);
-    return error;
- } else {
-    p = tmp;
- }
-
- Changes were instigated by Coverity error checking. JRA.
-****************************************************************************/
-
-void *Realloc(void *p, size_t size, bool free_old_on_error)
-{
-       void *ret=NULL;
-
-       if (size == 0) {
-               if (free_old_on_error) {
-                       SAFE_FREE(p);
-               }
-               DEBUG(2,("Realloc asked for 0 bytes\n"));
-               return NULL;
-       }
-
-#if defined(PARANOID_MALLOC_CHECKER)
-       if (!p) {
-               ret = (void *)malloc_(size);
-       } else {
-               ret = (void *)realloc_(p,size);
-       }
-#else
-       if (!p) {
-               ret = (void *)malloc(size);
-       } else {
-               ret = (void *)realloc(p,size);
-       }
-#endif
-
-       if (!ret) {
-               if (free_old_on_error && p) {
-                       SAFE_FREE(p);
-               }
-               DEBUG(0,("Memory allocation error: failed to expand to %d bytes\n",(int)size));
-       }
-
-       return(ret);
+ done:
+       return status;
 }
 
 /****************************************************************************
@@ -1222,9 +526,9 @@ int interpret_protocol(const char *str,int def)
                return(PROTOCOL_COREPLUS);
        if (strequal(str,"CORE+"))
                return(PROTOCOL_COREPLUS);
-  
+
        DEBUG(0,("Unrecognised protocol level %s\n",str));
-  
+
        return(def);
 }
 
@@ -1327,6 +631,9 @@ char *automount_lookup(TALLOC_CTX *ctx, const char *user_name)
        if ((nis_error = yp_match(nis_domain, nis_map, user_name,
                                        strlen(user_name), &nis_result,
                                        &nis_result_len)) == 0) {
+               if (nis_result_len > 0 && nis_result[nis_result_len] == '\n') {
+                       nis_result[nis_result_len] = '\0';
+               }
                value = talloc_strdup(ctx, nis_result);
                if (!value) {
                        return NULL;
@@ -1364,8 +671,8 @@ bool process_exists(const struct server_id pid)
        }
 
 #ifdef CLUSTER_SUPPORT
-       return ctdbd_process_exists(messaging_ctdbd_connection(), pid.vnn,
-                                   pid.pid);
+       return ctdbd_process_exists(messaging_ctdbd_connection(),
+                                   pid.vnn, pid.pid);
 #else
        return False;
 #endif
@@ -1422,7 +729,7 @@ uid_t nametouid(const char *name)
        char *p;
        uid_t u;
 
-       pass = getpwnam_alloc(talloc_autofree_context(), name);
+       pass = Get_Pwnam_alloc(talloc_tos(), name);
        if (pass) {
                u = pass->pw_uid;
                TALLOC_FREE(pass);
@@ -1460,22 +767,11 @@ gid_t nametogid(const char *name)
  Something really nasty happened - panic !
 ********************************************************************/
 
-void smb_panic(const char *const why)
+void smb_panic_s3(const char *why)
 {
        char *cmd;
        int result;
 
-#ifdef DEVELOPER
-       {
-
-               if (global_clobber_region_function) {
-                       DEBUG(0,("smb_panic: clobber_region() last called from [%s(%u)]\n",
-                                        global_clobber_region_function,
-                                        global_clobber_region_line));
-               } 
-       }
-#endif
-
        DEBUG(0,("PANIC (pid %llu): %s\n",
                    (unsigned long long)sys_getpid(), why));
        log_stack_trace();
@@ -1582,7 +878,7 @@ libunwind_failed:
 
        DEBUG(0, ("BACKTRACE: %lu stack frames:\n", 
                  (unsigned long)backtrace_size));
-       
+
        if (backtrace_strings) {
                int i;
 
@@ -1646,7 +942,7 @@ const char *readdirname(SMB_STRUCT_DIR *p)
 
        if (!p)
                return(NULL);
-  
+
        ptr = (SMB_STRUCT_DIRENT *)sys_readdir(p);
        if (!ptr)
                return(NULL);
@@ -1698,7 +994,7 @@ bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensit
                        }
                } else {
                        if((case_sensitive && (strcmp(last_component, namelist->name) == 0))||
-                                               (!case_sensitive && (StrCaseCmp(last_component, namelist->name) == 0))) {
+                                               (!case_sensitive && (strcasecmp_m(last_component, namelist->name) == 0))) {
                                DEBUG(8,("is_in_path: match succeeded\n"));
                                return True;
                        }
@@ -1714,25 +1010,31 @@ bool is_in_path(const char *name, name_compare_entry *namelist, bool case_sensit
  passing to is_in_path(). We do this for
  speed so we can pre-parse all the names in the list 
  and don't do it for each call to is_in_path().
- namelist is modified here and is assumed to be 
- a copy owned by the caller.
  We also check if the entry contains a wildcard to
  remove a potentially expensive call to mask_match
  if possible.
 ********************************************************************/
-void set_namearray(name_compare_entry **ppname_array, const char *namelist)
+
+void set_namearray(name_compare_entry **ppname_array, const char *namelist_in)
 {
        char *name_end;
-       const char *nameptr = namelist;
+       char *namelist;
+       char *nameptr;
        int num_entries = 0;
        int i;
 
        (*ppname_array) = NULL;
 
-       if((nameptr == NULL ) || ((nameptr != NULL) && (*nameptr == '\0'))) 
+       if((namelist_in == NULL ) || ((namelist_in != NULL) && (*namelist_in == '\0'))) 
                return;
 
+       namelist = talloc_strdup(talloc_tos(), namelist_in);
+       if (namelist == NULL) {
+               DEBUG(0,("set_namearray: talloc fail\n"));
+               return;
+       }
+       nameptr = namelist;
+
        /* We need to make two passes over the string. The
                first to count the number of elements, the second
                to split it.
@@ -1744,23 +1046,28 @@ void set_namearray(name_compare_entry **ppname_array, const char *namelist)
                        nameptr++;
                        continue;
                }
-               /* find the next / */
-               name_end = strchr_m(nameptr, '/');
+               /* anything left? */
+               if ( *nameptr == '\0' )
+                       break;
 
-               /* oops - the last check for a / didn't find one. */
+               /* find the next '/' or consume remaining */
+               name_end = strchr_m(nameptr, '/');
                if (name_end == NULL)
-                       break;
+                       name_end = (char *)nameptr + strlen(nameptr);
 
                /* next segment please */
                nameptr = name_end + 1;
                num_entries++;
        }
 
-       if(num_entries == 0)
+       if(num_entries == 0) {
+               talloc_free(namelist);
                return;
+       }
 
        if(( (*ppname_array) = SMB_MALLOC_ARRAY(name_compare_entry, num_entries + 1)) == NULL) {
                DEBUG(0,("set_namearray: malloc fail\n"));
+               talloc_free(namelist);
                return;
        }
 
@@ -1773,17 +1080,21 @@ void set_namearray(name_compare_entry **ppname_array, const char *namelist)
                        nameptr++;
                        continue;
                }
-               /* find the next / */
-               if ((name_end = strchr_m(nameptr, '/')) != NULL)
-                       *name_end = 0;
-
-               /* oops - the last check for a / didn't find one. */
-               if(name_end == NULL) 
+               /* anything left? */
+               if ( *nameptr == '\0' )
                        break;
 
+               /* find the next '/' or consume remaining */
+               name_end = strchr_m(nameptr, '/');
+               if (name_end)
+                       *name_end = '\0';
+               else
+                       name_end = nameptr + strlen(nameptr);
+
                (*ppname_array)[i].is_wild = ms_has_wild(nameptr);
                if(((*ppname_array)[i].name = SMB_STRDUP(nameptr)) == NULL) {
                        DEBUG(0,("set_namearray: malloc fail (1)\n"));
+                       talloc_free(namelist);
                        return;
                }
 
@@ -1791,28 +1102,13 @@ void set_namearray(name_compare_entry **ppname_array, const char *namelist)
                nameptr = name_end + 1;
                i++;
        }
-  
+
        (*ppname_array)[i].name = NULL;
 
+       talloc_free(namelist);
        return;
 }
 
-/****************************************************************************
- Routine to free a namearray.
-****************************************************************************/
-
-void free_namearray(name_compare_entry *name_array)
-{
-       int i;
-
-       if(name_array == NULL)
-               return;
-
-       for(i=0; name_array[i].name!=NULL; i++)
-               SAFE_FREE(name_array[i].name);
-       SAFE_FREE(name_array);
-}
-
 #undef DBGC_CLASS
 #define DBGC_CLASS DBGC_LOCKING
 
@@ -1851,7 +1147,7 @@ bool fcntl_getlock(int fd, SMB_OFF_T *poffset, SMB_OFF_T *pcount, int *ptype, pi
        *poffset = lock.l_start;
        *pcount = lock.l_len;
        *ppid = lock.l_pid;
-       
+
        DEBUG(3,("fcntl_getlock: fd %d is returned info %d pid %u\n",
                        fd, (int)lock.l_type, (unsigned int)lock.l_pid));
        return True;
@@ -1969,6 +1265,9 @@ void set_remote_arch(enum remote_arch_types type)
        case RA_CIFSFS:
                remote_arch_str = "CIFSFS";
                break;
+       case RA_OSX:
+               remote_arch_str = "OSX";
+               break;
        default:
                ra_type = RA_UNKNOWN;
                remote_arch_str = "UNKNOWN";
@@ -2007,17 +1306,8 @@ const char *tab_depth(int level, int depth)
 
 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)));
-               s++;
-               i++;
-       }
-       return(res);
+       TDB_DATA key = string_tdb_data(s);
+       return tdb_jenkins_hash(&key);
 }
 
 /*****************************************************************
@@ -2113,24 +1403,6 @@ int set_maxfiles(int requested_max)
 #endif
 }
 
-/*****************************************************************
- Possibly replace mkstemp if it is broken.
-*****************************************************************/  
-
-int smb_mkstemp(char *name_template)
-{
-#if HAVE_SECURE_MKSTEMP
-       return mkstemp(name_template);
-#else
-       /* have a reasonable go at emulating it. Hope that
-          the system mktemp() isn't completly hopeless */
-       char *p = mktemp(name_template);
-       if (!p)
-               return -1;
-       return open(p, O_CREAT|O_EXCL|O_RDWR, 0600);
-#endif
-}
-
 /*****************************************************************
  malloc that aborts with smb_panic on fail or zero size.
  *****************************************************************/  
@@ -2164,10 +1436,10 @@ void *smb_xmalloc_array(size_t size, unsigned int count)
        va_copy(ap2, ap);
 
        n = vasprintf(ptr, format, ap2);
+       va_end(ap2);
        if (n == -1 || ! *ptr) {
                smb_panic("smb_xvasprintf: out of memory");
        }
-       va_end(ap2);
        return n;
 }
 
@@ -2179,9 +1451,7 @@ char *myhostname(void)
 {
        static char *ret;
        if (ret == NULL) {
-               /* This is cached forever so
-                * use talloc_autofree_context() ctx. */
-               ret = get_myname(talloc_autofree_context());
+               ret = get_myname(NULL);
        }
        return ret;
 }
@@ -2328,7 +1598,7 @@ bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
 {
        char *p;
        ptrdiff_t len;
+
        p = strrchr_m(dir, '/'); /* Find final '/', if any */
 
        if (p == NULL) {
@@ -2336,7 +1606,7 @@ bool parent_dirname(TALLOC_CTX *mem_ctx, const char *dir, char **parent,
                        return False;
                }
                if (name) {
-                       *name = "";
+                       *name = dir;
                }
                return True;
        }
@@ -2404,11 +1674,11 @@ bool ms_has_wild_w(const smb_ucs2_t *s)
 
 bool mask_match(const char *string, const char *pattern, bool is_case_sensitive)
 {
-       if (strcmp(string,"..") == 0)
+       if (ISDOTDOT(string))
                string = ".";
-       if (strcmp(pattern,".") == 0)
+       if (ISDOT(pattern))
                return False;
-       
+
        return ms_fnmatch(pattern, string, Protocol <= PROTOCOL_LANMAN2, is_case_sensitive) == 0;
 }
 
@@ -2420,11 +1690,11 @@ bool mask_match(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)
+       if (ISDOTDOT(string))
                string = ".";
-       if (strcmp(pattern,".") == 0)
+       if (ISDOT(pattern))
                return False;
-       
+
        return ms_fnmatch(pattern, string, True, is_case_sensitive) == 0;
 }
 
@@ -2612,7 +1882,7 @@ bool name_to_fqdn(fstring fqdn, const char *name)
                        }
                }
        }
-       if (full && (StrCaseCmp(full, "localhost.localdomain") == 0)) {
+       if (full && (strcasecmp_m(full, "localhost.localdomain") == 0)) {
                DEBUG(1, ("WARNING: your /etc/hosts file may be broken!\n"));
                DEBUGADD(1, ("    Specifing the machine hostname for address 127.0.0.1 may lead\n"));
                DEBUGADD(1, ("    to Kerberos authentication problems as localhost.localdomain\n"));
@@ -2693,13 +1963,19 @@ uint32 get_my_vnn(void)
        return my_vnn;
 }
 
+static uint64_t my_unique_id = 0;
+
+void set_my_unique_id(uint64_t unique_id)
+{
+       my_unique_id = unique_id;
+}
+
 struct server_id pid_to_procid(pid_t pid)
 {
        struct server_id result;
        result.pid = pid;
-#ifdef CLUSTER_SUPPORT
+       result.unique_id = my_unique_id;
        result.vnn = my_vnn;
-#endif
        return result;
 }
 
@@ -2708,19 +1984,12 @@ struct server_id procid_self(void)
        return pid_to_procid(sys_getpid());
 }
 
-struct server_id server_id_self(void)
-{
-       return procid_self();
-}
-
 bool procid_equal(const struct server_id *p1, const struct server_id *p2)
 {
        if (p1->pid != p2->pid)
                return False;
-#ifdef CLUSTER_SUPPORT
        if (p1->vnn != p2->vnn)
                return False;
-#endif
        return True;
 }
 
@@ -2734,23 +2003,21 @@ bool procid_is_me(const struct server_id *pid)
 {
        if (pid->pid != sys_getpid())
                return False;
-#ifdef CLUSTER_SUPPORT
        if (pid->vnn != my_vnn)
                return False;
-#endif
        return True;
 }
 
 struct server_id interpret_pid(const char *pid_string)
 {
-#ifdef CLUSTER_SUPPORT
-       unsigned int vnn, pid;
        struct server_id result;
-       if (sscanf(pid_string, "%u:%u", &vnn, &pid) == 2) {
+       int pid;
+       unsigned int vnn;
+       if (sscanf(pid_string, "%u:%d", &vnn, &pid) == 2) {
                result.vnn = vnn;
                result.pid = pid;
        }
-       else if (sscanf(pid_string, "%u", &pid) == 1) {
+       else if (sscanf(pid_string, "%d", &pid) == 1) {
                result.vnn = get_my_vnn();
                result.pid = pid;
        }
@@ -2758,15 +2025,17 @@ struct server_id interpret_pid(const char *pid_string)
                result.vnn = NONCLUSTER_VNN;
                result.pid = -1;
        }
+       /* Assigning to result.pid may have overflowed
+          Map negative pid to -1: i.e. error */
+       if (result.pid < 0) {
+               result.pid = -1;
+       }
+       result.unique_id = 0;
        return result;
-#else
-       return pid_to_procid(atoi(pid_string));
-#endif
 }
 
 char *procid_str(TALLOC_CTX *mem_ctx, const struct server_id *pid)
 {
-#ifdef CLUSTER_SUPPORT
        if (pid->vnn == NONCLUSTER_VNN) {
                return talloc_asprintf(mem_ctx,
                                "%d",
@@ -2778,11 +2047,6 @@ char *procid_str(TALLOC_CTX *mem_ctx, const struct server_id *pid)
                                        (unsigned)pid->vnn,
                                        (int)pid->pid);
        }
-#else
-       return talloc_asprintf(mem_ctx,
-                       "%d",
-                       (int)pid->pid);
-#endif
 }
 
 char *procid_str_static(const struct server_id *pid)
@@ -2797,28 +2061,7 @@ bool procid_valid(const struct server_id *pid)
 
 bool procid_is_local(const struct server_id *pid)
 {
-#ifdef CLUSTER_SUPPORT
        return pid->vnn == my_vnn;
-#else
-       return True;
-#endif
-}
-
-int this_is_smp(void)
-{
-#if defined(HAVE_SYSCONF)
-
-#if defined(SYSCONF_SC_NPROC_ONLN)
-        return (sysconf(_SC_NPROC_ONLN) > 1) ? 1 : 0;
-#elif defined(SYSCONF_SC_NPROCESSORS_ONLN)
-        return (sysconf(_SC_NPROCESSORS_ONLN) > 1) ? 1 : 0;
-#else
-       return 0;
-#endif
-
-#else
-       return 0;
-#endif
 }
 
 /****************************************************************
@@ -3052,129 +2295,85 @@ void *talloc_zeronull(const void *context, size_t size, const char *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.
- */
+/****************************************************************
+ strip off leading '\\' from a hostname
+****************************************************************/
 
-NTSTATUS split_ntfs_stream_name(TALLOC_CTX *mem_ctx, const char *fname,
-                               char **pbase, char **pstream)
+const char *strip_hostname(const char *s)
 {
-       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 (!s) {
+               return NULL;
        }
 
-       if (sname[0] == '\0') {
-               /*
-                * no stream name, so no stream
-                */
-               goto done;
+       if (strlen_m(s) < 3) {
+               return s;
        }
 
-       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);
-       }
+       if (s[0] == '\\') s++;
+       if (s[0] == '\\') s++;
 
- done:
-       if (pbase != NULL) {
-               *pbase = base;
-       }
-       if (pstream != NULL) {
-               *pstream = stream;
-       }
-       return NT_STATUS_OK;
+       return s;
 }
 
-bool is_valid_policy_hnd(const struct policy_handle *hnd)
+bool tevent_req_poll_ntstatus(struct tevent_req *req,
+                             struct tevent_context *ev,
+                             NTSTATUS *status)
 {
-       struct policy_handle tmp;
-       ZERO_STRUCT(tmp);
-       return (memcmp(&tmp, hnd, sizeof(tmp)) != 0);
+       bool ret = tevent_req_poll(req, ev);
+       if (!ret) {
+               *status = map_nt_error_from_unix(errno);
+       }
+       return ret;
 }
 
-bool policy_hnd_equal(const struct policy_handle *hnd1,
-                     const struct policy_handle *hnd2)
+bool any_nt_status_not_ok(NTSTATUS err1, NTSTATUS err2, NTSTATUS *result)
 {
-       if (!hnd1 || !hnd2) {
-               return false;
+       if (!NT_STATUS_IS_OK(err1)) {
+               *result = err1;
+               return true;
        }
+       if (!NT_STATUS_IS_OK(err2)) {
+               *result = err2;
+               return true;
+       }
+       return false;
+}
 
-       return (memcmp(hnd1, hnd2, sizeof(*hnd1)) == 0);
+int timeval_to_msec(struct timeval t)
+{
+       return t.tv_sec * 1000 + (t.tv_usec+999) / 1000;
 }
 
-/****************************************************************
- strip off leading '\\' from a hostname
-****************************************************************/
+/*******************************************************************
+ Check a given DOS pathname is valid for a share.
+********************************************************************/
 
-const char *strip_hostname(const char *s)
+char *valid_share_pathname(TALLOC_CTX *ctx, const char *dos_pathname)
 {
-       if (!s) {
+       char *ptr = NULL;
+
+       if (!dos_pathname) {
                return NULL;
        }
 
-       if (strlen_m(s) < 3) {
-               return s;
+       ptr = talloc_strdup(ctx, dos_pathname);
+       if (!ptr) {
+               return NULL;
+       }
+       /* Convert any '\' paths to '/' */
+       unix_format(ptr);
+       ptr = unix_clean_name(ctx, ptr);
+       if (!ptr) {
+               return NULL;
        }
 
-       if (s[0] == '\\') s++;
-       if (s[0] == '\\') s++;
+       /* NT is braindead - it wants a C: prefix to a pathname ! So strip it. */
+       if (strlen(ptr) > 2 && ptr[1] == ':' && ptr[0] != '/')
+               ptr += 2;
 
-       return s;
+       /* Only absolute paths allowed. */
+       if (*ptr != '/')
+               return NULL;
+
+       return ptr;
 }