diff options
author | Rich Megginson <rmeggins@redhat.com> | 2007-07-18 20:37:12 +0000 |
---|---|---|
committer | Rich Megginson <rmeggins@redhat.com> | 2007-07-18 20:37:12 +0000 |
commit | 9dc51a21f16bc27e5d50ff072d6c94c301227efc (patch) | |
tree | 1b2f12e962ff74f39394b560f68fd0168bc6be01 /ldap/admin/src | |
parent | 1190f204bf5e3a18e759dbb6308e2e7e17dfba2a (diff) | |
download | ds-9dc51a21f16bc27e5d50ff072d6c94c301227efc.tar.gz ds-9dc51a21f16bc27e5d50ff072d6c94c301227efc.tar.xz ds-9dc51a21f16bc27e5d50ff072d6c94c301227efc.zip |
Resolves: bug 248145
Bug Description: Replace ds_newinst binary with perl script - remove dead code
Reviewed by: nhosoi (Thanks!)
Fix Description: This is my favorite part - removing all of the now dead code. I also had to fix the exit code so that you could use $? to test for the success or failure of the new setup scripts.
Platforms tested: RHEL4, FC6
Flag Day: no
Doc impact: no
Diffstat (limited to 'ldap/admin/src')
39 files changed, 23 insertions, 25681 deletions
diff --git a/ldap/admin/src/CGI_ENV b/ldap/admin/src/CGI_ENV deleted file mode 100644 index 7de4263b..00000000 --- a/ldap/admin/src/CGI_ENV +++ /dev/null @@ -1,68 +0,0 @@ -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# -The following is a debug printout which is useful for reference. It -is a dump of all the env vars for a real running CGI admin program. -*********************************************************************** -HTTP_HOST=asterix.mcom.com:9616 -HTTP_ACCEPT=image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */* -HTTP_USER_AGENT=Mozilla/2.0 (X11; U; SunOS 5.4 sun4m) -HTTP_CONNECTION=Keep-Alive -ADMSERV_PID=14001 -ADMSERV_ROOT=/export/free2/ns-home/admserv -NETSITE_ROOT=/export/free2/ns-home -SERVER_NAMES=slapd-asterix -CONFIG_DIR=/export/free2/ns-home/admserv/%s/ -COMMIT_LOG=/export/free2/ns-home/admserv/commit -BACKUPS=10 -PATH=/usr/sbin:/usr/bin -TZ=US/Pacific -SERVER_SOFTWARE=Netscape-Administrator/2.0b3 -SERVER_PORT=9616 -SERVER_NAME=asterix.mcom.com -SERVER_URL=http://asterix.mcom.com:9616 -REMOTE_HOST=goa.mcom.com -REMOTE_ADDR=207.1.137.54 -REMOTE_USER=admin -AUTH_TYPE=basic -HTTPS=OFF -GATEWAY_INTERFACE=CGI/1.1 -SERVER_PROTOCOL=HTTP/1.0 -REQUEST_METHOD=GET -SCRIPT_NAME=/slapd-asterix/bin/ds_pcontrol diff --git a/ldap/admin/src/Cgi.pm b/ldap/admin/src/Cgi.pm deleted file mode 100644 index a01d179b..00000000 --- a/ldap/admin/src/Cgi.pm +++ /dev/null @@ -1,102 +0,0 @@ -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# -package Cgi; - -sub parse { - my $line = shift; - my $assign; - my $var; - my $value; - - # save time, don't parse empty lines - return if (!$line); - - chomp( $line ); - if ( $raw ) { - $raw .= '&' . $line; - } else { - $raw = $line; - } - # decode the line first - $line = &decode($line); - # this only works if there are no '&' characters in var or value . . . - foreach $assign ( split( /&/, $line ) ) { - # assume the var is everything before the first '=' in assign - # and the value is everything after the first '=' - ( $var, $value ) = split( /=/, $assign, 2 ); - $main::cgiVars{$var} = $value; - } -} - -sub decode { - my $string = shift; - - $string =~ s/\+/ /g; - $string =~ s/%(\w\w)/chr(hex($1))/ge; - - return $string; -} - -sub main::freakOut { - my $i; - - for ( $i = 0 ; $i < scalar( @_ ) ; ++$i ) { - $_[$i] =~ s/'/\\'/g; - } - print "<SCRIPT language=JAVASCRIPT>\n"; - print "alert('@_');\n"; - print "location='index';\n</SCRIPT>\n"; - exit 0; -} - -if ($ENV{'QUERY_STRING'}) { - &parse( $ENV{'QUERY_STRING'} ); - $Cgi::QUERY_STRING = $ENV{'QUERY_STRING'}; -} - -if ( $ENV{'CONTENT_LENGTH'} ) { - read STDIN, $Cgi::CONTENT, $ENV{'CONTENT_LENGTH'}; - &parse( $Cgi::CONTENT ); -} - -# $Cgi::QUERY_STRING contains the query string and -# $Cgi::CONTENT contains what was passed in through stdin - -1; diff --git a/ldap/admin/src/cfg_sspt.c b/ldap/admin/src/cfg_sspt.c deleted file mode 100644 index 2bd6ab2d..00000000 --- a/ldap/admin/src/cfg_sspt.c +++ /dev/null @@ -1,1407 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - - -#include <stdio.h> -#include <stdarg.h> -#include <stdlib.h> -#include <assert.h> -#include "ldap.h" -#include "dsalib.h" -#include "nspr.h" -#include "plstr.h" -#include <string.h> - -#define __CFG_SSPT_C - -#include "cfg_sspt.h" - -/*#define CGI_DEBUG 1*/ - -#undef TEST_CONFIG /* for testing cn=config40 dummy entry instead of real one */ - -char* const NULLSTR = 0; - -char* const class_top = "top"; -char* const class_organization = "organization"; -char* const class_organizationalUnit = "organizationalunit"; -char* const class_person = "person"; -char* const class_organizationalPerson = "organizationalperson"; -char* const class_inetOrgPerson = "inetorgperson"; -char* const class_groupOfUniqueNames = "groupofuniquenames"; -char* const class_domain = "domain"; -char* const class_extensibleObject = "extensibleObject"; -char* const class_adminDomain = "nsadmindomain"; -char* const class_country = "country"; -char* const class_locality = "locality"; - -char* const name_objectClass = "objectclass"; -char* const name_cn = "cn"; -char* const name_sn = "sn"; -char* const name_givenname = "givenname"; -char* const name_uid = "uid"; -char* const name_userPassword = "userpassword"; -char* const name_passwordExpirationTime = "passwordExpirationTime"; -char* const name_o = "o"; -char* const name_ou = "ou"; -char* const name_dc = "dc"; -char* const name_member = "member"; -char* const name_uniqueMember = "uniquemember"; -char* const name_aci = "aci"; -char* const name_description = "description"; -char* const name_adminDomain = "nsadmindomainname"; -char* const name_c = "c"; -char* const name_st = "st"; -char* const name_l = "l"; - -char* const name_netscaperootDN = "o=NetscapeRoot"; - -char* const value_configAdminCN = "Configuration Administrator"; -char* const value_configAdminSN = "Administrator"; -char* const value_configAdminGN = "Configuration"; -char* const value_peopleOU = "People"; -char* const value_peopleDesc = "Standard branch for people (uid) entries"; -char* const value_groupsOU = "Groups"; -char* const value_groupsDesc = "Standard Branch for group entries"; -#ifdef TEST_CONFIG -char* const value_config40 = "config40"; -char* const value_config40DN = "cn=config40"; -#endif /* TEST_CONFIG */ - -char* dbg_log_file = "ds_sscfg.log"; - -char* const name_localDAGroup = "Directory Administrators"; -char* const value_localDAGroupDesc = "Entities with administrative access to this directory server"; - -static char* const ACI_self_allow = "(targetattr=\"" - "carLicense ||" - "description ||" - "displayName ||" - "facsimileTelephoneNumber ||" - "homePhone ||" - "homePostalAddress ||" - "initials ||" - "jpegPhoto ||" - "labeledURL ||" - "mail ||" - "mobile ||" - "pager ||" - "photo ||" - "postOfficeBox ||" - "postalAddress ||" - "postalCode ||" - "preferredDeliveryMethod ||" - "preferredLanguage ||" - "registeredAddress ||" - "roomNumber ||" - "secretary ||" - "seeAlso ||" - "st ||" - "street ||" - "telephoneNumber ||" - "telexNumber ||" - "title ||" - "userCertificate ||" - "userPassword ||" - "userSMIMECertificate ||" - "x500UniqueIdentifier\")" - "(version 3.0; acl \"Enable self write for common attributes\"; allow (write) " - "userdn=\"ldap:///self\";)"; - -static char* const ACI_anonymous_allow = "(targetattr!=\"userPassword\")" - "(version 3.0; " - "acl \"Enable anonymous access\"; allow (read, search, compare)" - "userdn=\"ldap:///anyone\";)"; - -static char* const ACI_anonymous_allow_with_filter = - "(targetattr=\"*\")(targetfilter=(%s))" - "(version 3.0; acl \"Default anonymous access\"; " - "allow (read, search) userdn=\"ldap:///anyone\";)"; - -static char* const ACI_config_admin_group_allow_all = "(targetattr=\"*\")" - "(version 3.0; " - "acl \"Enable Configuration Administrator Group modification\"; " - "allow (all) groupdn=\"ldap:///%s, %s=%s, %s, %s\";)"; - -static char* const ACI_config_admin_group_allow = "(targetattr=\"*\")" - "(version 3.0; " - "acl \"Configuration Administrators Group\"; allow (%s) " - "groupdn=\"ldap:///%s\";)"; - -static char* const ACI_local_DA_allow = "(targetattr = \"*\")(version 3.0; " - "acl \"Local Directory Administrators Group\"; allow (%s) " - "groupdn=\"ldap:///%s\";)"; - -static char* const ACI_group_expansion = "(targetattr=\"*\")" - "(version 3.0; acl \"Enable Group Expansion\"; " - "allow (read, search, compare) groupdnattr=\"uniquemember\";)"; - -static char* const ACI_user_allow_1 = "(targetattr=\"*\")(version 3.0; " - "acl \"Configuration Administrator\"; allow (%s) " - "userdn=\"ldap:///uid=%s, %s\";)"; - -static char* const ACI_user_allow_2 = "(targetattr=\"*\")(version 3.0; " - "acl \"Configuration Administrator\"; allow (%s) " - "userdn=\"ldap:///%s\";)"; -/* - This is a list of DSE entries that the Configuration Admin Group has - access to and the access rights for that entry -*/ -static struct _DSEEntriesAndAccess { - char *entryDN; - char *access; -} entryAndAccessList[] = { - {"cn=config", "all"}, - {"cn=schema", "all"} -}; - -static int entryAndAccessListSize = - sizeof(entryAndAccessList)/sizeof(entryAndAccessList[0]); - -int -getEntryAndAccess(int index, const char **entry, const char **access) -{ - if (!entry || !access) - return 0; - - *entry = 0; - *access = 0; - - if (index < 0 || index >= entryAndAccessListSize) - return 0; - - *entry = entryAndAccessList[index].entryDN; - *access = entryAndAccessList[index].access; - - return 1; -} - -static int -is_root_user(const char *name, QUERY_VARS* query) -{ - if (!name || !query->rootDN) { - return 0; - } - return !PL_strcasecmp(name, query->rootDN); -} - -/* -** --------------------------------------------------------------------------- -** -** Utility Routines - Functions for performing string and file operations. -** -*/ - -#ifdef CGI_DEBUG -#include <stdarg.h> -static void debug_log (const char* file, const char* format, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 2, 3))); -#else - ; -#endif - -static void -debug_log (const char* file, const char* format, ...) -{ - va_list args; - FILE* fp = fopen(file, "a+"); - if (fp) { - va_start(args, format); - vfprintf(fp, format, args); - va_end(args); - fflush(fp); - fclose(fp); - } -} - -static void -debug_log_array (const char* file, char* name, char** vals) -{ - FILE* fp = fopen(file, "a+"); - - if (fp) { - if (vals != NULL) { - for (; *vals != NULL; LDAP_UTF8INC(vals)) { - fprintf (fp, "%s: %s\n", name, *vals); - } - fflush(fp); - } - fclose(fp); - } -} - -#endif /* CGI_DEBUG */ - -static char * -extract_name_from_dn(const char *dn) -{ - char **rdnList = 0; - char *ret = 0; - if (!dn) - return ret; - - rdnList = ldap_explode_dn(dn, 1); /* leave out types */ - if (!rdnList || !rdnList[0]) - ret = strdup(dn); /* the given dn is not really a dn */ - else - ret = strdup(rdnList[0]); - - if (rdnList) - ldap_value_free(rdnList); - - return ret; -} - -int -entry_exists(LDAP* ld, const char* entrydn) -{ - int exists = 0; - int err; - - struct timeval sto = { 10L, 0L }; - LDAPMessage* pLdapResult; - - err = ldap_search_st(ld, entrydn, LDAP_SCOPE_BASE, - "objectClass=*", NULL, 0, &sto, &pLdapResult); - - if (err == LDAP_SUCCESS) - { - LDAPMessage* pLdapEntry; - char* dn; - - for (pLdapEntry = ldap_first_entry(ld, pLdapResult); - pLdapEntry != NULL; - pLdapEntry = ldap_next_entry(ld, pLdapEntry)) - { - if ((dn = ldap_get_dn(ld, pLdapEntry)) != NULL) - { - exists = 1; - free(dn); - /*ldap_memfree(dn);*/ - break; - } - } - - ldap_msgfree(pLdapResult); - } - - return exists; -} - -int -add_aci(LDAP* ld, char* DN, char* privilege) -{ - int err; - int ret = 0; - LDAPMod mod; - LDAPMod* mods[2]; - char* aci[2]; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "add_aci('%s', '%s')\n", - DN ? DN : "NULL", - privilege ? privilege : "NULL"); -#endif - - if (ld == NULL || DN == NULL || privilege == NULL) - { - return -1; - } - - mods[0] = &mod; - mods[1] = NULL; - mod.mod_op = LDAP_MOD_ADD; - mod.mod_type = name_aci; - mod.mod_values = aci; - aci[0] = privilege; - aci[1] = NULL; - /* fprintf (stdout, "ldap_modify_s('%s')<br>\n",DN); fflush (stdout); */ - err = ldap_modify_s (ld, DN, mods); - if (err != LDAP_SUCCESS && err != LDAP_TYPE_OR_VALUE_EXISTS) { - char* exp = "can't add privilege. "; - char* explanation = PR_smprintf("%s (%i) returned from ldap_modify_s(%s, %i). Privilege: %s", - ldap_err2string (err), err, DN, LDAP_MOD_ADD, aci[0]); - ds_report_warning (DS_INCORRECT_USAGE, exp, explanation); - PR_smprintf_free (explanation); - ret = 1; - } - - return ret; -} - -/* - Same as add_aci, except that the 3rd parameter is a format string - in printf style format, and the 4th - Nth parameters are a NULL terminated - list of strings to substitute in the format; basically just constructs - the correct aci string and passes it to add_aci -*/ -int add_aci_v(LDAP* ld, char* DN, char* format, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 3, 4))); -#else - ; -#endif -int -add_aci_v(LDAP* ld, char* DN, char* format, ...) -{ - char* acistring = NULL; - int len = 0; - int status = 0; - int fudge = 10; /* a little extra just to make sure */ - char *s = 0; - va_list ap; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "add_aci_v('%s', '%s')\n", - DN ? DN : "NULL", - format ? format : "NULL"); -#endif - - if (ld == NULL || DN == NULL || format == NULL) - { - return -1; - } - - /* determine the length of the string to allocate to hold - the aci string - */ - len += strlen(format) + fudge; - va_start(ap, format); - s = va_arg(ap, char*); - while (s) - { - len += strlen(s) + 1; - s = va_arg(ap, char*); - } - va_end(ap); - - va_start(ap, format); - acistring = (char *)malloc(len); - vsprintf(acistring, format, ap); - va_end(ap); - status = add_aci(ld, DN, acistring); - - free(acistring); - - return status; -} - -/* - Make a dn from lists of dn components. The format argument is in the - standard printf format. The varargs list contains the various dn - components. The string returned is malloc()'d and must be free()'d by - the caller after use. example: - make_dn("cn=%s, ou=%s, %s", "Admins", "TopologyManagement", "o=NetscapeRoot", NULL) - returns - "cn=Admins, ou=TopologyManagement, o=NetscapeRoot" -*/ -char * -make_dn(const char* format, ...) -{ - char *s; - int len = 0; - int fudge = 3; - va_list ap; - char *dnstring; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "make_dn('%s', ...)\n", - format ? format : "NULL"); -#endif - - if (format == NULL) - { - return NULL; - } - - /* determine the length of the string to allocate to hold - the dn string - */ - len += strlen(format) + fudge; - va_start(ap, format); - s = va_arg(ap, char*); - while (s) - { - len += strlen(s) + 3; - s = va_arg(ap, char*); - } - va_end(ap); - - va_start(ap, format); - dnstring = (char *)malloc(len); - vsprintf(dnstring, format, ap); - va_end(ap); - - return dnstring; -} - -char * -admin_user_exists(LDAP* ld, char* base, char *userID) -{ - int exists = 0; - int err; - char search_str[MAX_STRING_LEN]; - - struct timeval sto = { 10L, 0L }; - LDAPMessage* pLdapResult; - PR_snprintf (search_str, sizeof(search_str), "uid=%s*", userID ? userID : "admin"); - - err = ldap_search_st(ld, base, LDAP_SCOPE_SUBTREE, - search_str, NULL, 0, &sto, &pLdapResult); - - if (err == LDAP_SUCCESS) - { - LDAPMessage* pLdapEntry; - char* dn = NULL; - - for (pLdapEntry = ldap_first_entry(ld, pLdapResult); - pLdapEntry != NULL; - pLdapEntry = ldap_next_entry(ld, pLdapEntry)) - { - if ((dn = ldap_get_dn(ld, pLdapEntry)) != NULL) - { - exists = 1; - /*ldap_memfree(dn);*/ - break; - } - } - - ldap_msgfree(pLdapResult); - return dn; - } - - return NULL; -} - -static void -getUIDFromDN(const char *userID, char *uid) -{ - char **rdnListTypes = 0; - char **rdnListNoTypes = 0; - int ii = 0; - int uidindex = -1; - uid[0] = 0; - - rdnListTypes = ldap_explode_dn(userID, 0); - if (!rdnListTypes) - return; /* userID is not a DN */ - - /* find the first rdn in the given userID DN which begins with - "uid=" */ - for (ii = 0; uidindex < 0 && rdnListTypes[ii]; ++ii) - { - if (!PL_strncasecmp(rdnListTypes[ii], "uid=", 4)) - uidindex = ii; - } - ldap_value_free(rdnListTypes); - - if (uidindex < 0) /* did not find an rdn beginning with "uid=" */ - return; - - rdnListNoTypes = ldap_explode_dn(userID, 1); - PL_strncpyz(uid, rdnListNoTypes[uidindex], 1024); - ldap_value_free(rdnListNoTypes); - - return; -} - -static char * -create_ssadmin_user(LDAP* ld, char *base, char* userID, char* password) -{ - int err; - char *ret = 0; - char entrydn[1024] = {0}; - char realuid[1024] = {0}; - char *admin_dn = NULL; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_ssadmin_user('%s','%s','%s')\n", - base ? base : "NULL", userID ? userID : "NULL", - password ? password : "NULL"); -#endif - - if (ld == NULL || base == NULL || userID == NULL || *userID == '\0' || - password == NULL || *password == '\0') - { - return NULL; - } - - getUIDFromDN(userID, realuid); - if (realuid[0]) - { - PL_strncpyz(entrydn, userID, sizeof(entrydn)); - if (entry_exists(ld, entrydn)) - admin_dn = entrydn; - } - else - { - PR_snprintf(entrydn, sizeof(entrydn), "%s=%s, %s", name_uid, userID, base); - admin_dn = admin_user_exists(ld, base, userID); - PL_strncpyz(realuid, userID, sizeof(realuid)); - } - - if (admin_dn) - { - char error[BIG_LINE]; - PR_snprintf(error, sizeof(error), "A user with uid=%s \"%s\" already exists in the directory" - " and will not be overwritten.", realuid[0] ? realuid : "admin", admin_dn); - ds_send_error(error, 0); - return admin_dn; - } - else - { - LDAPMod* attrs[8]; - LDAPMod attr[7]; - char* objectClasses[5]; - char* cn[2]; - char* sn[2]; - char* givenname[2]; - char* uid[2]; - char* userPassword[2]; - char* passwordExpirationTime[2]; - - attrs[0] = &attr[0]; - attrs[1] = &attr[1]; - attrs[2] = &attr[2]; - attrs[3] = &attr[3]; - attrs[4] = &attr[4]; - attrs[5] = &attr[5]; - attrs[6] = &attr[6]; - attrs[7] = NULL; - attr[0].mod_op = LDAP_MOD_ADD; - attr[0].mod_type = name_objectClass; - attr[0].mod_values = objectClasses; - objectClasses[0] = class_top; - objectClasses[1] = class_person; - objectClasses[2] = class_organizationalPerson; - objectClasses[3] = class_inetOrgPerson; - objectClasses[4] = NULL; - attr[1].mod_op = LDAP_MOD_ADD; - attr[1].mod_type = name_cn; - attr[1].mod_values = cn; - cn[0] = value_configAdminCN; - cn[1] = NULL; - attr[2].mod_op = LDAP_MOD_ADD; - attr[2].mod_type = name_sn; - attr[2].mod_values = sn; - sn[0] = value_configAdminSN; - sn[1] = NULL; - attr[3].mod_op = LDAP_MOD_ADD; - attr[3].mod_type = name_givenname; - attr[3].mod_values = givenname; - givenname[0] = value_configAdminGN; - givenname[1] = NULL; - attr[4].mod_op = LDAP_MOD_ADD; - attr[4].mod_type = name_uid; - attr[4].mod_values = uid; - uid[0] = realuid; - uid[1] = NULL; - attr[5].mod_op = LDAP_MOD_ADD; - attr[5].mod_type = name_userPassword; - attr[5].mod_values = userPassword; - userPassword[0] = password; - userPassword[1] = NULL; - attr[6].mod_op = LDAP_MOD_ADD; - attr[6].mod_type = name_passwordExpirationTime; - attr[6].mod_values = passwordExpirationTime; - passwordExpirationTime[0] = "20380119031407Z"; - passwordExpirationTime[1] = NULL; - - /* fprintf (stdout, "ldap_add_s(%s)<br>\n", entrydn); fflush (stdout); */ - - err = ldap_add_s (ld, entrydn, attrs); - - if (err != LDAP_SUCCESS) - { - char *explanation = PR_smprintf("Unable to create administrative user." - " (%s (%i) returned from ldap_add_s(%s))", - ldap_err2string (err), err, entrydn); - ds_report_warning (DS_NETWORK_ERROR, " can't create user", explanation); - PR_smprintf_free (explanation); - ret = NULL; - } - } - - return NULL; -} - -static int -create_base_entry( - LDAP* ld, - char* basedn, - char *naming_attr_type, - char *naming_attr_value, - char *objectclassname -) -{ - int err; - int ret = 0; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_base_entry('%s','%s')\n", - basedn ? basedn : "NULL", naming_attr_value: "NULL"); -#endif - - if (ld == NULL || basedn == NULL || *basedn == '\0') - { - return -1; - } - - if (!entry_exists(ld, basedn)) - { - LDAPMod* attrs[3]; - LDAPMod attr[2]; - char* objectClasses[3]; - char* names[2]; - - attrs[0] = &attr[0]; - attrs[2] = NULL; - attr[0].mod_op = LDAP_MOD_ADD; - attr[0].mod_type = name_objectClass; - attr[0].mod_values = objectClasses; - objectClasses[0] = class_top; - objectClasses[1] = objectclassname; - objectClasses[2] = NULL; - attrs[1] = &attr[1]; - attr[1].mod_op = LDAP_MOD_ADD; - attr[1].mod_type = naming_attr_type; - attr[1].mod_values = names; - names[0] = naming_attr_value; - names[1] = NULL; - - /* fprintf (stdout, "ldap_add_s(%s)<br>\n", basedn); fflush (stdout); */ - - err = ldap_add_s (ld, basedn, attrs); - - if (err != LDAP_SUCCESS) - { - char* explanation = PR_smprintf("Unable to create base entry." - " (%s (%i) returned from ldap_add_s(%s))", - ldap_err2string (err), err, basedn); - ds_report_warning (DS_NETWORK_ERROR, " can't create base entry", - explanation); - PR_smprintf_free (explanation); - ret = 1; - } - } - - return ret; -} - -static int -create_organization(LDAP* ld, char* base, char* org) -{ - return create_base_entry(ld, base, name_o, org, class_organization); -} - -static int -create_organizational_unit(LDAP* ld, char* base, char* unit, char *description, - char *extra_objectclassName, - char *extra_attrName, - char *extra_attrValue) -{ - int err; - int ret = 0; - char *entrydn = NULL; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_organizational_unit('%s','%s')\n", - base ? base : "NULL", unit ? unit : "NULL"); -#endif - - if (ld == NULL || unit == NULL || *unit == '\0') - { - return -1; - } - - /* - if base is null, assume the unit is the full DN of the entry - to create; this assumes the caller knows what he/she is doing - and has already created the parent entry(ies) - */ - if (!base) - entrydn = strdup(unit); - else - entrydn = make_dn("%s=%s, %s", name_ou, unit, base, NULLSTR); - - if (!entry_exists(ld, entrydn)) - { - LDAPMod* attrs[5]; - LDAPMod attr[4]; - char* objectClasses[4]; - char* names[2]; - char* desc[2]; - char* extra[2]; - char *baseName = unit; - int attrnum = 0; - if (base) - { - baseName = strdup(unit); - } - else - { - /* since the unit is in DN form, we need to extract something to - use for the ou: attribute */ - baseName = extract_name_from_dn(unit); - } - attrs[0] = &attr[0]; - attrs[1] = &attr[1]; - attrs[2] = NULL; - attr[0].mod_op = LDAP_MOD_ADD; - attr[0].mod_type = name_objectClass; - attr[0].mod_values = objectClasses; - objectClasses[0] = class_top; - objectClasses[1] = class_organizationalUnit; - objectClasses[2] = extra_objectclassName; /* may be null */ - objectClasses[3] = NULL; - attr[1].mod_op = LDAP_MOD_ADD; - attr[1].mod_type = name_ou; - attr[1].mod_values = names; - names[0] = baseName; - names[1] = NULL; - attrnum = 2; - if (description && *description) - { - attr[attrnum].mod_op = LDAP_MOD_ADD; - attr[attrnum].mod_type = name_description; - attr[attrnum].mod_values = desc; - desc[0] = description; - desc[1] = NULL; - attrs[attrnum] = &attr[attrnum]; - attrs[++attrnum] = NULL; - } - if (extra_attrName && extra_attrValue && - *extra_attrName && *extra_attrValue) - { - attr[attrnum].mod_op = LDAP_MOD_ADD; - attr[attrnum].mod_type = extra_attrName; - attr[attrnum].mod_values = extra; - extra[0] = extra_attrValue; - extra[1] = NULL; - attrs[attrnum] = &attr[attrnum]; - attrs[++attrnum] = NULL; - } - - /* fprintf (stdout, "ldap_add_s(%s)<br>\n", DN); fflush (stdout); */ - - err = ldap_add_s (ld, entrydn, attrs); - if (baseName) - free(baseName); - - if (err != LDAP_SUCCESS) - { - char* explanation = PR_smprintf("Unable to create organizational unit." - " (%s (%i) returned from ldap_add_s(%s))", - ldap_err2string (err), err, entrydn); - ds_report_warning (DS_NETWORK_ERROR, " can't create organizational unit", - explanation); - PR_smprintf_free (explanation); - ret = 1; - } - } - - if (entrydn) - free(entrydn); - - return ret; -} - -static int -create_domain_component(LDAP* ld, char* base, char* domcomp) -{ - return create_base_entry(ld, base, name_dc, domcomp, class_domain); -} - -static int -create_country(LDAP* ld, char* base, char* country) -{ - return create_base_entry(ld, base, name_c, country, class_country); -} - -static int -create_state(LDAP* ld, char* base, char* state) -{ - return create_base_entry(ld, base, name_st, state, class_locality); -} - -static int -create_locality(LDAP* ld, char* base, char* locality) -{ - return create_base_entry(ld, base, name_l, locality, class_locality); -} - -static int -create_base(LDAP* ld, char* base) -{ - int ret = 0; - char* attr; - char **rdnList = 0; - char **rdnListNoTypes = 0; - enum BASETYPE { unknown, org, orgunit, domcomp, country, state, locality } base_type = unknown; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_base('%s')\n", base ? base : "NULL"); -#endif - - if (ld == NULL || base == NULL || *base == '\0') - { - return -1; - } - - rdnList = ldap_explode_dn(base, 0); - if (!rdnList) - { - char error[BIG_LINE]; - PR_snprintf(error, sizeof(error), "The given base suffix [%s] is not a valid DN", base); - ds_send_error(error, 0); - return -1; - } - - if (PL_strncasecmp(rdnList[0], "o=", 2) == 0) - { - base_type = org; - } - else if (PL_strncasecmp(rdnList[0], "ou=", 3) == 0) - { - base_type = orgunit; - } - else if (PL_strncasecmp(rdnList[0], "dc=", 3) == 0) - { - base_type = domcomp; - } - else if (PL_strncasecmp(rdnList[0], "c=", 2) == 0) - { - base_type = country; - } - else if (PL_strncasecmp(rdnList[0], "st=", 3) == 0) - { - base_type = state; - } - else if (PL_strncasecmp(rdnList[0], "l=", 2) == 0) - { - base_type = locality; - } - else - { - ds_report_warning (DS_INCORRECT_USAGE, " Unable to create the root suffix.", - "In order to create the root suffix in the directory, you must " - "specify a distinguished name beginning with o=, ou=, dc=, c=, st=, or l=. " - "If you wish to use something else for your root suffix, you " - "should first create the directory with one of these suffixes, then you can " - "create additional suffixes in any form you choose." - ); - return -1; - } - - ldap_value_free(rdnList); - /* - We need to extract from the base the value to use for the attribute - name_attr e.g. ou: foo or o: org. - */ - rdnListNoTypes = ldap_explode_dn(base, 1); - attr = rdnListNoTypes[0]; - - if (!entry_exists(ld, base)) - { - if (base_type == org) - { - ret = create_organization(ld, base, attr); - } - else if (base_type == orgunit) - { - /* this function is smart enough to extract the name from the DN */ - ret = create_organizational_unit(ld, 0, base, 0, 0, 0, 0); - } - else if (base_type == domcomp) - { - ret = create_domain_component(ld, base, attr); - } - else if (base_type == country) - { - ret = create_country(ld, base, attr); - } - else if (base_type == state) - { - ret = create_state(ld, base, attr); - } - else if (base_type == locality) - { - ret = create_locality(ld, base, attr); - } - } - - ldap_value_free(rdnListNoTypes); - - /* now add the anon search and self mod acis */ - if (!ret) - { - ret = add_aci(ld, base, ACI_anonymous_allow); - if (!ret) - ret = add_aci(ld, base, ACI_self_allow); - } - - return ret; -} - - -#ifdef TEST_CONFIG -static int -create_configEntry(LDAP* ld) -{ -/* - dn: cn=config40 - objectclass: top - objectclass: extensibleObject - cn: config40 - */ - char *entrydn = NULL; - int err; - int ret = 0; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_configEntry()\n"); -#endif - - if (ld == NULL) - { - return -1; - } - - entrydn = make_dn("%s=%s", name_cn, value_config40, NULLSTR); - if (!entry_exists(ld, entrydn)) - { - LDAPMod* attrs[3]; - LDAPMod attr[2]; - char* objectClasses[3]; - char* names[2]; - - attrs[0] = &attr[0]; - attrs[2] = NULL; - attr[0].mod_op = LDAP_MOD_ADD; - attr[0].mod_type = name_objectClass; - attr[0].mod_values = objectClasses; - objectClasses[0] = class_top; - objectClasses[1] = class_extensibleObject; - objectClasses[2] = NULL; - attrs[1] = &attr[1]; - attr[1].mod_op = LDAP_MOD_ADD; - attr[1].mod_type = name_cn; - attr[1].mod_values = names; - names[0] = value_config40; - names[1] = NULL; - - /* fprintf (stdout, "ldap_add_s(%s)<br>\n", DN); fflush (stdout); */ - - err = ldap_add_s (ld, entrydn, attrs); - - if (err != LDAP_SUCCESS) - { - char* explanation = PR_smprintf("Unable to create %s." - " (%s (%i) returned from ldap_add_s(%s))", - value_config40, ldap_err2string (err), err, entrydn); - ds_report_warning (DS_NETWORK_ERROR, " can't create config40", - explanation); - PR_smprintf_free (explanation); - ret = 1; - } - - } - - if (entrydn) - free(entrydn); - - return ret; -} -#endif - -int -create_group(LDAP* ld, char* base, char* group) -{ - int err; - int ret = 0; - LDAPMod* attrs[3]; - LDAPMod attr[2]; - char* objectClasses[3]; - char* names[2]; - char *entrydn = 0; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_group('%s','%s')\n", - base ? base : "NULL", group ? group : "NULL"); -#endif - - if (ld == NULL || base == NULL || *base == '\0' || - group == NULL || *group == '\0') - { - return -1; - } - - entrydn = make_dn("%s=%s, %s", name_cn, group, base, NULLSTR); - - if (!entry_exists(ld, entrydn)) - { - attrs[0] = &attr[0]; - attrs[1] = &attr[1]; - attrs[2] = NULL; - attr[0].mod_op = LDAP_MOD_ADD; - attr[0].mod_type = name_objectClass; - attr[0].mod_values = objectClasses; - objectClasses[0] = class_top; - objectClasses[1] = class_groupOfUniqueNames; - objectClasses[2] = NULL; - attr[1].mod_op = LDAP_MOD_ADD; - attr[1].mod_type = name_cn; - attr[1].mod_values = names; - names[0] = group; - names[1] = NULL; - /* fprintf (stdout, "ldap_add_s(%s)<br>\n", entrydn); fflush (stdout); */ - - err = ldap_add_s (ld, entrydn, attrs); - - if (err != LDAP_SUCCESS) - { - char* explanation = PR_smprintf("Unable to create group." - " (%s (%i) returned from ldap_add_s(%s))", - ldap_err2string (err), err, entrydn); - ds_report_warning (DS_NETWORK_ERROR, " can't create group", explanation); - PR_smprintf_free (explanation); - ret = 1; - } - } - - if (entrydn) - free(entrydn); - - return ret; -} - -int -create_consumer_dn(LDAP* ld, char* dn, char* hashedpw) -{ - int err; - int ret = 0; - LDAPMod* attrs[7]; - LDAPMod attr[6]; - char* objectClasses[3]; - char* names[2]; - char* snames[2]; - char* desc[2]; - char* pwd[2]; - char* passwordExpirationTime[2]; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "create_consumer_dn('%s','%s')\n", - dn ? dn : "NULL", hashedpw ? hashedpw : "NULL"); -#endif - - if (ld == NULL || dn == NULL || hashedpw == NULL) - { - return -1; - } - - if (!entry_exists(ld, dn)) - { - attrs[0] = &attr[0]; - attrs[1] = &attr[1]; - attrs[2] = &attr[2]; - attrs[3] = &attr[3]; - attrs[4] = &attr[4]; - attrs[5] = &attr[5]; - attrs[6] = NULL; - - attr[0].mod_op = LDAP_MOD_ADD; - attr[0].mod_type = name_objectClass; - attr[0].mod_values = objectClasses; - objectClasses[0] = class_top; - objectClasses[1] = class_person; - objectClasses[2] = NULL; - - attr[1].mod_op = LDAP_MOD_ADD; - attr[1].mod_type = name_cn; - attr[1].mod_values = names; - names[0] = "Replication Consumer"; - names[1] = NULL; - - attr[2].mod_op = LDAP_MOD_ADD; - attr[2].mod_type = name_sn; - attr[2].mod_values = snames; - snames[0] = "Consumer"; - snames[1] = NULL; - - attr[3].mod_op = LDAP_MOD_ADD; - attr[3].mod_type = name_description; - attr[3].mod_values = desc; - desc[0] = "Replication Consumer bind entity"; - desc[1] = NULL; - - attr[4].mod_op = LDAP_MOD_ADD; - attr[4].mod_type = name_userPassword; - attr[4].mod_values = pwd; - pwd[0] = hashedpw; - pwd[1] = NULL; - - attr[5].mod_op = LDAP_MOD_ADD; - attr[5].mod_type = name_passwordExpirationTime; - attr[5].mod_values = passwordExpirationTime; - passwordExpirationTime[0] = "20380119031407Z"; - passwordExpirationTime[1] = NULL; - - /* fprintf (stdout, "ldap_add_s(%s)<br>\n", DN); fflush (stdout); */ - - err = ldap_add_s (ld, dn, attrs); - - if (err != LDAP_SUCCESS) - { - char* explanation = PR_smprintf("Unable to create consumer dn." - " (%s (%i) returned from ldap_add_s(%s))", - ldap_err2string (err), err, dn); - ds_report_warning (DS_NETWORK_ERROR, " can't create consumer dn", explanation); - PR_smprintf_free (explanation); - ret = 1; - } - } - - return ret; -} - -static int -add_group_member(LDAP* ld, char* DN, char* attr, char* member) -{ - int err; - int ret = 0; - LDAPMod mod; - LDAPMod* mods[2]; - char* members[2]; - -#ifdef CGI_DEBUG - debug_log (dbg_log_file, "add_group_member('%s', '%s', '%s')\n", - DN ? DN : "NULL", - attr ? attr : "NULL", - member ? member : "NULL"); -#endif - - if (ld == NULL || DN == NULL || attr == NULL || member == NULL) - { - return -1; - } - - mods[0] = &mod; - mods[1] = NULL; - mod.mod_op = LDAP_MOD_ADD; - mod.mod_type = attr; - mod.mod_values = members; - members[0] = member; - members[1] = NULL; - /* fprintf (stdout, "ldap_modify_s('%s')<br>\n",DN); fflush (stdout); */ - err = ldap_modify_s (ld, DN, mods); - if (err != LDAP_SUCCESS && err != LDAP_TYPE_OR_VALUE_EXISTS) { - char* exp = "can't add member. "; - char* explanation = PR_smprintf("%s (%i) returned from ldap_modify_s(%s, %i).", - ldap_err2string (err), err, DN, LDAP_MOD_ADD); - ds_report_warning (DS_INCORRECT_USAGE, exp, explanation); - PR_smprintf_free (explanation); - ret = 1; - } - - return ret; -} - -static LDAP* -do_bind(SLAPD_CONFIG* slapd, char* rootdn, char* rootpw) -{ - LDAP* connection = NULL; - int retrymax = 1800; /* wait up to 30 min; init dbcache could be slow. */ - int err = LDAP_SUCCESS; - - /* added error retry to work around the slow start introduced - by blackflag 624053 */ - while ( retrymax-- ) - { - if (connection == NULL) { - connection = ldap_open ("127.0.0.1", slapd->port); - } - - if (connection) { - err = ldap_simple_bind_s (connection, rootdn, rootpw ? rootpw : ""); - if (LDAP_SUCCESS == err) - break; - } - - PR_Sleep(PR_SecondsToInterval(1)); - } - - if (connection == NULL) { - char* format = " Cannot connect to server."; - ds_report_warning (DS_NETWORK_ERROR, format, ""); - } else if (err != LDAP_SUCCESS) { - char* explanation = PR_smprintf("Unable to bind to server." - " (%s (%i) returned from ldap_simple_bind_s(%s))", - ldap_err2string (err), err, rootdn); - ds_report_warning (DS_NETWORK_ERROR, " can't bind to server", - explanation); - PR_smprintf_free (explanation); - ldap_unbind (connection); - connection = NULL; - } - fflush (stdout); - return connection; -} - -#ifdef TEST_CONFIG -int -config_configEntry(LDAP* connection, QUERY_VARS* query) -{ - /* initial ACIs for o=NetscapeRoot */ - - int ret = add_aci_v (connection, value_config40DN, ACI_self_allow, NULLSTR); - return ret; -} -#endif - -int -config_suitespot(SLAPD_CONFIG* slapd, QUERY_VARS* query) -{ - LDAP* connection; - const char* DN_formatUID = "uid=%s,%s"; - char* usageShortMsg = " Required field missing."; - char* usageErrorMsg = NULL; - int status = 0; - char *admin_domainDN = 0; - int ii = 0; - char *configAdminDN = 0; - char *adminGroupDN = 0; - char *parentDN = 0; - char *localDAGroupDN = 0; - char realuid[1024] = {0}; - - if (!query->rootDN || *query->rootDN == '\0') { - usageErrorMsg = "You must enter the distinguished name of a user with " - "unrestricted access to the directory."; - } else if (!query->rootPW || *query->rootPW == '\0') { - usageErrorMsg = "You must enter the password of the user with " - "unrestricted access to the directory."; - } - - if (usageErrorMsg) { - ds_report_warning (DS_INCORRECT_USAGE, usageShortMsg, usageErrorMsg); - return -1; - } - - if (!(connection = do_bind (slapd, query->rootDN, query->rootPW))) - return 1; - - if (query->suffix) - { - status = create_base(connection, query->suffix); - if (!status) - { - if (configAdminDN && !is_root_user(configAdminDN, query)) { - add_aci_v(connection, query->suffix, ACI_user_allow_2, - "all", configAdminDN, NULLSTR); - } - - status = create_group(connection, query->suffix, name_localDAGroup); - } - } - - if (!status && query->consumerDN && query->consumerPW && - PL_strcasecmp(query->consumerDN, query->rootDN)) - status = create_consumer_dn(connection, - query->consumerDN, query->consumerPW); - - if (!status) - { - if (query->suffix) - { - localDAGroupDN = make_dn("cn=%s, %s", name_localDAGroup, - query->suffix, NULLSTR); - } - else - { - localDAGroupDN = NULL; - } - for (ii = 0; ii < entryAndAccessListSize; ++ii) - { - if (query->cfg_sspt && adminGroupDN) { - add_aci_v(connection, entryAndAccessList[ii].entryDN, - ACI_config_admin_group_allow, - entryAndAccessList[ii].access, - adminGroupDN, NULLSTR); - } - if (configAdminDN && !is_root_user(configAdminDN, query)) { - add_aci_v(connection, entryAndAccessList[ii].entryDN, - ACI_user_allow_2, - entryAndAccessList[ii].access, - configAdminDN, NULLSTR); - } - if (localDAGroupDN) - { - add_aci_v(connection, entryAndAccessList[ii].entryDN, - ACI_local_DA_allow, - entryAndAccessList[ii].access, - localDAGroupDN, NULLSTR); - } - } - } - -#ifdef TEST_CONFIG - if (!status && query->testconfig) - status = create_configEntry(connection); - - if (!status && query->testconfig) - status = config_configEntry(connection, query); -#endif - - if (connection) - ldap_unbind (connection); - if (adminGroupDN) - free(adminGroupDN); - if (configAdminDN) - free(configAdminDN); - if (parentDN) - free(parentDN); - if (localDAGroupDN) - free(localDAGroupDN); - - return status; -} diff --git a/ldap/admin/src/cfg_sspt.h b/ldap/admin/src/cfg_sspt.h deleted file mode 100644 index 15ad7237..00000000 --- a/ldap/admin/src/cfg_sspt.h +++ /dev/null @@ -1,147 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#ifndef __cfg_sspt_h -#define __cfg_sspt_h - -#ifdef __cplusplus -extern "C" { /* Assume C declarations for C++ */ -#endif /* __cplusplus */ - -#include "ldap.h" -#include "dsalib.h" - -#define MAX_STRING_LEN 512 - -typedef struct _SLAPD_CONFIG { - char slapd_server_root[MAX_STRING_LEN + 1]; - int port; - char host[MAX_STRING_LEN]; - char root_dn[MAX_STRING_LEN]; -#define MAX_SUFFIXES 1024 - char* suffixes[MAX_SUFFIXES]; - int num_suffixes; -} SLAPD_CONFIG; - -typedef struct _query_vars { - char* suffix; - char* ssAdmID; - char* ssAdmPW1; - char* ssAdmPW2; - char* rootDN; - char* rootPW; - char* consumerDN; - char* consumerPW; - char* netscaperoot; - char* testconfig; - char* admin_domain; - int cfg_sspt; - char* config_admin_uid; -} QUERY_VARS; - -extern int -entry_exists(LDAP* ld, const char* entrydn); - -extern int -config_suitespot(SLAPD_CONFIG* slapd, QUERY_VARS* query); - -extern int -create_group(LDAP* ld, char* base, char* group); - -#ifndef __CFG_SSPT_C - -extern char* const class_top; -extern char* const class_organization; -extern char* const class_organizationalUnit; -extern char* const class_person; -extern char* const class_organizationalPerson; -extern char* const class_inetOrgPerson; -extern char* const class_groupOfUniqueNames; - -extern char* const name_objectClass; -extern char* const name_cn; -extern char* const name_sn; -extern char* const name_givenname; -extern char* const name_uid; -extern char* const name_userPassword; -extern char* const name_o; -extern char* const name_ou; -extern char* const name_member; -extern char* const name_uniqueMember; -extern char* const name_subtreeaci; -extern char* const name_netscaperoot; -extern char* const name_netscaperootDN; - -extern char* const value_suiteSpotAdminCN; -extern char* const value_suiteSpotAdminSN; -extern char* const value_suiteSpotAdminGN; -extern char* const value_adminGroupCN; -extern char* const value_netscapeServersOU; - -extern char* const field_suffix; -extern char* const field_ssAdmID; -extern char* const field_ssAdmPW1; -extern char* const field_ssAdmPW2; -extern char* const field_rootDN; -extern char* const field_rootPW; -extern char* const format_DN; -extern char* const format_simpleSearch; - -extern char* const insize_text; - -extern char* html_file; -extern char* dbg_log_file; - -#endif /* __CFG_SSPT_C */ - -/* - * iterate over the root DSEs we need to setup special ACIs for - * return true if entry and access are valid, false when the list - * is empty and entry and access are null - */ -int getEntryAndAccess(int index, const char **entry, const char **access); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif /* __cfg_sspt_h */ diff --git a/ldap/admin/src/configure_instance.cpp b/ldap/admin/src/configure_instance.cpp deleted file mode 100644 index c70cc7ea..00000000 --- a/ldap/admin/src/configure_instance.cpp +++ /dev/null @@ -1,2029 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/********************************************************************* -** -** -** NAME: -** configure_instance.cpp -** -** DESCRIPTION: -** Fedora Directory Server Configuration Program -** -** NOTES: -** Derived from the original ux-config.cc -** -** -*********************************************************************/ - -#include <iostream.h> -#include <fstream.h> -#include <stdio.h> /* printf, file I/O */ -#include <string.h> /* strlen */ -#include <ctype.h> -#include <sys/stat.h> -#ifdef XP_UNIX -#include <strings.h> -#include <pwd.h> -#include <grp.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <netdb.h> -#else -#include <io.h> -#endif -#include <stdlib.h> /* memset, rand stuff */ -#include <sys/types.h> -#include <errno.h> -#include <stdarg.h> -#include <time.h> - -extern "C" { -#include "ldap.h" -#include "dsalib.h" -} - -#include "nspr.h" -#include "plstr.h" - -#include "setupapi.h" -#ifdef XP_UNIX -#include "ux-util.h" -#endif -#include "ldapu.h" -#include "install_keywords.h" -#include "create_instance.h" -#include "cfg_sspt.h" -#include "configure_instance.h" -#include "dirver.h" - -#undef FILE_PATHSEP -#ifdef XP_WIN32 -#define FILE_PATHSEP "\\" -#else -#define FILE_PATHSEP "/" -#endif - -#ifdef XP_WIN32 -#define DEFAULT_TASKCONF "bin\\slapd\\install\\ldif\\tasks.ldif" -#define ROLEDIT_EXTENSION "bin\\slapd\\install\\ldif\\roledit.ldif" -#define COMMON_TASKS "bin\\slapd\\install\\ldif\\commonTasks.ldif" -#define SAMPLE_LDIF "bin\\slapd\\install\\ldif\\Example.ldif" -#define TEMPLATE_LDIF "bin\\slapd\\install\\ldif\\template.ldif" -#else -#define DEFAULT_TASKCONF "bin/slapd/install/ldif/tasks.ldif" -#define ROLEDIT_EXTENSION "bin/slapd/install/ldif/roledit.ldif" -#define COMMON_TASKS "bin/slapd/install/ldif/commonTasks.ldif" -#define SAMPLE_LDIF "bin/slapd/install/ldif/Example.ldif" -#define TEMPLATE_LDIF "bin/slapd/install/ldif/template.ldif" -#endif - -#ifndef PATH_MAX -#define PATH_MAX 256 -#endif - -// location of java runtime relative to server root -#ifdef XP_WIN32 -#define JAVA_RUNTIME "bin\\base\\jre\\bin\\jre" -#else -#define JAVA_RUNTIME "bin/base/jre/bin/jre" -#endif - -// location of class files for java -#define JAVA_DIR "java" -// location of jar files relative to java dir -#define JARS_DIR "jars" -// full name of class with main() for running admin console -#define CONSOLE_CLASS_NAME "com.netscape.management.client.console.Console" -// name of script file to generate relative to slapd instance directory -#define SCRIPT_FILE_NAME "start-console" - -#define DS_JAR_FILE_NAME "fedora-ds-1.0.jar" -#define DS_CONSOLE_CLASS_NAME "com.netscape.admin.dirserv.DSAdmin" - -#ifdef XP_WIN32 -#define strtok_r(x,y,z) strtok(x,y) -#include "proto-ntutil.h" -#endif - -#define SERVER_MIGRATION_CLASS "com.netscape.admin.dirserv.task.MigrateCreate" -#define SERVER_CREATION_CLASS "com.netscape.admin.dirserv.task.MigrateCreate" - -static InstallMode installMode = Interactive; -static InstallInfo *installInfo = NULL; -static InstallInfo *slapdInfo = NULL; -static InstallInfo *slapdINFFileInfo = NULL; -static InstallInfo *adminInfo = NULL; -static const char *infoFile = NULL; -static const char *logFile = NULL; - -static InstallLog *installLog = NULL; -static int reconfig = 0; // set to 1 if we are reconfiguring -/* - * iDSISolaris is set to 1 for Solaris 9+ specific installation. - * This can be done by passing -S as the command line argument. - */ -int iDSISolaris = 0; - -/* - * There is currently a bug in LdapEntry->printEntry - it will crash if given a NULL argument - * This is a workaround - */ -static void -my_printEntry(LdapEntry *ent, const char *filename, int which) -{ - ostream *os = NULL; - if (filename && ent) - { - // just use LdapEntry, which should work given a good filename - ent->printEntry(filename); - return; - } - else if (which) - { - os = &cerr; - } - else - { - os = &cout; - } - - if (!ent || !ent->entryDN() || ent->isEmpty()) - { - *os << "Error: entry to print is empty" << endl; - } - else - { - *os << "dn: " << ent->entryDN() << endl; - char **attrs = ent->getAttributeNames(); - for (int ii = 0; attrs && attrs[ii]; ++ii) - { - char **values = ent->getAttributes(attrs[ii]); - for (int jj = 0; values && values[jj]; jj++) - { - *os << attrs[ii] << ": " << values[jj] << endl; - } - - if (values) - { - ent->freeAttributes(values); - } - } - if (attrs) - { - ent->freeAttributeNames(attrs); - } - } -} - -// changes empty strings ("") to NULLs (0) -static char * -my_strdup(const char *s) -{ - char *n = 0; - if (s && *s) - { - n = new char[strlen(s) + 1]; - strcpy(n, s); - } - - return n; -} - -// changes empty strings ("") to NULLs (0) -static char * -my_c_strdup(const char *s) -{ - char *n = 0; - if (s && *s) - { - n = (char *)malloc(strlen(s) + 1); - strcpy(n, s); - } - - return n; -} - -static int -isAValidDN(const char *dn_to_test) -{ - int ret = 1; - - if (!dn_to_test || !*dn_to_test) - { - ret = 0; - } - else - { - char **rdnList = ldap_explode_dn(dn_to_test, 0); - char **rdnNoTypes = ldap_explode_dn(dn_to_test, 1); - if (!rdnList || !rdnList[0] || !rdnNoTypes || !rdnNoTypes[0] || - !strcasecmp(rdnList[0], rdnNoTypes[0])) - { - ret = 0; - } - if (rdnList) - ldap_value_free(rdnList); - if (rdnNoTypes) - ldap_value_free(rdnNoTypes); - } - - return ret; -} - -static void -initMessageLog(const char *filename) -{ - if (filename && !installLog) - { - logFile = my_c_strdup(filename); -#ifdef XP_UNIX - if (!logFile && installMode != Silent) - { - logFile = "/dev/tty"; - } -#endif - installLog = new InstallLog(logFile); - } -} - -static void -dsLogMessage(const char *level, const char *which, - const char *format, ...) -{ - char bigbuf[BIG_BUF*4]; - va_list ap; - va_start(ap, format); - PR_vsnprintf(bigbuf, BIG_BUF*4, format, ap); - va_end(ap); -#ifdef _WIN32 // always output to stdout (for CGIs), and always log - // if a log is available - fprintf(stdout, "%s %s %s\n", level, which, bigbuf); - fflush(stdout); - if (installLog) - installLog->logMessage(level, which, bigbuf); -#else // not Windows - if (installMode == Interactive) - { - fprintf(stdout, "%s %s %s\n", level, which, bigbuf); - fflush(stdout); - } - else - { - if (installLog) - installLog->logMessage(level, which, bigbuf); - else - fprintf(stdout, "%s %s %s\n", level, which, bigbuf); - fflush(stdout); - } -#endif - - return; -} - -static char * -getGMT() -{ - static char buf[20]; - time_t curtime; - struct tm ltm; - - curtime = time( (time_t *)0 ); -#ifdef _WIN32 - ltm = *gmtime( &curtime ); -#else - gmtime_r( &curtime, <m ); -#endif - strftime( buf, sizeof(buf), "%Y%m%d%H%M%SZ", <m ); - return buf; -} - -static void -normalizeDNs() -{ - static const char *DN_VALUED_ATTRS[] = { - SLAPD_KEY_SUFFIX, - SLAPD_KEY_ROOTDN, - SLAPD_KEY_REPLICATIONDN, - SLAPD_KEY_CONSUMERDN, - SLAPD_KEY_SIR_SUFFIX, - SLAPD_KEY_SIR_BINDDN - }; - static const int N = sizeof(DN_VALUED_ATTRS)/sizeof(DN_VALUED_ATTRS[0]); - static const char *URL_ATTRS[] = { - SLAPD_KEY_K_LDAP_URL, - SLAPD_KEY_USER_GROUP_LDAP_URL - }; - static const int NURLS = sizeof(URL_ATTRS)/sizeof(URL_ATTRS[0]); - - int ii; - for (ii = 0; slapdInfo && (ii < N); ++ii) - { - const char *attr = DN_VALUED_ATTRS[ii]; - char *dn = my_strdup(slapdInfo->get(attr)); - if (dn) - { - slapdInfo->set(attr, dn_normalize_convert(dn)); - delete [] dn; - } - } - - for (ii = 0; installInfo && (ii < NURLS); ++ii) - { - const char *attr = URL_ATTRS[ii]; - const char *url = installInfo->get(attr); - LDAPURLDesc *desc = 0; - if (url && !ldap_url_parse((char *)url, &desc) && desc) - { - char *dn = dn_normalize_convert(my_strdup(desc->lud_dn)); - int isSSL = !strncmp(url, "ldaps:", strlen("ldaps:")); - if (dn) - { - char port[6]; - PR_snprintf(port, sizeof(port), "%d", desc->lud_port); - NSString newurl = NSString("ldap") + - (isSSL ? "s" : "") + - "://" + desc->lud_host + - ":" + port + "/" + dn; - installInfo->set(attr, newurl); - delete [] dn; - } - } - if (desc) - ldap_free_urldesc(desc); - } -} - - -static int -featureIsEnabled(const char *s) -{ - if (!s || !*s || !strncasecmp(s, "no", strlen(s))) - return 0; // feature is disabled - - return 1; // feature is enabled -} - -static LdapErrorCode -add_sample_entries(const char *sroot, LdapEntry *ldapEntry) -{ - char tmp[MED_BUF]; - - if (sroot) - PR_snprintf(tmp, MED_BUF, "%s%s%s", sroot, FILE_PATHSEP, SAMPLE_LDIF); - else - strcpy(tmp, "test.ldif"); - - return insertLdifEntries(ldapEntry->ldap(), NULL, tmp, NULL); - -} - - -// in the given string s, replace all occurrances of token with replace -// the string return is allocated with new char [] -static char * -replace_token(const char *s, const char *token, int tokenlen, - const char *replace, int replacelen) -{ - char *ptr = (char*)strstr(s, token); - char *n = 0; - if (!ptr) - { - n = my_strdup(s); - return n; - } - - // count the number of occurances of the token - int ntokens = 1; - while (ptr && *ptr) - { - ptr = (char*)strstr(ptr+1, token); - ++ntokens; - } - - n = new char [strlen(s) + (ntokens * replacelen)]; - char *d = n; - const char *begin = s; - for (ptr = (char*)strstr(s, token); ptr && *ptr;) - { - int len = int(ptr - begin); - strncpy(d, begin, len); - d += len; - begin = ptr + tokenlen; - len = replacelen; - strncpy(d, replace, len); - d += len; - ptr = strstr(ptr+1, token); - } - // no more occurances of token in string; copy the rest - for (ptr = (char *)begin; ptr && *ptr; LDAP_UTF8INC(ptr)) - { - *d = *ptr; - LDAP_UTF8INC(d); - } - *d = 0; - - return n; -} - -static void -add_org_entries(const char *sroot, LdapEntry *ldapEntry, - const char *initialLdifFile, const char *org_size, - NSString sieDN) -{ - org_size = org_size; - - char tmp[MED_BUF]; - char *dn; - - LdapError ldapError; - char **vals; - static const char *TOKEN[] = { - "%%%SUFFIX%%%", - "%%%ORG%%%", - "%%%CONFIG_ADMIN_DN%%%" - }; - static const int TOKENLEN[] = { 12, 9, 21 }; - static const int NTOKENS = 3; - static const char *REPLACE[] = { 0, 0, 0 }; - static int REPLACELEN[] = { 0, 0, 0 }; - - REPLACE[0] = slapdInfo->get(SLAPD_KEY_SUFFIX); - const char *org = strchr(REPLACE[0], '='); - if (org) - REPLACE[1] = org+1; - - REPLACE[2] = slapdInfo->get(SLAPD_KEY_CONFIG_ADMIN_DN); - for (int ii = 0; ii < NTOKENS; ++ii) - { - if (REPLACE[ii]) - REPLACELEN[ii] = strlen(REPLACE[ii]); - } - - if (sroot) - { - if (!initialLdifFile || !*initialLdifFile || - !strncasecmp(initialLdifFile, "suggest", strlen(initialLdifFile))) - PR_snprintf(tmp, sizeof(tmp), "%s%s%s", sroot, FILE_PATHSEP, TEMPLATE_LDIF); - else - PL_strncpyz(tmp, initialLdifFile, sizeof(tmp)); - } - else - PL_strncpyz(tmp, "test.ldif", sizeof(tmp)); - - LdifEntry ldif(tmp); - - if (!ldif.isValid() || ldif.nextEntry() == -1) - { - dsLogMessage(SETUP_LOG_WARN, "Slapd", "File %s\ndoes not" - " appear to be a valid LDIF file.", tmp); - return; - } - - int entry_num = 0; - - do - { - entry_num++; - if (ldapEntry) - ldapEntry->clear(); - - for (int i = 0; i < ldif.numList(); i++) - { - const char *name = ldif.list(i); - if (!name || !*name) - continue; - - vals = ldif.getListItems(name); - if (!vals || !*vals) - continue; - - int n = ldif.numListItems(name); - if (!n) - continue; - - char **newvals = new char* [n+1]; - newvals[n] = 0; // null terminated - // go through the values replacing the token string with the value - for (int iii = 0; iii < n; ++iii) - { - newvals[iii] = my_strdup(vals[iii]); - for (int jj = 0; jj < NTOKENS; ++jj) - { - char *oldnewvals = newvals[iii]; - newvals[iii] = replace_token(newvals[iii], TOKEN[jj], TOKENLEN[jj], - REPLACE[jj], REPLACELEN[jj]); - delete [] oldnewvals; - } - } - - if (!strcasecmp(name, "dn")) - { - dn = my_strdup(newvals[0]); - } - else if (ldapEntry) - { - ldapEntry->addAttributes(name, (const char **) newvals); - } - else /* this is for debugging only */ - { - cerr << "name = " << name << " dn = " << dn << endl; - for (int jj = 0; jj < n; ++jj) - { - cerr << "old entry[" << jj << "] = " << vals[jj] << endl; - cerr << "new entry[" << jj << "] = " << newvals[jj] << endl; - } - cerr << "####" << endl; - } - ldif.freeListItems(vals); - for (int jj = 0; jj < n; ++jj) - delete [] newvals[jj]; - delete [] newvals; - } - - if (!ldapEntry) - continue; - - if (!dn || !*dn) - { - dsLogMessage(SETUP_LOG_WARN, "Slapd", "Entry number %d in file %s\ndoes not" - " contain a valid dn: attribute.\nThe file may be" - " corrupted or not in valid LDIF format.", - entry_num, tmp); - continue; - } - - if (entry_num == 1) - { - NSString aci = NSString( - "(targetattr = \"*\")(version 3.0; " - "acl \"SIE Group\"; allow (all)" - "groupdn = \"ldap:///") + sieDN + "\";)"; - // add the aci for the SIE group - ldapEntry->addAttribute("aci", aci); - } - - if (ldapEntry->exists(dn) == False) - { - ldapError = ldapEntry->insert(dn); - } - else - { - ldapError = ldapEntry->update(dn); - } - - if (ldapError != OKAY) - { - PR_snprintf(tmp, sizeof(tmp), "%d", ldapError.errorCode()); - dsLogMessage(SETUP_LOG_WARN, "Slapd", "Could not write entry %s (%s:%s)", dn, tmp, ldapError.msg()); - } - delete [] dn; - } while (ldif.nextEntry() != -1); -} - -// dsSIEDN will be something like: -// cn=slapd-foo, cn=NDS, cn=SS4.0, cn=FQDN, ou=admindomain, o=netscaperoot -static void -getAdminSIEDN(const char *dsSIEDN, const char *hostname, NSString& adminSIEDN) -{ - char *editablehostname = my_strdup(hostname); - char *eptr = strchr(editablehostname, '.'); - if (eptr) - *eptr = 0; - - char **rdnList = ldap_explode_dn(dsSIEDN, 0); - char *baseDN = 0; - if (rdnList && rdnList[0] && rdnList[1] && rdnList[2]) // dsSIEDN is a valid DN - { - int len = 0; - int ii; - for (ii = 2; rdnList[ii]; ++ii) - len += strlen(rdnList[ii]) + 3; - - baseDN = (char *)malloc(len+1); - baseDN[0] = 0; - for (ii = 2; rdnList[ii]; ++ii) - { - if (ii > 2) - strcat(baseDN, ", "); - strcat(baseDN, rdnList[ii]); - } - } - else - { - baseDN = my_c_strdup(dsSIEDN); - } - - if (rdnList) - ldap_value_free(rdnList); - - adminSIEDN = NSString("cn=admin-serv-") + editablehostname + - ", cn=Fedora Administration Server, " + baseDN; - - delete [] editablehostname; - free(baseDN); - - return; -} - -static void -setAppEntryInformation(LdapEntry *appEntry) -{ - // required attributes - if (!appEntry->getAttribute("objectclass")) - appEntry->addAttribute("objectclass", "nsApplication"); - appEntry->setAttribute("cn", slapdINFFileInfo->get("Name")); - appEntry->setAttribute("nsProductname", slapdINFFileInfo->get("Name")); - appEntry->setAttribute("nsProductversion", PRODUCTTEXT); - // optional attributes -/* - NSString temp = slapdINFFileInfo->get("Description"); - if ((NSString)NULL != temp) - appEntry->setAttribute("description", temp); -*/ - NSString temp = slapdINFFileInfo->get("NickName"); - if ((NSString)NULL == temp) - temp = "slapd"; - appEntry->setAttribute("nsNickName", temp); - temp = slapdINFFileInfo->get("BuildNumber"); - if ((NSString)NULL != temp) - appEntry->setAttribute("nsBuildNumber", temp); - temp = slapdINFFileInfo->get("Revision"); - if ((NSString)NULL != temp) - appEntry->setAttribute("nsRevisionNumber", temp); - temp = slapdINFFileInfo->get("SerialNumber"); - if ((NSString)NULL != temp) - appEntry->setAttribute("nsSerialNumber", temp); - temp = slapdINFFileInfo->get("Vendor"); - if ((NSString)NULL != temp) - appEntry->setAttribute("nsVendor", temp); - - if (!appEntry->getAttribute("nsInstalledLocation")) - appEntry->addAttribute("nsInstalledLocation", - installInfo->get(SLAPD_KEY_SERVER_ROOT)); - appEntry->setAttribute("installationTimeStamp", getGMT()); - temp = slapdINFFileInfo->get("Expires"); - if ((NSString)NULL != temp) - appEntry->setAttribute("nsExpirationDate", temp); - temp = slapdINFFileInfo->get("Security"); - if ((NSString)NULL != temp) - appEntry->setAttribute("nsBuildSecurity", temp); - - return; -} - -static LdapError -create_sie_and_isie(LdapEntry *sieEntry, LdapEntry *appEntry, NSString& sieDN) -{ - LdapError ldapError; // return value - const char *adminBrand = "Fedora"; - - // Prepare sieEntry - sieEntry->clear(); - - sieEntry->addAttribute("objectclass", "netscapeServer"); - sieEntry->addAttribute("objectclass", "nsDirectoryServer"); - sieEntry->addAttribute("objectclass", "nsResourceRef"); - sieEntry->addAttribute("objectclass", "nsConfig"); - sieEntry->addAttribute("nsServerSecurity", "off"); - NSString serverID = NSString("slapd-") + slapdInfo->get(SLAPD_KEY_SERVER_IDENTIFIER); - sieEntry->addAttribute("nsServerID", serverID); - sieEntry->addAttribute("nsBindDN", slapdInfo->get(SLAPD_KEY_ROOTDN)); - sieEntry->addAttribute("nsBaseDN", slapdInfo->get(SLAPD_KEY_SUFFIX)); - char *hashedPwd = (char *)ds_salted_sha1_pw_enc ( - (char *)slapdInfo->get(SLAPD_KEY_ROOTDNPWD)); - if (hashedPwd) - sieEntry->addAttribute("userPassword", hashedPwd); -// sieEntry->addAttribute("AuthenticationPassword", slapdInfo->get(SLAPD_KEY_ROOTDNPWD)); - sieEntry->addAttribute("serverHostName", installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME)); - sieEntry->addAttribute("serverRoot", installInfo->get(SLAPD_KEY_SERVER_ROOT)); - sieEntry->addAttribute("nsServerPort", slapdInfo->get(SLAPD_KEY_SERVER_PORT)); - sieEntry->addAttribute("nsSecureServerPort", "636"); -/* - NSString temp = slapdINFFileInfo->get("Description"); - if ((NSString)NULL != temp) - sieEntry->addAttribute("description", temp); -*/ - NSString name = NSString(slapdINFFileInfo->get("InstanceNamePrefix")) + " (" + - slapdInfo->get(SLAPD_KEY_SERVER_IDENTIFIER) + ")"; - sieEntry->addAttribute("serverProductName", name); - sieEntry->addAttribute("serverVersionNumber", slapdINFFileInfo->get("Version")); - sieEntry->addAttribute("installationTimeStamp", getGMT()); - NSString temp = installInfo->get(SLAPD_KEY_SUITESPOT_USERID); - if ((NSString)NULL != temp) // may not be present on NT . . . - sieEntry->addAttribute("nsSuiteSpotUser", temp); - - // Prepare appEntry - appEntry->clear(); - setAppEntryInformation(appEntry); - - NSString ssDN = installInfo->get(SLAPD_KEY_ADMIN_DOMAIN); - - // to make a disposable copy - char *fqdn = my_strdup(installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME)); - - LdapErrorCode code = createSIE(sieEntry, appEntry, fqdn, - installInfo->get(SLAPD_KEY_SERVER_ROOT), - ssDN, adminBrand); - delete [] fqdn; - - if (code != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "createSIE returned error code %d for ssDN=%s machinename=%s " - "server root=%s", (int)code, (const char *)ssDN, - installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME), - installInfo->get(SLAPD_KEY_SERVER_ROOT)); -#ifdef XP_UNIX - cerr << "Here is the sieEntry:" << endl; - my_printEntry(sieEntry, 0, 1); // output to cerr -#else - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "SIE entry printed to c:/temp/SIE.out"); - sieEntry->printEntry("c:/temp/SIE.out"); -#endif -#ifdef XP_UNIX - cerr << "Here is the appEntry:" << endl; - my_printEntry(appEntry, 0, 1); // output to cerr -#else - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "APP entry printed to c:/temp/APP.out"); - appEntry->printEntry("c:/temp/APP.out"); -#endif - return code; - } - -// dsLogMessage("Info", "Slapd", "Created configuration entry for server %s", -// (const char *)serverID); - - sieDN = sieEntry->entryDN(); - - NSString configDN, configTaskDN, opTaskDN, adminSIEDN; - getAdminSIEDN(sieDN, installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME), - adminSIEDN); - - // append the adminSIE to the create and migrate class names - appEntry->clear(); - NSString classname = NSString(SERVER_MIGRATION_CLASS"@"DS_JAR_FILE_NAME"@") + - adminSIEDN; - appEntry->addAttribute("nsServerMigrationClassname", classname); - classname = NSString(SERVER_CREATION_CLASS"@"DS_JAR_FILE_NAME"@") + - adminSIEDN; - appEntry->addAttribute("nsServerCreationClassname", classname); - if ((ldapError = appEntry->update(appEntry->entryDN())) != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "Error: Could not modify nsServerMigrationClassname " - "and/or nsServerCreationClassname in entry %s: error code %d\n", - appEntry->entryDN(), (int)ldapError); - return (int)ldapError; - } - - // Write configuration parameters (see ns-admin.conf) - sieEntry->clear(); - - sieEntry->addAttribute("objectclass", "nsResourceRef"); - sieEntry->addAttribute("objectclass", "nsAdminObject"); - sieEntry->addAttribute("objectclass", "nsDirectoryInfo"); - - /* - * Mandatory fields here - */ - NSString description = NSString("Configuration information for directory server ") + - serverID; - sieEntry->addAttribute ("cn", "configuration"); - NSString nsclassname = NSString(DS_CONSOLE_CLASS_NAME) + "@" + - DS_JAR_FILE_NAME + "@" + adminSIEDN; - sieEntry->addAttribute ("nsclassname", nsclassname); - sieEntry->addAttribute ("nsjarfilename", - DS_JAR_FILE_NAME); - char** rdnList = ldap_explode_dn(appEntry->entryDN(), 0); - if (rdnList) - { - int ii = 0; - int len = 0; - for (ii = 1; rdnList[ii]; ++ii) // skip first rdn - len += (strlen(rdnList[ii]) + 3); - char *adminGroupDN = (char *)calloc(1, len); - for (ii = 1; rdnList[ii]; ++ii) { - if (ii > 1) - strcat(adminGroupDN, ", "); - strcat(adminGroupDN, rdnList[ii]); - } - ldap_value_free(rdnList); - sieEntry->addAttribute("nsDirectoryInfoRef", adminGroupDN); - free(adminGroupDN); - } - - configDN = NSString("cn=configuration") + "," + sieDN; - - // allow modification by kingpin topology - createACIForConfigEntry(sieEntry, sieDN); - - if (sieEntry->exists(configDN) == False) - { - ldapError = sieEntry->insert(configDN); - } - else - { - ldapError = sieEntry->update(configDN); - } - - if (ldapError != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Could not update the configuration entry %s: error code %d", - (const char *)configDN, ldapError.errorCode()); - return (int)ldapError; - } else { -// dsLogMessage("Info", "Slapd", "Updated configuration entry for server %s", -// (const char *)serverID); - } - - // Write Tasks nodes - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local encoding - NSString filename = NSString(installInfo->get(SLAPD_KEY_SERVER_ROOT)) + - FILE_PATHSEP + DEFAULT_TASKCONF; - ldapError = insertLdifEntries(sieEntry->ldap(), sieDN, filename, - adminSIEDN); - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // back to utf8 - - if (ldapError != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Could not update the instance specific tasks entry %s: error code %d", - (const char *)sieDN, ldapError.errorCode()); - return ldapError; - } else { -// dsLogMessage("Info", "Slapd", "Added task information for server %s", -// (const char *)serverID); - } - - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local encoding - filename = NSString(installInfo->get(SLAPD_KEY_SERVER_ROOT)) + - FILE_PATHSEP + COMMON_TASKS; - ldapError = insertLdifEntries(sieEntry->ldap(), appEntry->entryDN(), - filename, adminSIEDN); - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // back to utf8 - - if (ldapError != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Could not update the general tasks entry %s: error code %d", - (const char *)appEntry->entryDN(), ldapError.errorCode()); - } else { -// dsLogMessage("Info", "Slapd", "Updated common task information for server %s", -// (const char *)serverID); - } - - return ldapError; -} - - -static LdapErrorCode -create_roledit_extension(Ldap* ldap) -{ - // - // If needed, we create "ou=Global Preferences,ou=<domain>,o=NetscapeRoot". - // The following code has been duplicated from setupGlobalPreferences() in - // setupldap.cpp - // - LdapEntry ldapEntry(ldap); - LdapError err; - NSString globalPref = DEFAULT_GLOBAL_PREFS_RDN; - NSString adminDomain = installInfo->get(SLAPD_KEY_ADMIN_DOMAIN); - char * domain = setupFormAdminDomainDN(adminDomain); - - globalPref = globalPref + LDAP_PATHSEP + domain; - -// dsLogMessage("Info", "Slapd", "Beginning update console role editor extensions"); - if (ldapEntry.retrieve(globalPref) != OKAY) - { - ldapEntry.setAttribute("objectclass", DEFAULT_GLOBAL_PREFS_OBJECT); - ldapEntry.setAttribute("ou", DEFAULT_GLOBAL_PREFS); - ldapEntry.setAttribute("aci", DEFAULT_GLOBAL_PREFS_ACI); - ldapEntry.setAttribute("description", "Default branch for Fedora Server Products Global Preferences"); -// dsLogMessage("Info", "Slapd", "Updating global preferences for console role editor extensions"); - err = ldapEntry.insert(globalPref); - } - else - { - ldapEntry.setAttribute("aci", DEFAULT_GLOBAL_PREFS_ACI); - ldapEntry.setAttribute("description", "Default branch for Fedora Server Products Global Preferences"); -// dsLogMessage("Info", "Slapd", "Updating global preferences for console role editor extensions"); - err = ldapEntry.replace(globalPref); - } - - if (err == OKAY) { -// dsLogMessage("Info", "Slapd", "Updated global console preferences for role editor extensions"); - } - - // - // Now let try to add the AdminResourceExtension entries. - // They are defined in the LDIF file named ROLEDIT_EXTENSION. - // - if (err == OKAY) - { -// dsLogMessage("Info", "Slapd", "Updating console role editor extensions"); - - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local encoding - NSString filename = NSString(installInfo->get(SLAPD_KEY_SERVER_ROOT)) + - FILE_PATHSEP + ROLEDIT_EXTENSION; - err = insertLdifEntries(ldap, domain, filename, NULL); - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // back to utf8 - } - - if(domain) free(domain); - - if (err.errorCode() == OKAY) { -// dsLogMessage("Info", "Slapd", "Updated console role editor extensions"); - } - - return err.errorCode(); -} - - -static int -create_ss_dir_tree(const char *hostname, NSString &sieDN) -{ - int status = 0; - - LdapError ldapError = OKAY; - NSString adminID = installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID); - NSString adminPwd = installInfo->get(SLAPD_KEY_SERVER_ADMIN_PWD); - Ldap ldap (ldapError, installInfo->get(SLAPD_KEY_K_LDAP_URL), - adminID, adminPwd, 0, 0); - - if (ldapError != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Ldap authentication failed for url %s user id %s (%d:%s)" , - installInfo->get(SLAPD_KEY_K_LDAP_URL), adminID.data(), - ldapError.errorCode(), ldapError.msg()); - return ldapError.errorCode(); - } - - LdapEntry *sieEntry = new LdapEntry(&ldap); - LdapEntry *appEntry = new LdapEntry(&ldap); - - LdapErrorCode code = create_sie_and_isie(sieEntry, appEntry, sieDN); - - if (code != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: failed to register Directory server as a Fedora server (%d)", - code); - return code; - } - - code = create_roledit_extension(&ldap); - - if (code != OKAY) - { - dsLogMessage(SETUP_LOG_WARN, "Slapd", - "WARNING: failed to add extensions for role edition (%d)", - code); - code = OKAY; // We can continue anyway - } - - const char *user_ldap_url = installInfo->get(SLAPD_KEY_USER_GROUP_LDAP_URL); - if (!user_ldap_url) - user_ldap_url = installInfo->get(SLAPD_KEY_K_LDAP_URL); - - code = addGlobalUserDirectory(&ldap, - installInfo->get(SLAPD_KEY_ADMIN_DOMAIN), - user_ldap_url, 0, 0); - - if (code != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: failed to add Global User Directory (%d)", - code); - return code; - } - - // we need to add some ACIs which will allow the SIE group to have - // admin access to the newly created directory - Ldap *new_ldap = 0; - int port = atoi(slapdInfo->get(SLAPD_KEY_SERVER_PORT)); - if (strcasecmp(ldap.host(), hostname) || ldap.port() != port) - { - const char *suffix = 0; - if (featureIsEnabled(slapdInfo->get(SLAPD_KEY_USE_EXISTING_UG))) - suffix = DEFAULT_ROOT_DN; - else - suffix = slapdInfo->get(SLAPD_KEY_SUFFIX); - NSString new_url = NSString("ldap://") + - hostname + ":" + slapdInfo->get(SLAPD_KEY_SERVER_PORT) + - "/" + suffix; - const char *userDN; - const char *userPwd; - if (!(userDN = slapdInfo->get(SLAPD_KEY_ROOTDN))) - userDN = ldap.userDN(); - if (!(userPwd = slapdInfo->get(SLAPD_KEY_ROOTDNPWD))) - userPwd = ldap.userPassword(); - new_ldap = new Ldap(ldapError, new_url, userDN, userPwd, - userDN, userPwd); - if (ldapError != OKAY) - { - dsLogMessage(SETUP_LOG_WARN, "Slapd", - "Could not open the new directory server [%s:%s] to add an aci [%d].", - (const char *)new_url, userDN, ldapError.errorCode()); - delete new_ldap; - new_ldap = 0; - } - } - else - new_ldap = &ldap; - - if (new_ldap) - { - const char *entry = 0; - const char *access = 0; - LdapEntry ent(new_ldap); - int ii = 0; - while (getEntryAndAccess(ii, &entry, &access)) - { - ++ii; - NSString aci = NSString( - "(targetattr = \"*\")(version 3.0; " - "acl \"SIE Group\"; allow (") + access + ")" - "groupdn = \"ldap:///" + sieDN + "\";)"; - ent.clear(); - ent.addAttribute("aci", aci); - ldapError = ent.update(entry); - if (ldapError != OKAY) - dsLogMessage(SETUP_LOG_WARN, "Slapd", - "Could not add aci %s to entry %s [%d].", - (const char *)aci, entry, ldapError.errorCode()); - } - } - - if (new_ldap && new_ldap != &ldap) - delete new_ldap; - - destroyLdapEntry(sieEntry); - destroyLdapEntry(appEntry); - - if (status == OKAY) { -// dsLogMessage("Info", "Slapd", "Updated console administration access controls"); - } - - return status; -} - -static void -create_console_script() -{ -#if 0 // does not work right now -#ifdef XP_UNIX - const char *sroot = installInfo->get(SLAPD_KEY_SERVER_ROOT); - const char *sid = slapdInfo->get(SLAPD_KEY_SERVER_IDENTIFIER); - const char *hn = installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME); - const char *port = slapdInfo->get(SLAPD_KEY_SERVER_PORT); - const char *suf = slapdInfo->get(SLAPD_KEY_SUFFIX); - const char *classpathSeparator = ":"; - - NSString scriptFilename = NSString(sroot) + FILE_PATHSEP + "slapd-" + - sid + FILE_PATHSEP + SCRIPT_FILE_NAME; - ofstream ofs(scriptFilename); - if (!ofs) - return; - - ofs << "#!/bin/sh" << endl; - ofs << "#" << endl; - ofs << "# This script will invoke the Fedora Management Console" << endl; - ofs << "#" << endl; - // see if there are any other .jar or .zip files in the java directory - // and add them to our class path too - ofs << "for file in " << sroot << FILE_PATHSEP << JAVA_DIR << FILE_PATHSEP - << JARS_DIR << FILE_PATHSEP << "*.jar ; do" << endl; - ofs << "\tCLASSPATH=${CLASSPATH}" << classpathSeparator << "$file" << endl; - ofs << "done" << endl; - - ofs << "for file in " << sroot << FILE_PATHSEP << JAVA_DIR << FILE_PATHSEP - << "*.jar ; do" << endl; - ofs << "\tCLASSPATH=${CLASSPATH}" << classpathSeparator << "$file" << endl; - ofs << "done" << endl; - - ofs << "for file in " << sroot << FILE_PATHSEP << JAVA_DIR << FILE_PATHSEP - << "*.zip ; do" << endl; - ofs << "\tCLASSPATH=${CLASSPATH}" << classpathSeparator << "$file" << endl; - ofs << "done" << endl; - - ofs << "export CLASSPATH" << endl; - - // go to the java dir - ofs << "cd " << sroot << FILE_PATHSEP << JAVA_DIR << endl; - // now, invoke the java runtime environment - ofs << sroot << FILE_PATHSEP << JAVA_RUNTIME - << " -classpath \"$CLASSPATH\" " - << CONSOLE_CLASS_NAME << " -d " << hn << " -p " << port << " -b " - << "\"" << suf << "\"" << endl; - - ofs.flush(); - ofs.close(); - - chmod(scriptFilename, 0755); -#endif -#endif // if 0 - - return; -} - -// check the install info read in to see if we have valid data -static int -info_is_valid() -{ - static const char *requiredFields[] = { - SLAPD_KEY_FULL_MACHINE_NAME, - SLAPD_KEY_SERVER_ROOT, - SLAPD_KEY_SERVER_IDENTIFIER, - SLAPD_KEY_SERVER_PORT, - SLAPD_KEY_ROOTDN, - SLAPD_KEY_ROOTDNPWD, - SLAPD_KEY_K_LDAP_URL, - SLAPD_KEY_SUFFIX, - SLAPD_KEY_SERVER_ADMIN_ID, - SLAPD_KEY_SERVER_ADMIN_PWD, - SLAPD_KEY_ADMIN_DOMAIN - }; - static int numRequiredFields = sizeof(requiredFields) / sizeof(requiredFields[0]); - - if (!installInfo || !slapdInfo) - return 0; - - for (int ii = 0; ii < numRequiredFields; ++ii) - { - const char *val = installInfo->get(requiredFields[ii]); - if (val && *val) - continue; - val = slapdInfo->get(requiredFields[ii]); - if (val && *val) - continue; - - // if we got here, the value was not found in either the install info or - // the slapd info - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "The required field %s is not present in the install info file.", - requiredFields[ii]); - return 0; - } - - return 1; -} - -static int -parse_commandline(int argc, char *argv[]) -{ - int opt; - - while ((opt = getopt(argc, argv, "rsSl:f:")) != EOF) - { - switch (opt) - { - case 'r': - reconfig = 1; - break; - case 's': - installMode = Silent; - break; - case 'S': - /* - * Solaris 9+ specific installation - */ - iDSISolaris = 1; - break; - case 'l': - initMessageLog(optarg); /* Log file to use */ - break; - case 'f': - infoFile = strdup(optarg); /* Install script */ - installInfo = new InstallInfo(infoFile); - installInfo->toUTF8(); - break; - default: - break; - } - } - - return 0; -} - -static const char * -changeYesNo2_0_1(const char *old) -{ - if (old && !strncasecmp(old, "yes", strlen(old))) - return "1"; - - return "0"; -} - -static void -init_from_config(server_config_s *cf) -{ - if (!cf) - return; - - if (!installInfo) - installInfo = new InstallInfo; - - if (!slapdInfo) - slapdInfo = new InstallInfo; - -#ifdef XP_WIN32 - ds_unixtodospath( cf->sroot); -#endif - - installInfo->set(SLAPD_KEY_SERVER_ROOT, cf->sroot); - installInfo->set(SLAPD_KEY_FULL_MACHINE_NAME, cf->servname); - - slapdInfo->set(SLAPD_KEY_SERVER_PORT, cf->servport); - installInfo->set(SLAPD_KEY_SERVER_ADMIN_ID, cf->cfg_sspt_uid); - installInfo->set(SLAPD_KEY_SERVER_ADMIN_PWD, cf->cfg_sspt_uidpw); - slapdInfo->set(SLAPD_KEY_SERVER_IDENTIFIER, cf->servid); - -#ifdef XP_UNIX - installInfo->set(SLAPD_KEY_SUITESPOT_USERID, cf->servuser); -#endif - - slapdInfo->set(SLAPD_KEY_SUFFIX, cf->suffix); - slapdInfo->set(SLAPD_KEY_ROOTDN, cf->rootdn); - slapdInfo->set(SLAPD_KEY_ROOTDNPWD, cf->rootpw); - - installInfo->set(SLAPD_KEY_ADMIN_DOMAIN, cf->admin_domain); - LDAPURLDesc *desc = 0; - if (cf->config_ldap_url && - !ldap_url_parse(cf->config_ldap_url, &desc) && desc) - { - const char *suffix = DEFAULT_ROOT_DN; - int isSSL = !strncmp(cf->config_ldap_url, "ldaps:", strlen("ldaps:")); - char port[6]; - PR_snprintf(port, sizeof(port), "%d", desc->lud_port); - NSString url = NSString("ldap") + - (isSSL ? "s" : "") + - "://" + desc->lud_host + - ":" + port + "/" + suffix; - installInfo->set(SLAPD_KEY_K_LDAP_URL, url); - ldap_free_urldesc(desc); - } - - if (cf->suitespot3x_uid) - slapdInfo->set(SLAPD_KEY_CONFIG_ADMIN_DN, cf->suitespot3x_uid); - else - slapdInfo->set(SLAPD_KEY_CONFIG_ADMIN_DN, cf->cfg_sspt_uid); - - /* - If we are here, that means we have been called as a CGI, which - means that there must already be an MC host, which means that - we are not creating an MC host, which means we must be creating - a UG host - */ - NSString UGLDAPURL = NSString("ldap://") + cf->servname + - ":" + cf->servport + "/" + cf->suffix; - installInfo->set(SLAPD_KEY_USER_GROUP_LDAP_URL, UGLDAPURL); - installInfo->set(SLAPD_KEY_USER_GROUP_ADMIN_ID, cf->rootdn); - installInfo->set(SLAPD_KEY_USER_GROUP_ADMIN_PWD, cf->rootpw); - - installInfo->addSection("slapd", slapdInfo); - - return; -} - -/* ----------------------- main ------------------------ */ - -/* - Initialize the cf structure based on data in the inf file, and also initialize - our static objects. Return 0 if everything was OK, and non-zero if there - were errors, like parsing a bogus inf file -*/ -extern "C" int create_config_from_inf( - server_config_s *cf, - int argc, - char *argv[] -) -{ - InstallInfo *admInfo; - if (parse_commandline(argc, argv)) - return 1; - - admInfo = installInfo->getSection("admin"); - slapdInfo = installInfo->getSection("slapd"); - if (!slapdInfo->get(SLAPD_KEY_SUFFIX)) - slapdInfo->set(SLAPD_KEY_SUFFIX, DEFAULT_ROOT_DN); - - if (installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID)) - slapdInfo->set(SLAPD_KEY_CONFIG_ADMIN_DN, - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID)); - - if (!info_is_valid()) - return 1; - - normalizeDNs(); - - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); - cf->sroot = my_c_strdup(installInfo->get(SLAPD_KEY_SERVER_ROOT)); - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); - cf->servname = my_c_strdup(installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME)); - - cf->servport = my_c_strdup(slapdInfo->get(SLAPD_KEY_SERVER_PORT)); - - if (admInfo && admInfo->get(SLAPD_KEY_ADMIN_SERVER_PORT)) { - cf->adminport = my_c_strdup(admInfo->get(SLAPD_KEY_ADMIN_SERVER_PORT)); - } else { - cf->adminport = my_c_strdup("80"); - } - - cf->cfg_sspt = my_c_strdup( - changeYesNo2_0_1(slapdInfo->get(SLAPD_KEY_SLAPD_CONFIG_FOR_MC))); - cf->suitespot3x_uid = my_c_strdup(installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID)); - cf->cfg_sspt_uid = my_c_strdup(installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID)); - cf->cfg_sspt_uidpw = my_c_strdup(installInfo->get(SLAPD_KEY_SERVER_ADMIN_PWD)); - cf->servid = my_c_strdup(slapdInfo->get(SLAPD_KEY_SERVER_IDENTIFIER)); - -#ifdef XP_UNIX - cf->servuser = my_c_strdup(installInfo->get(SLAPD_KEY_SUITESPOT_USERID)); -#endif - - cf->suffix = my_c_strdup(slapdInfo->get(SLAPD_KEY_SUFFIX)); - cf->rootdn = my_c_strdup(slapdInfo->get(SLAPD_KEY_ROOTDN)); - /* Encode the password in SSHA by default */ - cf->rootpw = my_c_strdup(slapdInfo->get(SLAPD_KEY_ROOTDNPWD)); - cf->roothashedpw = (char *)ds_salted_sha1_pw_enc (cf->rootpw); - - const char *test = slapdInfo->get(SLAPD_KEY_REPLICATIONDN); - const char *testpw = slapdInfo->get(SLAPD_KEY_REPLICATIONPWD); - if (test && *test && testpw && *testpw) - { - cf->replicationdn = my_c_strdup(slapdInfo->get(SLAPD_KEY_REPLICATIONDN)); - cf->replicationpw = my_c_strdup(slapdInfo->get(SLAPD_KEY_REPLICATIONPWD)); - cf->replicationhashedpw = (char *)ds_salted_sha1_pw_enc (cf->replicationpw); - } - - test = slapdInfo->get(SLAPD_KEY_CONSUMERDN); - testpw = slapdInfo->get(SLAPD_KEY_CONSUMERPWD); - if (test && *test && testpw && *testpw) - { - cf->consumerdn = my_c_strdup(test); - cf->consumerpw = my_c_strdup(testpw); - cf->consumerhashedpw = (char *)ds_salted_sha1_pw_enc (cf->consumerpw); - } - - cf->changelogdir = my_c_strdup(slapdInfo->get(SLAPD_KEY_CHANGELOGDIR)); - cf->changelogsuffix = my_c_strdup(slapdInfo->get(SLAPD_KEY_CHANGELOGSUFFIX)); - cf->admin_domain = my_c_strdup(installInfo->get(SLAPD_KEY_ADMIN_DOMAIN)); - cf->disable_schema_checking = - my_c_strdup( - changeYesNo2_0_1(slapdInfo->get(SLAPD_KEY_DISABLE_SCHEMA_CHECKING))); - - /* - Don't create dc=example,dc=com if the user did not select to add the - sample entries - */ - if (!featureIsEnabled(slapdInfo->get(SLAPD_KEY_ADD_SAMPLE_ENTRIES))) - { - cf->samplesuffix = NULL; - } - - cf->config_ldap_url = (char *)installInfo->get(SLAPD_KEY_K_LDAP_URL); - LDAPURLDesc *desc = 0; - if (cf->config_ldap_url && - !ldap_url_parse(cf->config_ldap_url, &desc) && desc) - { - const char *suffix = DEFAULT_ROOT_DN; - int isSSL = !strncmp(cf->config_ldap_url, "ldaps:", strlen("ldaps:")); - char port[6]; - PR_snprintf(port, sizeof(port), "%d", desc->lud_port); - NSString url = NSString("ldap") + - (isSSL ? "s" : "") + - "://" + desc->lud_host + - ":" + port + "/" + suffix; - installInfo->set(SLAPD_KEY_K_LDAP_URL, url); - cf->config_ldap_url = my_c_strdup(url); - ldap_free_urldesc(desc); - } - - if ((test = installInfo->get(SLAPD_KEY_USER_GROUP_LDAP_URL))) - cf->user_ldap_url = my_c_strdup(test); - else - cf->user_ldap_url = my_c_strdup(cf->config_ldap_url); - - cf->use_existing_config_ds = - featureIsEnabled(slapdInfo->get(SLAPD_KEY_USE_EXISTING_MC)); - - cf->use_existing_user_ds = - featureIsEnabled(slapdInfo->get(SLAPD_KEY_USE_EXISTING_UG)); - - if ((test = slapdInfo->get(SLAPD_KEY_INSTALL_LDIF_FILE)) && - !access(test, 0)) - { - cf->install_ldif_file = my_c_strdup(test); - // remove the fields from the slapdInfo so we don't try - // to handle this case later - slapdInfo->remove(SLAPD_KEY_ADD_ORG_ENTRIES); - slapdInfo->remove(SLAPD_KEY_INSTALL_LDIF_FILE); - } - - /* we also have to setup the environment to mimic a CGI */ - static char netsiteRoot[PATH_MAX+32]; - PR_snprintf(netsiteRoot, sizeof(netsiteRoot), "NETSITE_ROOT=%s", cf->sroot); - putenv(netsiteRoot); - - /* set the admin SERVER_NAMES = slapd-slapdIdentifier */ - static char serverNames[PATH_MAX+32]; - PR_snprintf(serverNames, sizeof(serverNames), "SERVER_NAMES=slapd-%s", cf->servid); - putenv(serverNames); - - /* get and set the log file */ - /* use the one given on the command line by default, otherwise, use - the one from the inf file */ - if (logFile || (test = slapdInfo->get(SLAPD_INSTALL_LOG_FILE_NAME))) - { - static char s_logfile[PATH_MAX+32]; - if (logFile) - { - PR_snprintf(s_logfile, sizeof(s_logfile), "DEBUG_LOGFILE=%s", logFile); - } - else - { - PR_snprintf(s_logfile, sizeof(s_logfile), "DEBUG_LOGFILE=%s", test); - /* also init the C++ api message log */ - initMessageLog(test); - } - putenv(s_logfile); - } - - return 0; -} - -extern "C" int -configure_instance_with_config( - server_config_s *cf, - int verbose, // if false, silent; if true, verbose - const char *lfile -) -{ - if (!cf) - return 1; - - infoFile = 0; - initMessageLog(lfile); - - if (!verbose) - installMode = Silent; - - init_from_config(cf); - - return configure_instance(); -} - -extern "C" int -configure_instance() -{ - char hn[BUFSIZ]; - int status = 0; - - dsLogMessage(SETUP_LOG_START, "Slapd", "Starting Slapd server configuration."); - - if (!info_is_valid()) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "Missing Configuration Parameters."); - return 1; - } - - if (installInfo == NULL || slapdInfo == NULL) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "Answer cache not found or invalid"); - return 1; - } - - adminInfo = installInfo->getSection("admin"); - - // next, find the slapd.inf file; it is in the dir <server root>/setup/slapd - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local encoding - NSString slapdinffile = NSString(installInfo->get(SLAPD_KEY_SERVER_ROOT)) - + FILE_PATHSEP + "setup" + FILE_PATHSEP + "slapd" + FILE_PATHSEP + - "slapd.inf"; - InstallInfo temp(slapdinffile); - if (!(slapdINFFileInfo = temp.getSection("slapd")) || - slapdINFFileInfo->isEmpty()) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "Missing configuration file %s", - (const char *)slapdinffile); - return 1; - } - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // back to utf8 - - hn[0] = '\0'; - - /* - * Get the full hostname. - */ - - if (!installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME)) - { - NSString h; - /* Force automatic detection of host name */ -#ifdef XP_UNIX - h = InstUtil::guessHostname(); -#else - /* stevross: figure out NT equivalent */ -#endif - PL_strncpyz(hn, h, BUFSIZ); - installInfo->set(SLAPD_KEY_FULL_MACHINE_NAME, hn); - } - else - { - PL_strncpyz(hn,installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME), BUFSIZ); - } - - NSString sieDN; - if ((status = create_ss_dir_tree(hn, sieDN))) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Did not add Directory Server information to Configuration Server."); - return status; - } - else - dsLogMessage(SETUP_LOG_SUCCESS, "Slapd", - "Added Directory Server information to Configuration Server."); - - // at this point we should be finished talking to the Mission Control LDAP - // server; we may need to establish a connection to the new instance - // we just created in order to write some of this optional stuff to it - - Ldap *ldap = 0; - LdapEntry *entry = 0; - LdapError ldapError = 0; - NSString newURL = NSString("ldap://") + hn + ":" + - slapdInfo->get(SLAPD_KEY_SERVER_PORT) + "/" + - slapdInfo->get(SLAPD_KEY_SUFFIX); - const char *bindDN = slapdInfo->get(SLAPD_KEY_ROOTDN); - const char *bindPwd = slapdInfo->get(SLAPD_KEY_ROOTDNPWD); - // install a sample tree - if (featureIsEnabled(slapdInfo->get(SLAPD_KEY_ADD_SAMPLE_ENTRIES))) - { - if (!ldap) - { - ldapError = 0; - ldap = new Ldap (ldapError, newURL, bindDN, bindPwd, 0, 0); - if (ldapError.errorCode()) - { - delete ldap; - ldap = 0; - dsLogMessage(SETUP_LOG_WARN, "Slapd", - "Could not add sample entries, ldap error code %d", - ldapError.errorCode()); - } - else - { - entry = new LdapEntry(ldap); - } - } - - if (entry) - { - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local - ldapError = add_sample_entries(installInfo->get(SLAPD_KEY_SERVER_ROOT), - entry); - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // back to utf8 - if (ldapError.errorCode()) - { - delete ldap; - ldap = 0; - dsLogMessage(SETUP_LOG_WARN, "Slapd", - "Could not add sample entries, ldap error code %d", - ldapError.errorCode()); - destroyLdapEntry(entry); - entry = 0; - } - } - } - - // create some default organizational entries based on org size, but only - // if we're creating the User Directory - if (!featureIsEnabled(slapdInfo->get(SLAPD_KEY_USE_EXISTING_UG)) && - featureIsEnabled(slapdInfo->get(SLAPD_KEY_ADD_ORG_ENTRIES))) - { - if (!ldap) - { - ldapError = 0; - ldap = new Ldap (ldapError, newURL, bindDN, bindPwd, 0, 0); - if (ldapError.errorCode()) - { - delete ldap; - ldap = 0; - dsLogMessage(SETUP_LOG_WARN, "Slapd", - "Could not populate with ldif file %s error code %d", - slapdInfo->get(SLAPD_KEY_ADD_ORG_ENTRIES), - ldapError.errorCode()); - } - else - { - entry = new LdapEntry(ldap); - } - } - - if (!isAValidDN(slapdInfo->get(SLAPD_KEY_CONFIG_ADMIN_DN))) - { - // its a uid - NSString adminDN = NSString("uid=") + - slapdInfo->get(SLAPD_KEY_CONFIG_ADMIN_DN) + - ", ou=Administrators, ou=TopologyManagement, " + - DEFAULT_ROOT_DN; - slapdInfo->set(SLAPD_KEY_CONFIG_ADMIN_DN, adminDN); - } - - if (entry) - { - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local - add_org_entries(installInfo->get(SLAPD_KEY_SERVER_ROOT), entry, - slapdInfo->get(SLAPD_KEY_INSTALL_LDIF_FILE), - slapdInfo->get(SLAPD_KEY_ORG_SIZE), sieDN); - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // back to utf8 - } - } - - if (ldap) - delete ldap; - if (entry) - destroyLdapEntry(entry); - - // create executable shell script to run the console - create_console_script(); - - return status; -} - -extern "C" int -reconfigure_instance(int argc, char *argv[]) -{ - char hn[BUFSIZ]; - - dsLogMessage(SETUP_LOG_START, "Slapd", "Starting Slapd server reconfiguration."); - - if (parse_commandline(argc, argv)) - return 1; - - if (installInfo == NULL) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "Answer cache not found or invalid"); - return 1; - } - - // next, find the slapd.inf file; it is in the dir <server root>/setup/slapd - installInfo->toLocal(SLAPD_KEY_SERVER_ROOT); // path needs local - NSString slapdinffile = NSString(installInfo->get(SLAPD_KEY_SERVER_ROOT)) - + FILE_PATHSEP + "setup" + FILE_PATHSEP + "slapd" + FILE_PATHSEP + - "slapd.inf"; - InstallInfo temp(slapdinffile); - if (!(slapdINFFileInfo = temp.getSection("slapd")) || - slapdINFFileInfo->isEmpty()) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", "Missing configuration file %s", - (const char *)slapdinffile); - return 1; - } - installInfo->toUTF8(SLAPD_KEY_SERVER_ROOT); // path needs local - - hn[0] = '\0'; - - /* - * Get the full hostname. - */ - - if (!installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME)) - { - NSString h; - /* Force automatic detection of host name */ -#ifdef XP_UNIX - h = InstUtil::guessHostname(); -#else - /* stevross: figure out NT equivalent */ -#endif - PL_strncpyz(hn, h, BUFSIZ); - installInfo->set(SLAPD_KEY_FULL_MACHINE_NAME, hn); - } - else - { - PL_strncpyz(hn,installInfo->get(SLAPD_KEY_FULL_MACHINE_NAME), BUFSIZ); - } - - // search for the app entry for the DS installation we just replaced - // open an LDAP connection to the Config Directory - LdapError le; - Ldap ldap(le, - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_PWD)); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Ldap authentication failed for url %s user id %s (%d:%s)", - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - le.errorCode(), le.msg()); - return le.errorCode(); - } - - // construct the base of the search - NSString baseDN = NSString("cn=") + hn + ", ou=" + - installInfo->get(SLAPD_KEY_ADMIN_DOMAIN) + ", " + - DEFAULT_ROOT_DN; - - // find the nsApplication entry corresponding to the slapd installation - // in the given server root -#ifdef XP_WIN32 - - char *pszServerRoot = my_strdup(installInfo->get(SLAPD_KEY_SERVER_ROOT)); - char *pszEscapedServerRoot = (char *)malloc(2*strlen(installInfo->get(SLAPD_KEY_SERVER_ROOT)) ); - char *p,*q; - - for(p=pszServerRoot,q=pszEscapedServerRoot; p && *p; p++) - { - *q = *p; - if(*p == '\\') - { - q++; - *q='\\'; - } - q++; - } - /* null terminate it */ - *q= *p; - - - NSString filter = - NSString("(&(objectclass=nsApplication)") + - "(nsnickname=slapd)(nsinstalledlocation=" + - pszEscapedServerRoot + "))"; - - if(pszServerRoot) - { - free(pszServerRoot); - } - - if(pszEscapedServerRoot) - { - free(pszEscapedServerRoot); - } -#else - NSString filter = - NSString("(&(objectclass=nsApplication)") + - "(nsnickname=slapd)(nsinstalledlocation=" + - installInfo->get(SLAPD_KEY_SERVER_ROOT) + "))"; -#endif - - int scope = LDAP_SCOPE_SUBTREE; - - LdapEntry ldapent(&ldap); - le = ldapent.retrieve(filter, scope, baseDN); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not find Directory Server Configuration\n" - "URL %s user id %s DN %s (%d:%s)" , - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)baseDN, - le.errorCode(), le.msg()); - return le.errorCode(); - } - - setAppEntryInformation(&ldapent); - - le = ldapent.replace(ldapent.entryDN()); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not update Directory Server Configuration\n" - "URL %s user id %s DN %s (%d:%s)" , - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)baseDN, - le.errorCode(), le.msg()); - return le.errorCode(); - } - - // now update the values in the SIEs under the ISIE - filter = NSString("(objectclass=nsDirectoryServer)"); - scope = LDAP_SCOPE_ONELEVEL; - baseDN = NSString(ldapent.entryDN()); - - ldapent.clear(); - le = ldapent.retrieve(filter, scope, baseDN); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not find Directory Server Instances\n" - "URL %s user id %s DN %s (%d:%s)", - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)baseDN, - le.errorCode(), le.msg()); - return le.errorCode(); - } - - // ldapent holds the search results, but ldapent.replace will wipe out that - // information; so, create a new entry to actually do the replace operation - // while we use the original ldapent to iterate the search results - - do - { - LdapEntry repEntry(ldapent.ldap()); - repEntry.retrieve(ldapent.entryDN()); - repEntry.setAttribute("serverVersionNumber", slapdINFFileInfo->get("Version")); - repEntry.setAttribute("installationTimeStamp", getGMT()); - - le = repEntry.replace(repEntry.entryDN()); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not update Directory Server Instance\n" - "URL %s user id %s DN %s (%d:%s)" , - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)repEntry.entryDN(), - le.errorCode(), le.msg()); - return le.errorCode(); - } - } - while (ldapent.next() == OKAY); - - // we have a new jar file dsXX.jar so we need to update all - // references to the old jar file name - filter = NSString("(|(nsclassname=*)(nsjarfilename=*)" - "(nsservermigrationclassname=*)" - "(nsservercreationclassname=*))"); - scope = LDAP_SCOPE_SUBTREE; - - ldapent.clear(); - le = ldapent.retrieve(filter, scope, baseDN); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not find Directory Server Instances\n" - "URL %s user id %s DN %s (%d:%s)", - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)baseDN, - le.errorCode(), le.msg()); - return le.errorCode(); - } - - do - { - LdapEntry repEntry(ldapent.ldap()); - repEntry.retrieve(ldapent.entryDN()); - - const char *replace[] = { - "nsclassname", - "nsservermigrationclassname", - "nsservercreationclassname" - }; - const int replaceSize = sizeof(replace)/sizeof(replace[0]); - - if (repEntry.getAttribute("nsjarfilename")) - { - repEntry.setAttribute("nsjarfilename", DS_JAR_FILE_NAME); - } - - for (int ii = 0; ii < replaceSize; ++ii) - { - char *val = repEntry.getAttribute(replace[ii]); - // the class name is of the form - // full class path and name[@jar file[@admin SIE]] - // so here's what we'll do: - // search for the first @ in the string; if there's not one, just - // skip it - // save the full class path and name to a temp var - // create the new classname by appending @new jar file to the full class - // name - // if there is a second @ in the original string, grab the rest of the - // original string after the second @ and append @string to the new - // classname - - const char *ptr = 0; - if (val && *val && (ptr = strstr(val, "@"))) - { - int len = int(ptr - val); - NSString newClass = NSString(val, len) + "@" + - DS_JAR_FILE_NAME; - ++ptr; - if (*ptr && (ptr = strstr(ptr, "@"))) { - newClass = NSString(val, len) + "@" + - DS_JAR_FILE_NAME + ptr; - } - repEntry.setAttribute(replace[ii], newClass); - } - } - - le = repEntry.replace(repEntry.entryDN()); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not update Directory Server Instance\n" - "URL %s user id %s DN %s (%d:%s)" , - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)repEntry.entryDN(), - le.errorCode(), le.msg()); - return le.errorCode(); - } - } - while (ldapent.next() == OKAY); - - // we no longer use nsperl - any CGIs which we used to invoke via perl?perlscript - // are now invoked directly by making the perl script executable - we need to - // search for all nsexecref: perl?perlscript and replace them with - // nsexecref: perlscript - filter = NSString("(nsexecref=perl*)"); - scope = LDAP_SCOPE_SUBTREE; - baseDN = name_netscaperootDN; - - ldapent.clear(); - le = ldapent.retrieve(filter, scope, baseDN); - if (le != OKAY) - { - if (le == NOT_FOUND) { - dsLogMessage(SETUP_LOG_INFO, "Slapd", - "No old nsperl references found"); - } else { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not find old nsperl references\n" - "URL %s user id %s DN %s (%d:%s)", - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)baseDN, - le.errorCode(), le.msg()); - return le.errorCode(); - } - } else { - do - { - LdapEntry repEntry(ldapent.ldap()); - repEntry.retrieve(ldapent.entryDN()); - char *val = repEntry.getAttribute("nsexecref"); - const char *ptr = 0; - if (val && *val && (ptr = strstr(val, "perl?"))) { - ptr = strchr(ptr, '?'); - ptr++; - NSString newscript = NSString(ptr); - repEntry.setAttribute("nsexecref", newscript); - } - - le = repEntry.replace(repEntry.entryDN()); - if (le != OKAY) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "ERROR: Could not fix old nsperl reference\n" - "URL %s user id %s DN %s (%d:%s)" , - installInfo->get(SLAPD_KEY_K_LDAP_URL), - installInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - (const char *)repEntry.entryDN(), - le.errorCode(), le.msg()); - return le.errorCode(); - } - } - while (ldapent.next() == OKAY); - } - - return 0; -} diff --git a/ldap/admin/src/configure_instance.h b/ldap/admin/src/configure_instance.h deleted file mode 100644 index aedde9e1..00000000 --- a/ldap/admin/src/configure_instance.h +++ /dev/null @@ -1,90 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/*********************************************************************** -** -** -** NAME -** configure_instance.h -** -** DESCRIPTION -** -** -** AUTHOR -** Rich Megginson <richm@netscape.com> -** -***********************************************************************/ - -#ifndef _CONFIGURE_INSTANCE_H_ -#define _CONFIGURE_INSTANCE_H_ - -#include "create_instance.h" - -#ifdef __cplusplus -extern "C" { -#endif - -int -create_config_from_inf( - server_config_s *cf, - int argc, - char *argv[] -); - -int -configure_instance_with_config( - server_config_s *cf, - int verbose, /* if false, silent; if true, verbose */ - const char *lfile /* log file */ -); - -int -configure_instance(); - -int -reconfigure_instance(int argc, char *argv[]); - -#ifdef __cplusplus -} -#endif - -#endif /* _CONFIGURE_INSTANCE_H_ */ diff --git a/ldap/admin/src/create_instance.c b/ldap/admin/src/create_instance.c deleted file mode 100644 index 7623e2e0..00000000 --- a/ldap/admin/src/create_instance.c +++ /dev/null @@ -1,4676 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * create_instance.c: Routines for creating an instance of a Directory Server - * - * These routines are not thread safe. - * - * Rob McCool - */ - -#define GW_CONF 1 -#define PB_CONF 2 - -#include "create_instance.h" -#include "cfg_sspt.h" - -#include <stdio.h> -#include <stdarg.h> -#include <string.h> - -#include <sys/stat.h> -#include <ctype.h> - -#define PATH_SIZE 1024 -#define ERR_SIZE 8192 - -/* delay time in seconds between referential integrity updates - 0 means continues */ -#define REFERINT_DELAY 0 - -/* 1=log changes for replaction, 0=don't replicate changes */ -#define REFERINT_LOG_CHANGES 0 - -#include "dsalib.h" -#include "dirver.h" - -#include "nspr.h" -#include "plstr.h" - -#ifdef XP_WIN32 -#define NOT_ABSOLUTE_PATH(str) \ - ((str[0] != '/') && (str[0] != '\\') && (str[2] != '/') && (str[2] != '\\')) -#define EADDRINUSE WSAEADDRINUSE -#define EACCES WSAEACCES -#include <winsock.h> -#include <io.h> -#include <regparms.h> -#include <nt/ntos.h> -#define SHLIB_EXT "dll" - -#else /* !XP_WIN32 */ - -#define NOT_ABSOLUTE_PATH(str) (str[0] != '/') -#include <errno.h> -#include <sys/types.h> -#include <unistd.h> -#include <pwd.h> - -#if !defined(HPUX) -#include <sys/select.h> /* FD_SETSIZE */ -#else -#include <sys/types.h> /* FD_SETSIZE is in types.h on HPUX */ -#endif - -#if !defined(AIX) -#include <sys/resource.h> /* get/setrlimit stuff */ -#endif - -#include <sys/socket.h> /* socket flags */ -#include <netinet/in.h> /* sockaddr_in */ -#include <arpa/inet.h> /* inet_addr */ -#ifdef HPUX -#ifdef __ia64 -#define SHLIB_EXT "so" -#else -#define SHLIB_EXT "sl" -#endif -#else -#define SHLIB_EXT "so" -#endif - -#endif /* !XP_WIN32 */ - -/* - NT doesn't strictly need these, but the libadmin API which is emulated - below uses them. - */ -#define NEWSCRIPT_MODE 0755 -#define NEWFILE_MODE 0644 -#define NEWDIR_MODE 0755 -#define NEWSECDIR_MODE 0700 - -#include <stdarg.h> - -#ifdef XP_WIN32 -OS_TYPE NS_WINAPI INFO_GetOperatingSystem (); -DWORD NS_WINAPI SERVICE_ReinstallNTService( LPCTSTR szServiceName, - LPCTSTR szServiceDisplayName, - LPCTSTR szServiceExe ); -#endif - -static void ds_gen_index(FILE* f, char* belowdn); -static char *ds_gen_orgchart_conf(char *sroot, char *cs_path, server_config_s *cf); -static char *ds_gen_gw_conf(char *sroot, char *cs_path, server_config_s *cf, int conf_type); -static char *install_ds(char *sroot, server_config_s *cf, char *param_name); - -#if defined (BUILD_PRESENCE) -static char *gen_presence_init_script(char *sroot, server_config_s *cf, - char *cs_path); -static int init_presence(char *sroot, server_config_s *cf, char *cs_path); -#endif - -static char *make_error(char *fmt, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 1, 2))); -#else - ; -#endif - -static char *make_error(char *fmt, ...) -{ - static char errbuf[ERR_SIZE]; - va_list args; - - va_start(args, fmt); - PR_vsnprintf(errbuf, sizeof(errbuf), fmt, args); - va_end(args); - return errbuf; -} - - -/* This is to determine if we can skip the port number checks. During -migration or server cloning, we may want to copy over an old configuration, -including the old port number, which may not currently have permission to -use; if we don't need to start the server right away, we can skip -certain checks -*/ -static int needToStartServer(server_config_s *cf) -{ - if (cf && ( - (cf->cfg_sspt && !strcmp(cf->cfg_sspt, "1")) || - (cf->start_server && !strcmp(cf->start_server, "1")) - )) - { - return 1; - } - - return 0; -} - -static int getSuiteSpotUserGroup(server_config_s* cf) -{ -#ifdef XP_UNIX - static const char *ssUsersFile = "ssusers.conf"; - char realFile[PATH_SIZE]; - char buf[1024]; - FILE *fp = NULL; - int status = 1; - - if (cf->servuser) - return 0; - - PR_snprintf(realFile, sizeof(realFile), "%s/%s", cf->config_dir, ssUsersFile); - if (!(fp = fopen(realFile, "r"))) - return 1; - - while (fgets(buf, sizeof(buf), fp)) - { - char *p = NULL; - - if (buf[0] == '#' || buf[0] == '\n') - continue; - - buf[strlen(buf) - 1] = 0; - if (NULL != (p = strstr(buf, "SuiteSpotUser"))) - { - p += strlen("SuiteSpotUser"); - while (ldap_utf8isspace(p)) - LDAP_UTF8INC(p); - cf->servuser = strdup(p); - status = 0; - break; - } - } - - if (fp) - fclose(fp); - - return status; -#else - return 0; -#endif -} - -/* ----------------------- Create default settings ------------------------ */ - - -void set_defaults(char *sroot, char *hn, server_config_s *conf) -{ - char *id = 0, *t = 0; - - conf->sroot = sroot; - - if (hn) - { - if( (t = strchr(hn, '.')) ) - *t = '\0'; - id = PR_smprintf("%s", hn); - if(t) - *t = '.'; - } - - conf->servname = hn; - conf->bindaddr = ""; - conf->cfg_sspt = NULL; - conf->suitespot3x_uid = NULL; - conf->cfg_sspt_uid = NULL; - conf->cfg_sspt_uidpw = NULL; - conf->servport = "389"; - conf->secserv = "off"; - conf->secservport = "636"; - conf->rootpw = ""; - conf->roothashedpw = ""; - conf->loglevel = NULL; - if (getenv("DEBUG_DS_LOG_LEVEL")) - conf->loglevel = getenv("DEBUG_DS_LOG_LEVEL"); - conf->suffix = "dc=example, dc=com"; -#ifndef DONT_ALWAYS_CREATE_NETSCAPEROOT - conf->netscaperoot = name_netscaperootDN; -#endif /* DONT_ALWAYS_CREATE_NETSCAPEROOT */ -#define CREATE_SAMPLE_SUFFIX -#ifdef CREATE_SAMPLE_SUFFIX - conf->samplesuffix = "dc=example, dc=com"; -#endif /* CREATE_SAMPLE_SUFFIX */ -#ifdef TEST_CONFIG - conf->netscaperoot = "cn=config40"; -#endif /* TEST_CONFIG */ - -#define ROOT_RDN "cn=Directory Manager" - conf->rootdn = ROOT_RDN; -/* conf->rootdn = malloc(strlen(ROOT_RDN) + 2 + strlen(conf->suffix) + 1); - sprintf(conf->rootdn, "%s, %s", ROOT_RDN, conf->suffix);*/ - conf->servid = id; - -#ifdef XP_UNIX - conf->servuser = NULL; -#ifdef THREAD_NSPR_KERNEL - conf->numprocs = "1"; - conf->maxthreads = "128"; -#else - conf->numprocs = "4"; - conf->maxthreads = "32"; -#endif -#else /* XP_WIN32 */ - conf->maxthreads = "32"; -#endif - conf->minthreads = "4"; - - conf->upgradingServer = 0; - - conf->start_server = "1"; - conf->install_full_schema = 1; - conf->admin_domain = NULL; - conf->user_ldap_url = NULL; - conf->use_existing_user_ds = 0; - conf->consumerdn = NULL; - conf->disable_schema_checking = NULL; - conf->install_ldif_file = NULL; - - conf->bak_dir = NULL; - conf->config_dir = NULL; - conf->sbindir = NULL; - conf->datadir = NULL; - conf->db_dir = NULL; - conf->docdir = NULL; - conf->inst_dir = NULL; - conf->ldif_dir = NULL; - conf->lock_dir = NULL; - conf->log_dir = NULL; - conf->plugin_dir = NULL; - conf->run_dir = NULL; - conf->sasl_path = NULL; - conf->schema_dir = NULL; - conf->sysconfdir = NULL; - conf->tmp_dir = NULL; -} - -/* ----------------- Sanity check a server configuration ------------------ */ - -char *create_instance_checkport(char *, char *); -char *create_instance_checkports(server_config_s *cf); -char *create_instance_checkuser(char *); -int create_instance_numbers(char *); -int create_instance_exists(char *fn, int type); -char *create_instance_copy(char *, char *, int, int); -char *create_instance_concatenate(char *, char *, int); -int create_instance_mkdir(char *, int); -char *create_instance_mkdir_p(char *, char *, int, struct passwd *); -static char *create_instance_strdup(const char *); - -#if defined( SOLARIS ) -/* - * Solaris 9+ specific installation - */ -int create_instance_symlink(char *, char *); -#endif /* SOLARIS */ - - -/* - returns NULL if the given dn is a valid dn, or an error string -*/ -static char * -isAValidDN(const char *dn_to_test) -{ - char *t = 0; - - if (!dn_to_test || !*dn_to_test) - { - t = "No value specified for the parameter."; - } - else - { - char **rdnList = ldap_explode_dn(dn_to_test, 0); - char **rdnNoTypes = ldap_explode_dn(dn_to_test, 1); - if (!rdnList || !rdnList[0] || !rdnNoTypes || !rdnNoTypes[0] || - !*rdnNoTypes[0] || !PL_strcasecmp(rdnList[0], rdnNoTypes[0])) - { - t = make_error("The given value [%s] is not a valid DN.", - dn_to_test); - } - if (rdnList) - ldap_value_free(rdnList); - if (rdnNoTypes) - ldap_value_free(rdnNoTypes); - } - - if (t) - return t; - - return NULL; -} - -/* - prints a message if the given dn uses LDAPv2 style quoting -*/ -void -checkForLDAPv2Quoting(const char *dn_to_test) -{ - if (ds_dn_uses_LDAPv2_quoting(dn_to_test)) - { - char *newdn = strdup(dn_to_test); - char *t; - dn_normalize_convert(newdn); - t = make_error( - "The given value [%s] is quoted in the deprecated LDAPv2 style\n" - "quoting format. It will be automatically converted to use the\n" - "LDAPv3 style escaped format [%s].", dn_to_test, newdn); - free(newdn); - ds_show_message(t); - } - - return; -} - -/* - returns NULL if the given string contains no 8 bit chars, otherwise an - error message -*/ -static char * -contains8BitChars(const char *s) -{ - char *t = 0; - - if (s && *s) - { - for (; !t && *s; ++s) - { - if (*s & 0x80) - { - t = make_error("The given value [%s] contains invalid 8 bit characters.", - s); - } - } - } - - return t; -} - -static char *sanity_check(server_config_s *cf, char *param_name) -{ - char *t; - register int x; - - if (!param_name) - return "Parameter param_name is null"; - - /* if we don't need to start the server right away, we can skip the - port number checks - */ - if (needToStartServer(cf)) - { - if( (t = create_instance_checkports(cf))) - { - PL_strncpyz(param_name, "servport", BIG_LINE); - return t; - } - - if ( cf->secserv && (strcmp(cf->secserv, "on") == 0) && (cf->secservport != NULL) && - (*(cf->secservport) != '\0') ) { - if ( (t = create_instance_checkport(cf->bindaddr, cf->secservport)) ) { - PL_strncpyz(param_name, "secservport", BIG_LINE); - return t; - } - } - } - - /* is the server identifier good? */ - for(x=0; cf->servid[x]; x++) { - if(strchr("/ &;`'\"|*!?~<>^()[]{}$\\", cf->servid[x])) { - PL_strncpyz(param_name, "servid", BIG_LINE); - return make_error("You used a shell-specific character in " - "your server id (the character was %c).", - cf->servid[x]); - } - } - -#ifdef XP_UNIX - if( (t = create_instance_checkuser(cf->servuser)) ) - { - PL_strncpyz(param_name, "servuser", BIG_LINE); - return t; - } -#endif - - /* make sure some drooling imbecile doesn't put in bogus numbers */ -#ifdef XP_UNIX - if((!create_instance_numbers(cf->numprocs)) || (atoi(cf->numprocs) <= 0)) - { - PL_strncpyz(param_name, "numprocs", BIG_LINE); - return ("The number of processes must be not be zero or " - "negative."); - } -#endif - if((!create_instance_numbers(cf->maxthreads)) || (atoi(cf->maxthreads) <= 0)) - { - PL_strncpyz(param_name, "maxthreads", BIG_LINE); - return ("The maximum threads must be not be zero or negative."); - } - if((!create_instance_numbers(cf->minthreads)) || (atoi(cf->minthreads) <= 0)) - { - PL_strncpyz(param_name, "minthreads", BIG_LINE); - return ("The minumum threads must be not be zero or negative."); - } - - if((atoi(cf->minthreads)) > (atoi(cf->maxthreads))) - { - PL_strncpyz(param_name, "minthreads", BIG_LINE); - return ("Minimum threads must be less than maximum threads."); - } - - /* see if the DN parameters are valid DNs */ - if (!cf->use_existing_user_ds && (t = isAValidDN(cf->suffix))) - { - PL_strncpyz(param_name, "suffix", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->suffix); - - if (NULL != (t = isAValidDN(cf->rootdn))) - { - PL_strncpyz(param_name, "rootdn", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->rootdn); - - if (cf->replicationdn && *cf->replicationdn && (t = isAValidDN(cf->replicationdn))) - { - PL_strncpyz(param_name, "replicationdn", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->replicationdn); - - if (cf->consumerdn && *cf->consumerdn && (t = isAValidDN(cf->consumerdn))) - { - PL_strncpyz(param_name, "consumerdn", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->consumerdn); - - if (cf->changelogsuffix && *cf->changelogsuffix && - (t = isAValidDN(cf->changelogsuffix))) - { - PL_strncpyz(param_name, "changelogsuffix", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->changelogsuffix); - - if (cf->netscaperoot && *cf->netscaperoot && - (t = isAValidDN(cf->netscaperoot))) - { - PL_strncpyz(param_name, "netscaperoot", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->netscaperoot); - - if (cf->samplesuffix && *cf->samplesuffix && - (t = isAValidDN(cf->samplesuffix))) - { - PL_strncpyz(param_name, "samplesuffix", BIG_LINE); - return t; - } - checkForLDAPv2Quoting(cf->samplesuffix); - - if (NULL != (t = contains8BitChars(cf->rootpw))) - { - PL_strncpyz(param_name, "rootpw", BIG_LINE); - return t; - } - - if (NULL != (t = contains8BitChars(cf->cfg_sspt_uidpw))) - { - PL_strncpyz(param_name, "cfg_sspt_uidpw", BIG_LINE); - return t; - } - - if (NULL != (t = contains8BitChars(cf->replicationpw))) - { - PL_strncpyz(param_name, "replicationpw", BIG_LINE); - return t; - } - - if (NULL != (t = contains8BitChars(cf->consumerpw))) - { - PL_strncpyz(param_name, "consumerpw", BIG_LINE); - return t; - } - - if (cf->cfg_sspt_uid && *cf->cfg_sspt_uid) - { - /* - If it is a valid DN, ok. Otherwise, it should be a uid, and should - be checked for 8 bit chars - */ - if (NULL != (t = isAValidDN(cf->cfg_sspt_uid))) - { - if (NULL != (t = contains8BitChars(cf->cfg_sspt_uid))) - { - PL_strncpyz(param_name, "cfg_sspt_uid", BIG_LINE); - return t; - } - } - else - checkForLDAPv2Quoting(cf->cfg_sspt_uid); - } - - return NULL; -} - -/* ----- From a configuration, set up a new server in the server root ----- */ - -/* ------------------ UNIX utilities for server creation ------------------ */ - -#ifdef XP_UNIX - -static char* -chownfile (struct passwd* pw, char* fn) -{ - if (pw != NULL && chown (fn, pw->pw_uid, pw->pw_gid) == -1) { - if (pw->pw_name != NULL) { - return make_error ("Could not change owner of %s to %s.", - fn, pw->pw_name); - } else { - return make_error ("Could not change owner of %s to (UID %li, GID %li).", - fn, (long)(pw->pw_uid), (long)(pw->pw_gid)); - } - } - return NULL; -} - -static char * -chowndir(char *dir, char *user) -{ - struct passwd *pw; - if (dir && *dir && user && *user && !geteuid()) { - if(!(pw = getpwnam(user))) - return make_error("Could not find UID and GID of user '%s'.", user); - return chownfile (pw, dir); - } - return NULL; -} - -#else - -#define chownfile(a, b) -#define chowndir(a, b) -#define chownsearch(a, b) - -#endif -char *gen_script(char *s_root, char *name, char *fmt, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 3, 4))); -#else - ; -#endif - -char *gen_script(char *s_root, char *name, char *fmt, ...) -{ - char fn[PATH_SIZE]; - FILE *f; - char *shell = "/bin/sh"; - va_list args; - - PR_snprintf(fn, sizeof(fn), "%s%c%s", s_root, FILE_PATHSEP, name); - if(!(f = fopen(fn, "w"))) - return make_error("Could not write to %s (%s).", fn, ds_system_errmsg()); - va_start(args, fmt); -#if !defined( XP_WIN32 ) -#if defined( OSF1 ) - /* - The standard /bin/sh has some rather strange behavior with "$@", - so use the posix version wherever possible. OSF1 4.0D should - always have this one available. - */ - if (!access("/usr/bin/posix/sh", 0)) - shell = "/usr/bin/posix/sh"; -#endif /* OSF1 */ - fprintf(f, "#!%s\n\n", shell); - /* - Neutralize shared library access. - - On HP-UX, SHLIB_PATH is the historical variable. - However on HP-UX 64 bit, LD_LIBRARY_PATH is also used. - We unset both too. - */ -#if defined( SOLARIS ) || defined( OSF1 ) || defined( LINUX2_0 ) - fprintf(f, "unset LD_LIBRARY_PATH\n"); -#endif -#if defined( HPUX ) - fprintf(f, "unset SHLIB_PATH\n"); - fprintf(f, "unset LD_LIBRARY_PATH\n"); -#endif -#if defined( AIX ) - fprintf(f, "unset LIBPATH\n"); -#endif -#endif - vfprintf(f, fmt, args); - -#if defined( XP_UNIX ) - fchmod(fileno(f), NEWSCRIPT_MODE); -#endif - fclose(f); -#if defined( XP_WIN32 ) - chmod( fn, NEWSCRIPT_MODE); -#endif - return NULL; -} - -char *gen_script_auto(char *s_root, char *cs_path, - char *name, server_config_s *cf) -{ - char myperl[PATH_SIZE]; - char fn[PATH_SIZE], ofn[PATH_SIZE]; - const char *table[18][2]; - - if (PR_FAILURE == PR_Access(cs_path, PR_ACCESS_EXISTS)) { - printf("Notice: %s does not exist, skipping %s . . .\n", cs_path, name); - return NULL; - } - -#if defined (IS_FHS_OPT) - PR_snprintf(ofn, sizeof(ofn), "%s%cscript-templates%ctemplate-%s", - cf->datadir, FILE_PATHSEP, FILE_PATHSEP, name); -#else - PR_snprintf(ofn, sizeof(ofn), "%s%c%s%cscript-templates%ctemplate-%s", - cf->datadir, FILE_PATHSEP, cf->package_name, - FILE_PATHSEP, FILE_PATHSEP, name); -#endif - PR_snprintf(fn, sizeof(fn), "%s%c%s", cs_path, FILE_PATHSEP, name); - create_instance_mkdir(cs_path, NEWDIR_MODE); -#ifdef USE_NSPERL - PR_snprintf(myperl, sizeof(myperl), "!%s%cbin%cslapd%cadmin%cbin%cperl", - cf->prefix, FILE_PATHSEP, FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP); -#else - strcpy(myperl, "!/usr/bin/env perl"); -#endif - - table[0][0] = "DS-ROOT"; - table[0][1] = cf->prefix; - table[1][0] = "DS-BRAND"; - table[1][1] = cf->package_name; - table[2][0] = "SEP"; - table[2][1] = FILE_PATHSEPP; - table[3][0] = "SERVER-NAME"; - table[3][1] = cf->servname; - table[4][0] = "SERVER-PORT"; - table[4][1] = cf->servport; - table[5][0] = "PERL-EXEC"; - table[6][0] = "DEV-NULL"; -#if !defined( XP_WIN32 ) - table[5][1] = myperl; - table[6][1] = " /dev/null "; -#else - table[5][1] = " perl script"; - table[6][1] = " NUL "; -#endif - table[7][0] = "ROOT-DN"; - table[7][1] = cf->rootdn; - table[8][0] = "LDIF-DIR"; - table[8][1] = cf->ldif_dir; - table[9][0] = "SERV-ID"; - table[9][1] = cf->servid; - - table[10][0] = "BAK-DIR"; - table[10][1] = cf->bak_dir; - table[11][0] = "SERVER-DIR"; - table[11][1] = cf->sroot; - table[12][0] = "CONFIG-DIR"; - table[12][1] = cf->config_dir; - table[13][0] = "RUN-DIR"; - table[13][1] = cf->run_dir; - table[14][0] = "PRODUCT-NAME"; - table[14][1] = PRODUCT_NAME; - table[15][0] = "SERVERBIN-DIR"; - table[15][1] = cf->sbindir; - table[16][0] = "DB-DIR"; - table[16][1] = cf->db_dir; - table[17][0] = table[17][1] = NULL; - - if (generate_script(ofn, fn, NEWSCRIPT_MODE, table) != 0) { - return make_error("Could not write %s to %s (%s).", ofn, fn, - ds_system_errmsg()); - } - - return NULL; -} - - -/* ------------------ NT utilities for server creation ------------------ */ - -#ifdef XP_WIN32 - -char * -service_exists(char *servid) -{ - DWORD status, lasterror = 0; - char szServiceName[MAX_PATH] = {0}; - PR_snprintf(szServiceName, sizeof(szServiceName),"%s-%s", SVR_ID_SERVICE, servid); - /* if the service already exists, error */ - status = SERVICE_GetNTServiceStatus(szServiceName, &lasterror ); - if ( (lasterror == ERROR_SERVICE_DOES_NOT_EXIST) || - (status == SERVRET_ERROR) || (status == SERVRET_REMOVED) ) { - return 0; - } else { return - make_error("Server %s already exists: cannot create another. " - "Please choose a different name or delete the " - "existing server.", - szServiceName); - } - - return 0; -} - -void setup_nteventlogging(char *szServiceId, char *szMessageFile) -{ - HKEY hKey; - char szKey[MAX_PATH]; - DWORD dwData; - - PR_snprintf(szKey, sizeof(szKey), "SYSTEM\\CurrentControlSet\\Services\\EventLog\\Application\\%s", szServiceId); - - if(RegCreateKey(HKEY_LOCAL_MACHINE, szKey, &hKey) == ERROR_SUCCESS) - { - if(RegSetValueEx(hKey, "EventMessageFile", 0, REG_SZ, (LPBYTE)szMessageFile, strlen(szMessageFile) + 1) == ERROR_SUCCESS) - { - dwData = EVENTLOG_ERROR_TYPE | EVENTLOG_WARNING_TYPE | EVENTLOG_INFORMATION_TYPE; - RegSetValueEx(hKey, "TypesSupported", 0, REG_DWORD, (LPBYTE) &dwData, sizeof(DWORD)); - } - RegCloseKey(hKey); - } -} - - -char *add_ntservice(server_config_s *cf) -{ - char szMessageFile[MAX_PATH]; - char szServiceExe[MAX_PATH], szServiceDisplayName[MAX_PATH], szServiceName[MAX_PATH]; - DWORD dwLastError; - - PR_snprintf(szServiceExe, sizeof(szServiceExe), "%s/bin/%s/server/%s", - cf->prefix, SVR_DIR_ROOT, SVR_EXE); - PR_snprintf(szServiceName, sizeof(szServiceName),"%s-%s", SVR_ID_SERVICE, cf->servid); - PR_snprintf(szServiceDisplayName, sizeof(szServiceDisplayName), "%s (%s)", SVR_NAME_FULL_VERSION, - cf->servid); - - /* install new service - if already installed, try and remove and - then reinstall */ - dwLastError = SERVICE_ReinstallNTService( szServiceName, - szServiceDisplayName, szServiceExe ); - if ( dwLastError != NO_ERROR ) { - return make_error ( "While installing %s Service, the " - "NT Service Manager reported error %d (%s)", - szServiceDisplayName, dwLastError, ds_system_errmsg() ); - } - - // setup event logging registry keys, do this after service creation - PR_snprintf(szMessageFile, sizeof(szMessageFile), "%s\\bin\\%s\\server\\%s", - cf->prefix, SVR_DIR_ROOT, "slapdmessages30.dll"); - setup_nteventlogging(szServiceName, szMessageFile); - - // TODO: add perfmon setup code -ahakim 11/22/96 - return NULL; -} - -char *setup_ntserver(server_config_s *cf) -{ - char line[MAX_PATH], *sroot = cf->prefix; - char subdir[MAX_PATH]; - char NumValuesBuf[3]; - DWORD Result; - HKEY hServerKey; - DWORD NumValues; - DWORD iterator; - int value_already_exists = 0; - DWORD type_buffer; - char value_data_buffer[MAX_PATH]; - DWORD sizeof_value_data_buffer; - - /* MLM - Adding ACL directories authdb and authdb/default */ - PR_snprintf(subdir, sizeof(subdir), "%s%cauthdb", sroot, FILE_PATHSEP); - if( (create_instance_mkdir(subdir, NEWDIR_MODE)) ) - return make_error("mkdir %s failed (%s)", subdir, ds_system_errmsg()); - - PR_snprintf(subdir, sizeof(subdir), "%s%cauthdb%cdefault", sroot, FILE_PATHSEP, FILE_PATHSEP); - if( (create_instance_mkdir(subdir, NEWDIR_MODE)) ) - return make_error("mkdir %s failed (%s)", subdir, ds_system_errmsg()); - - /* Create DS-nickname (corresponding to ServiceID) key in registry */ - PR_snprintf(line, sizeof(line), "%s\\%s\\%s-%s", KEY_SOFTWARE_NETSCAPE, SVR_KEY_ROOT, - SVR_ID_SERVICE, cf->servid); - - Result = RegCreateKey(HKEY_LOCAL_MACHINE, line, &hServerKey); - if (Result != ERROR_SUCCESS) { - return make_error("Could not create registry server key %s - error %d (%s)", - line, GetLastError(), ds_system_errmsg()); - } - - // note that SVR_ID_PRODUCT is being used here, which is of the form dsX - // as opposed to SVR_ID_SERVICE, which is of the form dsX30 - PR_snprintf(line, sizeof(line), "%s\\%s-%s\\config", sroot, SVR_ID_PRODUCT, cf->servid); - Result = RegSetValueEx(hServerKey, VALUE_CONFIG_PATH, 0, REG_SZ, - line, strlen(line) + 1); - - RegCloseKey(hServerKey); - - /* Create SNMP key in registry */ - PR_snprintf(line, sizeof(line), "%s\\%s\\%s", KEY_SOFTWARE_NETSCAPE, SVR_KEY_ROOT, - KEY_SNMP_CURRENTVERSION); - - Result = RegCreateKey(HKEY_LOCAL_MACHINE, line, &hServerKey); - if (Result != ERROR_SUCCESS) { - return make_error("Could not create registry server key %s - error %d (%s)", - line, GetLastError(), ds_system_errmsg()); - } - - - /* Create the SNMP Pathname value */ - PR_snprintf(line, sizeof(line), "%s\\%s", sroot, SNMP_PATH); - Result = RegSetValueEx(hServerKey, VALUE_APP_PATH, 0, REG_SZ, - line, strlen(line) + 1); - RegCloseKey(hServerKey); - - /* write SNMP extension agent value to Microsoft SNMP Part of Registry) */ - PR_snprintf(line, sizeof(line), "%s\\%s", KEY_SERVICES, KEY_SNMP_SERVICE); - Result = RegOpenKeyEx(HKEY_LOCAL_MACHINE, - line, - 0, - KEY_ALL_ACCESS, - &hServerKey); - /* if its there set the value, otherwise go on to the next thing */ - if (Result == ERROR_SUCCESS) - { - /* extension agents should have linearly increasing value, - make sure it doesn't already exist, find last one and increment - value for new key */ - - PR_snprintf(line, sizeof(line), "%s\\%s\\%s", KEY_SOFTWARE_NETSCAPE, SVR_KEY_ROOT, KEY_SNMP_CURRENTVERSION); - - Result = RegQueryInfoKey(hServerKey, NULL, NULL, NULL, NULL, NULL, - NULL, &NumValues, NULL, NULL, NULL, NULL); - - if (Result == ERROR_SUCCESS){ - for(iterator = 0; iterator <= NumValues; iterator++) - { - /* initialize to max size to avoid - ERROR_MORE_DATA because size gets set - to actual size of key after call - to RegQueryValueEx, previously there - was a bug if last key was smaller - than this one it would return ERROR_MORE_DATA - and it would not find the key if it was already there - */ - sizeof_value_data_buffer=MAX_PATH; - PR_snprintf(NumValuesBuf, sizeof(NumValuesBuf), "%d", iterator); - Result = RegQueryValueEx(hServerKey, - NumValuesBuf, - NULL, - &type_buffer, - value_data_buffer, - &sizeof_value_data_buffer - ); - - if(!strcmp(value_data_buffer, line)) - { - value_already_exists = 1; - } - } - } - - if(!value_already_exists) - { - PR_snprintf(NumValuesBuf, sizeof(NumValuesBuf), "%d", NumValues + 1); - Result = RegSetValueEx(hServerKey, NumValuesBuf, 0, REG_SZ, - line, strlen(line) + 1); - - /* couldn't set this value, so there is a real problem */ - if (Result != ERROR_SUCCESS) - { - return make_error("Could not set value %s (%d)", - line, Result); - } - } - - } - RegCloseKey(hServerKey); - - return NULL; -} -#endif - -static char * -create_scripts(server_config_s *cf, char *param_name) -{ - char *t = NULL, *sroot = cf->sroot; - char subdir[PATH_SIZE]; - - /* Create slapd-nickname directory */ - PR_snprintf(subdir, sizeof(subdir), "%s%c"PRODUCT_NAME"-%s", - sroot, FILE_PATHSEP, cf->servid); -#ifdef XP_UNIX - t = gen_script(cf->inst_dir, RESTART_SCRIPT, - "\n" - "# Script that restarts the ns-slapd server.\n" - "# Exit status can be:\n" - "# 0: Server restarted successfully\n" - "# 1: Server could not be started\n" - "# 2: Server started successfully (was not running)\n" - "# 3: Server could not be stopped\n" - "\n" - "server_already_stopped=0\n" - "%s/stop-slapd\n" - "status=$?\n" - "if [ $status -eq 1 ] ; then\n" - " exit 3;\n" - "else\n" - " if [ $status -eq 2 ] ; then\n" - " server_already_stopped=1\n" - " fi\n" - "fi\n" - "%s/start-slapd\n" - "status=$?\n" - "if [ $server_already_stopped -eq 1 ] && [ $status -eq 0 ] ; then\n" - " exit 2;\n" - "fi\n" - "exit $status\n", - cf->inst_dir, cf->inst_dir ); - if(t) return t; - -#else /* XP_WIN32 */ - /* Windows platforms have some extra setup */ - if( (t = setup_ntserver(cf)) ) - return t; - - /* generate start script */ - t = gen_script(subdir, START_SCRIPT".bat", "net start slapd-%s\n", cf->servid); - if(t) return t; - - /* generate stop script */ - t = gen_script(subdir, STOP_SCRIPT".bat", "net stop slapd-%s\n", cf->servid); - if(t) return t; - - /* generate restart script */ - t = gen_script(subdir, RESTART_SCRIPT".bat", "net stop slapd-%s\n" - "net start slapd-%s\n", cf->servid, cf->servid); - if(t) return t; -#endif /* XP_WIN32 */ - - return t; /* should be NULL */ -} - -/* ---------------------- Update server script files ---------------------- */ -int update_server(server_config_s *cf) -{ - char *t; - char error_param[BIG_LINE] = {0}; - -#if defined( SOLARIS ) - /* - * Solaris 9+ specific installation - */ - char otherline[PATH_SIZE]; - char subdirvar[PATH_SIZE]; - char subdiretc[PATH_SIZE]; - char *sub; -#endif /* SOLARIS */ - - error_param[0] = 0; /* init to empty string */ - -#ifdef XP_UNIX - if (!cf->servuser) - getSuiteSpotUserGroup(cf); -#else - /* Abort if the service exists on NT */ - if (t = service_exists(cf->servid)) { - PL_strncpyz(error_param, "servid", BIG_LINE); - goto out; - } -#endif - - if( (t = sanity_check(cf, error_param)) ) - goto out; - - t = create_scripts(cf, error_param); - if(t) goto out; - -out: - if(t) - { - char *msg; - if (error_param[0]) - { - msg = PR_smprintf("%s.error:could not update server %s - %s", - error_param, cf->servid, t); - } - else - { - msg = PR_smprintf("error:could not update server %s - %s", - cf->servid, t); - } - ds_show_message(msg); - PR_smprintf_free(msg); - return 1; - } - else - return 0; -} - -/* ---------------------- Create configuration files ---------------------- */ -char *create_server(server_config_s *cf, char *param_name) -{ -#if defined (BUILD_PRESENCE) - char line[PATH_SIZE] -#endif - char *t, *sroot = cf->sroot; - struct passwd *pw = getpwnam(cf->servuser); - -#if defined( SOLARIS ) - /* - * Solaris 9+ specific installation - */ - char otherline[PATH_SIZE]; - char subdirvar[PATH_SIZE]; - char subdiretc[PATH_SIZE]; - char *sub; -#endif /* SOLARIS */ - - if (param_name) - param_name[0] = 0; /* init to empty string */ - -#ifdef XP_UNIX - if (!cf->servuser) - getSuiteSpotUserGroup(cf); -#else - /* Abort if the service exists on NT */ - if (t = service_exists(cf->servid)) { - PL_strncpyz(param_name, "servid", BIG_LINE); - return t; - } -#endif - - if( (t = sanity_check(cf, param_name)) ) - return t; - - /* Create slapd-nickname directory (instance directory) */ - if( (create_instance_mkdir_p("inst dir", cf->inst_dir, NEWDIR_MODE, pw)) ) - return make_error("make inst dir %s failed (%s)", - cf->inst_dir, ds_system_errmsg()); - - /* Create config directory */ - if( (create_instance_mkdir_p("config dir", cf->config_dir, NEWDIR_MODE, pw)) ) - return make_error("make config dir %s failed (%s)", - cf->config_dir, ds_system_errmsg()); - - /* Create config_dir/schema directory */ - if( (create_instance_mkdir_p("schema dir", cf->schema_dir, NEWDIR_MODE, pw)) ) - return make_error("make schema dir %s failed (%s)", - cf->schema_dir, ds_system_errmsg()); - -#if defined (BUILD_PRESENCE) - /* Create config_dir/presence directory */ - PR_snprintf(line, sizeof(line), "%s%cpresence", - cf->config_dir, FILE_PATHSEP); - if( (create_instance_mkdir(line, NEWDIR_MODE)) ) - return make_error("mkdir %s failed (%s)", line, ds_system_errmsg()); -#endif - - /* Create log directory */ - if( (create_instance_mkdir_p("log dir", cf->log_dir, NEWSECDIR_MODE, pw)) ) - return make_error("make log dir %s failed (%s)", - cf->log_dir, ds_system_errmsg()); - - /* Create lock directory */ - if( (create_instance_mkdir_p("lock dir", cf->lock_dir, NEWSECDIR_MODE, pw)) ) - return make_error("make lock dir %s failed (%s)", - cf->lock_dir, ds_system_errmsg()); - - /* Create run directory */ - if( (create_instance_mkdir_p("run dir", cf->run_dir, NEWSECDIR_MODE, pw)) ) - return make_error("make run dir %s failed (%s)", - cf->run_dir, ds_system_errmsg()); - - /* Create tmp directory */ - if( (create_instance_mkdir_p("tmp dir", cf->tmp_dir, NEWSECDIR_MODE, pw)) ) - return make_error("make tmp dir %s failed (%s)", - cf->tmp_dir, ds_system_errmsg()); - - /* Create cert directory */ - if( (create_instance_mkdir_p("cert dir", cf->cert_dir, NEWSECDIR_MODE, pw)) ) - return make_error("make cert dir %s failed (%s)", - cf->cert_dir, ds_system_errmsg()); - t = create_scripts(cf, param_name); - if(t) return t; - -#ifdef XP_WIN32 - if ( INFO_GetOperatingSystem () == OS_WINNT ) { - - if( (t = add_ntservice(cf)) ) - return t; - } -#endif - - /* Create subdirectories and config files for directory server */ - if( (t = install_ds(sroot, cf, param_name)) ) - return t; - - /* XXXrobm using link to start script instead of automatically doing it */ - return NULL; -} - -/* ------------------------- Copied from libadmin ------------------------- */ - -/* - These replace the versions in libadmin to allow error returns. - - XXXrobm because libadmin calls itself a lot, I'm replacing ALL the - functions this file requires - */ - - -/* - * input: - * fn: file/dir name - * type: - * if you don't care of the file type, 0 - * if file, PR_FILE_FILE - * if directory, PR_FILE_DIRECTORY - * else, PR_FILE_OTHER - * - * return value: - * 0: does not exist - * 1: exists - * -1: exists, but unexpected type - */ -int -create_instance_exists(char *fn, int type) -{ - PRFileInfo finfo; - - if(PR_GetFileInfo(fn, &finfo) == PR_FAILURE) - return 0; /* does not exist */ - else { - if (type > 0) { - if (type == finfo.type) { - return 1; - } else { - return -1; - } - } else { - return 1; - } - } -} - - -int -create_instance_mkdir(char *dir, int mode) -{ - int rv = 0; - if (NULL == dir) - return -1; - rv = create_instance_exists(dir, PR_FILE_DIRECTORY); - if (rv < 0) { /* not a directory */ - PR_Delete(dir); - rv = 0; - } - if(0 == rv) { /* dir does not exist */ -#ifdef XP_UNIX - if(mkdir(dir, mode) == -1) -#else /* XP_WIN32 */ - if(!CreateDirectory(dir, NULL)) -#endif /* XP_WIN32 */ - return -1; - } - return 0; -} - - -char *create_instance_mkdir_p(char *str, char *dir, int mode, struct passwd *pw) -{ - static char errmsg[ERR_SIZE]; - struct stat fi; - char *t; - - if (NULL == dir) { - PR_snprintf(errmsg, sizeof(errmsg), "NULL is passed to make \"%s\"", - str?str:"unknown"); - return errmsg; - } - -#ifdef XP_UNIX - t = dir + 1; -#else /* XP_WIN32 */ - t = dir + 3; -#endif /* XP_WIN32 */ - - while(1) { - t = strchr(t, FILE_PATHSEP); - - if(t) *t = '\0'; - if(stat(dir, &fi) == -1) { - if(create_instance_mkdir(dir, mode) == -1) { - PR_snprintf(errmsg, sizeof(errmsg), "mkdir %s for \"%s\" failed (%s)", dir, str, ds_system_errmsg()); - return errmsg; - } - if (pw) - chownfile(pw, dir); - } - if(t) - { - *t = FILE_PATHSEP; - LDAP_UTF8INC(t); - } - else break; - } - return NULL; -} - - -int create_instance_numbers(char *target) -{ - char *p; - for(p=target; *p; LDAP_UTF8INC(p) ) - { - if(!ldap_utf8isdigit(p)) - return 0; - } - return 1; -} - -static char *create_instance_strdup(const char *s) -{ - char *result = NULL; - if (s) { - result = PL_strdup(s); - } - - return result; -} - -#if defined( SOLARIS ) -/* - * Solaris 9+ specific installation - */ -int create_instance_symlink(char *actualpath, char *sympath) -{ - if(symlink(actualpath, sympath) == -1) - return -1; - return 0; -} -#endif /* SOLARIS */ - - -/* --------------------------------- try* --------------------------------- */ - - -/* robm This doesn't use net_ abstractions because they drag in SSL */ -int trybind(char *addr, int port) -{ - int sd; - struct sockaddr_in sa_server; - int ret; - -#ifdef XP_WIN32 - WSADATA wsd; - - if(WSAStartup(MAKEWORD(1, 1), &wsd) != 0) - return -1; -#endif - - if ((sd = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP)) == -1) - goto you_lose; - - if (addr == NULL) - addr = "127.0.0.1"; /* use the local loopback address */ - - memset((char *) &sa_server, 0, sizeof(sa_server)); - sa_server.sin_family=AF_INET; - sa_server.sin_addr.s_addr = inet_addr(addr); - sa_server.sin_port=htons((short)port); - ret = connect(sd, (struct sockaddr *) &sa_server,sizeof(sa_server)); - if (ret == -1) - ret = 0; /* could not connect, so port is not in use; that's good */ - else - { - ret = -1; /* connection succeeded, port in use, bad */ - errno = EADDRINUSE; - } -#ifdef XP_UNIX - close(sd); -#else - closesocket(sd); - WSACleanup(); -#endif - return ret; - -you_lose: -#ifdef XP_WIN32 - WSACleanup(); -#endif - return -1; -} - - -#ifdef XP_UNIX -#include <pwd.h> -#include <fcntl.h> - -int tryuser(char *user) -{ - struct passwd *pw; - char fn[128]; - int fd, ret; - - setpwent(); - if(!(pw = getpwnam(user))) - return -1; - - endpwent(); - - if(geteuid()) - return 0; - - PR_snprintf(fn, sizeof(fn), "/tmp/trychown.%ld", (long)getpid()); - if( (fd = creat(fn, 0777)) == -1) - return 0; /* Hmm. */ - ret = chown(fn, pw->pw_uid, pw->pw_gid); - close(fd); - unlink(fn); - return (ret == -1 ? -2 : 0); -} -#endif /* XP_UNIX */ - - -/* --------------------------- create_instance_check* ---------------------------- */ - -char *create_instance_checkports(server_config_s *cf) -{ - /* allow port 0 if ldapifilepath is specified */ -#if defined(ENABLE_LDAPI) - if (!cf->ldapifilepath || strcmp(cf->servport, "0")) { -#endif - return create_instance_checkport(cf->bindaddr, cf->servport); -#if defined(ENABLE_LDAPI) - } -#endif - - return NULL; -} - - -char *create_instance_checkport(char *addr, char *sport) -{ - int port; - - port = atoi(sport); - if((port < 1) || (port > 65535)) { - return ("Valid port numbers are between 1 and 65535"); - } - if(trybind(addr, port) == -1) { - if(errno == EADDRINUSE) { - return make_error("Port %d is already in use", port); - } - /* XXXrobm if admin server not running as root, you lose. */ - else if(errno == EACCES) { - return ("Ports below 1024 require super user access. " - "You must run the installation as root to install " - "on that port."); - } else { - ds_report_warning(DS_WARNING, "port", "That port is not available"); - } - } - return NULL; -} - -#ifdef XP_UNIX -char *create_instance_checkuser(char *user) -{ - if (user && *user) switch(tryuser(user)) { - case -1: - return make_error ("Can't find a user named '%s'." - "\nPlease select or create another user.", - user); - case -2: - return make_error ("Can't change a file to be owned by %s." - "\nPlease select or create another user.", - user); - } - return NULL; -} -#endif - - -/* --------------------------------- copy --------------------------------- */ - -#define COPY_BUFFER_SIZE 4096 - -#ifdef XP_UNIX - - -char *create_instance_copy(char *sfile, char *dfile, int mode, int needbakup) -{ - int sfd, dfd, len; - struct stat fi; - - char copy_buffer[COPY_BUFFER_SIZE]; - unsigned long read_len; - -/* Make sure we're in the right umask */ - umask(022); - - if( (sfd = open(sfile, O_RDONLY)) == -1) { - return make_error("Cannot open %s for reading (%s)", sfile, - ds_system_errmsg()); - } - if (stat(sfile, &fi) < 0) { - return make_error("Cannot stat %s (%s)", sfile, ds_system_errmsg()); - } - if(!(S_ISREG(fi.st_mode))) { - close(sfd); - return make_error("%s is not a regular file", sfile); - } - len = fi.st_size; - - if (needbakup) { - if (0 == stat(dfile, &fi)) { /* file exists */ - if (S_ISREG(fi.st_mode) || S_ISDIR(fi.st_mode)) { - char *bak_dfile = PR_smprintf("%s.bak", dfile); - if (NULL != bak_dfile) { - rename(dfile, bak_dfile); /* make a back up; - ignore any errors */ - PR_smprintf_free(bak_dfile); - } - } - } - } - - if( (dfd = open(dfile, O_RDWR | O_CREAT | O_TRUNC, mode)) == -1) - return make_error("Cannot open file %s for writing (%s)", dfile, - ds_system_errmsg()); - - while(len) { - read_len = len>COPY_BUFFER_SIZE?COPY_BUFFER_SIZE:len; - - if ( (read_len = read(sfd, copy_buffer, read_len) ) == -1 ) { - close(sfd); close(dfd); - return make_error("Cannot read from file %s (%s)", - sfile, ds_system_errmsg()); - } - - if ( write(dfd, copy_buffer, read_len) != read_len ) { - close(sfd); close(dfd); - return make_error("Error writing to file %s from copy of %s (%s)", - dfile, sfile, ds_system_errmsg()); - } - - len -= read_len; - } - close(sfd); - close(dfd); - /* BERT! */ - return NULL; -} - -#else /* XP_WIN32 */ -char *create_instance_copy(char *sfile, char *dfile, int mode, int bakup) -{ - HANDLE sfd, dfd, MapHandle; - PCHAR fp; - PCHAR fpBase; - DWORD BytesWritten = 0; - DWORD len; - - if( (sfd = CreateFile(sfile, GENERIC_READ, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) - == INVALID_HANDLE_VALUE) { - return make_error("Cannot open file %s for reading (%s)", sfile, - ds_system_errmsg()); - } - len = GetFileSize(sfd, NULL); - if( (MapHandle = CreateFileMapping(sfd, NULL, PAGE_READONLY, - 0, 0, NULL)) == NULL) { - return make_error("Cannot create file mapping of %s (%s)", sfile, - ds_system_errmsg()); - } - if (!(fpBase = fp = MapViewOfFile(MapHandle, FILE_MAP_READ, 0, 0, 0))) { - return make_error("Cannot map file %s (%s)", sfile, ds_system_errmsg()); - } - if( (dfd = CreateFile(dfile, GENERIC_READ | GENERIC_WRITE, - FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,OPEN_ALWAYS, - FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE) { - return make_error("Cannot open destination file %s for writing (%s)", - dfile, ds_system_errmsg()); - } - while ( len) { - if(!WriteFile(dfd, fp, len, &BytesWritten, NULL)) { - return ("Cannot write new file %s (%s)", dfile, ds_system_errmsg()); - } - len -= BytesWritten; - fp += BytesWritten; - } - CloseHandle(sfd); - UnmapViewOfFile(fpBase); - CloseHandle(MapHandle); - FlushFileBuffers(dfd); - CloseHandle(dfd); - /* BERT! */ - return NULL; -} -#endif - -static int -file_is_type_x(const char *dirname, const char *filename, PRFileType x) -{ - struct PRFileInfo inf; - int status = 0; - char *fullpath = PR_smprintf("%s/%s", dirname, filename); - if (PR_SUCCESS == PR_GetFileInfo(fullpath, &inf) && - inf.type == x) - status = 1; - - PR_smprintf_free(fullpath); - - return status; -} - -/* return true if the given path and file corresponds to a directory */ -static int -is_a_dir(const char *dirname, const char *filename) -{ - return file_is_type_x(dirname, filename, PR_FILE_DIRECTORY); -} - -static char * -ds_copy_group_files_using_mode_owner(char *src_dir, char *dest_dir, - char *filter, int use_mode, struct passwd *pw) -{ - char *t = 0; - PRDir *ds = 0; - PRDirEntry *d = 0; - char src_file[PATH_SIZE], dest_file[PATH_SIZE], fullname[PATH_SIZE]; - - if(!(ds = PR_OpenDir(src_dir))) { - return make_error("Can't read directory %s (%s)", src_dir, ds_system_errmsg()); - } - while( (d = PR_ReadDir(ds, 0)) ) { - if(d->name[0] != '.') { - if(!filter || strstr(d->name, filter)) { - PR_snprintf(fullname, sizeof(fullname), "%s/%s", src_dir, d->name); - if(PR_SUCCESS != PR_Access(fullname, PR_ACCESS_EXISTS)) - continue; - PR_snprintf(src_file, sizeof(src_file), "%s%c%s", src_dir, FILE_PATHSEP, d->name); - PR_snprintf(dest_file, sizeof(dest_file), "%s%c%s", dest_dir, FILE_PATHSEP, d->name); - if(is_a_dir(src_dir, d->name)) { - char *sub_src_dir = strdup(src_file); - char *sub_dest_dir = strdup(dest_file); - if( (t = create_instance_mkdir_p(sub_dest_dir, sub_dest_dir, NEWDIR_MODE, pw)) ) - return(t); - if( (t = ds_copy_group_files_using_mode_owner(sub_src_dir, sub_dest_dir, filter, use_mode, pw)) ) - return t; - free(sub_src_dir); - free(sub_dest_dir); - } - else { - if( (t = create_instance_copy(src_file, dest_file, use_mode, 0 )) ) - return t; - if (pw) - chownfile(pw, dest_file); - } - } - } - } - PR_CloseDir(ds); - return(NULL); -} - -static char * -ds_copy_group_files_using_mode(char *src_dir, char *dest_dir, - char *filter, int use_mode) -{ - return ds_copy_group_files_using_mode_owner(src_dir, dest_dir, filter, use_mode, NULL); -} - -static char * -ds_copy_group_files(char *src_dir, char *dest_dir, char *filter) -{ - return ds_copy_group_files_using_mode(src_dir, dest_dir, filter, - NEWFILE_MODE); -} - -/* this macro was copied from libldap/tmplout.c */ -#define HREF_CHAR_ACCEPTABLE( c ) (( c >= '-' && c <= '9' ) || \ - ( c >= '@' && c <= 'Z' ) || \ - ( c == '_' ) || \ - ( c >= 'a' && c <= 'z' )) - -/* this function is based on libldap/tmplout.c:strcat_escaped */ -void fputs_escaped(char *s, FILE *fp) -{ - char *hexdig = "0123456789ABCDEF"; - register unsigned char c; - for ( ; (c = *(unsigned char*)s); ++s ) { - if ( HREF_CHAR_ACCEPTABLE( c )) { - putc( c, fp ); - } else { - fprintf( fp, "%%%c%c", hexdig[ (c >> 4) & 0x0F ], hexdig[ c & 0x0F ] ); - } - } -} - -/* ------------- Create config files for Directory Server -------------- */ - -static char * -ds_cre_subdirs(server_config_s *cf, struct passwd* pw) -{ - char subdir[PATH_SIZE], *t = NULL; - - /* create db dir */ - if( (t = create_instance_mkdir_p("db dir", cf->db_dir, NEWDIR_MODE, pw)) ) - return(t); - - /* create ldif dir */ - if( (t = create_instance_mkdir_p("ldif dir", cf->ldif_dir, NEWDIR_MODE, pw)) ) - return(t); - -#ifdef DSML - /* create subdir <a_server>/dsml */ - PR_snprintf(subdir, sizeof(subdir), "%s%cdsml", cs_path, FILE_PATHSEP); - if( (t = create_instance_mkdir_p("dsml dir", subdir, NEWDIR_MODE, pw)) ) - return(t); -#endif - /* create bak dir */ - if( (t = create_instance_mkdir_p("backup dir", cf->bak_dir, NEWDIR_MODE, pw)) ) - return(t); - - /* Create slapd-nickname/confbak directory */ - PR_snprintf(subdir, sizeof(subdir), "%s%cconfbak", cf->config_dir, FILE_PATHSEP); - if( (t=create_instance_mkdir_p("config bak dir", subdir, NEWDIR_MODE, pw)) ) - return(t); - -#ifdef DSGW - /* create subdir <server_root>/dsgw/context */ - PR_snprintf(subdir, sizeof(subdir), "%s%cclients", sroot, FILE_PATHSEP); - if (is_a_dir(subdir, "dsgw")) { /* only create dsgw stuff if we are installing it */ - PR_snprintf(subdir, sizeof(subdir), "%s%cclients%cdsgw%ccontext", sroot, FILE_PATHSEP,FILE_PATHSEP,FILE_PATHSEP); - if( (t = create_instance_mkdir_p("dsgw context dir", subdir, NEWDIR_MODE, pw)) ) - return(t); - } - - /* create subdir <prefix>/bin/slapd/authck */ - /* dsgw cookie dir */ - PR_snprintf(subdir, sizeof(subdir), "%s%cbin%cslapd%cauthck", - cf->prefix, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP); - if( (t = create_instance_mkdir_p("authck dir", subdir, NEWDIR_MODE, pw)) ) - return(t); -#endif - - return (t); -} - -#define CREATE_LDIF2DB() \ - gen_script_auto(mysroot, mycs_path, "ldif2db.pl", cf) - -#define CREATE_DB2INDEX() \ - gen_script_auto(mysroot, mycs_path, "db2index.pl", cf) - -#define CREATE_DB2LDIF() \ - gen_script_auto(mysroot, mycs_path, "db2ldif.pl", cf) - -#define CREATE_DB2BAK() \ - gen_script_auto(mysroot, mycs_path, "db2bak.pl", cf) - -#define CREATE_BAK2DB() \ - gen_script_auto(mysroot, mycs_path, "bak2db.pl", cf) - -#define CREATE_VERIFYDB() \ - gen_script_auto(mysroot, mycs_path, "verify-db.pl", cf) - -/* tentatively moved to mycs_path */ -#ifdef MOVE_TO_ADMIN_SERVER -#define CREATE_REPL_MONITOR_CGI() \ - gen_script_auto(mysroot, mycs_path, "repl-monitor-cgi.pl", cf) -#endif - -#define CREATE_ACCOUNT_INACT(_commandName) \ - gen_script_auto(mysroot, cs_path, _commandName, cf) - -#define CREATE_MIGRATE5TO7() \ - gen_script_auto(mysroot, mycs_path, "migrate5to7", cf) - -#define CREATE_MIGRATE6TO7() \ - gen_script_auto(mysroot, mycs_path, "migrate6to7", cf) - -#define CREATE_MIGRATEINSTANCE7() \ - gen_script_auto(mysroot, mycs_path, "migrateInstance7", cf) - -#define CREATE_MIGRATETO7() \ - gen_script_auto(mysroot, mycs_path, "migrateTo7", cf) - -#define CREATE_NEWPWPOLICY() \ - gen_script_auto(mysroot, mycs_path, "ns-newpwpolicy.pl", cf) - -#define CREATE_BAK2DB_SH() \ - gen_script_auto(mysroot, mycs_path, "bak2db", cf) - -#define CREATE_DB2BAK_SH() \ - gen_script_auto(mysroot, mycs_path, "db2bak", cf) - -#define CREATE_DB2INDEX_SH() \ - gen_script_auto(mysroot, mycs_path, "db2index", cf) - -#define CREATE_DB2LDIF_SH() \ - gen_script_auto(mysroot, mycs_path, "db2ldif", cf) - -#define CREATE_LDIF2DB_SH() \ - gen_script_auto(mysroot, mycs_path, "ldif2db", cf) - -#define CREATE_LDIF2LDAP_SH() \ - gen_script_auto(mysroot, mycs_path, "ldif2ldap", cf) - -#define CREATE_MONITOR_SH() \ - gen_script_auto(mysroot, mycs_path, "monitor", cf) - -#define CREATE_RESTORECONFIG_SH() \ - gen_script_auto(mysroot, mycs_path, "restoreconfig", cf) - -#define CREATE_SAVECONFIG_SH() \ - gen_script_auto(mysroot, mycs_path, "saveconfig", cf) - -#define CREATE_START_SLAPD_SH() \ - gen_script_auto(mysroot, mycs_path, "start-slapd", cf) - -#define CREATE_STOP_SLAPD_SH() \ - gen_script_auto(mysroot, mycs_path, "stop-slapd", cf) - -#define CREATE_SUFFIX2INSTANCE_SH() \ - gen_script_auto(mysroot, mycs_path, "suffix2instance", cf) - -#define CREATE_VLVINDEX_SH() \ - gen_script_auto(mysroot, mycs_path, "vlvindex", cf) - -#ifdef XP_UNIX -char *ds_gen_scripts(char *sroot, server_config_s *cf, char *cs_path) -{ - char *t = NULL; - char *server = sroot; - char *admin = sroot; - char *tools = cf->bindir; - char *cl_scripts[7] = {"dsstop", "dsstart", "dsrestart", "dsrestore", "dsbackup", "dsimport", "dsexport"}; - char *cl_javafiles[7] = {"DSStop", "DSStart", "DSRestart", "DSRestore", "DSBackup", "DSImport", "DSExport"}; - int cls = 0; /*Index into commandline script names and java names - RJP*/ - char *mysroot, *mycs_path; - -#if defined( SOLARIS ) - /* - * Solaris 9+ specific installation - */ - char fn[PATH_SIZE]; -#endif /* SOLARIS */ - - mysroot = sroot; - mycs_path = cs_path; - - t = CREATE_LDIF2DB(); - if(t) return t; - - t = CREATE_DB2INDEX(); - if(t) return t; - - t = CREATE_MIGRATE5TO7(); - if(t) return t; - - t = CREATE_MIGRATE6TO7(); - if(t) return t; - - t = CREATE_MIGRATEINSTANCE7(); - if(t) return t; - - t = CREATE_MIGRATETO7(); - if(t) return t; - - t = CREATE_BAK2DB_SH(); - if(t) return t; - - t = CREATE_DB2BAK_SH(); - if(t) return t; - - t = CREATE_DB2INDEX_SH(); - if(t) return t; - - t = CREATE_DB2LDIF_SH(); - if(t) return t; - - t = CREATE_LDIF2DB_SH(); - if(t) return t; - - t = CREATE_LDIF2LDAP_SH(); - if(t) return t; - - t = CREATE_MONITOR_SH(); - if(t) return t; - - t = CREATE_RESTORECONFIG_SH(); - if(t) return t; - - t = CREATE_SAVECONFIG_SH(); - if(t) return t; - - t = CREATE_START_SLAPD_SH(); - if(t) return t; - - t = CREATE_STOP_SLAPD_SH(); - if(t) return t; - - t = CREATE_SUFFIX2INSTANCE_SH(); - if(t) return t; - - t = CREATE_VLVINDEX_SH(); - if(t) return t; - - t = gen_script(cs_path, "getpwenc", - "cd %s\n" - "PATH=%s:$PATH;export PATH\n" - "if [ $# -lt 2 ]\n" - "then\n" - "\techo \"Usage: getpwenc scheme passwd\"\n" - "\texit 1\n" - "fi\n\n" - "pwdhash -D %s -H -s \"$@\"\n", - server, cf->config_dir, cs_path); - if(t) return t; - - t = CREATE_DB2LDIF(); - if(t) return t; - - t = CREATE_DB2BAK(); - if(t) return t; - - t = CREATE_BAK2DB(); - if(t) return t; - - t = CREATE_VERIFYDB(); - if(t) return t; - -#ifdef MOVE_TO_ADMIN_SERVER - t = CREATE_REPL_MONITOR_CGI(); - if(t) return t; -#endif - - t = CREATE_ACCOUNT_INACT("ns-inactivate.pl"); - if(t) return t; - - t = CREATE_ACCOUNT_INACT("ns-activate.pl"); - if(t) return t; - - t = CREATE_ACCOUNT_INACT("ns-accountstatus.pl"); - if(t) return t; - - t = CREATE_NEWPWPOLICY(); - if(t) return t; - - return (t); -} -#else -/* Windows; haven't updated */ -char *ds_gen_scripts(char *sroot, server_config_s *cf, char *cs_path) -{ - char *t = NULL; - char server[PATH_SIZE], admin[PATH_SIZE], tools[PATH_SIZE]; - char cgics_path[PATH_SIZE]; - char *cl_scripts[7] = {"dsstop.bat", "dsstart.bat", "dsrestart.bat", "dsrestore.bat", "dsbackup.bat", "dsimport.bat", "dsexport.bat"}; - char *cl_javafiles[7] = {"DSStop", "DSStart", "DSRestart", "DSRestore", "DSBackup", "DSImport", "DSExport"}; - int cls = 0; /*Index into commandline script names and java names - RJP*/ - char *mysroot, *mycs_path; - - { - char *p, *q; - int n; - - for (n = 0, p = sroot; p = strchr(p, '/'); n++, p++) ; - for (p = sroot; p = strchr(p, '\\'); n++, p++) ; - mysroot = (char *)malloc(strlen(sroot) + n + 1); - for (p = sroot, q = mysroot; *p; p++, q++) { - if ('/' == *p || '\\' == *p) { - *q++ = '\\'; - *q = '\\'; - } else - *q = *p; - } - *q = '\0'; - - for (n = 0, p = cs_path; p = strchr(p, '/'); n++, p++) ; - for (p = cs_path; p = strchr(p, '\\'); n++, p++) ; - mycs_path = (char *)malloc(strlen(cs_path) + n + 1); - for (p = cs_path, q = mycs_path; *p; p++, q++) { - if ('/' == *p || '\\' == *p) { - *q++ = '\\'; - *q = '\\'; - } else - *q = *p; - } - *q = '\0'; - } - - PR_snprintf(server, sizeof(server), "%s/bin/"PRODUCT_NAME"/server", cf->prefix); - PR_snprintf(admin, sizeof(admin), "%s/bin/"PRODUCT_NAME"/admin/bin", cf->prefix); - PR_snprintf(tools, sizeof(tools), "%s/shared/bin", sroot); - PR_snprintf(cgics_path, sizeof(cgics_path), "%s/bin/admin/admin/bin", cf->prefix); - - ds_unixtodospath( cs_path ); - ds_unixtodospath( server ); - ds_unixtodospath( admin ); - ds_unixtodospath( sroot ); - ds_unixtodospath( tools ); - ds_unixtodospath( cgics_path ); - - t = gen_script(cs_path, "monitor.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "if %%1.==. goto noparam\n" - "\"%s\\ldapsearch\" -p %s -b %%1 " - "-s base \"objectClass=*\"\n" - "set rc=%%errorlevel%%\n" - "goto proceed\n" - ":noparam\n" - "\"%s\\ldapsearch\" -p %s -b \"cn=monitor\" " - "-s base \"objectClass=*\"\n" - "set rc=%%errorlevel%%\n" - ":proceed\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - tools, cf->servport, tools, cf->servport); - if(t) return t; - - t = gen_script(cs_path, "saveconfig.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n" - "namegen\n" - "call bstart\n" - "set config_ldif=%s\\confbak\\%%DATESTR%%.ldif\n" - "call bend\n" - "del bend.bat\n" - "slapd db2ldif -s \"%s\" -a \"%%config_ldif%%\" -N" - " -D \"%s\" -n NetscapeRoot 2>&1\n" - "set rc=%%errorlevel%%\n" - "if %%rc%%==0 goto done\n" - "echo Error occurred while saving configuration\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, cf->netscaperoot, cs_path); - if(t) return t; - - t = gen_script(cs_path, "restoreconfig.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n" - "set latestscript=%s\\latest_config.bat\n" - "if EXIST \"%%latestscript%%\" del \"%%latestscript%%\"\n" - "latest_file \"%s\\confbak\\*.ldif\" \"%%latestscript%%\"\n" - "if not EXIST \"%%latestscript%%\" goto noconfig\n" - "call \"%%latestscript%%\"\n" - "del \"%%latestscript%%\"\n" - "slapd ldif2db -D \"%s\" -i \"%%LATEST_FILE%%\"" - " -n NetscapeRoot 2>&1\n" - "set rc=%%errorlevel%%\n" - "if %%rc%%==0 goto done\n" - "echo Error occurred while saving configuration\n" - "goto done\n" - ":noconfig\n" - "set rc=0\n" /* no error */ - "echo No configuration to restore in %s\\confbak\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, cs_path, cs_path, cs_path); - if(t) return t; - - t = gen_script(cs_path, "ldif2db.bat", - "@if not \"%%echo%%\" == \"on\" echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n\n" - "set noconfig=0\n" - "if [%%2] == [] goto incorrect\n" - "if [%%3] == [] goto incorrect\n" - "if [%%4] == [] goto incorrect\n\n" - "set args=\n" - ":getargs\n" - "if [%%1] == [] goto import\n" - "set args=%%args%% %%1\n" - "shift\n" - "goto getargs\n\n" - ":incorrect\n" - ":usage\n" - "echo \"Usage: ldif2db -n backend_instance | {-s \"includesuffix\"}* " - "{-i ldif-file}* [-O] [{-x \"excludesuffix\"}*]\"\n" - "set rc=1\n" - "goto done\n\n" - ":import\n" - "echo importing data ...\n" - "slapd ldif2db -D \"%s\" %%args%% 2>&1\n\n" - "set rc=%%errorlevel%%\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path); - if(t) return t; - - /* new code for dsml import */ - t = gen_script(cs_path, "dsml2db.bat", - "@if not \"%%echo%%\" == \"on\" echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n\n" - "set noconfig=0\n" - "if [%%2] == [] goto incorrect\n" - "if [%%3] == [] goto incorrect\n" - "if [%%4] == [] goto incorrect\n\n" - "set args=\n" - "goto getargs\n" - ":setdsml\n" - "set dsmlfile=\n" - "set dsmlfile=%%2\n" - "shift\n" - "shift\n" - "goto getargs\n" - ":getargs\n" - "if [%%1] == [] goto import\n" - "if [%%1] == [-i] goto setdsml\n" - "set args=%%args%% %%1\n" - "shift\n" - "goto getargs\n\n" - ":incorrect\n" - ":usage\n" - "echo \"Usage: dsml2db -n backend_instance | {-s \"includesuffix\"}* " - "{-i dsml-file} [{-x \"excludesuffix\"}*]\"\n" - "set rc=1\n" - "goto done\n\n" - ":import\n" - "%s\\bin\\base\\jre\\bin\\java -Dverify=true -classpath \".;%s\\java\\ldapjdk.jar;%s\\java\\jars\\crimson.jar;%s\\java\\jars\\xmltools.jar\" com.netscape.xmltools.DSML2LDIF %%dsmlfile%%\n" - "set rc=%%errorlevel%%\n" - "if %%rc%%==0 goto realimport else goto done\n" - ":realimport\n" - "echo importing data ...\n" - "%s\\bin\\base\\jre\\bin\\java -classpath \".;%s\\java\\ldapjdk.jar;%s\\java\\jars\\crimson.jar;%s\\java\\jars\\xmltools.jar\" com.netscape.xmltools.DSML2LDIF %%dsmlfile%% | slapd ldif2db -D \"%s\" -i - %%args%% 2>&1\n\n" - "set rc=%%errorlevel%%\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, sroot, sroot, sroot, sroot, sroot, sroot, sroot, sroot, cs_path); - if(t) return t; - - t = gen_script(cs_path, "ldif2ldap.bat", - "@echo off\n" - "\"%s\\ldapmodify\" -a -p %s -D %%1 -w %%2 -f %%3\n", - tools, cf->servport); - if(t) return t; - - t = CREATE_LDIF2DB(); - if(t) return t; - - t = CREATE_DB2INDEX(); - if(t) return t; - - t = CREATE_MIGRATE5TO7(); - if(t) return t; - - t = CREATE_MIGRATE6TO7(); - if(t) return t; - - t = CREATE_MIGRATEINSTANCE7(); - if(t) return t; - - t = CREATE_MIGRATETO7(); - if(t) return t; - - t = gen_script(cs_path, "getpwenc.bat", - "@echo off\n" - "\"%s\\pwdhash\" -D \"%s\" -H -s %%1 %%2\n", - server, cs_path); - if(t) return t; - - t = gen_script(cs_path, "db2ldif.bat", - "@if not \"%%echo%%\" == \"on\" echo off\n\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n\n" - "if [%%2] == [] goto err\n\n" - "set arg=\n" - "set ldif_file=\n\n" - ":again\n" - "if \"%%1\" == \"\" goto next\n" - "if \"%%1\" == \"-n\" goto doubletag\n" - "if \"%%1\" == \"-s\" goto doubletag\n" - "if \"%%1\" == \"-x\" goto doubletag\n" - "if \"%%1\" == \"-a\" goto setldif\n" - "if \"%%1\" == \"-N\" goto singletag\n" - "if \"%%1\" == \"-r\" goto singletag\n" - "if \"%%1\" == \"-C\" goto singletag\n" - "if \"%%1\" == \"-u\" goto singletag\n" - "if \"%%1\" == \"-m\" goto singletag\n" - "if \"%%1\" == \"-o\" goto singletag\n" - "if \"%%1\" == \"-U\" goto singletag\n" - "if \"%%1\" == \"-M\" goto singletag\n" - "if \"%%1\" == \"-E\" goto singletag\n" - "goto next\n\n" - ":doubletag\n" - "set arg=%%1 %%2 %%arg%%\n" - "shift\n" - "shift\n" - "goto again\n\n" - ":singletag\n" - "set arg=%%1 %%arg%%\n" - "shift\n" - "goto again\n\n" - ":setldif\n" - "set ldif_file=%%2\n" - "shift\n" - "shift\n" - "goto again\n\n" - ":next\n" - "if not \"%%ldif_file%%\" == \"\" goto givenldif\n\n" - "namegen\n" - "call bstart\n" - "set ldif_file=\"%s\\ldif\\%%DATESTR%%.ldif\"\n" - "call bend\n" - "del bend.bat\n\n" - ":givenldif\n" - "\"%s\\slapd\" db2ldif -D \"%s\" -a %%ldif_file%% %%arg%%\n" - "set rc=%%errorlevel%%\n" - "goto done\n\n" - ":err\n" - "echo \"Usage: db2ldif -n backend_instance | " - "{-s \"includesuffix\"}* [{-x \"excludesuffix\"}*] [-N] [-r] [-C] " - "[-u] [-U] [-m] [-M] [-1] [-a outputfile]\"\n\n" - "set rc=1\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, server, cs_path); - if(t) return t; - - t = CREATE_DB2LDIF(); - if(t) return t; - - /* new code for dsml export */ - t = gen_script(cs_path, "db2dsml.bat", - "@if not \"%%echo%%\" == \"on\" echo off\n\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n\n" - "if [%%2] == [] goto err\n\n" - "set arg=\n" - "set dsml_file=\n\n" - ":again\n" - "if \"%%1\" == \"\" goto next\n" - "if \"%%1\" == \"-n\" goto doubletag\n" - "if \"%%1\" == \"-s\" goto doubletag\n" - "if \"%%1\" == \"-x\" goto doubletag\n" - "if \"%%1\" == \"-a\" goto setdsml\n" - "if \"%%1\" == \"-N\" goto singletag\n" - "if \"%%1\" == \"-r\" goto singletag\n" - "if \"%%1\" == \"-C\" goto singletag\n" - "if \"%%1\" == \"-u\" goto singletag\n" - "if \"%%1\" == \"-m\" goto singletag\n" - "if \"%%1\" == \"-o\" goto singletag\n" - "if \"%%1\" == \"-U\" goto singletag\n" - "if \"%%1\" == \"-M\" goto singletag\n" - "goto next\n\n" - ":doubletag\n" - "set arg=%%1 %%2 %%arg%%\n" - "shift\n" - "shift\n" - "goto again\n\n" - ":singletag\n" - "set arg=%%1 %%arg%%\n" - "shift\n" - "goto again\n\n" - ":setdsml\n" - "set dsml_file=%%2\n" - "shift\n" - "shift\n" - "goto again\n\n" - ":next\n" - "if not \"%%dsml_file%%\" == \"\" goto givendsml\n\n" - "namegen\n" - "call bstart\n" - "set dsml_file=\"%s\\dsml\\%%DATESTR%%.dsml\"\n" - "echo dsmlfile: %%dsml_file%%\n" - "call bend\n" - "del bend.bat\n\n" - ":givendsml\n" - "%s\\bin\\base\\jre\\bin\\java -Dverify=true -classpath \".;%s\\java\\ldapjdk.jar;%s\\java\\jars\\xmltools.jar\" com.netscape.xmltools.LDIF2DSML -s -o %%dsml_file%%\n" - "set rc=%%errorlevel%%\n" - "if %%rc%%==0 goto realimport else goto done\n\n" - ":realimport\n" - "\"%s\\slapd\" db2ldif -D \"%s\" -a - -1 %%arg%% | %s\\bin\\base\\jre\\bin\\java -classpath \".;%s\\java\\ldapjdk.jar;%s\\java\\jars\\xmltools.jar\" com.netscape.xmltools.LDIF2DSML -s -o %%dsml_file%%\n" - "set rc=%%errorlevel%%\n" - "goto done\n\n" - ":err\n" - "echo \"Usage: db2dsml -n backend_instance | " - "{-s \"includesuffix\"}* [{-x \"excludesuffix\"}*]" - "[-u] [-a outputfile]\"\n\n" - "set rc=1\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, sroot, sroot, sroot, server, cs_path, sroot, sroot, sroot); - if(t) return t; - - t = gen_script(cs_path, "db2bak.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n" - "if %%1.==. goto nobak\n" - "set bakdir=%%1\n" - "goto backup\n" - ":nobak\n" - "namegen\n" - "call bstart\n" - "set bakdir=\"%s\\bak\\%%DATESTR%%\"\n" - "call bend\n" - "del bend.bat\n" - ":backup\n" - "\"%s\\slapd\" db2archive -D \"%s\" -a %%bakdir%% " - "%%2 %%3 %%4 %%5 %%6 %%7 %%8\n" - "set rc=%%errorlevel%%\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, server, cs_path); - if(t) return t; - - t = CREATE_DB2BAK(); - if(t) return t; - - t = gen_script(cs_path, "db2index.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n" - "if %%1.==. goto indexall\n\n" - "if %%2.==. goto err\n" - "if %%3.==. goto err\n\n" - "set bakdir=%%1\n" - "goto backup\n\n" - ":indexall\n" - "namegen\n" - "call bstart\n" - "set bakdir=\"%s\\bak\\%%DATESTR%%\"\n" - "call bend\n" - "del bend.bat\n" - "\"%s\\slapd\" upgradedb -D \"%s\" -f -a %%bakdir%%\n" - "set rc=%%errorlevel%%\n" - "goto done\n\n" - ":backup\n" - "\"%s\\slapd\" db2index -D \"%s\" " - "%%1 %%2 %%3 %%4 %%5 %%6 %%7 %%8\n" - "set rc=%%errorlevel%%\n" - "goto done\n\n" - ":err\n" - "echo \"Usage: db2index [-n backend_instance | {-s instancesuffix}* -t attribute[:indextypes[:matchingrules]] -T vlvattribute]\"\n\n" - "set rc=1\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, server, cs_path, server, cs_path); - if(t) return t; - - t = gen_script(cs_path, "vlvindex.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "if [%%2] == [] goto usage\n" - "if [%%3] == [] goto usage\n" - "if [%%4] == [] goto usage\n\n" - "\"%s\\slapd\" db2index -D \"%s\" \"%%@\"\n" - "set rc=%%errorlevel%%\n" - "goto done\n\n" - ":usage\n" - "echo \"Usage: vlvindex -n backend_instance | {-s includesuffix}* {-T attribute}\"\n\n" - "set rc=1\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path); - if(t) return t; - - t = gen_script(cs_path, "bak2db.bat", - "@echo off\n" - "pushd & setlocal\n\n" - "if [%%1] == [] (goto :usage)\n" - "if not [%%4] == [] (goto :usage)\n\n" - "set archivedir=%%1\n" - "set rc=0\n\n" - ":getopts\n" - "shift\n" - "if [%%1]==[] (goto :main)\n" - "if [%%1]==[-n] (if not [%%2]==[] (set bename=%%2) else (goto :usage)) else (goto :getopts)\n\n" - ":main\n" - "call :relative %%archivedir%%\n" - "if defined bename (\n" - "\"%s\\slapd\" archive2db -D \"%s\" -a %%archivedir%% -n %%bename%%\n" - ") else (\n" - "\"%s\\slapd\" archive2db -D \"%s\" -a %%archivedir%%\n" - ")\n" - "set rc=%%ERRORLEVEL%%\n" - "popd\n" - "goto :done\n\n" - "goto :EOF\n" - ":usage\n" - "echo %%0 archivedir [-n backendname]\n" - "goto :done\n\n" - "goto :EOF\n" - ":relative\n" - "set archivedir=%%~f1\n\n" - "goto :EOF\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, server, cs_path); - if(t) return t; - - t = gen_script(cs_path, "upgradedb.bat", - "@echo off\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n" - "if %%1.==. goto nobak\n" - "set bakdir=%%1\n" - "goto backup\n" - ":nobak\n" - "namegen\n" - "call bstart\n" - "set bakdir=\"%s\\bak\\upgradedb_%%DATESTR%%\"\n" - "call bend\n" - "del bend.bat\n" - ":backup\n" - "\"%s\\slapd\" upgradedb -D \"%s\" -a %%bakdir%% " - "%%2 %%3 %%4 %%5 %%6 %%7 %%8\n" - "set rc=%%errorlevel%%\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, cs_path, server, cs_path); - if(t) return t; - - t = CREATE_BAK2DB(); - if(t) return t; - - t = CREATE_VERIFYDB(); - if(t) return t; - -#ifdef MOVE_TO_ADMIN_SERVER - t = CREATE_REPL_MONITOR_CGI(); - if(t) return t; -#endif - - t = gen_script(cs_path, "suffix2instance.bat", - "@if not \"%%echo%%\" == \"on\" echo off\n\n" - "setlocal\n" - "set rc=0\n" - "PATH=\"%s\";%%PATH%%\n\n" - "if [%%2] == [] goto err\n\n" - "set arg=\n\n" - ":again\n" - "if \"%%1\" == \"\" goto next\n" - "if \"%%1\" == \"-s\" goto doubletag\n" - "shift\n" - "goto again\n\n" - ":doubletag\n" - "set arg=%%1 %%2 %%arg%%\n" - "shift\n" - "shift\n" - "goto again\n\n" - ":next\n" - "\"%s\\slapd\" suffix2instance -D \"%s\" %%arg%%\n" - "set rc=%%errorlevel%%\n" - "goto done\n\n" - ":err\n" - "echo Usage: suffix2instance {-s \"suffix\"}*\n\n" - "set rc=1\n" - ":done\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - server, server, cs_path); - if(t) return t; - - t = CREATE_ACCOUNT_INACT("ns-inactivate.pl"); - if(t) return t; - - t = CREATE_ACCOUNT_INACT("ns-activate.pl"); - if(t) return t; - - t = CREATE_ACCOUNT_INACT("ns-accountstatus.pl"); - if(t) return t; - - t = gen_script(cs_path, "dsml-activate.bat", - "@echo off\n" - "setlocal\n" - "PATH=%s\\bin\\slapd\\admin\\bin;%%PATH%%\n" - "perl \"%s\\dsml-activate.pl\" %%*\n" - "set rc=%%errorlevel%%\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - cf->prefix, cs_path); - if(t) return t; - - - - t = CREATE_NEWPWPOLICY(); - if(t) return t; - - t = gen_script(cs_path, "ns-newpwpolicy.cmd", - "@echo off\n" - "setlocal\n" - "PATH=%s\\bin\\slapd\\admin\\bin;%%PATH%%\n" - "perl \"%s\\ns-newpwpolicy.pl\" %%*\n" - "set rc=%%errorlevel%%\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - cf->prefix, cs_path); - if(t) return t; - - free(mysroot); - free(mycs_path); - - /*Generate the java commandline tools in bin/slapd/server*/ - for (cls = 0; cls < 7; cls++) { - t = gen_script(server, cl_scripts[cls], - "@echo off\npushd \"%s\"\n\n" - "setlocal\n" - "set LANG=en\n" - "set arg=\n" - "set rc=0\n" - ":getarg\n" - "if %%1.==. goto start\n" - "if %%1==-l goto getlang\n" - "set arg=%%arg%% %%1\n" - "shift\n" - "goto getarg\n" - ":getlang\n" - "shift\n" - "set LANG=%%1\n" - "shift\n" - "goto getarg\n" - ":start\n" - ".\\bin\\base\\jre\\bin\\jre -classpath " - ".;.\\java;.\\bin\\base\\jre\\lib;" - ".\\bin\\base\\jre\\lib\\rt.jar;.\\bin\\base\\jre\\lib\\i18n.jar;" - ".\\java\\base.jar;.\\java\\jars\\ds40.jar;.\\java\\jars\\ds40_%%LANG%%.jar;" - ".\\java\\swingall.jar;.\\java\\ssl.zip;" - ".\\java\\ldapjdk.jar;.\\java\\mcc40.jar;.\\java\\mcc40_%%LANG%%.jar;" - ".\\java\\nmclf40.jar;.\\java\\nmclf40_%%LANG%%.jar " - "com.netscape.admin.dirserv.cmdln.%s %%arg%%\n" - "set rc=%%errorlevel%%\n" - "popd\n" - "if defined MKSARGS exit %%rc%%\n" - "exit /b %%rc%%\n", - sroot, cl_javafiles[cls]); - if(t) return t; - } - - - - return (t); -} -#endif - - -void -suffix_gen_conf(FILE* f, char * suffix, char *be_name) -{ - char* belowdn; - - fprintf(f, "dn: cn=%s,cn=ldbm database,cn=plugins,cn=config\n", be_name); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "objectclass: nsBackendInstance\n"); - fprintf(f, "nsslapd-cachesize: -1\n"); - fprintf(f, "nsslapd-cachememsize: 10485760\n"); - fprintf(f, "nsslapd-suffix: %s\n", suffix); - fprintf(f, "cn: %s\n", be_name); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=monitor,cn=%s,cn=ldbm database,cn=plugins,cn=config\n", be_name); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: monitor\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=\"%s\",cn=mapping tree,cn=config\n", suffix); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "objectclass: nsMappingTree\n"); - fprintf(f, "cn: \"%s\"\n", suffix); - fprintf(f, "nsslapd-state: backend\n"); - fprintf(f, "nsslapd-backend: %s\n", be_name); - fprintf(f, "\n"); - - /* Parent entry for attribute encryption config entries */ - - fprintf(f, "dn: cn=encrypted attributes,cn=%s,cn=ldbm database,cn=plugins,cn=config\n", be_name); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: encrypted attributes\n"); - fprintf(f, "\n"); - - /* Parent entry for attribute encryption keys */ - - fprintf(f, "dn: cn=encrypted attribute keys,cn=%s,cn=ldbm database,cn=plugins,cn=config\n", be_name); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: encrypted attributes keys\n"); - fprintf(f, "\n"); - - /* Indexes for the ldbm instance */ - - fprintf(f, "dn: cn=index,cn=%s,cn=ldbm database,cn=plugins,cn=config\n", be_name); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: index\n"); - fprintf(f, "\n"); - - belowdn = PR_smprintf("cn=index,cn=%s,cn=ldbm database,cn=plugins,cn=config", be_name); - ds_gen_index(f, belowdn); - PR_smprintf_free(belowdn); - - /* done with ldbm entries */ -} - -#define MKSYNTAX(_name,_fn) do { \ - fprintf(f, "dn: cn=%s,cn=plugins,cn=config\n", (_name)); \ - fprintf(f, "objectclass: top\n"); \ - fprintf(f, "objectclass: nsSlapdPlugin\n"); \ - fprintf(f, "objectclass: extensibleObject\n"); \ - fprintf(f, "cn: %s\n",(_name)); \ - fprintf(f, "nsslapd-pluginpath: %s/libsyntax-plugin%s\n", cf->plugin_dir, shared_lib); \ - fprintf(f, "nsslapd-plugininitfunc: %s\n", (_fn)); \ - fprintf(f, "nsslapd-plugintype: syntax\n"); \ - fprintf(f, "nsslapd-pluginenabled: on\n"); \ - fprintf(f, "\n"); \ - } while (0) - -char *ds_gen_confs(char *sroot, server_config_s *cf, char *cs_path) -{ - char* t = NULL; - char src[PATH_SIZE], dest[PATH_SIZE]; - char fn[PATH_SIZE], line[1024]; - FILE *f = 0, *srcf = 0; - int rootdse = 0; - char *shared_lib; - struct passwd *pw = getpwnam(cf->servuser); - char *prefix = cf->prefix; - - PR_snprintf(fn, sizeof(fn), "%s%c%s", - cf->config_dir, FILE_PATHSEP, DS_CONFIG_FILE); - if(!(f = fopen(fn, "w"))) - return make_error("Can't write to %s (%s)", - cf->config_dir, ds_system_errmsg()); - -#if defined( XP_WIN32 ) - shared_lib = ".dll"; -#else -#ifdef HPUX -#ifdef __ia64 - shared_lib = ".so"; -#else - shared_lib = ".sl"; -#endif -#else -#ifdef AIX -#if OSVERSION >= 4200 - shared_lib = ".so"; -#else - shared_lib = "_shr.a"; -#endif -#else - shared_lib = ".so"; -#endif -#endif -#endif - - fprintf(f, "dn: cn=config\n"); - fprintf(f, "cn: config\n"); - fprintf(f, "objectclass:top\n"); - fprintf(f, "objectclass:extensibleObject\n"); - fprintf(f, "objectclass:nsslapdConfig\n"); - fprintf(f, "nsslapd-schemadir: %s\n", cf->schema_dir); - fprintf(f, "nsslapd-lockdir: %s\n", cf->lock_dir); - fprintf(f, "nsslapd-tmpdir: %s\n", cf->tmp_dir); - fprintf(f, "nsslapd-certdir: %s\n", cf->cert_dir); - fprintf(f, "nsslapd-ldifdir: %s\n", cf->ldif_dir); - fprintf(f, "nsslapd-instancedir: %s\n", cf->inst_dir); - fprintf(f, "nsslapd-bakdir: %s\n", cf->bak_dir); -/* We use the system SASL by default on Linux, so we don't need to set sasl path */ - if (NULL != cf->sasl_path) { - fprintf(f, "nsslapd-saslpath: %s\n", cf->sasl_path); - } - fprintf(f, "nsslapd-accesslog-logging-enabled: on\n"); - fprintf(f, "nsslapd-accesslog-maxlogsperdir: 10\n"); - fprintf(f, "nsslapd-accesslog-mode: 600\n"); - fprintf(f, "nsslapd-accesslog-maxlogsize: 100\n"); - fprintf(f, "nsslapd-accesslog-logrotationtime: 1\n"); - fprintf(f, "nsslapd-accesslog-logrotationtimeunit: day\n"); - fprintf(f, "nsslapd-accesslog-logrotationsync-enabled: off\n"); - fprintf(f, "nsslapd-accesslog-logrotationsynchour: 0\n"); - fprintf(f, "nsslapd-accesslog-logrotationsyncmin: 0\n"); - fprintf(f, "nsslapd-accesslog: %s/access\n", cf->log_dir); - fprintf(f, "nsslapd-enquote-sup-oc: off\n"); - fprintf(f, "nsslapd-localhost: %s\n", cf->servname); - fprintf(f, "nsslapd-schemacheck: %s\n", - (cf->disable_schema_checking && !strcmp(cf->disable_schema_checking, "1")) ? "off" : "on"); - fprintf(f, "nsslapd-rewrite-rfc1274: off\n"); - fprintf(f, "nsslapd-return-exact-case: on\n"); - fprintf(f, "nsslapd-ssl-check-hostname: on\n"); - fprintf(f, "nsslapd-port: %s\n", cf->servport); -#if defined(ENABLE_LDAPI) - if (cf->ldapifilepath) { - fprintf(f, "nsslapd-ldapifilepath: %s\n", cf->ldapifilepath); - fprintf(f, "nsslapd-ldapilisten: on\n"); - } else { - fprintf(f, "nsslapd-ldapifilepath: %s/%s-%s.socket\n", cf->run_dir, PRODUCT_NAME, cf->servid); - fprintf(f, "nsslapd-ldapilisten: off\n"); - } -#if defined(ENABLE_AUTOBIND) - fprintf(f, "nsslapd-ldapiautobind: on\n"); -#endif /* ENABLE_AUTOBIND */ - fprintf(f, "nsslapd-ldapimaprootdn: cn=Directory Manager\n"); - fprintf(f, "nsslapd-ldapimaptoentries: off\n"); - fprintf(f, "nsslapd-ldapiuidnumbertype: uidNumber\n"); - fprintf(f, "nsslapd-ldapigidnumbertype: gidNumber\n"); - fprintf(f, "nsslapd-ldapientrysearchbase: dc=example, dc=com\n"); - fprintf(f, "nsslapd-ldapiautodnsuffix: cn=peercred,cn=external,cn=auth\n"); -#endif /* ENABLE_LDAPI */ - -#if !defined( XP_WIN32 ) - if (cf->servuser && *(cf->servuser)) { - fprintf(f, "nsslapd-localuser: %s\n", cf->servuser); - } -#endif - fprintf(f, "nsslapd-errorlog-logging-enabled: on\n"); - fprintf(f, "nsslapd-errorlog-mode: 600\n"); - fprintf(f, "nsslapd-errorlog-maxlogsperdir: 2\n"); - fprintf(f, "nsslapd-errorlog-maxlogsize: 100\n"); - fprintf(f, "nsslapd-errorlog-logrotationtime: 1\n"); - fprintf(f, "nsslapd-errorlog-logrotationtimeunit: week\n"); - fprintf(f, "nsslapd-errorlog-logrotationsync-enabled: off\n"); - fprintf(f, "nsslapd-errorlog-logrotationsynchour: 0\n"); - fprintf(f, "nsslapd-errorlog-logrotationsyncmin: 0\n"); - fprintf(f, "nsslapd-errorlog: %s/errors\n", cf->log_dir); - if (cf->loglevel) - fprintf(f, "nsslapd-errorlog-level: %s\n", cf->loglevel); - fprintf(f, "nsslapd-auditlog: %s/audit\n", cf->log_dir); - fprintf(f, "nsslapd-auditlog-mode: 600\n"); - fprintf(f, "nsslapd-auditlog-maxlogsize: 100\n"); - fprintf(f, "nsslapd-auditlog-logrotationtime: 1\n"); - fprintf(f, "nsslapd-auditlog-logrotationtimeunit: day\n"); - fprintf(f, "nsslapd-rootdn: %s\n", cf->rootdn); -#if !defined(_WIN32) && !defined(AIX) - { - unsigned int maxdescriptors = FD_SETSIZE; - struct rlimit rl; - if (getrlimit(RLIMIT_NOFILE, &rl) == 0) - maxdescriptors = (unsigned int)rl.rlim_max; - fprintf(f, "nsslapd-maxdescriptors: %d\n", maxdescriptors); - } -#endif - fprintf(f, "nsslapd-max-filter-nest-level: 40\n" ); - fprintf(f, "nsslapd-rootpw: %s\n", cf->roothashedpw); - if (getenv("DEBUG_SINGLE_THREADED")) - fprintf(f, "nsslapd-threadnumber: 1\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=plugins, cn=config\nobjectclass: top\nobjectclass: nsContainer\ncn: plugins\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=Password Storage Schemes,cn=plugins, cn=config\n"); - fprintf(f, "objectclass: top\nobjectclass: nsContainer\ncn: Password Storage Schemes\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SSHA,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SSHA\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: ssha_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SSHA256,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SSHA256\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: ssha256_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SSHA384,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SSHA384\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: ssha384_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SSHA512,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SSHA512\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: ssha512_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SHA,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SHA\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: sha_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SHA256,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SHA256\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: sha256_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SHA384,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SHA384\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: sha384_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=SHA512,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: SHA512\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: sha512_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - -#if !defined(_WIN32) - fprintf(f, "dn: cn=CRYPT,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: CRYPT\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: crypt_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); -#endif - - fprintf(f, "dn: cn=MD5,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: MD5\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: md5_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=CLEAR,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: CLEAR\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: clear_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=NS-MTA-MD5,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "cn: NS-MTA-MD5\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpwdstorage-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: ns_mta_md5_pwd_storage_scheme_init\n"); - fprintf(f, "nsslapd-plugintype: pwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=DES,cn=Password Storage Schemes,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: DES\n"); - fprintf(f, "nsslapd-pluginpath: %s/libdes-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: des_init\n"); - fprintf(f, "nsslapd-plugintype: reverpwdstoragescheme\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-pluginarg0: nsmultiplexorcredentials\n"); - fprintf(f, "nsslapd-pluginarg1: nsds5ReplicaCredentials\n"); - fprintf(f, "nsslapd-pluginid: des-storage-scheme\n"); - fprintf(f, "\n"); - - MKSYNTAX("Case Ignore String Syntax","cis_init"); - MKSYNTAX("Case Exact String Syntax","ces_init"); - MKSYNTAX("Space Insensitive String Syntax","sicis_init"); - MKSYNTAX("Binary Syntax","bin_init"); - MKSYNTAX("Octet String Syntax","octetstring_init"); - MKSYNTAX("Boolean Syntax","boolean_init"); - MKSYNTAX("Generalized Time Syntax","time_init"); - MKSYNTAX("Telephone Syntax","tel_init"); - MKSYNTAX("Integer Syntax","int_init"); - MKSYNTAX("Distinguished Name Syntax","dn_init"); - MKSYNTAX("OID Syntax","oid_init"); - MKSYNTAX("URI Syntax","uri_init"); - MKSYNTAX("JPEG Syntax","jpeg_init"); - MKSYNTAX("Country String Syntax","country_init"); - MKSYNTAX("Postal Address Syntax","postal_init"); - - fprintf(f, "dn: cn=State Change Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: State Change Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libstatechange-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: statechange_init\n"); - fprintf(f, "nsslapd-plugintype: postoperation\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=Roles Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Roles Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libroles-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: roles_init\n"); - fprintf(f, "nsslapd-plugintype: object\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: State Change Plugin\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: Views\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=ACL Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: ACL Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libacl-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: acl_init\n"); - fprintf(f, "nsslapd-plugintype: accesscontrol\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=ACL preoperation,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: ACL preoperation\n"); - fprintf(f, "nsslapd-pluginpath: %s/libacl-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: acl_preopInit\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=Legacy Replication Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Legacy Replication Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libreplication-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: replication_legacy_plugin_init\n"); - fprintf(f, "nsslapd-plugintype: object\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: Multimaster Replication Plugin\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: Class of Service\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=Multimaster Replication Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Multimaster Replication Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libreplication-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: replication_multimaster_plugin_init\n"); - fprintf(f, "nsslapd-plugintype: object\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: ldbm database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: DES\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: Class of Service\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=Retro Changelog Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Retro Changelog Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libretrocl-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: retrocl_plugin_init\n"); - fprintf(f, "nsslapd-plugintype: object\n"); - fprintf(f, "nsslapd-pluginenabled: off\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: Class of Service\n"); - fprintf(f, "\n"); - - - /* cos needs to be placed before other same type'ed plugins (postoperation) */ - fprintf(f, "dn: cn=Class of Service,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Class of Service\n"); - fprintf(f, "nsslapd-pluginpath: %s/libcos-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: cos_init\n"); - fprintf(f, "nsslapd-plugintype: object\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: State Change Plugin\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: Views\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=Views,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Views\n"); - fprintf(f, "nsslapd-pluginpath: %s/libviews-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: views_init\n"); - fprintf(f, "nsslapd-plugintype: object\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: State Change Plugin\n"); - fprintf(f, "\n"); - - /* - * LP: Turn referential integrity plugin OFF by default - * defect 518862 - */ - fprintf(f, "dn: cn=referential integrity postoperation,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: referential integrity postoperation\n"); - fprintf(f, "nsslapd-pluginpath: %s/libreferint-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: referint_postop_init\n"); - fprintf(f, "nsslapd-plugintype: postoperation\n"); - fprintf(f, "nsslapd-pluginenabled: off\n"); - fprintf(f, "nsslapd-pluginArg0: %d\n", REFERINT_DELAY); - fprintf(f, "nsslapd-pluginArg1: %s/logs/referint\n", cs_path); - fprintf(f, "nsslapd-pluginArg2: %d\n", REFERINT_LOG_CHANGES); - fprintf(f, "nsslapd-pluginArg3: member\n"); - fprintf(f, "nsslapd-pluginArg4: uniquemember\n"); - fprintf(f, "nsslapd-pluginArg5: owner\n"); - fprintf(f, "nsslapd-pluginArg6: seeAlso\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - if (!cf->use_existing_user_ds) { - t = cf->suffix; - } else { - t = cf->netscaperoot; - } - - /* - * LP: Turn attribute uniqueness plugin OFF by default - * defect 518862 - */ - fprintf(f, "dn: cn=attribute uniqueness,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: attribute uniqueness\n"); - fprintf(f, "nsslapd-pluginpath: %s/libattr-unique-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: NSUniqueAttr_Init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: off\n"); - fprintf(f, "nsslapd-pluginarg0: uid\n"); - fprintf(f, "nsslapd-pluginarg1: %s\n", t); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=7-bit check,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: 7-bit check\n"); - fprintf(f, "nsslapd-pluginpath: %s/libattr-unique-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: NS7bitAttr_Init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-pluginarg0: uid\n"); - fprintf(f, "nsslapd-pluginarg1: mail\n"); - fprintf(f, "nsslapd-pluginarg2: userpassword\n"); - fprintf(f, "nsslapd-pluginarg3: ,\n"); - fprintf(f, "nsslapd-pluginarg4: %s\n", t); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - - t = 0; - - fprintf(f, "dn: cn=Internationalization Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Internationalization Plugin\n"); - fprintf(f, "nsslapd-pluginpath: %s/libcollation-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: orderingRule_init\n"); - fprintf(f, "nsslapd-plugintype: matchingRule\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-pluginarg0: %s/slapd-collations.conf\n", cf->config_dir); - fprintf(f, "\n"); - -#ifdef ENABLE_BITWISE - fprintf(f, "dn: cn=Bitwise Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectClass: top\n"); - fprintf(f, "objectClass: nsSlapdPlugin\n"); - fprintf(f, "objectClass: extensibleObject\n"); - fprintf(f, "cn: Bitwise Plugin\n"); - fprintf(f, "nsslapd-pluginPath: %s/libbitwise-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-pluginInitfunc: bitwise_init\n"); - fprintf(f, "nsslapd-pluginType: matchingRule\n"); - fprintf(f, "nsslapd-pluginEnabled: on\n"); - fprintf(f, "\n"); -#endif - - /* The HTTP client plugin */ - fprintf(f, "dn: cn=HTTP Client,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: HTTP Client\n"); - fprintf(f, "nsslapd-pluginpath: %s/libhttp-client-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: http_client_init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - -#if defined (BUILD_PRESENCE) - /* The IM presence plugin root */ - fprintf(f, "dn: cn=Presence,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Presence\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpresence-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: presence_init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "nsslapd-plugin-depends-on-named: HTTP Client\n"); - fprintf(f, "\n"); - - /* The AIM presence plugin */ - fprintf(f, "dn: cn=AIM Presence,cn=Presence,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: AIM Presence\n"); - fprintf(f, "nsim-id: nsAIMid\n"); - fprintf(f, "nsim-urltext: http://big.oscar.aol.com/$nsaimid?on_url=http://online&off_url=http://offline\n"); - fprintf(f, "nsim-urlgraphic: http://big.oscar.aol.com/$nsaimid?on_url=http://online&off_url=http://offline\n"); - fprintf(f, "nsim-onvaluemaptext: http://online\n"); - fprintf(f, "nsim-offvaluemaptext: http://offline\n"); - fprintf(f, "nsim-urltextreturntype: TEXT\n"); - fprintf(f, "nsim-urlgraphicreturntype: TEXT\n"); - fprintf(f, "nsim-requestmethod: REDIRECT\n"); - fprintf(f, "nsim-statustext: nsAIMStatusText\n"); - fprintf(f, "nsim-statusgraphic: nsAIMStatusGraphic\n"); - fprintf(f, "\n"); - - /* The ICQ presence plugin */ - fprintf(f, "dn: cn=ICQ Presence,cn=Presence,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: ICQ Presence\n"); - fprintf(f, "nsim-id: nsICQid\n"); - fprintf(f, "nsim-urltext: http://online.mirabilis.com/scripts/online.dll?icq=$nsicqid&img=5\n"); - fprintf(f, "nsim-urlgraphic: http://online.mirabilis.com/scripts/online.dll?icq=$nsicqid&img=5\n"); - fprintf(f, "nsim-onvaluemaptext: /lib/image/0,,4367,00.gif\n"); - fprintf(f, "nsim-offvaluemaptext: /lib/image/0,,4349,00.gif\n"); - fprintf(f, "nsim-urltextreturntype: TEXT\n"); - fprintf(f, "nsim-urlgraphicreturntype: TEXT\n"); - fprintf(f, "nsim-requestmethod: REDIRECT\n"); - fprintf(f, "nsim-statustext: nsICQStatusText\n"); - fprintf(f, "nsim-statusgraphic: nsICQStatusGraphic\n"); - fprintf(f, "\n"); - - /* The Yahoo presence plugin */ - fprintf(f, "dn: cn=Yahoo Presence,cn=Presence,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Yahoo Presence\n"); - fprintf(f, "nsim-id: nsYIMid\n"); - fprintf(f, "nsim-urltext: http://opi.yahoo.com/online?u=$nsyimid&m=t\n"); - fprintf(f, "nsim-urlgraphic: http://opi.yahoo.com/online?u=$nsyimid&m=g&t=0\n"); - fprintf(f, "nsim-onvaluemaptext: $nsyimid is ONLINE\n"); - fprintf(f, "nsim-offvaluemaptext: $nsyimid is NOT ONLINE\n"); - fprintf(f, "nsim-urltextreturntype: TEXT\n"); - fprintf(f, "nsim-urlgraphicreturntype: BINARY\n"); - fprintf(f, "nsim-requestmethod: GET\n"); - fprintf(f, "nsim-statustext: nsYIMStatusText\n"); - fprintf(f, "nsim-statusgraphic: nsYIMStatusGraphic\n"); - fprintf(f, "\n"); -#endif - - fprintf(f, "dn: cn=Pass Through Authentication,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: Pass Through Authentication\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpassthru-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: passthruauth_init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: off\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "\n"); - -#ifdef ENABLE_PAM_PASSTHRU -#if !defined( XP_WIN32 ) - /* PAM Pass Through Auth plugin - off by default */ - fprintf(f, "dn: cn=PAM Pass Through Auth,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "objectclass: pamConfig\n"); - fprintf(f, "cn: PAM Pass Through Auth\n"); - fprintf(f, "nsslapd-pluginpath: %s/libpam-passthru-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: pam_passthruauth_init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: off\n"); - fprintf(f, "nsslapd-pluginLoadGlobal: true\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: database\n"); - fprintf(f, "pamMissingSuffix: ALLOW\n"); - if (cf->netscaperoot) { - fprintf(f, "pamExcludeSuffix: %s\n", cf->netscaperoot); - } - fprintf(f, "pamExcludeSuffix: cn=config\n"); - fprintf(f, "pamIDMapMethod: RDN\n"); - fprintf(f, "pamIDAttr: notUsedWithRDNMethod\n"); - fprintf(f, "pamFallback: FALSE\n"); - fprintf(f, "pamSecure: TRUE\n"); - fprintf(f, "pamService: ldapserver\n"); - fprintf(f, "\n"); -#endif /* NO PAM FOR WINDOWS */ -#endif /* ENABLE_PAM_PASSTHRU */ - -#ifdef ENABLE_DNA - fprintf(f, "dn: cn=Distributed Numeric Assignment Plugin,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "objectclass: nsContainer\n"); - fprintf(f, "cn: Distributed Numeric Assignment Plugin\n"); - fprintf(f, "nsslapd-plugininitfunc: dna_init\n"); - fprintf(f, "nsslapd-plugintype: preoperation\n"); - fprintf(f, "nsslapd-pluginenabled: off\n"); - fprintf(f, "nsslapd-pluginPath: %s/libdna-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "\n"); -#endif /* ENABLE_DNA */ - - fprintf(f, "dn: cn=ldbm database,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: ldbm database\n"); - fprintf(f, "nsslapd-pluginpath: %s/libback-ldbm%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: ldbm_back_init\n"); - fprintf(f, "nsslapd-plugintype: database\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: Syntax\n"); - fprintf(f, "nsslapd-plugin-depends-on-type: matchingRule\n"); - fprintf(f, "\n"); - - if (strlen(cf->suffix) == 0){ - rootdse = 1; - } - - /* Entries for the ldbm plugin */ - fprintf(f, "dn: cn=config,cn=ldbm database,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: config\n"); - fprintf(f, "nsslapd-lookthroughlimit: 5000\n"); - fprintf(f, "nsslapd-mode: 600\n"); - fprintf(f, "nsslapd-directory: %s\n", cf->db_dir); - fprintf(f, "nsslapd-dbcachesize: 10485760\n"); - /* will be default from 6.2 or 6.11... */ - if (getenv("USE_OLD_IDL_SWITCH")) { - fprintf(f, "nsslapd-idl-switch: old\n"); - } - fprintf(f, "\n"); - - /* Placeholder for the default user-defined ldbm indexes */ - fprintf(f, "dn: cn=default indexes, cn=config,cn=ldbm database,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: default indexes\n"); - fprintf(f, "\n"); - - /* default user-defined ldbm indexes */ - ds_gen_index(f, "cn=default indexes, cn=config,cn=ldbm database,cn=plugins,cn=config"); - - fprintf(f, "dn: cn=monitor, cn=ldbm database, cn=plugins, cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: monitor\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=database, cn=monitor, cn=ldbm database, cn=plugins, cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: database\n"); - fprintf(f, "\n"); - - /* Entries for the chaining backend plugin */ - fprintf(f, "dn: cn=chaining database,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsSlapdPlugin\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: chaining database\n"); - fprintf(f, "nsslapd-pluginpath: %s/libchainingdb-plugin%s\n", cf->plugin_dir, shared_lib); - fprintf(f, "nsslapd-plugininitfunc: chaining_back_init\n"); - fprintf(f, "nsslapd-plugintype: database\n"); - fprintf(f, "nsslapd-pluginenabled: on\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=config,cn=chaining database,cn=plugins,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: config\n"); - fprintf(f, "nsTransmittedControls: 2.16.840.1.113730.3.4.2\n"); - fprintf(f, "nsTransmittedControls: 2.16.840.1.113730.3.4.9\n"); - fprintf(f, "nsTransmittedControls: 1.2.840.113556.1.4.473\n"); - fprintf(f, "nsTransmittedControls: 1.3.6.1.4.1.1466.29539.12\n"); - fprintf(f, "nsPossibleChainingComponents: cn=resource limits,cn=components,cn=config\n"); - fprintf(f, "nsPossibleChainingComponents: cn=certificate-based authentication,cn=components,cn=config\n"); - fprintf(f, "nsPossibleChainingComponents: cn=ACL Plugin,cn=plugins,cn=config\n"); - fprintf(f, "nsPossibleChainingComponents: cn=old plugin,cn=plugins,cn=config\n"); - fprintf(f, "nsPossibleChainingComponents: cn=referential integrity postoperation,cn=plugins,cn=config\n"); - fprintf(f, "nsPossibleChainingComponents: cn=attribute uniqueness,cn=plugins,cn=config\n"); - fprintf(f, "\n"); - - free(t); - t = NULL; - - /* suffix for the mapping tree */ - fprintf(f, "dn: cn=mapping tree,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: mapping tree\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=tasks,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: tasks\n"); - fprintf(f, "\n"); - - if (!cf->use_existing_user_ds) - { - suffix_gen_conf(f, cf->suffix, "userRoot"); - } - - if ( cf->samplesuffix && cf->suffix && PL_strcasecmp(cf->samplesuffix, cf->suffix)) - { - suffix_gen_conf(f, cf->samplesuffix, "sampleRoot"); - } - - if ( cf->testconfig && cf->suffix && PL_strcasecmp(cf->testconfig, cf->suffix)) - { - suffix_gen_conf(f, cf->testconfig, "testRoot"); - } - - - /* tasks */ - fprintf(f, "dn: cn=import,cn=tasks,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: import\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=export,cn=tasks,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: export\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=backup,cn=tasks,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: backup\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=restore,cn=tasks,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: restore\n"); - fprintf(f, "\n"); - - fprintf(f, "dn: cn=upgradedb,cn=tasks,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: upgradedb\n"); - fprintf(f, "\n"); - /* END of tasks */ - - - fprintf(f, "dn: cn=replication,cn=config\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: extensibleObject\n"); - fprintf(f, "cn: replication\n"); - fprintf(f, "\n"); - - if( cf->replicationdn && *(cf->replicationdn) ) - { - fprintf(f, "dn: cn=replication4,cn=replication,cn=config\n"); - fprintf(f, "cn: replication4\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsConsumer4Config\n"); - fprintf(f, "nsslapd-updatedn: %s\n", cf->replicationdn); - fprintf(f, "nsslapd-updatepw: %s\n", cf->replicationhashedpw); - fprintf(f, "\n"); - } - - if(cf->changelogdir && *(cf->changelogdir) ) - { - fprintf(f, "dn: cn=changelog4,cn=config\n"); - fprintf(f, "cn: changelog4\n"); - fprintf(f, "objectclass: top\n"); - fprintf(f, "objectclass: nsChangelog4Config\n"); - fprintf(f, "nsslapd-changelogdir: %s\n", cf->changelogdir); - fprintf(f, "nsslapd-changelogsuffix: %s\n", cf->changelogsuffix); - fprintf(f, "nsslapd-changelogmaxage: 2d\n"); - fprintf(f, "\n"); - - /* create the changelog directory */ - if( (t = create_instance_mkdir_p("changelog dir", cf->changelogdir, NEWDIR_MODE, pw)) ) - return(t); - } - - fclose (f); - - PR_snprintf(src, sizeof(src), "%s%c%s", - cf->config_dir, FILE_PATHSEP, DS_CONFIG_FILE); - PR_snprintf(dest, sizeof(dest), "%s%c%s", - cf->config_dir, FILE_PATHSEP, DS_ORIGCONFIG_FILE); - create_instance_copy(src, dest, 0600, 0 ); - - /* install certmap.conf at <configdir> */ - PR_snprintf(src, sizeof(src), "%s%c%s%c/config/certmap.conf", - cf->sysconfdir, FILE_PATHSEP, cf->package_name, FILE_PATHSEP); - PR_snprintf(dest, sizeof(dest), "%s/certmap.conf", cf->config_dir); - create_instance_copy(src, dest, 0600, 0 ); - - /* generate <confdir>/slapd-collations.conf */ - PR_snprintf(src, sizeof(src), "%s%c%s%c/config/%s-collations.conf", - cf->sysconfdir, FILE_PATHSEP, cf->package_name, - FILE_PATHSEP, PRODUCT_NAME); - PR_snprintf(dest, sizeof(dest), "%s%c%s-collations.conf", - cf->config_dir, FILE_PATHSEP, PRODUCT_NAME); - if (!(srcf = fopen(src, "r"))) { - return make_error("Can't read from %s (%s)", src, ds_system_errmsg()); - } - if (!(f = fopen(dest, "w"))) { - return make_error("Can't write to %s (%s)", dest, ds_system_errmsg()); - } - while (fgets(line, sizeof(line), srcf)) { - if ((line[0] != '\0') && (fputs(line, f) == EOF)) { - make_error("Error writing to file %s from copy of %s (%s)", - dest, src, ds_system_errmsg()); - } - } - if (!feof(srcf)) { - make_error("Error reading from file %s (%s)", src, ds_system_errmsg()); - } - fclose(srcf); - fclose(f); - - if (cf->install_full_schema) { - /* - * <sysconfdir>/PACKAGE_NAME/schema to schema_dir - */ - PR_snprintf(src, sizeof(src), "%s%c%s%cschema", - cf->sysconfdir, FILE_PATHSEP, cf->package_name, FILE_PATHSEP); - if (NULL != (t = ds_copy_group_files_using_mode_owner(src, cf->schema_dir, 0, NEWFILE_MODE, pw))) - return t; - } else { - PR_snprintf(src, sizeof(src), "%s%c%s%cschema%c00core.ldif", - cf->sysconfdir, FILE_PATHSEP, cf->package_name, FILE_PATHSEP, FILE_PATHSEP); - PR_snprintf(dest, sizeof(dest), "%s%c00core.ldif", - cf->schema_dir, FILE_PATHSEP); - if( (t = create_instance_copy(src, dest, NEWFILE_MODE, 0 )) ) { - return t; - } else { - if (pw) { - chownfile(pw, dest); - } - } - } -#if defined (BUILD_PRESENCE) - PR_snprintf(src, sizeof(src), "%s%c%s%c/config/presence", - cf->sysconfdir, FILE_PATHSEP, cf->package_name, FILE_PATHSEP); - PR_snprintf(dest, sizeof(dest), "%s/presence", cf->config_dir); - if (t = ds_copy_group_files(src, dest, 0)) - return t; -#endif - -#if defined (ORGCHART) - /* Generate the orgchart configuration */ - PR_snprintf(src, sizeof(src), "%s/clients", sroot); - if (is_a_dir(src, "orgchart")) { - if (NULL != (t = ds_gen_orgchart_conf(sroot, cs_path, cf))) { - return t; - } - } -#endif - -#if defined (DSGW) - /* Generate dsgw.conf */ - PR_snprintf(src, sizeof(src), "%s/clients", sroot); - if (is_a_dir(src, "dsgw")) { - if (NULL != (t = ds_gen_gw_conf(sroot, cs_path, cf, GW_CONF))) { - return t; - } - - /* Generate pb.conf */ - if (NULL != (t = ds_gen_gw_conf(sroot, cs_path, cf, PB_CONF))) { - return t; - } - } -#endif - - return NULL; /* Everything worked fine */ -} - -/* - * Function: ds_gen_gw_conf - * - * Returns: pointer to error message, or NULL if all went well - * - * Description: This generates the gateway configuration files - * for the regular gateway stuff and for the phonebook. - * - * Author: RJP - * - */ -static char * -ds_gen_gw_conf(char *sroot, char *cs_path, server_config_s *cf, int conf_type) -{ - char dest[PATH_SIZE]; - char src[PATH_SIZE]; - char line[1024]; - FILE *f = NULL; - FILE *srcf = NULL; - char *t = NULL; - const char *ctxt; - - if (conf_type == GW_CONF) { - ctxt = "dsgw"; - } else { - ctxt = "pb"; - } - /* - * generate .../dsgw/context/[dsgw|pb].conf by creating the file, placing - * install-specific config. file lines at the start of file, and then - * copying the rest from NS-HOME/dsgw/config/dsgw.tmpl - */ - - PR_snprintf(dest, sizeof(dest), "%s%cclients%cdsgw%ccontext%c%s.conf", sroot, FILE_PATHSEP,FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP, ctxt); - - /* If the config file already exists, just return success */ - if (create_instance_exists(dest, PR_FILE_FILE)) { - return(NULL); - } - - /* Attempt to open that bad boy */ - if(!(f = fopen(dest, "w"))) { - return make_error("Can't write to %s (%s)", dest, ds_system_errmsg()); - } - - /* Write out the appropriate values */ - fprintf(f, "# Used by Directory Server Gateway\n"); - fprintf(f, "baseurl\t\"ldap://%s:%s/", cf->servname, cf->servport); - fputs_escaped(cf->suffix, f); - fputs("\"\n\n",f); - if (cf->rootdn && *(cf->rootdn)) { - t = ds_enquote_config_value(DS_ROOTDN, cf->rootdn); - fprintf(f, "dirmgr\t%s\n\n", t ); - if (t != cf->rootdn) free(t); - } - - t = ds_enquote_config_value(DS_SUFFIX, cf->suffix); - fprintf(f, "location-suffix\t%s\n\n", t); - if (t != cf->suffix) free(t); - - - fprintf(f, "securitypath\t\"%s%calias%c%s-cert.db\"\n\n", cf->cert_dir, FILE_PATHSEP, FILE_PATHSEP, ctxt ); - - fprintf(f, "# The url base to the orgchart application.\n#No link from the DSGW to the orgchart will appear in the UI if this configuration line is commented out.\n"); - fprintf(f, "url-orgchart-base\thttp://%s:%s/clients/orgchart/bin/org?context=%s&data=\n\n", cf->servname, cf->adminport ? cf->adminport : "80", ctxt); - - /* copy in template */ - if (conf_type == GW_CONF) { - PR_snprintf(src, sizeof(src), "%s%cclients%cdsgw%cconfig%cdsgw.tmpl", - sroot, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP); - } else if (conf_type == PB_CONF) { - PR_snprintf(src, sizeof(src), "%s%cclients%cdsgw%cpbconfig%cpb.tmpl", - sroot, FILE_PATHSEP,FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP); - } else { - /*This should never, ever happen if this function is called correctly*/ - fclose(f); - return make_error("Unknown gateway config file requested"); - } - - - /* Try to open the dsgw.conf template file (dsgw.tmpl) */ - if(!(srcf = fopen(src, "r"))) { - fclose(f); - return make_error("Can't read %s (%s)", src, ds_system_errmsg()); - } - - while(fgets(line, sizeof(line), srcf)) { - fputs(line, f); - } - - fclose(srcf); - fclose(f); - - /* Generate default.conf */ - if (conf_type == GW_CONF) { - struct passwd* pw = NULL; - char defaultconf[PATH_SIZE]; - -#if !defined( XP_WIN32 ) - /* find the server's UID and GID */ - if (cf->servuser && *(cf->servuser)) { - if ((pw = getpwnam (cf->servuser)) == NULL) { - return make_error("Could not find UID and GID of user '%s'.", cf->servuser); - } else if (pw->pw_name == NULL) { - pw->pw_name = cf->servuser; - } - } -#endif - - PR_snprintf(defaultconf, sizeof(defaultconf), "%s%cclients%cdsgw%ccontext%cdefault.conf", sroot, - FILE_PATHSEP,FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP); - - create_instance_copy(dest, defaultconf, NEWFILE_MODE, 0 ); - chownfile (pw, defaultconf); - } - unlink(src); - - return NULL; -} - - -/* - * Function: ds_gen_orgchart_conf - * - * Returns: pointer to error message, or NULL if all went well - * - * Description: This generates the orgchart configuration file - * - * Author: RJP - * - */ -static char * -ds_gen_orgchart_conf(char *sroot, char *cs_path, server_config_s *cf) -{ - char dest[PATH_SIZE]; - char src[PATH_SIZE]; - char line[1024]; - FILE *f = NULL; - FILE *srcf = NULL; - - /* - * generate .../clients/orgchart/config.txt by creating the file, placing - * install-specific config. file lines at the start of file, and then - * copying the rest from NS-HOME/clients/orgchart/config.tmpl - */ - PR_snprintf(dest, sizeof(dest), "%s%cclients%corgchart%cconfig.txt", sroot, FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP ); - PR_snprintf(src, sizeof(src), "%s%cclients%corgchart%cconfig.tmpl", sroot, FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP); - - /* If the config file already exists, just return success */ - if (create_instance_exists(dest, PR_FILE_FILE)) { - return(NULL); - } - - /* Attempt to open that bad boy */ - if(!(f = fopen(dest, "w"))) { - return make_error("Cannot write to %s (%s)", dest, ds_system_errmsg()); - } - - /* Write out the appropriate values */ - fprintf(f, "#############\n#\n#\n"); - fprintf(f, "# Configuration file for Directory Server Org Chart\n"); - fprintf(f, "# ----------------------------------------------------------\n#\n#\n"); - fprintf(f, "#############\n\n\n#\n"); - fprintf(f, "# Blank lines in this file, as well as lines that\n"); - fprintf(f, "# start with at least one \"#\" character, are both ignored.\n"); - fprintf(f, "#\n#\n"); - fprintf(f, "# Name/Value pairs below are (and need to be) separated with\n"); - fprintf(f, "# one or more tabs (or spaces)\n"); - fprintf(f, "#\n"); - - fprintf(f, "ldap-host\t%s\n", cf->servname); - fprintf(f, "ldap-port\t%s\n", cf->servport); - fprintf(f, "ldap-search-base\t%s\n\n", cf->suffix); - - fprintf(f, "#\n# If you would like to have the phonebook icon visible, you must\n"); - fprintf(f, "# supply the partial phonebook URL below, which will have each\n"); - fprintf(f, "# given user's DN attribute value concatenated to the end.\n"); - fprintf(f, "#\n# For example, you could specify below something close to:\n"); - fprintf(f, "#\n# url-phonebook-base http://hostname.domain.com/dsgw/bin/dosearch?context=default&hp=localhost&dn=\n#\n\n"); - fprintf(f, "url-phonebook-base\thttp://%s:%s/clients/dsgw/bin/dosearch?context=pb&hp=%s:%s&dn=\n\n",cf->servname, cf->adminport ? cf->adminport : "80", cf->servname, cf->servport); - - /* Try to open the config.txt template file (config.tmpl) */ - if(!(srcf = fopen(src, "r"))) { - fclose(f); - return make_error("Can't read %s (%s)", src, ds_system_errmsg()); - } - - while(fgets(line, sizeof(line), srcf)) { - fputs(line, f); - } - - fclose(srcf); - fclose(f); - - unlink(src); - return NULL; -} - -#if defined (BUILD_PRESENCE) -/* - * Function: gen_presence_init - * - * Description: Creates a script to initialize images for use in the IM - * Presence plugin. - */ -#define PRESENCE_LDIF "init_presence_images.ldif" -static char *gen_presence_init_script(char *sroot, server_config_s *cf, - char *cs_path) -{ - char fn[PATH_SIZE]; - char dir[PATH_SIZE]; - FILE *f; - - PR_snprintf(dir, sizeof(dir), "%s%cconfig%cpresence", - cs_path, FILE_PATHSEP, FILE_PATHSEP); - PR_snprintf(fn, sizeof(fn), "%s%c%s", - dir, FILE_PATHSEP, PRESENCE_LDIF); - - if(!(f = fopen(fn, "w"))) - return make_error("Could not write to %s (%s).", fn, ds_system_errmsg()); - - fprintf( f, - "dn:cn=ICQ Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-onvaluemapgraphic\n" - "nsim-onvaluemapgraphic: %s%cicq-online.gif\n" - "\n" - "dn:cn=ICQ Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-offvaluemapgraphic\n" - "nsim-offvaluemapgraphic: %s%cicq-offline.gif\n" - "\n" - "dn:cn=ICQ Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-disabledvaluemapgraphic\n" - "nsim-disabledvaluemapgraphic: %s%cicq-disabled.gif\n" - "\n" - "dn:cn=AIM Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-onvaluemapgraphic\n" - "nsim-onvaluemapgraphic: %s%caim-online.gif\n" - "\n" - "dn:cn=AIM Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-offvaluemapgraphic\n" - "nsim-offvaluemapgraphic: %s%caim-offline.gif\n" - "\n" - "dn:cn=AIM Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-disabledvaluemapgraphic\n" - "nsim-disabledvaluemapgraphic: %s%caim-offline.gif\n" - "\n" - "dn:cn=Yahoo Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-offvaluemapgraphic\n" - "nsim-offvaluemapgraphic: %s%cyahoo-offline.gif\n" - "\n" - "dn:cn=Yahoo Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-onvaluemapgraphic\n" - "nsim-onvaluemapgraphic: %s%cyahoo-online.gif\n" - "\n" - "dn:cn=Yahoo Presence,cn=Presence,cn=plugins,cn=config\n" - "changeType:modify\n" - "replace:nsim-disabledvaluemapgraphic\n" - "nsim-disabledvaluemapgraphic: %s%cyahoo-offline.gif\n", - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP, - dir, FILE_PATHSEP - ); - fclose(f); - return NULL; -} - -/* - * Function init_presence - * - * Description: Runs ldapmodify to initialize the images used by the - * IM presence plugin - */ -static int init_presence(char *sroot, server_config_s *cf, char *cs_path) -{ - char cmd[PATH_SIZE]; - char tools[PATH_SIZE]; - char precmd[PATH_SIZE]; - - precmd[0] = 0; - PR_snprintf(tools, sizeof(tools), "%s%cshared%cbin", - cf->prefix, FILE_PATHSEP, FILE_PATHSEP); - -#ifdef XP_UNIX - PR_snprintf(precmd, sizeof(precmd), "cd %s;", tools); -#endif - - PR_snprintf(cmd, sizeof(cmd), "%s%s%cldapmodify -q -p %d -b -D \"%s\" -w \"%s\" " - "-f %s%s%cconfig%cpresence%c%s%s", - precmd, - tools, FILE_PATHSEP, - atoi(cf->servport), - cf->rootdn, - cf->rootpw, - ENQUOTE, cs_path, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, - PRESENCE_LDIF, ENQUOTE); - return ds_exec_and_report( cmd ); -} -#endif - -/* - * Function: ds_gen_index - * - * Description: This generates the default index list. - * This function is passed the parent entry below which the nsIndex - * entries must be created. This allows to use it when creating: - * - the default index list (ie belowdn = cn=default indexes,cn=config...) - * - the userRoot backend (ie belowdn = cn=index,cn=userRoot...) - * - */ -static void -ds_gen_index(FILE* f, char* belowdn) -{ -#define MKINDEX(_name, _inst, _sys, _type1, _type2, _type3) do { \ - char *_type2str = (_type2), *_type3str = (_type3); \ - fprintf(f, "dn: cn=%s,%s\n", (_name), (_inst)); \ - fprintf(f, "objectclass: top\n"); \ - fprintf(f, "objectclass: nsIndex\n"); \ - fprintf(f, "cn: %s\n", (_name)); \ - fprintf(f, "nssystemindex: %s\n", (_sys) ? "true" : "false"); \ - if (_type1) \ - fprintf(f, "nsindextype: %s\n", (_type1)); \ - if (_type2str) \ - fprintf(f, "nsindextype: %s\n", _type2str); \ - if (_type3str) \ - fprintf(f, "nsindextype: %s\n", _type3str); \ - fprintf(f, "\n"); \ -} while (0) - - MKINDEX("aci", belowdn, 1, "pres", NULL, NULL); - MKINDEX("cn", belowdn, 0, "pres", "eq", "sub"); - MKINDEX("entrydn", belowdn, 1, "eq", NULL, NULL); - MKINDEX("givenName", belowdn, 0, "pres", "eq", "sub"); - MKINDEX("mail", belowdn, 0, "pres", "eq", "sub"); - MKINDEX("mailAlternateAddress", belowdn, 0, "eq", NULL, NULL); - MKINDEX("mailHost", belowdn, 0, "eq", NULL, NULL); - MKINDEX("member", belowdn, 0, "eq", NULL, NULL); - MKINDEX("nsCalXItemId", belowdn, 0, "pres", "eq", "sub"); - MKINDEX("nsLIProfileName", belowdn, 0, "eq", NULL, NULL); - MKINDEX("nsUniqueId", belowdn, 1, "eq", NULL, NULL); - MKINDEX("nswcalCALID", belowdn, 0, "eq", NULL, NULL); - MKINDEX("numsubordinates", belowdn, 1, "pres", NULL, NULL); - MKINDEX("objectclass", belowdn, 1, "eq", NULL, NULL); - MKINDEX("owner", belowdn, 0, "eq", NULL, NULL); - MKINDEX("parentid", belowdn, 1, "eq", NULL, NULL); - MKINDEX("pipstatus", belowdn, 0, "eq", NULL, NULL); - MKINDEX("pipuid", belowdn, 0, "pres", NULL, NULL); - MKINDEX("seeAlso", belowdn, 0, "eq", NULL, NULL); - MKINDEX("sn", belowdn, 0, "pres", "eq", "sub"); - MKINDEX("telephoneNumber", belowdn, 0, "pres", "eq", "sub"); - MKINDEX("uid", belowdn, 0, "eq", NULL, NULL); - MKINDEX("ntUniqueId", belowdn, 0, "eq", NULL, NULL); - MKINDEX("ntUserDomainId", belowdn, 0, "eq", NULL, NULL); - MKINDEX("uniquemember", belowdn, 0, "eq", NULL, NULL); -} - - - -static char *install_ds(char *sroot, server_config_s *cf, char *param_name) -{ - SLAPD_CONFIG slapd_conf; - QUERY_VARS query_vars; - char *t, src[PATH_SIZE], dest[PATH_SIZE], big_line[PATH_SIZE]; - struct passwd* pw = NULL; - int isrunning; - int status = 0; -#ifdef XP_WIN32 - WSADATA wsadata; -#endif - -#if !defined( XP_WIN32 ) - /* find the server's UID and GID */ - if (cf->servuser && *(cf->servuser)) { - if ((pw = getpwnam (cf->servuser)) == NULL) { - PL_strncpyz(param_name, "servuser", BIG_LINE); - return make_error("Could not find UID and GID of user '%s'.", - cf->servuser); - } else if (pw->pw_name == NULL) { - pw->pw_name = cf->servuser; - } - } -#endif - - /* create all <a_server>/<subdirs> */ - if ( (t = ds_cre_subdirs(cf, pw)) ) - return(t); - - /* Generate all scripts */ - if ( (t = ds_gen_scripts(sroot, cf, cf->inst_dir)) ) - return(t); - -#if defined( XP_WIN32 ) - ds_dostounixpath( sroot ); - ds_dostounixpath( cf->inst_dir ); -#endif - - /* Generate all conf files */ - if ( (t = ds_gen_confs(sroot, cf, cf->inst_dir)) ) - return(t); - -#ifdef DSML - /* new code for dsml sample files */ - PR_snprintf(src, sizeof(src), - "%s%cbin%c"PRODUCT_NAME"%cinstall%cdsml%cExample.dsml", - cf->prefix, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP); - PR_snprintf(dest, sizeof(dest), "%s%cdsml%cExample.dsml", - bogus, FILE_PATHSEP, FILE_PATHSEP); - create_instance_copy(src, dest, NEWFILE_MODE, 1); - chownfile (pw, dest); - - PR_snprintf(src, sizeof(src), - "%s%cbin%c"PRODUCT_NAME"%cinstall%cdsml%cExample-roles.dsml", - cf->prefix, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP); - PR_snprintf(dest, sizeof(dest), "%s%cdsml%cExample-roles.dsml", - bogus, FILE_PATHSEP, FILE_PATHSEP); - create_instance_copy(src, dest, NEWFILE_MODE, 1); - chownfile (pw, dest); - - PR_snprintf(src, sizeof(src), - "%s%cbin%c"PRODUCT_NAME"%cinstall%cdsml%cEuropean.dsml", - sroot, FILE_PATHSEP, FILE_PATHSEP, FILE_PATHSEP, - FILE_PATHSEP, FILE_PATHSEP); - PR_snprintf(dest, sizeof(dest), "%s%cdsml%cEuropean.dsml", - bogus, FILE_PATHSEP, FILE_PATHSEP); - create_instance_copy(src, dest, NEWFILE_MODE, 1); - chownfile (pw, dest); -#endif - - /* - If the user has specified an LDIF file to use to initialize the database, - load it now - */ - if (cf->install_ldif_file && !access(cf->install_ldif_file, 0)) - { - char msg[2*PATH_SIZE] = {0}; - int status = ds_ldif2db_backend_subtree(cf->install_ldif_file, NULL, cf->suffix); - if (status) - PR_snprintf(msg, sizeof(msg), "The file %s could not be loaded", - cf->install_ldif_file); - else - PR_snprintf(msg, sizeof(msg), "The file %s was successfully loaded", - cf->install_ldif_file); - ds_show_message(msg); - free(cf->install_ldif_file); - cf->install_ldif_file = NULL; - } - - /* - All of the config files have been written, and the server should - be ready to go. Start the server if the user specified to start - it or if we are configuring the server to serve as the repository - for SuiteSpot (Mission Control) information - Only attempt to start the server if the port is not in use - In order to start the server, there must either be an ldapifilepath - specified or a valid port. If the port is not "0" it must be valid. - */ - if(needToStartServer(cf) && !(t = create_instance_checkports(cf))) - { - PR_snprintf(big_line, sizeof(big_line),"SERVER_NAMES=slapd-%s",cf->servid); - putenv(big_line); - - isrunning = ds_get_updown_status(); - - if (isrunning != DS_SERVER_UP) - { - int start_status = 0; - int verbose = 1; - char errorlog[PATH_SIZE]; - - if (getenv("USE_DEBUGGER")) - verbose = 0; - /* error log file */ - PR_snprintf(errorlog, sizeof(errorlog), "%s%cerrors", cf->log_dir, FILE_PATHSEP); - start_status = ds_bring_up_server_install(verbose, cf->inst_dir, errorlog); - - if (start_status != DS_SERVER_UP) - { - /* - If we were going to configure the server for SuiteSpot (Mission - Control), the server must be running. Therefore, it is a very - bad thing, and we want to exit with a non zero exit code so the - caller will know something went wrong. - Otherwise, if the user just wanted to start the server for some - reason, just exit with a zero and the messages printed will - let the user know the server wasn't started. - */ - char *msg; - if (start_status == DS_SERVER_PORT_IN_USE) - msg = "The server could not be started because the port is in use."; - else if (start_status == DS_SERVER_MAX_SEMAPHORES) - msg = "No more servers may be installed on this system.\nPlease refer to documentation for information about how to\nincrease the number of installed servers per system."; - else if (start_status == DS_SERVER_CORRUPTED_DB) - msg = "The server could not be started because the database is corrupted."; - else if (start_status == DS_SERVER_NO_RESOURCES) - msg = "The server could not be started because the operating system is out of resources (e.g. CPU memory)."; - else if (start_status == DS_SERVER_COULD_NOT_START) - msg = "The server could not be started due to invalid command syntax or operating system resource limits."; - else - msg = "The server could not be started."; - - if( cf->cfg_sspt && !strcmp(cf->cfg_sspt, "1") ) - { - ds_report_error(DS_SYSTEM_ERROR, "server", msg); - return msg; - } - else - { - ds_show_message(msg); - return 0; - } - } - else - { - ds_show_message("Your new directory server has been started."); - } - } - -#ifdef XP_UNIX - ds_become_localuser_name (cf->servuser); -#endif -#ifdef XP_WIN32 - if( errno = WSAStartup(0x0101, &wsadata ) != 0 ) - { - char szTmp[512]; - /*replaced errno > -1 && errno < sys_nerr ? sys_errlist[errno] : - "unknown" with strerror(errno)*/ - PR_snprintf(szTmp, sizeof(szTmp), "Error: Windows Sockets initialization failed errno %d (%s)<br>\n", errno, - strerror(errno), 0 ); - - fprintf (stdout, szTmp); - return 0; - } -#endif /* XP_WIN32 */ - - /* if an already hashed password is given, we cannot do the configure_suitespot() - stuff below, because that requires the clear text password in order to - bind to the server. This also means that default entries and default - acis will not be added to the server. - */ - if (cf->rootpw == cf->roothashedpw) { - if (status) - return make_error ("Could not configure server (%d).", status); - return NULL; - } - - memset( &query_vars, 0, sizeof(query_vars) ); - if (!cf->use_existing_user_ds) - query_vars.suffix = create_instance_strdup( cf->suffix ); - query_vars.ssAdmID = create_instance_strdup( cf->cfg_sspt_uid ); - query_vars.ssAdmPW1 = create_instance_strdup( cf->cfg_sspt_uidpw ); - query_vars.ssAdmPW2 = create_instance_strdup( cf->cfg_sspt_uidpw ); - query_vars.rootDN = create_instance_strdup( cf->rootdn ); - query_vars.rootPW = create_instance_strdup( cf->rootpw ); - query_vars.admin_domain = create_instance_strdup( cf->admin_domain ); - query_vars.netscaperoot = create_instance_strdup( cf->netscaperoot ); - query_vars.testconfig = create_instance_strdup( cf->testconfig ); - query_vars.consumerDN = create_instance_strdup(cf->consumerdn); - query_vars.consumerPW = create_instance_strdup(cf->consumerhashedpw); - if (cf->cfg_sspt && !strcmp(cf->cfg_sspt, "1")) - query_vars.cfg_sspt = 1; - else - query_vars.cfg_sspt = 0; - - query_vars.config_admin_uid = create_instance_strdup(cf->cfg_sspt_uid); - - memset(&slapd_conf, 0, sizeof(SLAPD_CONFIG)); - if (sroot) - PL_strncpyz(slapd_conf.slapd_server_root, sroot, sizeof(slapd_conf.slapd_server_root)); - if (cf->servport) - slapd_conf.port = atoi(cf->servport); - if (cf->servname) - PL_strncpyz(slapd_conf.host, cf->servname, sizeof(slapd_conf.host)); - - status = config_suitespot(&slapd_conf, &query_vars); - if (status == -1) /* invalid or null arguments or configuration */ - return "Invalid arguments for server configuration."; - } - else if (t) /* just notify the user about the port conflict */ - { - ds_show_message(t); - } - -#if defined (BUILD_PRESENCE) - /* Create script for initializing IM Presence images */ - if ((NULL == t) && (0 == status)) - { - if ( (t = gen_presence_init_script(sroot, cf, cf->inst_dir)) ) - return(t); - /* Initialize IM Presence images */ - status = init_presence(sroot, cf, cf->inst_dir); - if (status) - return make_error ("ds_exec_and_report() failed (%d).", status); - } -#endif - - if (status) - return make_error ("Could not configure server (%d).", status); - - return(NULL); -} - -/* ----------- Create a new server from configuration variables ----------- */ - - -int create_config(server_config_s *cf) -{ - char *t = NULL; - char error_param[BIG_LINE] = {0}; - - t = create_server(cf, error_param); - if(t) - { - char *msg; - if (error_param[0]) - { - msg = PR_smprintf("%s.error:could not create server %s - %s", - error_param, cf->servid, t); - } - else - { - msg = PR_smprintf("error:could not create server %s - %s", - cf->servid, t); - } - ds_show_message(msg); - PR_smprintf_free(msg); - } - else - { - ds_show_message("Created new Directory Server"); - return 0; - } - - return 1; -} - - -/* ------ check passwords are same and satisfy minimum length policy------- */ -static int check_passwords(char *pw1, char *pw2) -{ - if (strcmp (pw1, pw2) != 0) { - ds_report_error (DS_INCORRECT_USAGE, " different passwords", - "Enter the password again." - " The two passwords you entered are different."); - return 1; - } - - if ( ((int) strlen(pw1)) < 8 ) { - ds_report_error (DS_INCORRECT_USAGE, " password too short", - "The password must be at least 8 characters long."); - return 1; - } - - return 0; -} - -static char * -set_path_attribute(char *attr, char *defaultval, char *prefix) -{ - char *temp = ds_a_get_cgi_var(attr, NULL, NULL); - char *rstr = NULL; - if (prefix && strlen(prefix) > 0) { - if (NULL == temp || '\0' == *temp) { - if (NULL == defaultval) { - rstr = PR_smprintf("%s", prefix); - } else if (FILE_PATHSEP == *defaultval) { - rstr = PR_smprintf("%s%s", prefix, defaultval); - } else { - rstr = PR_smprintf("%s%c%s", prefix, FILE_PATHSEP, defaultval); - } - } else { - if (NULL == temp) { - rstr = PR_smprintf("%s", prefix); - } else if (FILE_PATHSEP == *temp) { - rstr = PR_smprintf("%s%s", prefix, temp); - } else { - rstr = PR_smprintf("%s%c%s", prefix, FILE_PATHSEP, temp); - } - } - } else { - if (NULL == temp || '\0' == *temp) { - rstr = defaultval; - } else { - rstr = PL_strdup(temp); - } - } - return rstr; -} - -/* ------ Parse the results of a form and create a server from them ------- */ -/* - * FHS description - * cf->prefix: %{_prefix} - * cf->sroot: %{_libdir}/PACKAGE_NAME - * cf->localstatedir: %{_localstatedir} - * cf->sysconfdir: %{_sysconfdir} - * cf->bindir: %{_bindir} - * cf->sbindir: %{_sbindir} - * cf->datadir: %{_datadir} - * cf->docdir: %{_docdir} - * cf->inst_dir: <sroot>/slapd-<servid> - * cf->config_dir: <localstatedir>/lib/PACKAGE_NAME/slapd-<servid> - * cf->schema_dir: <localstatedir>/lib/PACKAGE_NAME/slapd-<servid>/schema - * cf->lock_dir: <localstatedir>/lock/PACKAGE_NAME/slapd-<servid> - * cf->log_dir: <localstatedir>/log/PACKAGE_NAME/slapd-<servid> - * cf->run_dir: <localstatedir>/run/PACKAGE_NAME (slapd-instance.pid slapd-instance.startpid files) - * cf->db_dir: <localstatedir>/lib/PACKAGE_NAME/slapd-<servid>/db - * cf->bak_dir: <localstatedir>/lib/PACKAGE_NAME/slapd-<servid>/bak - * cf->tmp_dir: <localstatedir>/tmp/PACKAGE_NAME/slapd-<servid> - * cf->ldif_dir: <datadir>/<brand-ds>/ldif - * cf->cert_dir: <sysconfdir>/PACKAGE_NAME/slapd-<servid> - * cf->sasl_path: %{_libdir}/sasl2 - * cf->plugin_dir: <sroot>/plugins - * - * NOTES: - * If prefix is given, all the other paths start from prefix. - * NETSITE_ROOT is treated as a secondary prefix. (If prefix is also set, - * it's ignored. If prefix is not set, NETSITE_ROOT becomes prefix. - * If both are not set, the paths start from '/'.) - * Therefore, NETSITE_ROOT is not mandatory any more. - */ - -int parse_form(server_config_s *cf) -{ - char *rm = getenv("REQUEST_METHOD"); - char *qs = getenv("QUERY_STRING"); - char *cfg_sspt_uid_pw1 = NULL; - char *cfg_sspt_uid_pw2 = NULL; - char *temp = NULL; - char *prefix = NULL; - int prefixlen = 0; - LDAPURLDesc *desc = 0; - - cf->package_name = PACKAGE_NAME; - if (rm && qs && !strcmp(rm, "GET")) - { - ds_get_begin(qs); - } - else if (ds_post_begin(stdin)) - { - return 1; - } - - if (rm) - { - printf("Content-type: text/plain\n\n"); - } - /* else we are being called from server installation; no output */ - - prefix = getenv("NETSITE_ROOT"); - temp = ds_a_get_cgi_var("prefix", NULL, NULL); - if (NULL != temp) { - prefix = cf->prefix = PL_strdup(temp); - } else if (NULL != prefix) { - cf->prefix = PL_strdup(prefix); /* value of NETSITE_ROOT */ - } else { - prefix = cf->prefix = PL_strdup("/"); - } - -#if defined (IS_FHS_OPT) - cf->sroot = PR_smprintf("%sopt%c%s", prefix, FILE_PATHSEP, cf->package_name); -#else - cf->sroot = PR_smprintf("%s%s%c%s", - prefix, LIBDIR, FILE_PATHSEP, cf->package_name); -#endif - - temp = ds_a_get_cgi_var("sasl_path", NULL, NULL); - if (NULL != temp) { - /* if sasl_path is given, we set it in the conf file regardless of - * the platform. */ - cf->sasl_path = PL_strdup(temp); - } -#if !defined( LINUX ) - /* if not linux, we package sasl2 with DS, - and always set it in the conf file. */ - else - { - cf->sasl_path = PR_smprintf("%s%s%csasl2", prefix, LIBDIR, FILE_PATHSEP); - } -#endif - -#if defined (IS_FHS_OPT) - cf->plugin_dir = PR_smprintf("%s%s%cplugins", prefix, LIBDIR, FILE_PATHSEP); -#else - cf->plugin_dir = PR_smprintf("%s%cplugins", cf->sroot, FILE_PATHSEP); -#endif - - if (!(cf->servname = ds_a_get_cgi_var("servname", "Server Name", - "Please give a hostname for your server."))) - { - return 1; - } - - cf->bindaddr = ds_a_get_cgi_var("bindaddr", NULL, NULL); -#if defined(ENABLE_LDAPI) - temp = ds_a_get_cgi_var("ldapifilepath", NULL, NULL); - if (NULL != temp) { - cf->ldapifilepath = PL_strdup(temp); - } -#endif - - temp = ds_a_get_cgi_var("servport", NULL, NULL); - if (!temp -#if defined(ENABLE_LDAPI) - && !cf->ldapifilepath -#endif - ) { -#if defined(ENABLE_LDAPI) - ds_show_message("error: either servport or ldapifilepath must be specified."); -#else - ds_show_message("error: servport must be specified."); -#endif - return 1; - } - - if (NULL != temp) { - cf->servport = PL_strdup(temp); - } else { - cf->servport = PL_strdup("0"); - } - - cf->cfg_sspt = ds_a_get_cgi_var("cfg_sspt", NULL, NULL); - cf->cfg_sspt_uid = ds_a_get_cgi_var("cfg_sspt_uid", NULL, NULL); - if (cf->cfg_sspt_uid && *(cf->cfg_sspt_uid) && - !(cf->cfg_sspt_uidpw = ds_a_get_cgi_var("cfg_sspt_uid_pw", NULL, NULL))) - { - - if (!(cfg_sspt_uid_pw1 = ds_a_get_cgi_var("cfg_sspt_uid_pw1", "Password", - "Enter the password for the Mission Control Administrator's account."))) - { - return 1; - } - - if (!(cfg_sspt_uid_pw2 = ds_a_get_cgi_var("cfg_sspt_uid_pw2", "Password", - "Enter the password for the Mission Control Administrator account, " - "twice."))) - { - return 1; - } - - if (strcmp (cfg_sspt_uid_pw1, cfg_sspt_uid_pw2) != 0) - { - ds_report_error (DS_INCORRECT_USAGE, " different passwords", - "Enter the Mission Control Administrator account password again." - " The two Mission Control Administrator account passwords " - "you entered are different."); - return 1; - } - if ( ((int) strlen(cfg_sspt_uid_pw1)) < 1 ) { - ds_report_error (DS_INCORRECT_USAGE, " password too short", - "The password must be at least 1 character long."); - return 1; - } - cf->cfg_sspt_uidpw = cfg_sspt_uid_pw1; - } - - if (cf->cfg_sspt && *cf->cfg_sspt && !strcmp(cf->cfg_sspt, "1") && - !cf->cfg_sspt_uid) - { - ds_report_error (DS_INCORRECT_USAGE, - " Userid not specified", - "A Userid for Mission Control Administrator must be specified."); - return 1; - } - cf->start_server = ds_a_get_cgi_var("start_server", NULL, NULL); - if (temp = ds_a_get_cgi_var("install_full_schema", NULL, NULL)) { - cf->install_full_schema = atoi(temp); - } - cf->secserv = ds_a_get_cgi_var("secserv", NULL, NULL); - if (cf->secserv && strcmp(cf->secserv, "off")) - cf->secservport = ds_a_get_cgi_var("secservport", NULL, NULL); - if (!(cf->servid = ds_a_get_cgi_var("servid", "Server Identifier", - "Please give your server a short identifier."))) - { - return 1; - } - -#ifdef XP_UNIX - cf->servuser = ds_a_get_cgi_var("servuser", NULL, NULL); -#endif - - cf->suffix = dn_normalize_convert(ds_a_get_cgi_var("suffix", NULL, NULL)); - - if (cf->suffix == NULL) { - cf->suffix = ""; - } - - cf->rootdn = dn_normalize_convert(ds_a_get_cgi_var("rootdn", NULL, NULL)); - if (cf->rootdn && *(cf->rootdn)) { - if (!(cf->rootpw = ds_a_get_cgi_var("rootpw", NULL, NULL))) - { - char* pw1 = ds_a_get_cgi_var("rootpw1", "Password", - "Enter the password for the unrestricted user."); - char* pw2 = ds_a_get_cgi_var("rootpw2", "Password", - "Enter the password for the unrestricted user, twice."); - - if (!pw1 || !pw2 || check_passwords(pw1, pw2)) - { - return 1; - } - - cf->rootpw = pw1; - } - if (strchr(cf->rootpw, '}') && - (!PL_strncasecmp(cf->rootpw, "{SHA", 4) || - !PL_strncasecmp(cf->rootpw, "{SSHA", 5) || - !PL_strncasecmp(cf->rootpw, "{CRYPT}", 7) || - !PL_strncasecmp(cf->rootpw, "{MD5}", 5))) { - /* assume the password is already hashed */ - cf->roothashedpw = cf->rootpw; - } else { /* assume cleartext password */ - /* Encode the password in SSHA by default */ - cf->roothashedpw = (char *)ds_salted_sha1_pw_enc (cf->rootpw); - } - } - - cf->admin_domain = ds_a_get_cgi_var("admin_domain", NULL, NULL); - - if ((temp = ds_a_get_cgi_var("use_existing_user_ds", NULL, NULL))) { - cf->use_existing_user_ds = atoi(temp); - } else { - cf->use_existing_user_ds = 0; /* we are creating it */ - } - - /* if being called as a CGI, the user_ldap_url will be the directory - we're creating */ - /* this is the directory we're creating, and we cannot create an ssl - directory, so we don't have to worry about ldap vs ldaps here */ - if ((temp = ds_a_get_cgi_var("user_ldap_url", NULL, NULL))) { - cf->user_ldap_url = strdup(temp); - } else { - cf->user_ldap_url = PR_smprintf("ldap://%s:%s/%s", cf->servname, - cf->servport, cf->suffix); - } - - cf->samplesuffix = NULL; - - cf->disable_schema_checking = ds_a_get_cgi_var("disable_schema_checking", - NULL, NULL); - - cf->adminport = ds_a_get_cgi_var("adminport", NULL, NULL); - - cf->install_ldif_file = ds_a_get_cgi_var("install_ldif_file", NULL, NULL); - - cf->localstatedir = set_path_attribute("localstatedir", LOCALSTATEDIR, prefix); - cf->sysconfdir = set_path_attribute("sysconfdir", SYSCONFDIR, prefix); - cf->bindir = set_path_attribute("bindir", BINDIR, prefix); - cf->sbindir = set_path_attribute("sbindir", SBINDIR, prefix); - cf->datadir = set_path_attribute("datadir", DATADIR, prefix); - cf->docdir = set_path_attribute("docdir", DOCDIR, prefix); - - temp = ds_a_get_cgi_var("inst_dir", NULL, NULL); - if (NULL == temp) { - cf->inst_dir = PR_smprintf("%s%c%s-%s", - cf->sroot, FILE_PATHSEP, PRODUCT_NAME, cf->servid); - } else { - cf->inst_dir = PL_strdup(temp); - } - - temp = ds_a_get_cgi_var("config_dir", NULL, NULL); - if (NULL == temp) { - cf->config_dir = PR_smprintf("%s%c%s%c%s-%s", - cf->sysconfdir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid); - } else { - cf->config_dir = PL_strdup(temp); - } - /* set config dir to the environment variable DS_CONFIG_DIR */ - ds_set_config_dir(cf->config_dir); - - cf->schema_dir = ds_a_get_cgi_var("schema_dir", NULL, NULL); - temp = ds_a_get_cgi_var("schema_dir", NULL, NULL); - if (NULL == temp) { - cf->schema_dir = PR_smprintf("%s%c%s%c%s-%s%cschema", - cf->sysconfdir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); - } else { - cf->schema_dir = PL_strdup(temp); - } - - temp = ds_a_get_cgi_var("lock_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->lock_dir = PR_smprintf("%s%c%s%c%s-%s%clock", - cf->localstatedir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#else - cf->lock_dir = PR_smprintf("%s%clock%c%s%c%s-%s", - cf->localstatedir, FILE_PATHSEP, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid); -#endif - } else { - cf->lock_dir = PL_strdup(temp); - } - - temp = ds_a_get_cgi_var("log_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->log_dir = PR_smprintf("%s%c%s%c%s-%s%clog", - cf->localstatedir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#else - cf->log_dir = PR_smprintf("%s%clog%c%s%c%s-%s", - cf->localstatedir, FILE_PATHSEP, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid); -#endif - } else { - cf->log_dir = PL_strdup(temp); - } - - temp = ds_a_get_cgi_var("run_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->run_dir = PR_smprintf("%s%c%s%c%s-%s%crun", - cf->localstatedir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#else - cf->run_dir = PR_smprintf("%s%crun%c%s", - cf->localstatedir, FILE_PATHSEP, FILE_PATHSEP, - cf->package_name); -#endif - } else { - cf->run_dir = PL_strdup(temp); - } - /* set run dir to the environment variable DS_RUN_DIR */ - ds_set_run_dir(cf->run_dir); - - temp = ds_a_get_cgi_var("db_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->db_dir = PR_smprintf("%s%c%s%c%s-%s%cdb", - cf->localstatedir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#else - cf->db_dir = PR_smprintf("%s%clib%c%s%c%s-%s%cdb", - cf->localstatedir, FILE_PATHSEP, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#endif - } else { - cf->db_dir = PL_strdup(temp); - } - - temp = ds_a_get_cgi_var("bak_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->bak_dir = PR_smprintf("%s%c%s%c%s-%s%cbak", - cf->localstatedir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#else - cf->bak_dir = PR_smprintf("%s%clib%c%s%c%s-%s%cbak", - cf->localstatedir, FILE_PATHSEP, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#endif - } else { - cf->bak_dir = PL_strdup(temp); - } - /* set bak dir to the environment variable DS_BAK_DIR */ - ds_set_bak_dir(cf->bak_dir); - - temp = ds_a_get_cgi_var("ldif_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->ldif_dir = PR_smprintf("%s%cldif", - cf->datadir, FILE_PATHSEP); -#else - cf->ldif_dir = PR_smprintf("%s%c%s%cldif", - cf->datadir, FILE_PATHSEP, cf->package_name, FILE_PATHSEP); -#endif - } else { - cf->ldif_dir = PL_strdup(temp); - } - - temp = ds_a_get_cgi_var("tmp_dir", NULL, NULL); - if (NULL == temp) { -#if defined (IS_FHS_OPT) - cf->tmp_dir = PR_smprintf("%s%c%s%c%s-%s%ctmp", - cf->localstatedir, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid, FILE_PATHSEP); -#else - cf->tmp_dir = PR_smprintf("%s%ctmp%c%s%c%s-%s", - cf->localstatedir, FILE_PATHSEP, FILE_PATHSEP, - cf->package_name, FILE_PATHSEP, - PRODUCT_NAME, cf->servid); -#endif - } else { - cf->tmp_dir = PL_strdup(temp); - } - /* set tmp dir to the environment variable DS_TMP_DIR */ - ds_set_tmp_dir(cf->tmp_dir); - - temp = ds_a_get_cgi_var("cert_dir", NULL, NULL); - if (NULL == temp) { - cf->cert_dir = PL_strdup(cf->config_dir); - } else { - cf->cert_dir = PL_strdup(temp); - } - - return 0; -} diff --git a/ldap/admin/src/create_instance.h b/ldap/admin/src/create_instance.h deleted file mode 100644 index 1e8d2665..00000000 --- a/ldap/admin/src/create_instance.h +++ /dev/null @@ -1,229 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * create_instance.h: create an instance of a directory server - * - * Rob McCool - */ - - -#ifndef _create_instance_h -#define _create_instance_h - -#ifdef __cplusplus -extern "C" { /* Assume C declarations for C++ */ -#endif /* __cplusplus */ - -#ifndef PACKAGE_NAME -#define PACKAGE_NAME "fedora-ds" -#endif - -#ifdef XP_UNIX -#define PRODUCT_NAME "slapd" -#define PRODUCT_BIN "ns-slapd" -#ifndef LOCALSTATEDIR -#define LOCALSTATEDIR "/var" -#endif -#ifndef SYSCONFDIR -#define SYSCONFDIR "/etc" -#endif -#if defined (IS_FHS) -#ifndef LIBDIR -#define LIBDIR "/usr/lib" -#endif -#ifndef BINDIR -#define BINDIR "/usr/bin" -#endif -#ifndef SBINDIR -#define SBINDIR "/usr/sbin" -#endif -#ifndef DATADIR -#define DATADIR "/usr/share" -#endif -#ifndef DOCDIR -#define DOCDIR "/usr/doc" -#endif -#else /* RPM */ -#ifndef LIBDIR -#define LIBDIR "/lib" -#endif -#ifndef BINDIR -#define BINDIR "/bin" -#endif -#ifndef SBINDIR -#define SBINDIR "/sbin" -#endif -#ifndef DATADIR -#define DATADIR "/share" -#endif -#ifndef DOCDIR -#define DOCDIR "/doc" -#endif -#endif /* IS_FHS */ -#else /* Windows */ -#define PRODUCT_NAME "slapd" -#define PRODUCT_BIN "slapd" -#define LOCALSTATEDIR "\\var" -#define SYSCONFDIR "\\etc" -#define LIBDIR "\\usr\\lib" -#define BINDIR "\\usr\\bin" -#define SBINDIR "\\usr\\sbin" -#define DATADIR "\\usr\\share" -#define DOCDIR "\\usr\\doc" -#endif - -typedef struct { - char *sroot; /* _libdir */ - char *localstatedir; - char *sysconfdir; - char *bindir; - char *sbindir; - char *datadir; - char *docdir; - - char *package_name; - char *lang; - - char *servname; - char *bindaddr; - char *servport; - char *suitespot3x_uid; - char *cfg_sspt; - char *cfg_sspt_uid; - char *cfg_sspt_uidpw; - char *secserv; - char *secservport; - char *rootdn; - char *rootpw; - char *roothashedpw; - char *replicationdn; - char *replicationpw; - char *replicationhashedpw; - char *consumerdn; - char *consumerpw; - char *consumerhashedpw; - char *changelogdir; - char *changelogsuffix; - char *suffix; - char *loglevel; - char *netscaperoot; - char *samplesuffix; - char *testconfig; - char *servid; -#ifdef XP_UNIX - char *servuser; - char *numprocs; -#endif - char *minthreads; - char *maxthreads; - int upgradingServer; - - char * start_server; - - char * admin_domain; - char * user_ldap_url; - int use_existing_user_ds; - char * disable_schema_checking; - char * install_ldif_file; - char *adminport; - char *inst_dir; - char *config_dir; - char *schema_dir; - char *lock_dir; - char *log_dir; - char *run_dir; - char *db_dir; - char *bak_dir; - char *ldif_dir; - char *plugin_dir; - char *tmp_dir; - char *cert_dir; - char *sasl_path; - char *prefix; -#if defined(ENABLE_LDAPI) - char *ldapifilepath; -#endif - int install_full_schema; -} server_config_s; - - -#ifdef NS_UNSECURE -#define DEFAULT_ID "unsecure" -#else -#define DEFAULT_ID "secure" -#endif - -/* - Initialize a server config structure with default values, using sroot - as the server root, and hn as the machine's full host name. - */ -void set_defaults(char *sroot, char *hn, server_config_s *conf); - -/* - Create a server using the given configuration structure. This affects - files and directories in the structure's server root. space for param_name - should be allocated by the caller e.g. char param_name[ENOUGH_ROOM]. - If there was a problem with one of the parameters passed in for instance - creation e.g. servport is out of range, the param_name parameter will be - filled in with "servport" and the error message returned will contain - additional detail - */ -char *create_server(server_config_s *cf, char *param_name); -/* - Update script files in the instance directory -*/ -int update_server(server_config_s *cf); - -/* from script-gen.c */ -int generate_script(const char *inpath, const char *outpath, int mode, - const char *table[][2]); - -/* richm - moved from instindex.cpp */ -int create_config(server_config_s *cf); -int parse_form(server_config_s *cf); - -#ifdef __cplusplus -} -#endif /* __cplusplus */ - -#endif diff --git a/ldap/admin/src/ds_newinst.c b/ldap/admin/src/ds_newinst.c deleted file mode 100644 index 5de0c4d7..00000000 --- a/ldap/admin/src/ds_newinst.c +++ /dev/null @@ -1,156 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * ds_newinst.c - creates a new instance of directory server, scripts, - * configuration, etc. Does not create any Admin Server stuff or - * deal with any setuputil stuff, but may be optionally used to create - * and configure the config suffix (o=NetscapeRoot) - */ - -#include <nss.h> -#include <nspr.h> - -#include "create_instance.h" - -#include "dsalib.h" -#include "ldap.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -/* --------------------------------- main --------------------------------- */ - -static void -printInfo(int argc, char *argv[], char *envp[], FILE* fp) -{ - int ii = 0; - if (!fp) - fp = stdout; - - fprintf(fp, "Program name = %s\n", argv[0]); - for (ii = 1; ii < argc; ++ii) - { - fprintf(fp, "argv[%d] = %s\n", ii, argv[ii]); - } - - for (ii = 0; envp[ii]; ++ii) - { - fprintf(fp, "%s\n", envp[ii]); - } - - fprintf(fp, "#####################################\n"); -} - -int main(int argc, char *argv[], char *envp[]) -{ - char *rm = getenv("REQUEST_METHOD"); - int status = 0; - server_config_s cf; - char *infFileName = 0; - int reconfig = 0; - int ii = 0; - int cgi = 0; - - /* Initialize NSS to make ds_salted_sha1_pw_enc() happy */ - if (NSS_NoDB_Init(NULL) != SECSuccess) { - ds_report_error(DS_GENERAL_FAILURE, " initialization failure", - "Unable to initialize the NSS subcomponent."); - exit(1); - } - - /* make stdout unbuffered */ - setbuf(stdout, 0); - -#ifdef XP_WIN32 - if ( getenv("DEBUG_DSINST") ) - DebugBreak(); -#endif - - memset(&cf, 0, sizeof(cf)); - set_defaults(0, 0, &cf); - - /* scan cmd line arguments */ - for (ii = 0; ii < argc; ++ii) - { - if (!strcmp(argv[ii], "-f") && (ii + 1) < argc && - argv[ii+1]) - infFileName = argv[ii+1]; - else if (!strcmp(argv[ii], "-r")) - reconfig = 1; - } - - /* being called as a CGI */ - if (rm) - { - cgi = 1; - status = parse_form(&cf); - if (!status) - status = create_config(&cf); - } - /* case 3: punt */ - else - { - ds_report_error ( - DS_INCORRECT_USAGE, - "No request method specified", - "A REQUEST_METHOD must be specified (POST, GET) to run this CGI program."); - status = 1; - } - - if (cgi) - { - /* The line below is used by the console to detect - the end of the operation. See replyHandler() in - MigrateCreate.java */ - fprintf(stdout, "NMC_Status: %d\n", status); - /* In the past, we used to call rpt_success() or rpt_err() - according to status. However these functions are not designed - for our case: they print an HTTP header line "Content-type: text/html" */ - } - -#if defined( hpux ) - _exit(status); -#else - exit(status); -#endif -} diff --git a/ldap/admin/src/ds_newinst.pl.in b/ldap/admin/src/ds_newinst.pl.in deleted file mode 100644 index 739f7a2a..00000000 --- a/ldap/admin/src/ds_newinst.pl.in +++ /dev/null @@ -1,399 +0,0 @@ -#!/usr/bin/env perl -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -use Net::Domain qw(hostfqdn); -use IPC::Open2; -use Symbol; -use CGI::Util qw(escape); -use Cwd; -use File::Basename; - -sub usage { - my $msg = shift; - print <<EOF; -Error: $msg -Usage: $0 [-|filename.inf] [args] -The filename, if any, should be specified first. After the filename, other args -can be provided to override settings in the provided file in this format: - section.param=value -e.g. - General.FullMachineName=foo.example.com -or - "slapd.Suffix=dc=example, dc=com" - -So, for example, if you use - $0 filename.inf General.FullMachineName=bar.example.com -And your filename.inf file has - [General] - FullMachineName= foo.example.com -$0 will use bar.example.com for FullMachineName since that was the one passed on the command line - -$0 will attempt to generate reasonable default values for some of the parameters, but there are a couple that must be specified: - slapd.ServerPort slapd.RootDNPwd -Also General.SuiteSpotUserID must be specified if running as root. If not running as root, the uid of the user will be used. -EOF - exit 1 -} - -sub getCgiContentAndLength { - my $args = shift; - my $content = ""; - my $firsttime = 1; - while (my ($kk, $vv) = each %{$args}) { - next if (!defined($kk) || !defined($vv)); - if ($firsttime) { - $firsttime = 0; - } else { - $content = $content . "&"; - } - $content = $content . $kk . "=" . escape($vv); - } - my $length = length($content); - - return ($content, $length); -} - -# fakes out the ds_newinst program into thinking it is getting cgi input -sub cgiFake { - my ($verbose, $prog, $args) = @_; - # construct content string - my ($content, $length) = &getCgiContentAndLength($args); - - # setup CGI environment - $ENV{REQUEST_METHOD} = "POST"; - $ENV{CONTENT_LENGTH} = $length; - $ENV{SERVER_NAMES} = 'slapd-' . $args->{servid}; - -# print "content = $content\n"; - - # open the program - my $curdir = getcwd(); - my $dir = dirname($prog); - my $exe = basename($prog); - chdir $dir; - my $input = gensym(); - my $output = gensym(); - # make sure the child exit code is reset before starting the fake - # cgi program - $? = 0; - my $pid = open2($input, $output, "./$exe"); - sleep(1); # allow prog to init stdin read buffers - print $output $content; - close $output; - - if ($?) { - print "Warning: $prog returned code $? and $!\n"; - } - - my $exitCode = 1; - my @lines; - while (<$input>) { - print $_ if ($verbose); - push @lines, $_; - if (/^NMC_Status:\s*(\d+)/) { - $exitCode = $1; - last; - } - } - close $input; - chdir $curdir; - - if ($exitCode) { - print "CGI $prog failed with $exitCode: here is the output:\n"; - map { print $_ } @lines; - } - - if ($exitCode != 0) { - print "Error: could not run $prog: $exitCode\n"; - return $exitCode; - } - - return 0; -} - -sub addAndCheck { - my $dest = shift; - my $dkey = shift; - my $source = shift; - my $ssec = shift; - my $skey = shift; - - if (! $source->{$ssec}->{$skey}) { - usage("Missing required parameter $ssec - $skey\n"); - } - - $dest->{$dkey} = $source->{$ssec}->{$skey}; -} - -sub readInfFile { - my $filename = shift; - my $fh; - if ($filename eq "-") { - $fh = \*STDIN; - } else { - open(IN, $filename) or usage("could not open file $filename: $!"); - $fh = \*IN; - } - while (<$fh>) { - # e.g. [General] - if (/^\[(.*?)\]/) { - $curSection = $1; - } elsif (/^\s*$/) { - next; # skip blank lines - } elsif (/^\s*\#/) { - next; # skip comment lines - } elsif (/^\s*(.*?)\s*=\s*(.*?)\s*$/) { - $table{$curSection}->{$1} = $2; - } - } - if ($filename ne "-") { - close IN; - } -} - -usage("No arguments given") if (!@ARGV); - -# process command line arguments -for (@ARGV) { - if (/^([\w_-]+)\.([\w_-]+)=(.*)$/) { # e.g. section.param=value - $table{$1}->{$2} = $3; - } else { # file? - readInfFile($_); - } -} - -#printhash (\%table); - -# set default values -if (!$table{General}->{FullMachineName}) { - $table{General}->{FullMachineName} = hostfqdn; -} - -if (!$table{General}->{SuiteSpotUserID}) { - if ($> != 0) { # if not root, use the user's uid - $table{General}->{SuiteSpotUserID} = getlogin; - } - # otherwise, the uid must be specified -} - -if (!$table{slapd}->{RootDN}) { - $table{slapd}->{RootDN} = "cn=Directory Manager"; -} - -if (!$table{slapd}->{Suffix}) { - my $suffix = $table{General}->{FullMachineName}; - # convert fqdn to dc= domain components - $suffix =~ s/^[^\.]*\.//; # just the domain part - $suffix = "dc=$suffix"; - $suffix =~ s/\./, dc=/g; - $table{slapd}->{Suffix} = $suffix; -} - -if (!$table{slapd}->{ServerIdentifier}) { - my $servid = $table{General}->{FullMachineName}; - # strip out the leftmost domain component - $servid =~ s/\..*$//; - $table{slapd}->{ServerIdentifier} = $servid; -} - -# next, construct a hash table with our arguments - -my %cgiargs = (); -my $package_name = "@package_name@"; -# the following items are always required -addAndCheck(\%cgiargs, "servname", \%table, "General", "FullMachineName"); -addAndCheck(\%cgiargs, "servuser", \%table, "General", "SuiteSpotUserID"); -addAndCheck(\%cgiargs, "rootdn", \%table, "slapd", "RootDN"); -addAndCheck(\%cgiargs, "rootpw", \%table, "slapd", "RootDNPwd"); -addAndCheck(\%cgiargs, "servid", \%table, "slapd", "ServerIdentifier"); -addAndCheck(\%cgiargs, "suffix", \%table, "slapd", "Suffix"); - -if (defined($table{"General"}->{"ServerRoot"})) { - $cgiargs{"sroot"} = $table{"General"}->{"ServerRoot"}; -} else { - $cgiargs{"sroot"} = '@serverdir@'; -} - -# either servport or ldapifilepath must be specified - the server must -# listen to something . . . -my $canlisten = 0; -if (defined($table{"slapd"}->{"ServerPort"}) && - $table{"slapd"}->{"ServerPort"} > 0) { - $canlisten = 1; - $cgiargs{"servport"} = $table{"slapd"}->{"ServerPort"}; -} else { - $cgiargs{"servport"} = "0"; # 0 means do not listen -} -if (defined($table{"slapd"}->{"ldapifilepath"})) { - $canlisten = 1; - $cgiargs{"ldapifilepath"} = $table{"slapd"}->{"ldapifilepath"}; -} -if (! $canlisten) { - usage("Either ServerPort or ldapifilepath must be specified in the slapd section"); -} - -# the following items are optional - -$cgiargs{"lock_dir"} = $table{"slapd"}->{"lock_dir"}; -$cgiargs{"log_dir"} = $table{"slapd"}->{"log_dir"}; -$cgiargs{"run_dir"} = $table{"slapd"}->{"run_dir"}; -$cgiargs{"db_dir"} = $table{"slapd"}->{"db_dir"}; -$cgiargs{"bak_dir"} = $table{"slapd"}->{"bak_dir"}; -$cgiargs{"ldif_dir"} = $table{"slapd"}->{"ldif_dir"}; -$cgiargs{"tmp_dir"} = $table{"slapd"}->{"tmp_dir"}; -$cgiargs{"cert_dir"} = $table{"slapd"}->{"cert_dir"}; -$cgiargs{"localstatedir"} = $table{"slapd"}->{"localstatedir"}; -$cgiargs{"sysconfdir"} = $table{"slapd"}->{"sysconfdir"}; -$cgiargs{"bindir"} = $table{"slapd"}->{"bindir"}; -$cgiargs{"sbindir"} = $table{"slapd"}->{"sbindir"}; -$cgiargs{"datadir"} = $table{"slapd"}->{"datadir"}; -$cgiargs{"docdir"} = $table{"slapd"}->{"docdir"}; -$cgiargs{"inst_dir"} = $table{"slapd"}->{"inst_dir"}; -$cgiargs{"schema_dir"} = $table{"slapd"}->{"schema_dir"}; -$cgiargs{"sasl_path"} = $table{"slapd"}->{"sasl_path"}; -if ($table{"slapd"}->{"config_dir"}) { - $cgiargs{"config_dir"} = $table{"slapd"}->{"config_dir"}; -} else { - $cgiargs{"config_dir"} = "@instconfigdir@/slapd-" . $table{"slapd"}->{"ServerIdentifier"}; -} - -# check to see if this instance already exists -if (-d $cgiargs{"config_dir"}) { - print STDERR "Error: the server already exists at ", $cgiargs{"config_dir"}, "\n"; - print STDERR "Please remove it first if you really want to recreate it,\n"; - print STDERR "or use a different ServerIdentifier to create another instance.\n"; - exit 1; -} - -# port number for Admin Server - used to configure some web apps -$cgiargs{adminport} = $table{admin}->{Port}; - -# If this is set, the new DS instance will be set up for use as -# a Configuration DS (e.g. o=NetscapeRoot) -if ($table{slapd}->{SlapdConfigForMC} =~ /yes/i) { - $cgiargs{cfg_sspt} = "1"; -} -# set this to 1 to register this DS with an existing Configuration DS -# or 0 to create this DS as a new Configuration DS -$cgiargs{use_existing_config_ds} = $table{slapd}->{UseExistingMC}; -# set this to 1 when creating a new Configuration DS if you do not -# want to configure the new DS to also serve user data -$cgiargs{use_existing_user_ds} = $table{slapd}->{UseExistingUG}; - -# the following items are required to register this new instance with a config DS -# or to make the new instance a Configuration DS -if ($cgiargs{cfg_sspt} || - $table{General}->{ConfigDirectoryAdminID} || - $table{General}->{ConfigDirectoryAdminPwd} || - $table{General}->{ConfigDirectoryLdapURL} || - $table{General}->{AdminDomain}) { - addAndCheck(\%cgiargs, "cfg_sspt_uid", \%table, "General", "ConfigDirectoryAdminID"); - addAndCheck(\%cgiargs, "cfg_sspt_uid_pw", \%table, "General", "ConfigDirectoryAdminPwd"); - addAndCheck(\%cgiargs, "ldap_url", \%table, "General", "ConfigDirectoryLdapURL"); - addAndCheck(\%cgiargs, "admin_domain", \%table, "General", "AdminDomain"); -} - -# -if ($table{General}->{UserDirectoryLdapURL}) { - $cgiargs{user_ldap_url} = $table{General}->{UserDirectoryLdapURL}; -} else { - $cgiargs{user_ldap_url} = $cgiargs{ldap_url}; -} - -if ($table{General}->{prefix}) { - $prefix = $table{General}->{prefix}; -} -$cgiargs{prefix} = $prefix; - -if ($table{General}->{PackageName}) { - $package_name = $table{General}->{PackageName}; -} - -# populate the DS with this file - the suffix in this file must -# be the suffix specified in the suffix argument above -# the filename should use the full absolute path -$cgiargs{install_ldif_file} = $table{slapd}->{InstallLdifFile}; - -# if for some reason you do not want the server started after instance creation -# then you can set -# [slapd] -# start_server = 0 -# NOTE that if you are creating the -# Configuration DS, it will be started anyway - -if (defined($table{"slapd"}->{"start_server"})) { - $cgiargs{start_server} = $table{"slapd"}->{"start_server"}; -} else { # default is on - $cgiargs{start_server} = 1; -} - -# if for some reason you do not want the full schema to be installed, -# (such as needing to replace much of it with an AD-like schema), then set -# [slapd] -# install_full_schema = 0 - -if (defined($table{"slapd"}->{"install_full_schema"})) { - $cgiargs{install_full_schema} = $table{"slapd"}->{"install_full_schema"}; -} else { - # server-side default is on -} - -my $prog = "@bindir@/ds_newinst"; -if (! -x $prog) { - $prog = "@libdir@/$package_name/ds_newinst"; -} - -my $rc = &cgiFake($verbose, $prog, \%cgiargs); - -if (!$rc) { - print "Success! Your new directory server instance was created\n"; -} else { - print "Error: Could not create new directory server instance\n"; -} - -exit $rc; - -sub printhash { - my $table = shift; - - while (my ($key,$val) = each %{$table}) { - print "[$key]\n"; - while (my ($k2,$v2) = each %{$val}) { - print "$k2 = $v2\n"; - } - } -} diff --git a/ldap/admin/src/ds_remove_uninst.cpp b/ldap/admin/src/ds_remove_uninst.cpp deleted file mode 100644 index b7699176..00000000 --- a/ldap/admin/src/ds_remove_uninst.cpp +++ /dev/null @@ -1,360 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -// ds_remove_uninst.cpp -// -// ds_remove routines that use c++ calls in adminutil -// -#include <iostream.h> -#include <fstream.h> -#include <stdio.h> /* printf, file I/O */ -#include <string.h> /* strlen */ -#include <ctype.h> -#ifdef XP_UNIX -#include <strings.h> -#include <pwd.h> -#include <grp.h> -#include <sys/socket.h> -#include <netinet/in.h> -#include <arpa/inet.h> -#include <netdb.h> -#endif -#include <stdlib.h> /* memset, rand stuff */ -#include <sys/types.h> -#include <errno.h> -#include <stdarg.h> -#include <time.h> - -#include "ds_remove_uninst.h" - -#ifdef __cplusplus -extern "C" { -#endif -#include "dsalib.h" -#ifdef __cplusplus -} - -#include "prprf.h" - -#endif -#ifdef XP_UNIX -#include "ux-util.h" -#endif -#include "ldapu.h" -#include "install_keywords.h" -#include "global.h" -#include "setupapi.h" - -#define MAX_STR_SIZE 512 -static void dsLogMessage(const char *level, const char *which, - const char *format, ...) -#ifdef __GNUC__ - __attribute__ ((format (printf, 3, 4))); -#else - ; -#endif - -static InstallLog *installLog = NULL; - -static void -dsLogMessage(const char *level, const char *which, - const char *format, ...) -{ - char bigbuf[BIG_BUF*4]; - va_list ap; - va_start(ap, format); - PR_vsnprintf(bigbuf, sizeof(bigbuf), format, ap); - va_end(ap); -#ifdef _WIN32 // always output to stdout (for CGIs), and always log - // if a log is available - fprintf(stdout, "%s %s %s\n", level, which, bigbuf); - fflush(stdout); - if (installLog) - installLog->logMessage(level, which, bigbuf); -#else // not Windows - if (installLog) - installLog->logMessage(level, which, bigbuf); - else - fprintf(stdout, "%s %s %s\n", level, which, bigbuf); - fflush(stdout); -#endif - - return; -} - -// replace \ in path with \\ for LDAP search filters -static char * -escapePath(const char *path) -{ - char *s = 0; - if (path) { - s = new char [(strlen(path)+1)*2]; // worst case - char *p = s; - const char *pp = path; - for (; *pp; ++pp, ++p) { - if (*pp == '\\') { - *p++ = *pp; - } - *p = *pp; - } - *p = 0; - } - - return s; -} - -static LdapErrorCode -localRemoveISIE(LdapEntry &isieEntry) -{ - /* stevross: for now explicitly delete ISIE because it's not getting - removed by removeSIE for some reason */ - LdapError err = isieEntry.dropAll(isieEntry.entryDN()); - if (err.errorCode()) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Error: could not remove ISIE entry %s: error = %d", - (const char *)isieEntry.entryDN(), (int)err.errorCode()); - } - - // OK to remove, recursively go up the tree and remove all - char *dn = new char [strlen(isieEntry.entryDN()) + 10]; - char **explodedDN = ldap_explode_dn(isieEntry.entryDN(), 0); - int i = 0; - - while (1) - { - dn[0] = 0; - char **s = &explodedDN[i]; - while (*s != NULL) - { - strcat(dn, *s); - strcat(dn, LDAP_PATHSEP); - s++; - } - - if (*s == NULL) - { - dn[strlen(dn)-strlen(LDAP_PATHSEP)] = 0; - } - - if (strcasecmp(dn, DEFAULT_ROOT_DN) == 0) - { - break; - } - - err = isieEntry.retrieve(OBJECT_CLASS_FILTER, LDAP_SCOPE_ONELEVEL, dn); - - if (err == NOT_FOUND) - { - isieEntry.drop(dn); - ++i; - } - else - { - break; - } - } - - delete [] dn; - ldap_value_free(explodedDN); - - return OKAY; -} - -////////////////////////////////////////////////////////////////////////////// -// removeInstanceLDAPEntries -// -// -// remove sie, isie of this instance -// -// -// -// - -int removeInstanceLDAPEntries(const char *pszLdapHost, - const char *pszPort, - const char *pszLdapSuffix, - const char *pszUser, - const char *pszPw, - const char *pszInstanceName, - const char *pszInstanceHost, - const char *pszServerRoot) -{ - char szSearchBase[] = "o=NetscapeRoot"; - - /* open LDAP connection */ - LdapError ldapError = 0; - NSString newURL = NSString("ldap://") + pszLdapHost + ":" + - pszPort + "/" + pszLdapSuffix; - Ldap ldap(ldapError, newURL, pszUser, pszPw, 0, 0); - if (ldapError.errorCode()) - { - return 1; - } - - /* get SIE entry */ - char *sroot = escapePath(pszServerRoot); - LdapEntry sieEntry(&ldap); - NSString sieFilter = NSString("(&(serverhostname=") + pszInstanceHost + - ")(cn=" + pszInstanceName + ")(serverroot=" + - sroot + "))"; - ldapError = sieEntry.retrieve(sieFilter, LDAP_SCOPE_SUBTREE, szSearchBase); - if (ldapError.errorCode()) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Error: could not find the SIE entry using filter %s: error = %d", - (const char *)sieFilter, (int)ldapError.errorCode()); - delete [] sroot; - return 1; - } - - /* get ISIE entry */ - LdapEntry isieEntry(&ldap); - NSString isieFilter = - NSString("(&(objectclass=nsApplication)(uniquemember=") + - sieEntry.entryDN() + ")(nsinstalledlocation=" + - sroot + "))"; - ldapError = isieEntry.retrieve(isieFilter, LDAP_SCOPE_SUBTREE, szSearchBase); - if (ldapError.errorCode()) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Error: could not find the ISIE entry using filter %s: error = %d", - (const char *)isieFilter, (int)ldapError.errorCode()); - delete [] sroot; - return 1; - } - - /* delete the SIE and ISIE entry */ - LdapErrorCode code = removeSIE(&ldap, sieEntry.entryDN(), False); - if (code) - { - dsLogMessage(SETUP_LOG_FATAL, "Slapd", - "Error: could not remove SIE entry %s: error = %d", - (const char *)sieEntry.entryDN(), (int)code); - return code; - } - - code = localRemoveISIE(isieEntry); - - delete [] sroot; - return code; -} - - -int ds_uninst_set_cgi_env(char *pszInfoFileName) -{ - InstallInfo *uninstallInfo = NULL; - InstallInfo *instanceInfo = NULL; - static char szQueryString[512] = {0}; - static char szScriptName[512] = {0}; - static char szNetsiteRoot[512] = {0}; - const char *serverID = 0; - const char *tmp; - - uninstallInfo = new InstallInfo(pszInfoFileName); - - if (!uninstallInfo) - return 1; - - instanceInfo = uninstallInfo->getSection("uninstall"); - if (!instanceInfo) - instanceInfo = uninstallInfo; - - putenv("REQUEST_METHOD=GET"); - if (instanceInfo->get(SLAPD_KEY_SERVER_IDENTIFIER)) - serverID = instanceInfo->get(SLAPD_KEY_SERVER_IDENTIFIER); - else if (ds_get_server_name()) - serverID = ds_get_server_name(); - - if (serverID) - PR_snprintf(szQueryString, sizeof(szQueryString), "QUERY_STRING=InstanceName=%s", - serverID); - - putenv(szQueryString); - - if (instanceInfo->get(SLAPD_KEY_SERVER_ROOT)) - PR_snprintf(szNetsiteRoot, sizeof(szNetsiteRoot), "NETSITE_ROOT=%s", - instanceInfo->get(SLAPD_KEY_SERVER_ROOT)); - putenv(szNetsiteRoot); - - if (serverID) - PR_snprintf(szScriptName, sizeof(szScriptName), "SCRIPT_NAME=/%s/Tasks/Operation/Remove", - serverID); - putenv(szScriptName); - - // remove SIE entry - const char *host = instanceInfo->get(SLAPD_KEY_K_LDAP_HOST); - char port[20] = {0}; - if (instanceInfo->get(SLAPD_KEY_K_LDAP_PORT)) - strncpy(port, instanceInfo->get(SLAPD_KEY_K_LDAP_PORT), sizeof(port)-1); - const char *suffix = instanceInfo->get(SLAPD_KEY_SUFFIX); - const char *ldapurl = instanceInfo->get(SLAPD_KEY_K_LDAP_URL); - LDAPURLDesc *desc = 0; - if (ldapurl && !ldap_url_parse((char *)ldapurl, &desc) && desc) { - if (!host) - host = desc->lud_host; - if (port[0] == 0) - PR_snprintf(port, sizeof(port), "%d", desc->lud_port); - if (!suffix) - suffix = desc->lud_dn; - } - - // get and set the log file - if ((tmp = instanceInfo->get(SLAPD_INSTALL_LOG_FILE_NAME))) - { - static char s_logfile[PATH_MAX+32]; - PR_snprintf(s_logfile, sizeof(s_logfile), "DEBUG_LOGFILE=%s", tmp); - putenv(s_logfile); - installLog = new InstallLog(tmp); - } - - removeInstanceLDAPEntries(host, port, suffix, - instanceInfo->get(SLAPD_KEY_SERVER_ADMIN_ID), - instanceInfo->get(SLAPD_KEY_SERVER_ADMIN_PWD), - serverID, - instanceInfo->get(SLAPD_KEY_FULL_MACHINE_NAME), - instanceInfo->get(SLAPD_KEY_SERVER_ROOT)); - - if (desc) - ldap_free_urldesc(desc); - return 0; -} diff --git a/ldap/admin/src/ds_remove_uninst.h b/ldap/admin/src/ds_remove_uninst.h deleted file mode 100644 index 6ce2b6b1..00000000 --- a/ldap/admin/src/ds_remove_uninst.h +++ /dev/null @@ -1,60 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* ds_remove_uninst.h */ - - -#ifndef _DS_REMOVE_UNINST_H_ -#define _DS_REMOVE_UNINST_H_ - -#ifdef __cplusplus -extern "C" { -#endif - - -int ds_uninst_set_cgi_env(char *pszInfoFileName); - -#ifdef __cplusplus -} -#endif - -#endif diff --git a/ldap/admin/src/fix_secmod_db_64 b/ldap/admin/src/fix_secmod_db_64 deleted file mode 100755 index 3588a35f..00000000 --- a/ldap/admin/src/fix_secmod_db_64 +++ /dev/null @@ -1,105 +0,0 @@ -#!/bin/sh -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# We still have 32 bit applications shipped with the 64 bit DS -# that need to access secmod.db and the root certs file -# nssckbi shared library. However, 32 bit apps cannot load -# the 64 bit version of this shared library. This script -# changes secmod.db to have both the 32 bit and 64 bit versions -# of nssckbi. - -# The first argument is the name of the directory where secmod.db -# and the nssckbi shared libraries (64 bit and 32 bit) are. If -# secmod.db does not exist an error will occur. - -# The second argument is the path of the modutil -# command. If the path is omitted then PATH will be used. - -usage() -{ - echo Error: $1 - echo The first argument is the name of the directory where secmod.db - echo and the nssckbi shared libraries '(64 bit and 32 bit)' are. If - echo secmod.db does not exist an error will occur. - echo The second argument is the path where the modutil command - echo is found. -} - -dir="$1" -shift -modutildir="$1" -modutil=$modutildir/modutil -LD_LIBRARY_PATH=$modutildir/../lib:$LD_LIBRARY_PATH -SHLIB_PATH=$modutildir/../lib:$SHLIB_PATH -export LD_LIBRARY_PATH SHLIB_PATH - -# see if correct argument was given -if test \! \( "$dir" -a -d "$dir" \) ; then - usage "Invalid directory $dir" - exit 1 -fi - -# see if the files are there - -lib64=$dir/*nssckbi.* -lib32=$dir/*nssckbi32.* - -if test \! \( -f $lib64 -a -f $lib32 \) ; then - usage "Files $lib64 and/or $lib32 do not exist in dir $dir" - exit 2 -fi - -if test \! -f $dir/secmod.db ; then - usage "$dir/secmod.db does not exist" - exit 3 -fi - -modname="Root Certs 32 bit" - -# see if the module already exists -exists=0 -$modutil -force -nocertdb -dbdir $dir -list | grep "$modname" > /dev/null 2>&1 && exists=1 - -if test $exists -ne 1 ; then - $modutil -force -nocertdb -dbdir $dir -add "$modname" -libfile $lib32 || usage "Could not add $modname to $dir/secmod.db: $?" -else - echo "Module $modname already added to secmod.db" -fi diff --git a/ldap/admin/src/getConfigInfo b/ldap/admin/src/getConfigInfo deleted file mode 100644 index 981bcec9..00000000 --- a/ldap/admin/src/getConfigInfo +++ /dev/null @@ -1,166 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# Get some configuration information from an instance - -BEGIN { - $| = 1; - # print CGI header - print "Content-type: text/plain\n\n"; - - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - # get the server root directory - $sroot = $ENV{'NETSITE_ROOT'}; - @INC = ( '.', '../../../admin/admin/bin' ); - grep { s@/@\\@g } @INC if $isNT; -} - -sub sigDieHandler { - print @_, "\n"; - print "NMC_STATUS: ", $!+0, "\n"; - exit $!; -} - -$SIG{__DIE__} = 'sigDieHandler'; - -# process the CGI input -use Cgi; - -$oldSlapdConf = $cgiVars{'oldServerRoot'} . $PATHSEP . 'slapd-' . - $cgiVars{'oldServerName'} . $PATHSEP . 'config' . $PATHSEP . - 'slapd.conf'; - -$foundLocalUser = 0; - -open(OLDSLAPDCONF, $oldSlapdConf) or - die "Error: could not open old config file $oldSlapdConf: $!"; -while ($line = <OLDSLAPDCONF>) { - chop $line; - foreach $key (keys %cgiVars) { - $param = $cgiVars{$key}; - if ($line =~ /^$param\s+/i) { - ($value = $') =~ s/^[\"]//; - # remove leading " - $value =~ s/[\"]$//; - # remove trailing " - print $key, ':', $value, "\n"; - if (lc($param) eq 'localuser') { - $foundLocalUser = 1; - } - } - } - if ($line =~ /^directory\s+/i) { $dbdir = $';} - # the user may have given us a network mounted old home directory, but in the - # old instance's config files, the root directory referred to is usually - # a local directory. For example, suppose there is an automounter map for - # hosts which maps onto /h e.g. /h/oldhost would contain all directories - # exported via NFS. Similarly, for NT, you could do \\oldhost\c to look - # at the C: drive on the old host. Or the user may have network mounted - # the old server root some other way. Anyway, we need to determine what - # the old server root was local to the original host because that is what - # will be referred to it the old config files. So, we look at the errorlog - # directive in slapd.conf and use whatever comes before the slapd-oldname - elsif ($line =~ /\werrorlog\s+(.*)slapd-$cgiVars{'oldServerName'}/i) { - $realOldDir = $1; - } - elsif ($line =~ /^security\s+/i) { - if (lc($') eq 'on') { - $security = 1; - } - } - elsif ($line =~ /^encryption-alias\s+/i) { - $encryptionalias = $'; - } -} -close(OLDSLAPDCONF); - -if (! $realOldDir) { - $realOldDir = $cgiVars{'oldServerRoot'}; -} - -# if security is enabled, see if there is a cert and key db -if ($security && $encryptionalias) { - $secDir = $cgiVars{'oldServerRoot'} . $PATHSEP . 'alias'; - opendir(SECDIR, $secDir) or - die "Error: could not open alias dir $secDir : $!"; - foreach (readdir(SECDIR)) { - if (! /[.][.]?/) { - if (/^$encryptionalias/i) { - print 'needSecPwd:true', "\n"; - last; - } - } - } - closedir(SECDIR); -} - -# the dbdir is stored as a local dir, but we may need a network dir -($networkDbDir = $dbdir) =~ s/^$realOldDir/$cgiVars{'oldServerRoot'}/ig; - -if (! $isNT && $cgiVars{'oldlocaluser'} && ! $foundLocalUser) { - # get the local user by doing a stat of the db directory - $olduid = (stat($networkDbDir))[4]; - # convert the numeric uid to string name - setpwent; - while (@ent = getpwent) { - if ($ent[2] == $olduid) { - print 'oldlocaluser:', $ent[0], "\n"; - last; - } - } - endpwent; -} - -if (! $isNT && $cgiVars{'newlocaluser'}) { - open(SSUSERS, "$sroot${PATHSEP}shared${PATHSEP}config${PATHSEP}ssusers.conf") or - die "Error: could not open $sroot${PATHSEP}shared${PATHSEP}config${PATHSEP}ssusers.conf: $!"; - while (<SSUSERS>) { - chop; - if (/^SuiteSpotUser\s+/i) { - print 'newlocaluser:', $', "\n"; - } - } - close(SSUSERS); -} - -print "NMC_STATUS: 0\n"; -exit 0; diff --git a/ldap/admin/src/import2info b/ldap/admin/src/import2info deleted file mode 100755 index ad225e68..00000000 --- a/ldap/admin/src/import2info +++ /dev/null @@ -1,90 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# Get information to import a 1.x Directory server's info - -BEGIN { @INC = ( '../../../admin/admin/bin' , '.' ); } - -$| = 1; -use Cgi; - -$isNT = -d '\\'; -$cgiVars{'server'} =~ /-/; -$root = $ENV{'NETSITE_ROOT'}; -$oldDir = $cgiVars{'dir'}; -$oldDir =~ s/\\/\//g; -$oldHome = "$oldDir/$cgiVars{'server'}"; -$snmpfile = "$oldHome/config/snmp.conf"; - -$ds30 = 0; -if ( -e $snmpfile) { - open ( SRC, $snmpfile) | "Can't open $snmpfile: $!\n"; - while ( <SRC> ) { - if ($_=~/^Version/ ) { - $where = index ($_, "3.0"); - if ($where > -1 ) { - $ds30 =1; - } - } - } -} - -# QUERY_STRING still set from invocation - -print "Content-type: text/html\n\n"; -if ($ds30) { - print "<HTML><HEAD><TITLE>Import 3.0 Directory Server Info</TITLE></HEAD>\n"; - print "<BODY>\n"; - print "<H1><center>The server you are attempting to migrate is a 3.0 directory server. There is no need to migrate a 3.0 server to 3.1 server.</center></H1>\n"; - print "</BODY></HTML>\n"; -} else { - print "<HTML><HEAD><TITLE>Import 1.x Directory Server Info</TITLE></HEAD>\n"; - print "<BODY>\n"; - print "<H1>Import 1.x Directory Server Info</H1>\n"; - print '<FORM action="import" method="GET">', "\n"; - print "<INPUT type=hidden name=\"dir\" value=\"$cgiVars{'dir'}\">\n"; - print "<INPUT type=hidden name=\"server\" value=\"$cgiVars{'server'}\">\n"; - $cgiVars{'server'} =~ /-/; - print "Name: $`-<INPUT type=text name=\"name\" value=\"$'\"><P>\n"; - print "<P><INPUT type=submit value=\"Import\">\n"; - print "</FORM>\n</BODY></HTML>\n"; -} - diff --git a/ldap/admin/src/init_ds_env.c b/ldap/admin/src/init_ds_env.c deleted file mode 100644 index f6ca8a03..00000000 --- a/ldap/admin/src/init_ds_env.c +++ /dev/null @@ -1,95 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * Set up environment for CGIs. - * - * Rob Weltman - */ - -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include "libadminutil/admutil.h" -#include "libadminutil/distadm.h" -#include "init_ds_env.h" -#include "dsalib.h" -#include "prprf.h" - -int init_ds_env() -{ - char *m = getenv("REQUEST_METHOD"); - char *qs = NULL; - int proceed = 0; - - (void)ADMUTIL_Init(); - if ( m != NULL ) { - if( !strcmp(m, "GET") ) { - qs = GET_QUERY_STRING(); - if ( qs && *qs ) { - ds_get_begin(qs); - } - proceed = 1; - } else if(!strcmp(m, "POST")) { - if (ds_post_begin(stdin)) { - proceed = 0; - } else { - proceed = 1; - } - } - } - - if(!proceed) { - char msg[2000]; - PR_snprintf(msg, sizeof(msg), "ErrorString: REQUEST_METHOD=%s," - "QUERY_STRING=%s\n", - (m == NULL) ? "<undefined>" : m, - (qs == NULL) ? "<undefined>" : qs); - rpt_err( GENERAL_FAILURE, - msg, - "", - "" ); - return 1; - } - - return 0; -} diff --git a/ldap/admin/src/init_ds_env.h b/ldap/admin/src/init_ds_env.h deleted file mode 100644 index 7e6b7275..00000000 --- a/ldap/admin/src/init_ds_env.h +++ /dev/null @@ -1,48 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * Set up environment for CGIs. - * - * Rob Weltman - */ -extern int init_ds_env(); diff --git a/ldap/admin/src/install_keywords.h b/ldap/admin/src/install_keywords.h deleted file mode 100644 index 9106a1cf..00000000 --- a/ldap/admin/src/install_keywords.h +++ /dev/null @@ -1,148 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/********************************************************************* -** -** -** NAME: -** install_keywords.h -** -** DESCRIPTION: -** Miscellaneous stuffs used by ux-update or ux-config -** -** NOTES: -** -** -*/ - -#ifndef _INSTALL_KEYWORDS_H_ -#define _INSTALL_KEYWORDS_H_ - -#include "global.h" - - -#ifdef XP_UNIX -#define SLAPD_KEY_FULL_MACHINE_NAME MACHINE_NAME -#else -#define SLAPD_KEY_FULL_MACHINE_NAME "FullMachineName" -#endif -#define SLAPD_KEY_SERVER_ROOT "ServerRoot" -#define SLAPD_KEY_SERVER_PORT "ServerPort" -#define SLAPD_KEY_SECURITY_ON "SecurityOn" -#define SLAPD_KEY_SECURE_SERVER_PORT "SecureServerPort" -#define SLAPD_KEY_SLAPD_CONFIG_FOR_MC "SlapdConfigForMC" - -#ifdef XP_UNIX -#define SLAPD_KEY_SERVER_ADMIN_ID MC_ADMIN_ID -#define SLAPD_KEY_SERVER_ADMIN_PWD MC_ADMIN_PWD -#else -#define SLAPD_KEY_SERVER_ADMIN_ID "ConfigDirectoryAdminID" -#define SLAPD_KEY_SERVER_ADMIN_PWD "ConfigDirectoryAdminPwd" -#endif - -#define SLAPD_KEY_SERVER_IDENTIFIER "ServerIdentifier" -#define SLAPD_KEY_SUITESPOT_USERID SS_USER_ID -#define SLAPD_KEY_SUFFIX "Suffix" -#define SLAPD_KEY_ROOTDN "RootDN" -#define SLAPD_KEY_ROOTDNPWD "RootDNPwd" -#define SLAPD_KEY_ADMIN_SERVER_PORT "Port" -#define SLAPD_KEY_OLD_SERVER_ROOT "OldServerRoot" - -#ifdef XP_UNIX -#define SLAPD_KEY_K_LDAP_URL CONFIG_LDAP_URL -#else -#define SLAPD_KEY_K_LDAP_URL "ConfigDirectoryLdapURL" -#endif - -#define SLAPD_KEY_K_LDAP_HOST CONFIG_DS_HOST -#define SLAPD_KEY_K_LDAP_PORT CONFIG_DS_PORT -#define SLAPD_KEY_BASE_SUFFIX CONFIG_DS_SUFFIX -#define SLAPD_KEY_ADMIN_SERVER_ID "ServerAdminID" -#define SLAPD_KEY_ADMIN_SERVER_PWD "ServerAdminPwd" -#define SLAPD_KEY_ADD_SAMPLE_ENTRIES "AddSampleEntries" -#define SLAPD_KEY_ADD_ORG_ENTRIES "AddOrgEntries" -#define SLAPD_KEY_INSTALL_LDIF_FILE "InstallLdifFile" -#define SLAPD_KEY_ORG_SIZE "OrgSize" -#define SLAPD_KEY_SETUP_CONSUMER "SetupConsumer" -#define SLAPD_KEY_CIR_HOST "CIRHost" -#define SLAPD_KEY_CIR_PORT "CIRPort" -#define SLAPD_KEY_CIR_SUFFIX "CIRSuffix" -#define SLAPD_KEY_CIR_BINDDN "CIRBindDN" -#define SLAPD_KEY_CIR_BINDDNPWD "CIRBindDNPwd" -#define SLAPD_KEY_CIR_SECURITY_ON "CIRSecurityOn" -#define SLAPD_KEY_CIR_INTERVAL "CIRInterval" -#define SLAPD_KEY_CIR_DAYS "CIRDays" -#define SLAPD_KEY_CIR_TIMES "CIRTimes" -#define SLAPD_KEY_SETUP_SUPPLIER "SetupSupplier" -#define SLAPD_KEY_REPLICATIONDN "ReplicationDN" -#define SLAPD_KEY_REPLICATIONPWD "ReplicationPwd" -#define SLAPD_KEY_CHANGELOGDIR "ChangeLogDir" -#define SLAPD_KEY_CHANGELOGSUFFIX "ChangeLogSuffix" -#define SLAPD_KEY_USE_REPLICATION "UseReplication" -#define SLAPD_KEY_CONSUMERDN "ConsumerDN" -#define SLAPD_KEY_CONSUMERPWD "ConsumerPwd" -#define SLAPD_KEY_SIR_HOST "SIRHost" -#define SLAPD_KEY_SIR_PORT "SIRPort" -#define SLAPD_KEY_SIR_SUFFIX "SIRSuffix" -#define SLAPD_KEY_SIR_BINDDN "SIRBindDN" -#define SLAPD_KEY_SIR_BINDDNPWD "SIRBindDNPwd" -#define SLAPD_KEY_SIR_SECURITY_ON "SIRSecurityOn" -#define SLAPD_KEY_SIR_DAYS "SIRDays" -#define SLAPD_KEY_SIR_TIMES "SIRTimes" -#define SLAPD_KEY_USE_EXISTING_MC "UseExistingMC" -#define SLAPD_KEY_ADMIN_DOMAIN "AdminDomain" -#define SLAPD_KEY_DISABLE_SCHEMA_CHECKING "DisableSchemaChecking" -#define SLAPD_KEY_USE_EXISTING_UG "UseExistingUG" -#define SLAPD_KEY_USER_GROUP_LDAP_URL "UserDirectoryLdapURL" -#define SLAPD_KEY_UG_HOST "UGHost" -#define SLAPD_KEY_UG_PORT "UGPort" -#define SLAPD_KEY_UG_SUFFIX "UGSuffix" -#define SLAPD_KEY_USER_GROUP_ADMIN_ID "UserDirectoryAdminID" -#define SLAPD_KEY_USER_GROUP_ADMIN_PWD "UserDirectoryAdminPwd" -#define SLAPD_KEY_CONFIG_ADMIN_DN "ConfigAdminDN" -/* This is used to pass the name of the log file used in the main setup - program to the ds_create or ds_remove (for uninstall) so that - they can all use the same log file -*/ -#define SLAPD_INSTALL_LOG_FILE_NAME "LogFileName" - -#endif // _INSTALL_KEYWORDS_H_ diff --git a/ldap/admin/src/instindex.cpp b/ldap/admin/src/instindex.cpp deleted file mode 100644 index 05c3fbee..00000000 --- a/ldap/admin/src/instindex.cpp +++ /dev/null @@ -1,194 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * index.c: Shows the first page you see on install - * - * Rob McCool - */ - -#include <nss.h> -#include <libadminutil/distadm.h> - -#include "create_instance.h" -#include "configure_instance.h" - -#include "dsalib.h" -#include "ldap.h" - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> - -/* --------------------------------- main --------------------------------- */ -#if NEEDED_FOR_DEBUGGING -static void -printInfo(int argc, char *argv[], char *envp[], FILE* fp) -{ - int ii = 0; - if (!fp) - fp = stdout; - - fprintf(fp, "Program name = %s\n", argv[0]); - for (ii = 1; ii < argc; ++ii) - { - fprintf(fp, "argv[%d] = %s\n", ii, argv[ii]); - } - - for (ii = 0; envp[ii]; ++ii) - { - fprintf(fp, "%s\n", envp[ii]); - } - - fprintf(fp, "#####################################\n"); -} -#endif - -#if defined (__hpux) && defined (__ia64) -int main(int argc, char *argv[], char *envp[]) -#else -int main(int argc, char *argv[], char * /*envp*/ []) -#endif -{ - char *rm = getenv("REQUEST_METHOD"); - int status = 0; - server_config_s cf; - char *infFileName = 0; - int reconfig = 0; - int ii = 0; - int cgi = 0; - - (void)ADMUTIL_Init(); - - /* Initialize NSS to make ds_salted_sha1_pw_enc() happy */ - if (NSS_NoDB_Init(NULL) != SECSuccess) { - ds_report_error(DS_GENERAL_FAILURE, " initialization failure", - "Unable to initialize the NSS subcomponent."); - exit(1); - } - - /* make stdout unbuffered */ - setbuf(stdout, 0); - -#ifdef XP_WIN32 - if ( getenv("DEBUG_DSINST") ) - DebugBreak(); -#endif - - memset(&cf, 0, sizeof(cf)); - set_defaults(0, 0, &cf); - - /* scan cmd line arguments */ - for (ii = 0; ii < argc; ++ii) - { - if (!strcmp(argv[ii], "-f") && (ii + 1) < argc && - argv[ii+1]) - infFileName = argv[ii+1]; - else if (!strcmp(argv[ii], "-r")) - reconfig = 1; - } - - /* case 1: being called as program -f inffile */ - if (infFileName) - { - FILE *infFile = fopen(infFileName, "r"); - if (!infFile) - { - ds_report_error(DS_INCORRECT_USAGE, infFileName, - "This file could not be opened. A valid file must be given."); - status = 1; - } - else - fclose(infFile); - - if (!status) - status = create_config_from_inf(&cf, argc, argv); - if (reconfig) - { - status = update_server(&cf); - if (!status) - status = reconfigure_instance(argc, argv); - } - else - { - if (!status) - status = create_config(&cf); - if (!status) - status = configure_instance(); - } - } - /* case 2: being called as a CGI */ - else if (rm) - { - cgi = 1; - status = parse_form(&cf); - if (!status) - status = create_config(&cf); - if (!status) - status = configure_instance_with_config(&cf, 1, 0); - } - /* case 3: punt */ - else - { - ds_report_error ( - DS_INCORRECT_USAGE, - "No request method specified", - "A REQUEST_METHOD must be specified (POST, GET) to run this CGI program."); - status = 1; - } - - if (cgi) - { - /* The line below is used by the console to detect - the end of the operation. See replyHandler() in - MigrateCreate.java */ - fprintf(stdout, "NMC_Status: %d\n", status); - /* In the past, we used to call rpt_success() or rpt_err() - according to status. However these functions are not designed - for our case: they print an HTTP header line "Content-type: text/html" */ - } - -#if defined( hpux ) - _exit(status); -#endif - return status; -} diff --git a/ldap/admin/src/key.rc b/ldap/admin/src/key.rc deleted file mode 100644 index d4e2473a..00000000 --- a/ldap/admin/src/key.rc +++ /dev/null @@ -1,182 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ -//Microsoft Visual C++ generated resource script. -// -#include "resource.h" - -#define APSTUDIO_READONLY_SYMBOLS -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 2 resource. -// -#include "afxres.h" - -///////////////////////////////////////////////////////////////////////////// -#undef APSTUDIO_READONLY_SYMBOLS - - -///////////////////////////////////////////////////////////////////////////// -// -// Dialog -// - -IDD_GETPATH DIALOG DISCARDABLE 0, 0, 293, 155 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "NETSCAPE KEY PAIR FILE GENERATION" -FONT 8, "MS Sans Serif" -BEGIN - EDITTEXT IDE_PATH,93,110,159,13,ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,39,130,50,14 - PUSHBUTTON "Cancel",IDCANCEL,193,129,50,14 - LTEXT "Welcome to the key pair file generator. With this program you can generate the public and private keys that your server uses for secure communications.Make sure that you enter the full pathname of the key file.", - IDC_STATIC,17,17,253,28 - LTEXT "First the server needs to know where to put the new key. You should NOT overwrite an existing key pair file ! Place the new key in a separate location. Make a note of the new key's location ! You will need it later when you request a certificate.", - IDC_STATIC,17,50,251,33 - LTEXT "Key File Location:",IDC_STATIC,17,113,63,8 - LTEXT "If you installed the server into the root c:\\Navgold, you can store the key file in c:\\Navgold\\Server\\<serverid>\\ssl\\key.db", - IDC_STATIC,17,87,251,16 -END - -IDD_GETPASSWORD DIALOG DISCARDABLE 0, 0, 293, 144 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "NETSCAPE KEY PAIR FILE PASSWORD" -FONT 8, "MS Sans Serif" -BEGIN - EDITTEXT IDE_GETPASSWORD,98,104,159,13,ES_PASSWORD | - ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,45,125,50,14 - PUSHBUTTON "Cancel",IDCANCEL,190,123,50,14 - LTEXT "Finally, enter a password which will be used to encrypt the key pair file. You will use this password when starting up and shutting down your server.", - IDC_STATIC,18,24,253,20 - LTEXT "Note: Be sure to keep this password safe ! If you must write down the password, the physical safety of the recording is your responsibility.", - IDC_STATIC,18,50,251,19 - LTEXT "Password",IDC_STATIC,18,105,63,8 - LTEXT "The password must be at least 8 characters long, and must contain at least one non-alphabetic character in it. It should not be a word in any dictionary.", - IDC_STATIC,18,77,255,24 - LTEXT "A random seed has been successfully generated !!", - IDC_STATIC,18,4,246,15 -END - -IDD_GETPASSWORD2 DIALOG DISCARDABLE 0, 0, 265, 116 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "NETSCAPE KEY PAIR FILE PASSWORD" -FONT 8, "MS Sans Serif" -BEGIN - EDITTEXT IDE_GETPASSWORD2,67,50,159,13,ES_PASSWORD | - ES_AUTOHSCROLL - DEFPUSHBUTTON "OK",IDOK,67,78,50,14 - PUSHBUTTON "Cancel",IDCANCEL,176,78,50,14 - LTEXT "Password",-1,10,54,50,8 - LTEXT "Reenter the password for verification:",-1,10,18,255,24 -END - -IDD_GETCERT DIALOG DISCARDABLE 0, 0, 293, 115 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "NETSCAPE KEY CERTIFICATE GENERATION" -FONT 8, "MS Sans Serif" -BEGIN - DEFPUSHBUTTON "OK",IDOK,125,90,50,14 - LTEXT "Congratulations ! Your new key is in the file:", - IDC_STATIC,19,17,253,14 - LTEXT "The next step is to generate a certificate. Select the hyperlink ""Request or renew a certificate from the server manager.", - IDC_STATIC,19,60,251,22 - LTEXT "Static",IDC_KEYFILE,19,38,223,8 -END - -IDD_GETSEED DIALOG DISCARDABLE 0, 0, 301, 156 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "NETSCAPE RANDOM NUMBER SEED GENERATION" -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "Next a random seed must be generated to complete the creation of your key pair file. You have to provide mouse input for this to happen. Move your mouse continuously and randomly on the desktop to provide this input.", - IDC_STATIC,15,12,250,29 - LTEXT "On NT3.51 systems a progress bar will appear to inform you how much more random mouse input the program needs to generate its random seed. When enough input has been obtained from you, another dialog box will notify you.", - IDC_STATIC,15,48,259,25 - LTEXT "As you move the mouse, the location of the cursor is sampled at random intervals and this is added to a sample of a high frequency counter to generate the random seed. Click OK to begin.", - IDC_STATIC,15,83,256,33 - PUSHBUTTON "OK",IDOK,125,137,50,14 - LTEXT "This process could take from 30 seconds to a minute of continuous mouse input.", - IDC_STATIC,15,119,281,8 -END - -IDD_UPDATE DIALOG DISCARDABLE 0, 0, 185, 74 -STYLE DS_MODALFRAME | WS_POPUP | WS_VISIBLE | WS_CAPTION | WS_SYSMENU -CAPTION "Collecting Random User Input ....." -FONT 8, "MS Sans Serif" -BEGIN - LTEXT "Static",IDC_UPDATE,13,8,150,59 -END - - -#ifdef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// TEXTINCLUDE -// - -1 TEXTINCLUDE DISCARDABLE -BEGIN - "resource.h\0" -END - -2 TEXTINCLUDE DISCARDABLE -BEGIN - "#include ""afxres.h""\r\n" - "\0" -END - -3 TEXTINCLUDE DISCARDABLE -BEGIN - "\r\n" - "\0" -END - -///////////////////////////////////////////////////////////////////////////// -#endif // APSTUDIO_INVOKED - - -#ifndef APSTUDIO_INVOKED -///////////////////////////////////////////////////////////////////////////// -// -// Generated from the TEXTINCLUDE 3 resource. -// - - -///////////////////////////////////////////////////////////////////////////// -#endif // not APSTUDIO_INVOKED - diff --git a/ldap/admin/src/latest_file.c b/ldap/admin/src/latest_file.c deleted file mode 100644 index 7e38b368..00000000 --- a/ldap/admin/src/latest_file.c +++ /dev/null @@ -1,135 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/*********************************************************************** -** -** NAME -** latest_file.c -** -** DESCRIPTION -** Creates a batch file which assigns the latest file matching a given -** pattern to the environment variable LATEST_FILE. For use in NT batch -** files. -** -** AUTHOR -** <rweltman@netscape.com> -** -***********************************************************************/ - -/*********************************************************************** -** Includes -***********************************************************************/ - - -/* - * Given a pattern to match, creates a batch file with the latest full - * file name to set to LATEST_FILE. No file is created if there are no - * matching files. - */ -#if defined( _WIN32 ) -#include <stdlib.h> -#include <stdio.h> -#include <string.h> -#include <io.h> - - -int main (int argc, char **argv) -{ - char *szWildcardFileSpec; - char *szOutput; - char dir[1024]; - char latest[1024]; - char *dirEnd; - time_t latest_time = 0; - long hFile; - struct _finddata_t fileinfo; - FILE *fBatch; - - if ( argc < 3 ) { - fprintf( stderr, "Usage: %s PATTERN OUTPUTFILE\n", argv[0] ); - return 1; - } - - szWildcardFileSpec = argv[1]; - szOutput = argv[2]; - - /* Get directory part of path */ - strncpy( dir, szWildcardFileSpec, sizeof(dir)-1 ); - dir[sizeof(dir)-1] = (char)0; - dirEnd = strrchr( dir, '\\' ); - if ( dirEnd != NULL ) { - *dirEnd = 0; - } - - /* Expand file specification */ - hFile = _findfirst( szWildcardFileSpec, &fileinfo); - if( hFile == -1 ) { - perror( "No matching files!" ); - return -1; - } - - _snprintf( latest, sizeof(latest), "%s\\%s", dir, fileinfo.name ); - latest[sizeof(latest)-1] = (char)0; - latest_time = fileinfo.time_create; - - while( _findnext( hFile, &fileinfo ) == 0 ) { - if ( fileinfo.time_create > latest_time ) { - _snprintf( latest, sizeof(latest), "%s\\%s", dir, fileinfo.name ); - latest[sizeof(latest)-1] = (char)0; - latest_time = fileinfo.time_create; - } - } - - _findclose( hFile ); - - /* create batch file */ - fBatch = fopen (szOutput, "w"); - if ( fBatch == NULL ) { - perror ("Unable to create batch file!"); - return 1; - } - fprintf( fBatch, "set LATEST_FILE=%s\n", latest ); - fclose (fBatch); - - return 0; -} -#endif /* ( XP_WIN32 ) */ diff --git a/ldap/admin/src/migrateInstance b/ldap/admin/src/migrateInstance deleted file mode 100644 index 95cab4b1..00000000 --- a/ldap/admin/src/migrateInstance +++ /dev/null @@ -1,581 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# migrate an old server instance to a new server instance - -BEGIN { - $| = 1; - # print CGI header - print "Content-type: text/plain\n\n"; - require 'uname.lib'; - - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - # get the server root directory - $sroot = $ENV{'NETSITE_ROOT'}; - $exitCode = 0; - @INC = ( '.', '../../../admin/admin/bin' ); - grep { s@/@\\@g } @INC if $isNT; - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - $slapdExecName = $isNT ? 'slapd.exe' : 'ns-slapd'; - $nullFile = $isNT ? 'nul' : '/dev/null'; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; - if ($isNT) { - # we have to pass batch files directly to the NT command interpreter - $com_spec = $ENV{ComSpec}; - if (!$com_spec) { - $com_spec = $ENV{COMSPEC}; - } - if (!$com_spec || ! -f $com_spec) { - # find the first available command interpreter - foreach $drive (c..z) { - $com_spec = "$drive:\\winnt\\system32\\cmd.exe"; - last if (-f $com_spec); - $com_spec = undef; - } - if (! $com_spec) { - # punt and pray - $com_spec = 'c:\winnt\system32\cmd.exe'; - } - } - $os = "WINNT"; - } else { - $os = &uname("-s"); - } - - if ( ($os eq "AIX") || ($os eq "HP-UX") ) { - $sigChildHandler = 'sigChildHandler'; - } -} - -sub mySystem { - my $cmd = $_[0]; - # the system {$cmd} avoids some NT shell quoting problems if the $cmd - # needs to be quoted e.g. contains spaces; the map puts double quotes - # around the arguments on NT which are stripped by the command - # interpreter cmd.exe; but don't quote things which are already quoted - my @fixargs = map { /^[\"].*[\"]$/ ? $_ : $quote . $_ . $quote } @_; - my $rc = 0; - if ($cmd =~ /[.](bat|cmd)$/) { - # we have to pass batch files directly to the NT command interpreter - $cmd = $com_spec; -# print "system $cmd /c \"@fixargs\"\n"; - $rc = system {$cmd} '/c', "\"@fixargs\""; - } else { -# print "system $cmd \"@fixargs\"\n"; - $rc = system {$cmd} @fixargs; - } - - return $rc; -} - -sub getNextEntry { - my $fh = shift; - my @entry = (); # an array of strings, each string is 1 attr/value pair - my $line = ""; - while (($line = <$fh>) && !($line =~ /^$/)) { # entry is terminated by EOF or empty line34 - chop $line; - if ($line =~ /^\s/) { # line begins with a single space char - $entry[@entry-1] .= $'; # add continuation to line - } else { - push @entry, $line; - } - } - return @entry; -} - -sub runAndIgnoreOutput { - my $cmd = shift; - print "\n."; - open(RUNCMD, "${quote}$cmd${quote} 2>&1 |") or die "Error: could not run $cmd: $!"; - print "\n." ; - sleep(1); # allow pipe to fill with data - print "\n." ; - while (<RUNCMD>) { -# print; - } - my $code = close(RUNCMD); -# print "runAndIgnore: code=$code status=$?\n"; - return $?; -} - -sub printEntry { - my $fh = shift; - foreach (@_) { - print $fh $_, "\n"; - } - print $fh "\n"; -} - -sub reportAndExit { - my $now_time = gmtime; - print "END migration at ", $now_time, " GMT\n"; - print "Exit status is ", $exitCode, "\n"; - if ($? == 0 && $exitCode == 0) { - print "NMC_STATUS: 0\n"; - } else { - # not necessary to show this - print '$?=', $?+0, ' $!=', $!+0, ' $exitCode=', $exitCode, "\n"; - print shift, "\n"; - print "NMC_STATUS: $exitCode\n"; - } - - print "###MIGRATION FINISHED###\n"; - - exit($exitCode); -} - -# put stderr on stdout -open(STDERR, ">&STDOUT" ); -# use unbuffered output -select(STDERR); -$| = 1; -select(STDOUT); -$| = 1; -$TRACELEVEL = 0 ; - -sub sigChildHandler { -# print "in sig child handler\n"; -# print "args = @_\n"; -} - -$SIG{__DIE__} = 'exit'; -$SIG{'QUIT'} = 'exit'; -$SIG{'INT'} = 'exit'; -$SIG{'TERM'} = 'exit'; -# AIX needs a SIGCHILD handler for pipes -if (defined($sigChildHandler)) { - $SIG{'CHLD'} = $sigChildHandler; - $SIG{'CLD'} = $sigChildHandler; -} - -# the atexit handler -END { - $! = 0; - $? = $exitCode; - if ($exitCode == 0) { - # just give a report if the operation was successfull - &reportAndExit; } -} - -# process the CGI input -use Cgi; - -if (($sroot =~ m#/$#) || ($sroot =~ m#\\$#)) { - chop $sroot; -} - -if (($cgiVars{'oldServerRoot'} =~ m#/$#) || ($cgiVars{'oldServerRoot'} =~ m#\\$#)) { - chop $cgiVars{'oldServerRoot'}; -} - -$instanceDir = $sroot . $PATHSEP . 'slapd-' . $cgiVars{'servid'}; - -######################################################################################### -# get the Directory Server version -# For the moment the migration works only from 4.x version to 5.0 version -# As for as previous versions are concerned we don't migrate neither 1.x nor 3.x -######################################################################################### - -($oldVersion, $oldMinor) = &getVersion($cgiVars{'oldServerRoot'}); -print "\n\noldVersion: $oldVersion, oldMinor: $oldMinor" ; - - -if ($oldVersion < 4) { - # migration of version under 4 is not supported - # abort the use of the migration script up to 5.1 - $exitCode = 1 ; - die "\n\n\n\n\n\n\nThe migration of a $oldVersion.x directory instance is not available." . - "\n\nINFORMATION" . - "\nYou can also migrate a 4.x directory server." . - "\nIt must be executed manually through a command line." . - "\nPlease refer to the product documentation to get usage and prerequisites\n"; -} -else { - # print begin message - $now_time = gmtime; - print "BEGIN migration at: ", $now_time, " GMT\n"; - $oldSlapdConf = $cgiVars{'oldServerRoot'} . $PATHSEP . 'slapd-' . - $cgiVars{'oldServerName'} . $PATHSEP . 'config' . $PATHSEP . - 'slapd.conf'; - - open(OLDSLAPDCONF, $oldSlapdConf) or - die "Error: could not open old config file $oldSlapdConf: $!"; - while(<OLDSLAPDCONF>) { - chop; - if (/^port\s+/i) { - if (! $cgiVars{'servport'}) { - $cgiVars{'servport'} = $'; - $old_port = $' ; - $Cgi::CONTENT .= '&servport=' . $'; - if ($ENV{'QUERY_STRING'}) { - $ENV{'QUERY_STRING'} .= '&servport=' . $'; - } - } - } elsif (/^rootdn\s+/i) { - if (! $cgiVars{'rootdn'}) { - ($value = $') =~ s/^[\"]//; - # remove leading " - $value =~ s/[\"]$//; - # remove trailing " - $cgiVars{'rootdn'} = $value; - $Cgi::CONTENT .= '&rootdn=' . $value; - if ($ENV{'QUERY_STRING'}) { - $ENV{'QUERY_STRING'} .= '&rootdn=' . $value; - } - } - } - } - close(OLDSLAPDCONF); - - $testDir = $instanceDir . $PATHSEP . 'config'; - - # check if it's necessary or not to stop the old server - if (-d $testDir) { - printTrace("\ninstance already exists \n",3) ; - # the instance already exists - $DSEldif = $instanceDir. $PATHSEP . 'config' . $PATHSEP . 'dse.ldif'; - open(DSELDIF, $DSEldif) or - die "Error: could not open old config file $DSEldif: $!"; - while(<DSELDIF>) { - chop; - if (/^nsslapd-port:\s+/i) { - $cgiVars{'servport'} = $'; - $Cgi::CONTENT .= '&servport=' . $'; - if ($ENV{'QUERY_STRING'}) { - $ENV{'QUERY_STRING'} .= '&servport=' . $'; - } - } elsif (/^nsslapd-rootdn:\s+/i) { - ($value = $') =~ s/^[\"]//; - # remove leading " - $value =~ s/[\"]$//; - # remove trailing " - $cgiVars{'rootdn'} = $value; - $Cgi::CONTENT .= '&rootdn=' . $value; - if ($ENV{'QUERY_STRING'}) { - $ENV{'QUERY_STRING'} .= '&rootdn=' . $value; - } - } - } - close(DSELDIF); - if ($old_port eq $cgiVars{'servport'}) { - # need to stop the old instance - if ($cgiVars{'shutdown_old_server'}) { - &stopServer($cgiVars{'oldServerRoot'}, 'slapd-' . $cgiVars{'oldServerName'}); - } - } - &startServer(); - } - else { - # need to stop the old instance - if ($cgiVars{'shutdown_old_server'}) { - &stopServer($cgiVars{'oldServerRoot'}, 'slapd-' . $cgiVars{'oldServerName'}); - } - } - - @cgi = keys(%cgiVars); - printTrace("\ncgi: @cgi",3); - printTrace("\npwd: $cgiVars{'rootpw'}, rootdn: $cgiVars{'rootdn'}, port: $cgiVars{'servport'}, - old_instance -o: $cgiVars{'oldServerRoot'}$PATHSEPslapd-$cgiVars{'oldServerName'}, - new_instance -n: $sroot$PATHSEPslapd-$cgiVars{'servid'}",3) ; - - # if the instance does not exist, create it - if (! -d $testDir) { - print "Creating the new instance . . .\n"; - printTrace("\nbefore instance creation\n",3) ; - # call the instance creation program; we should already be in the same - # directory; if we are being called as a CGI, index will parse the CGI - # parameters, otherwise, it will use the command line parameters - if ($isNT) { - $myprog = "ds_create.exe"; - } else { - $myprog = "./ds_create"; - } - printTrace("\nafter instance creation\n",3) ; - - # since we already parsed stdin, we need to pass it to the instance creation - # CGI somehow; fortunately, we saved the old contents of stdin in the - # $Cgi::CONTENT, so just pipe that into our CGI - # print "executing $myprog @ARGV\n"; - open(INDEX, "|$myprog @ARGV") or die "Error: system($myprog, @ARGV): $!"; - sleep(1); # allow prog to init stdin read buffers - print INDEX $Cgi::CONTENT, "\n"; - close INDEX; - - $exitCode = $?; - if ($exitCode != 0) { - die "Error: could not create new instance: $!"; - } - - - } else { - } - - - printTrace("\nBefore instance created test\n",3) ; - - chdir("$sroot${PATHSEP}bin${PATHSEP}slapd${PATHSEP}admin${PATHSEP}bin"); - - # Now that the new instance is created, merge in the old configuration data - # $cgiVars{'oldServerRoot'} will contain the full path of the old server - # root directory - # $cgiVars{'oldServerName'} will contain the old instance name - $myscript = "migrateInstance5"; - # print "executing $myscript $sroot $cgiVars{'oldServerRoot'} $cgiVars{'servid'} $cgiVars{'oldServerName'} $savedLdif\n"; - - @args = ($, $myscript, '-p', $cgiVars{'servport'}, '-D', $cgiVars{'rootdn'}, '-w', $cgiVars{'rootpw'}, '-o', - $cgiVars{'oldServerRoot'} . $PATHSEP . 'slapd-' . $cgiVars{'oldServerName'}, '-n', - $sroot . $PATHSEP . 'slapd-' . $cgiVars{'servid'}, '-noinput'); - $exitCode = &mySystem(@args); - die "Error: @args: $!" if ($exitCode != 0); - } - - -sub startServer { - my $errLog = $instanceDir . $PATHSEP . 'logs' . $PATHSEP . 'errors'; - # emulate tail -f - # if the last line we see does not contain "slapd started", try again - my $done = 0; - my $started = 0; - my $code = 0; - my $lastLine = ""; - my $timeout = time + 60; # 1 minute - my $startCmd = $instanceDir . $PATHSEP . 'start' . $script_suffix; - if (! -f $startCmd) { - $startCmd = $instanceDir . $PATHSEP . 'start-slapd' . $script_suffix; - } - $code = &mySystem($startCmd); - open(IN, $errLog) or die "Could not open error log $errLog: $!"; - my $pos = tell(IN); - while (($done == 0) && (time < $timeout)) { - for (; ($done == 0) && ($_ = <IN>); $pos = tell(IN)) { - $lastLine = $_; -# print; - # the server has already been started and shutdown once . . . - if (/slapd started\./) { - $started++; - if ($started == 2) { - $done = 1; - } - # sometimes the server will fail to come up; in that case, restart it - } elsif (/Initialization Failed/) { -# print "Server failed to start: $_"; - $code = &mySystem($startCmd); - # sometimes the server will fail to come up; in that case, restart it - } elsif (/exiting\./) { -# print "Server failed to start: $_"; - $code = &mySystem($startCmd); - } - } - if ($lastLine =~ /PR_Bind/) { - # server port conflicts with another one, just report and punt - print $lastLine; - print "This server cannot be started until the other server on this\n"; - print "port is shutdown.\n"; - $done = 1; - } - if ($done == 0) { - # rest a bit, then . . . - sleep(2); - # . . . reset the EOF status of the file desc - seek(IN, $pos, 0); - } - } - close(IN); - - if ($started < 2) { - $! = $code; -# $now = time; -# if ($now > $timeout) { -# print "Possible timeout: timeout=$timeout now=$now\n"; -# } - die "Error: could not start server: $!"; - } - - return 0; -} - -sub stopServer { - my $root = shift; - my $name = shift; - $maxStopIterations = 60; - print "Shutting down server $name . . .\n"; - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop' . $script_suffix . $quote; - if (! -f $stopCmd) { - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop-slapd' . $script_suffix . $quote; - } - - if (! -f $stopCmd) { - # no stop command, probably a 1.X system; for NT, we'll try net stop - # for unix, we'll get the pid and kill it - if ($isNT) { - $stopCmd = 'net stop ' . $name; - } else { - # see if there is a pid file - $pidfile = $root . $PATHSEP . $name . $PATHSEP . 'logs' . - $PATHSEP . 'pid'; - if (open(PIDFILE, $pidfile)) { - chomp($pid = <PIDFILE>); - close(PIDFILE); - while ($maxStopIterations-- && !$exitCode) { - $exitCode = kill(15, $pid); - } - $stopCmd = undef; - } - } - } - - # keep looping until the stop cmd returns an error code, which usually - # means that what ever we want to stop is stopped, or some other error - # occurred e.g. permission, or no such service - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - while ($stopCmd && $maxStopIterations-- && !$exitCode) { - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - } - - if (!$maxStopIterations) { - print "Warning: could not shutdown the old server: $!\n"; - } - - sleep(10) if ($isNT); - - $exitCode = 0; -} - -############################################################################# -# print message error to the user standard output. - -sub printTrace { - - my $Msg = shift ; - my $level = shift ; - if ($level <= $TRACELEVEL) { - print($Msg); - } - -} - -############################################################################# - -sub getVersion { - my $rootDir = shift; - my $version = 0; - my $minor = 0; - my $progDir = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - my $progDir2 = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}"; - # get the current directory so we can go back to it - my $curdir = &getCwd; - - # find the slapd executable - $prog = $rootDir . $progDir . $slapdExecName; - if (! -f $prog) { - $prog = $rootDir . $progDir2 . $slapdExecName; - if (-f $prog && $isNT) { - # if slapd is in bin/slapd and we're on NT, just assume version 1; - # apparently, slapd.exe doesn't like the -v argument . . . - return ( '1', $minor ); - } - } - - # read the old version from the old slapd program - chdir($rootDir . $progDir) or - die "Could not chdir to $rootDir${progDir}: $!: "; - open(F, "${quote}${quote}$prog${quote} -v${quote} 2>&1 |") or - die "Could not run slapd program $prog: $!"; - sleep(1); # allow some data to accumulate in the pipe -# print "Output from $prog -v:\n"; - while (<F>) { - print; - if (/^Netscape-Directory\/(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - last; - } - elsif (/^Netscape-Directory\(restriced-mode\)\/(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - last; - } - } - $code = close(F); -# print "$prog returned code=$code status=$?\n"; - - # done determining versions; go back to orig directory - chdir($curdir) or die "Could not chdir to $curdir: $!: "; - - $version == 0 and - die "Could not determine version of the directory server in $rootDir: "; - - return ( $version, $minor ); -} - - -############################################################################# - -sub getCwd { - my $command = $isNT ? "cd" : "/bin/pwd"; - open(PWDCMD, "$command 2>&1 |") or - die "Error: could not execute $command: $!"; - # without the following sleep, reading from the pipe will - # return nothing; I guess it gives the pwd command time - # to get some data to read . . . - sleep(1); - my $curdir; - while (<PWDCMD>) { - if (!$curdir) { - chomp($curdir = $_); - } - } - my $code = close(PWDCMD); -# if ($code || $?) { -# print "$command returned code=$code status=$? dir=$curdir\n"; -# } -# print "getCwd curdir=\[$curdir\]\n"; - return $curdir; -} - -############################################################################# -############################################################################# -############################################################################# diff --git a/ldap/admin/src/migrateLocalDB b/ldap/admin/src/migrateLocalDB deleted file mode 100644 index 90e9a97f..00000000 --- a/ldap/admin/src/migrateLocalDB +++ /dev/null @@ -1,297 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# Migrate a SuiteSpot 2.X or 3.X localdb to a 4.0 directory server - -BEGIN { - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - @INC = ( '.', '../../../admin/admin/bin' ); - grep { s@/@\\@g } @INC if $isNT; - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; -} - -sub getNextEntry { - my $fh = shift; - my @entry = (); # an array of strings, each string is 1 attr/value pair - my $line = ""; - while (($line = <$fh>) && !($line =~ /^$/)) { # entry is terminated by EOF or empty line34 - chop $line; - if ($line =~ /^\s/) { # line begins with a single space char - $entry[@entry-1] .= $'; # add continuation to line - } else { - push @entry, $line; - } - } - return @entry; -} - -# given a string of the form string:value, return everything to the left of the : -sub getAttrName { - my $s = shift; - $s =~ s/[:].*$//; - return $s; -} - -sub printEntry { - my $fh = shift; - foreach (@_) { - print $fh $_, "\n"; - } - print $fh "\n"; -} - -sub usage { - print 'Usage: perl migrateLocalDb <userdb> <new suffix> [<new instance>]', "\n"; - print "\t", '<userdb> - full path to the userdb directory to migrate', "\n"; - print "\t", ' e.g. /usr/netscape/suitespot3/userdb', "\n"; - print "\t", '<new suffix> - new suffix e.g. dc=example,dc=com; may be empty', "\n"; - print "\t", '<new instance> - full path to the destination instance', "\n"; - print "\t", ' e.g. /usr/netscape/server4/slapd-foo', "\n"; - print "The new instance is optional. If not given, the local db will\n"; - print "be converted to the LDIF file userdb/localdb.ldif, but\n"; - print "it will not be added to the database of the new instance.\n"; -} - -sub sigDieHandler { - print @_, "\n"; - print "\n"; - &usage(); - print "\n"; - print "NMC_STATUS: ", 0+$!, "\n"; - exit $!; -} - -$SIG{__DIE__} = 'sigDieHandler'; - -# check for command line arguments -if (@ARGV > 0) { - $localDBPath = $ARGV[0]; - $newSuffix = $ARGV[1]; - $instanceDir = $ARGV[2]; - $bindDN = $ARGV[3]; - $bindPwd = $ARGV[4]; - # the perl executable should be in server root/install/ - $relPath = '/install/'; - $relPath =~ s#/#\\#g if ($isNT); - ($sroot = $) =~ s#$relPath.*$##; -} elsif ($ENV{'REQUEST_METHOD'}) { - $| = 1; - # print CGI header - print "Content-type: text/plain\n\n"; - - # process the CGI input - use Cgi; - - # get the server root directory - $sroot = $ENV{'NETSITE_ROOT'}; - - $localDBPath = $cgiVars{'localDBPath'}; - $newSuffix = $cgiVars{'newSuffix'}; - $instanceDir = $cgiVars{'instanceDir'}; - $bindDN = $cgiVars{'bindDN'}; - $bindPwd = $cgiVars{'bindPwd'}; -} else { - die ""; -} - -# this is a table of attributes which have DN syntax -%dnAttrs = ( - 'aliasedobjectname', "\n", - 'member', "\n", - 'owner', "\n", - 'roleoccupant', "\n", - 'seealso', "\n", - 'dn', "\n", - 'uniquemember', "\n", - 'creatorsname', "\n", - 'modifiersname', "\n", - 'manager', "\n", - 'documentauthor', "\n", - 'secretary', "\n", - 'associatedname', "\n", - 'ditredirect', "\n", - 'targetdn', "\n", - 'newrdn', "\n", - 'newsuperior', "\n", - 'lastmodifiedby', "\n", - 'replicaroot', "\n", - 'replicabinddn', "\n", - 'cirreplicaroot', "\n", - 'cirbinddn', "\n", - 'vlvbase', "\n", - 'netscapemdsuffix', "\n", - 'changelog', "\n", - 'obsoletedbydocument', "\n", - 'obsoletesdocument', "\n", - 'reciprocalnaminglink', "\n", - 'updatedbydocument', "\n", - 'updatesdocument', "\n" -); - -print "Begin local db migration\n"; - -# see if the parameters are valid -# check localdb path -die "Error: could not find the local db $localDBPath" if (! -d $localDBPath); -# check suffix? - -# get the old server root directory -# step 1: convert the local db to an ldif file -# lookup the old suffix from the lcache.conf -$lcache = $localDBPath . $PATHSEP . 'ldap' . $PATHSEP . 'config' . $PATHSEP . - 'lcache.conf'; -open(LCACHE, "$lcache") or die "Error: could not open config file $lcache"; -while (<LCACHE>) { - chop; - if (/^suffix\s+/i) { - $oldSuffix = $'; - $oldSuffix =~ s/^[\"]//; - # trim leading " - $oldSuffix =~ s/[\"]$//; - # trim trailing " - print "The old suffix is $oldSuffix\n"; - } -} -close(LCACHE); - -print "Converting the local db to LDIF . . .\n"; -# run the ldapsearch -C command -$cmddir = $localDBPath . $PATHSEP . 'ldap' . $PATHSEP . 'tools'; -@cmd = ($quote . $cmddir . $PATHSEP . 'ldapsearch' . $quote, '-C', - "${quote}$lcache${quote}", - '-s', 'sub', '-b', "\"$oldSuffix\"", '"objectclass=*"'); -chdir($cmddir) or die "Error: could not change to directory $cmddir"; -open(READCMD, "${quote}@cmd${quote}|") or die "Error: could not execute @cmd"; -if ($instanceDir) { - $outputFile = $instanceDir . $PATHSEP . 'ldif' . $PATHSEP . 'localdb.ldif'; -} else { - $outputFile = $localDBPath . $PATHSEP . 'localdb.ldif'; -} - -open(OUT, ">$outputFile") or die "Error: could not write file $outputFile"; -while (@entry = getNextEntry(\*READCMD)) { - # for each entry, replace the old suffix with the new one; if there - # was no old suffix, just append the new one to the DN value attrs - if ($newSuffix && $newSuffix ne '""') { - if ($oldSuffix && $oldSuffix ne '""') { - grep { s/$oldSuffix/$newSuffix/ig } @entry; - } else { - for ($ii = 0; $ii < @entry; ++$ii) { - $name = &getAttrName($entry[$ii]); - if ($dnAttrs{lc($name)}) { - $entry[$ii] .= ", $newSuffix"; - } - } - } - } - - printEntry(\*OUT, @entry); -} -close(READCMD); -close(OUT); - -if ($? != 0) { - die "Error: could not read local db from $localDBPath"; -} elsif (! -s $outputFile) { - die "Error: converted local db is empty"; -} - -# check instance dir - -if ($instanceDir) { - if (! -d $instanceDir) { - # use may have given relative path - $instanceDir = $sroot . $PATHSEP . $instanceDir; - die "Error: could not find the instance dir $instanceDir in server root $sroot" - if (! -d $instanceDir); - } - -# step 2: load the converted LDIF file into the target directory server -# if the bindDN and password were given, attempt to use ldif2ldap, otherwise, -# shutdown the server and use ldif2db - - if ($bindDN && $bindPwd) { - } else { - print "Shutting down the server . . .\n"; - # shutdown the server - $stopCmd = $quote . $instanceDir . $PATHSEP . 'stop-slapd' . $script_suffix . $quote; - system($stopCmd); - print "Warning: could not shutdown the server in $instanceDir.\nThe server may already be down." if ($? != 0); - sleep(10); # give the server time to shutdown - - # add the new suffix to the slapd.ldbm.conf - if ($newSuffix && $newSuffix ne '""') { - print "Adding suffix $newSuffix . . .\n"; - $slc = $instanceDir . $PATHSEP . 'config' . $PATHSEP . 'slapd.ldbm.conf'; - open(SLC, ">>$slc") or - print "Warning: could not add the suffix $newSuffix: import may fail.\n"; - print SLC "suffix\t\"$newSuffix\"\n"; - close(SLC); - } - - print "Importing the local db LDIF file . . .\n"; - # import the LDIF file - @impCmd = ($quote . $instanceDir . $PATHSEP . 'ldif2db' . $quote, - '-C', '-i', "${quote}$outputFile${quote}"); - system(@impCmd); - die "Error: could not import LDIF file $outputFile" if ($? != 0); - - print "Restarting the server . . .\n"; - # start the server - $startCmd = $quote . $instanceDir . $PATHSEP . 'start-slapd' . $script_suffix . $quote; - system($startCmd); - print "Warning: could not restart the server in $instanceDir" if ($? != 0); - } - - print "Finished. The local db has been imported to $instanceDir.\n"; -} else { - print "Finished. The local db has been written to $outputFile.\n"; -} - -if (%cgiVars) { - print "NMC_STATUS: 0\n"; -} - -exit 0; diff --git a/ldap/admin/src/migratePwdFile b/ldap/admin/src/migratePwdFile deleted file mode 100644 index 5b76381a..00000000 --- a/ldap/admin/src/migratePwdFile +++ /dev/null @@ -1,122 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# -# -# Convert an old password.txt file into the new pin.txt format -# This script requires a single argument which is the directory and -# server instance prefix of the two files (e.g. /servers/alias/slapd-foo) -# -# ISSUES: -# This code sets the mode of the created file to 660 (allows suitespot -# group access. Should it also set the user and group values? Where -# should they come from? -# -BEGIN { - $isNT = -d "\\"; - $PS = $isNT ? "\\" : "/"; -} - -$sroot = $ARGV[0]; -$prefix = $ARGV[1]; - -# -# create the names for the old (password) and new (pin) files -# -$pwdfile = "${prefix}-password.txt"; -$pinfile = "${prefix}-pin.txt"; - -if (-f $pwdfile && ! -f $pinfile) { - open(PWDFILE, $pwdfile) || die "Cannot open password file: $pwdfile\n"; - - my $count = 0; - my $pin; - while(<PWDFILE>) { - chomp; # trim new line - - if ($count == 0) { - $pin = $_; - } - - $count = $count+1; - } - close PWDFILE; - - if ($count == 0) { - die "No password found in password file\n"; - } elsif ($count != 1) { - print "Extra lines found in password file\n"; - } - - open(PINFILE, ">$pinfile") || die "Cannot create pin file: $pinfile\n"; - print PINFILE "Software (Internal) Token:$pin\n"; - close PINFILE; - chmod 0660, $pinfile; - - # set the ownership of the file; should be the same as the slapd user id - if (! $isNT) { - $confFile = "$sroot${PS}$prefix${PS}config${PS}slapd.conf"; - open(CONF, $confFile) or die "Error: cannot open $confFile: $!"; - while (<CONF>) { - if (/^localuser\s+/i) { - chomp($newuser = $'); - last; - } - } - close(CONF); - if (!$newuser) { - $confFile = "$sroot${PS}shared${PS}config${PS}ssusers.conf"; - open(SSUSERS, $confFile) or - die "Error: could not open $confFile: $!"; - while (<SSUSERS>) { - chop; - if (/^SuiteSpotUser\s+/i) { - $newuser = $'; - last; - } - } - close(SSUSERS); - } - if ($newuser) { - chown $newuser, $pinfile; - } - } -} - -exit 0; diff --git a/ldap/admin/src/migrateTo11.in b/ldap/admin/src/migrateTo11.in deleted file mode 100644 index 01ba572c..00000000 --- a/ldap/admin/src/migrateTo11.in +++ /dev/null @@ -1,644 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# Copyright (C) 2007 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# cmd line parsing -use Getopt::Long; -# tempfiles -use File::Temp qw(tempfile tempdir); - -# load perldap -use Mozilla::LDAP::Conn; -use Mozilla::LDAP::Utils qw(normalizeDN); -use Mozilla::LDAP::API qw(ldap_explode_dn); -use Mozilla::LDAP::LDIF; - -# these are the attributes for which we will always use -# the new value, or which do not apply anymore -my %ignoreOld = -( - 'nsslapd-errorlog' => 'nsslapd-errorlog', - 'nsslapd-accesslog' => 'nsslapd-accesslog', - 'nsslapd-auditlog' => 'nsslapd-auditlog', - 'nskeyfile' => 'nsKeyfile', - 'nscertfile' => 'nsCertfile', - 'nsslapd-pluginpath' => 'nsslapd-pluginPath', - 'nsslapd-plugintype' => 'nsslapd-pluginType', - 'nsslapd-pluginversion' => 'nsslapd-pluginVersion', - 'nsslapd-plugin-depends-on-named' => 'nsslapd-plugin-depends-on-named', -# these are new attrs that we should just pass through - 'nsslapd-schemadir' => 'nsslapd-schemadir', - 'nsslapd-lockdir' => 'nsslapd-lockdir', - 'nsslapd-tmpdir' => 'nsslapd-tmpdir', - 'nsslapd-certdir' => 'nsslapd-certdir', - 'nsslapd-ldapifilepath' => 'nsslapd-ldapifilepath', - 'nsslapd-ldapilisten' => 'nsslapd-ldapilisten', - 'nsslapd-ldapiautobind' => 'nsslapd-ldapiautobind', - 'nsslapd-ldapimaprootdn' => 'nsslapd-ldapimaprootdn', - 'nsslapd-ldapimaptoentries' => 'nsslapd-ldapimaptoentries', - 'nsslapd-ldapiuidnumbertype' => 'nsslapd-ldapiuidnumbertype', - 'nsslapd-ldapigidnumbertype' => 'nsslapd-ldapigidnumbertype', - 'nsslapd-ldapientrysearchbase' => 'nsslapd-ldapientrysearchbase', - 'nsslapd-ldapiautodnsuffix' => 'nsslapd-ldapiautodnsuffix' -); - -# these are the attributes for which we will always use -# the old value -my %alwaysUseOld = -( - 'aci' => 'aci' -); - -# global vars used throughout script + subs -my $pkgname = "@package_name@"; -# this is the new pkgname which may be something like -# fedora-ds-base - we have to strip off the -suffix -if ($pkgname =~ /-(core|base)$/) { - $pkgname =~ s/-(core|base)$//; -} -my $oldpkgname = $pkgname; -my $oldsroot = "/opt/$oldpkgname"; - -# figure out the current bdb version -my $db_version=`db_verify -V`; -my ($db_major_version, $db_minor_version); -if ($db_version =~ /Berkeley DB (\d+)\.(\d+)/) { - $db_major_version = $1; - $db_minor_version = $2; -} -my $db_verstr = "bdb/${db_major_version}.${db_minor_version}/libback-ldbm"; - -my $debuglevel = 0; -# use like this: -# debug(3, "message"); -# this will only print "message" if $debuglevel is 3 or higher (-vvv on the command line) -sub debug { - my ($level, @rest) = @_; - if ($level <= $debuglevel) { - print STDERR "+" x $level, @rest; - } -} - -sub getNewDbDir { - my ($ent, $attr, $inst) = @_; - my %objclasses = map { lc($_) => $_ } $ent->getValues('objectclass'); - my $cn = $ent->getValues('cn'); - my $newval; - if ($objclasses{nsbackendinstance}) { - $newval = "@localstatedir@/lib/$pkgname/$inst/db/$cn"; - } elsif (lc $cn eq 'config') { - $newval = "@localstatedir@/lib/$pkgname/$inst/db"; - } elsif (lc $cn eq 'changelog5') { - $newval = "@localstatedir@/lib/$pkgname/$inst/cldb"; - } - debug(2, "New value [$newval] for attr $attr in entry ", $ent->getDN(), "\n"); - return $newval; -} - -sub migrateCredentials { - my ($ent, $attr, $inst) = @_; - my $oldval = $ent->getValues($attr); - debug(3, "Executing migratecred -o $oldsroot/$inst -n @instconfigdir@/$inst -c $oldval . . .\n"); - my $newval = `migratecred -o $oldsroot/$inst -n @instconfigdir@/$inst -c $oldval`; - debug(3, "Converted old value [$oldval] to new value [$newval] for attr $attr in entry ", $ent->getDN(), "\n"); - return $newval; -} - -# these are attributes that we have to transform from -# the old value to the new value (e.g. a pathname) -# The key of this hash is the attribute name. The value -# is an anonymous sub which takes two arguments - the entry -# and the old value. The return value of the sub is -# the new value -my %transformAttr = -( - 'nsslapd-directory' => \&getNewDbDir, - 'nsslapd-db-logdirectory' => \&getNewDbDir, - 'nsslapd-changelogdir' => \&getNewDbDir, - 'nsds5replicacredentials' => \&migrateCredentials, - 'nsmultiplexorcredentials' => \&migrateCredentials -); - -#nsslapd-directory - if same as old path, convert to new, otherwise, leave it -#nsslapd-logdirectory - if same as old path, convert to new, otherwise, leave it - -#nsslapd-accesslog -#nsslapd-errorlog -#nsslapd-auditlog - -#nskeyfile -#nscertfile - -#dn: cn=Internationalization Plugin -#nsslapd-pluginArg0: $inst/config/slapd-collations.conf - -#dn: cn=referential integrity postoperation -#nsslapd-pluginarg1: $inst/logs/referint - -# don't forget changelogdb and certmap.conf -# [General] -# FullMachineName= localhost.localdomain -# SuiteSpotUserID= nobody -# ServerRoot= /usr/lib64/fedora-ds -# [slapd] -# ServerPort= 1100 -# ServerIdentifier= localhost -# Suffix= dc=example,dc=com -# RootDN= cn=Directory Manager -# RootDNPwd= Secret123 - -sub createInfFileFromDseLdif { - my $oldroot = shift; - my $inst = shift; - my $fname = "$oldroot/$inst/config/dse.ldif"; - my $id; - ($id = $inst) =~ s/^slapd-//; - open( DSELDIF, "$fname" ) || die "Can't open $fname: $!"; - my ($outfh, $inffile) = tempfile(SUFFIX => '.inf'); - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($ent = readOneEntry $in) { - my $dn = $ent->getDN(); - if ($dn =~ /cn=config/) { - print $outfh "[General]\n"; - print $outfh "FullMachineName = ", $ent->getValues('nsslapd-localhost'), "\n"; - print $outfh "SuiteSpotUserID = ", $ent->getValues('nsslapd-localuser'), "\n"; - print $outfh "ServerRoot = @serverdir@\n"; - print $outfh "[slapd]\n"; - print $outfh "RootDN = ", $ent->getValues('nsslapd-rootdn'), "\n"; - print $outfh "RootDNPwd = ", $ent->getValues('nsslapd-rootpw'), "\n"; - print $outfh "ServerPort = ", $ent->getValues('nsslapd-port'), "\n"; - print $outfh "ServerIdentifier = $id\n"; - print $outfh "Suffix = o=deleteAfterMigration\n"; - print $outfh "start_server= 0\n"; - last; - } - } - close $outfh; - close DSELDIF; - - return $inffile; -} - -sub makeNewInst { - my ($ds_newinst, $inffile) = @_; - system ($ds_newinst, $inffile) == 0 or - die "Could not create new instance using $ds_newinst with inffile $inffile: $?"; -} - -sub copyDatabaseDirs { - my $srcdir = shift; - my $destdir = shift; - if (-d $srcdir && ! -d $destdir) { - debug(0, "Copying database directory $srcdir to $destdir\n"); - system ("cp -p -r $srcdir $destdir") == 0 or - die "Could not copy database directory $srcdir to $destdir: $?"; - } elsif (! -d $srcdir) { - die "Error: database directory $srcdir does not exist"; - } else { - debug(0, "The destination directory $destdir already exists, copying files/dirs individually\n"); - foreach my $file (glob("$srcdir/*")) { - debug(3, "Copying $file to $destdir\n"); - if (-f $file) { - system ("cp -p $file $destdir") == 0 or - die "Error: could not copy $file to $destdir: $!"; - } elsif (-d $file) { - system ("cp -p -r $file $destdir") == 0 or - die "Error: could not copy $file to $destdir: $!"; - } - } - } -} - -sub copyDatabases { - my $oldroot = shift; - my $inst = shift; - my $newdbdir = shift; - - # global config and instance specific config are children of this entry - my $basedbdn = normalizeDN("cn=ldbm database,cn=plugins,cn=config"); - # get the list of databases, their index and transaction log locations - my $fname = "$oldroot/$inst/config/dse.ldif"; - open( DSELDIF, "$fname" ) || die "Can't open $fname: $!"; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF); - my $targetdn = normalizeDN("cn=config,cn=ldbm database,cn=plugins,cn=config"); - while ($ent = readOneEntry $in) { - next if (!$ent->getDN()); # just skip root dse - # look for the one level children of $basedbdn - my @rdns = ldap_explode_dn($ent->getDN(), 0); - my $parentdn = normalizeDN(join(',', @rdns[1..$#rdns])); - if ($parentdn eq $basedbdn) { - my $cn = $ent->getValues('cn'); - my %objclasses = map { lc($_) => $_ } $ent->getValues('objectclass'); - if ($cn eq 'config') { # global config - debug(1, "Found ldbm database plugin config entry ", $ent->getDN(), "\n"); - my $dir = $ent->getValues('nsslapd-directory'); - my $homedir = $ent->getValues('nsslapd-db-home-directory'); - my $logdir = $ent->getValues('nsslapd-db-logdirectory'); - debug(1, "old db dir = $dir homedir = $homedir logdir = $logdir\n"); - my $srcdir = $homedir || $dir || "$oldroot/$inst/db"; - copyDatabaseDirs($srcdir, $newdbdir); - copyDatabaseDirs($logdir, $newdbdir) if ($logdir && $logdir ne $srcdir); - } elsif ($objclasses{nsbackendinstance}) { - debug(1, "Found ldbm database instance entry ", $ent->getDN(), "\n"); - my $dir = $ent->getValues('nsslapd-directory'); - # the default db instance directory is - # $oldroot/$inst/$cn - debug(1, "old instance $cn dbdir $dir\n"); - my $srcdir = $dir || "$oldroot/$inst/db/$cn"; - copyDatabaseDirs($srcdir, "$newdbdir/$cn"); - } # else just ignore for now - } - } - close DSELDIF; - - # server automagically upgrades database if needed -# upgradeDatabase($newdbdir); - # fix the DBVERSION files -# updateDBVERSION($newdbdir); - # fix guardian files -# updateDBguardian($newdbdir); -} - -sub copyChangelogDB { - my $oldroot = shift; - my $inst = shift; - my $newdbdir = shift; - # changelog config entry - my $cldn = normalizeDN("cn=changelog5, cn=config"); - my $fname = "$oldroot/$inst/config/dse.ldif"; - open( DSELDIF, "$fname" ) || die "Can't open $fname: $!"; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF); - while ($ent = readOneEntry $in) { - my $targetdn = normalizeDN($ent->getDN()); - if ($targetdn eq $cldn) { - my $oldcldir = $ent->getValues('nsslapd-changelogdir'); - debug(1, "old cldb dir = $oldcldir\n"); - my $srcdir = $oldcldir || "$oldroot/$inst/cldb"; - copyDatabaseDirs($srcdir, $newdbdir); - - # server automagically upgrades database if needed -# upgradeDatabase($newdbdir); - - last; - } - } - close DSELDIF; -} - -sub fixAttrsInEntry { - my ($ent, $inst) = @_; - for my $attr (keys %{$ent}) { - my $lcattr = lc $attr; - if ($transformAttr{$lcattr}) { - $ent->setValues($attr, &{$transformAttr{$lcattr}}($ent, $attr, $inst)); - } - } -} - -sub mergeEntries { - my ($old, $new, $inst) = @_; - my %inoldonly; # attrs in old entry but not new one - my %innewonly; # attrs in new entry but not old one - my @attrs; # attrs common to old and new - # if the attribute exists in the old entry but not the new one - # we should probably add it (checking for special cases first) - # if the attribute exists in the new entry but not the old one - # we might have to delete it from the new entry - # first, get a list of all attributes - foreach my $attr (keys %{$old}) { - if (! $new->exists($attr)) { - $inoldonly{$attr} = $attr; - } else { - push @attrs, $attr; - } - } - foreach my $attr (keys %{$new}) { - if (! $old->exists($attr)) { - $innewonly{$attr} = $attr; - } - } - - # iterate through the attr lists - my $cn = lc $new->getValues("cn"); - foreach my $attr (keys %inoldonly, keys %innewonly, @attrs) { - my $lcattr = lc $attr; - if ($ignoreOld{$lcattr}) { - next; # use new value or just omit if attr is obsolete - } elsif ($transformAttr{$lcattr}) { - # only transform if the value is in the old entry - if (!$innewonly{$attr}) { - $new->setValues($attr, &{$transformAttr{$lcattr}}($old, $attr, $inst)); - } - } elsif ($cn eq "internationalization plugin" and $lcattr eq "nsslapd-pluginarg0") { - next; # use the new value of this path name - } elsif ($cn eq "referential integrity postoperation" and $lcattr eq "nsslapd-pluginarg1") { - next; # use the new value of this path name - } elsif ($innewonly{$attr}) { - $new->remove($attr); # in new but not old - just remove it - } else { - $new->setValues($attr, $old->getValues($attr)); # use old value - } - } -} - -sub mergeDseLdif { - my $oldroot = shift; - my $inst = shift; - my $ent; - - # first, read in old file - my %olddse; # map of normalized DN to Entry - my @olddns; # the DNs in their original order - my $fname = "$oldroot/$inst/config/dse.ldif"; - open( OLDDSELDIF, $fname ) || die "Can't open $fname: $!"; - my $in = new Mozilla::LDAP::LDIF(*OLDDSELDIF); - while ($ent = readOneEntry $in) { - my $dn = normalizeDN($ent->getDN()); - push @olddns, $dn; - $olddse{$dn} = $ent; - } - close OLDDSELDIF; - - # next, read in new file - my %newdse; # map of normalized DN to Entry - my @newdns; # the DNs in their original order that are not in olddns - $fname = "@instconfigdir@/$inst/dse.ldif"; - open( NEWDSELDIF, $fname ) || die "Can't open $fname: $!"; - $in = new Mozilla::LDAP::LDIF(*NEWDSELDIF); - while ($ent = readOneEntry $in) { - my $dn = normalizeDN($ent->getDN()); - $newdse{$dn} = $ent; - if (! exists $olddse{$dn}) { - push @newdns, $dn; - } - } - close NEWDSELDIF; - - # temp file for new, merged dse.ldif - my ($dsefh, $tmpdse) = tempfile(SUFFIX => '.ldif'); - # now, compare entries - # if the entry exists in the old tree but not the new, add it - # if the entry exists in the new tree but not the old, delete it - # otherwise, merge the entries - # @olddns contains the dns in the old dse.ldif, including ones that - # may also be in the new dse.ldif - # @newdns contains dns that are only in the new dse.ldif - for my $dn (@olddns, @newdns) { - my $oldent = $olddse{$dn}; - my $newent = $newdse{$dn}; - my $outputent; - if ($oldent && !$newent) { - # may have to fix up some values in the old entry - fixAttrsInEntry($oldent, $inst); - # output $oldent - $outputent = $oldent; - } elsif (!$oldent && $newent) { - next if ($dn =~ /o=deleteAfterMigration/i); - # output $newent - $outputent = $newent; - } else { #merge - # $newent will contain the merged entry - mergeEntries($oldent, $newent, $inst); - $outputent = $newent; - } - # special fix for rootDSE - perldap doesn't like "" for a dn - if (! $outputent->getDN()) { - my $ary = $outputent->getLDIFrecords(); - shift @$ary; # remove "dn" - shift @$ary; # remove the empty dn value - print $dsefh "dn:\n"; - print $dsefh (Mozilla::LDAP::LDIF::pack_LDIF (78, $ary), "\n"); - } else { - Mozilla::LDAP::LDIF::put_LDIF($dsefh, 78, $outputent); - } - } - close $dsefh; - - return $tmpdse; -} - -sub usage { - print STDERR <<EOF; -Usage: $0 [-h] [-v....v] [-o /path/to/oldserverroot] [-i slapd-instance ... -i slapd-instanceN] - -INTRODUCTION - -This script will copy instances (data and configuration) from the old -server root directory to their new FHS locations. This script does a -copy only - the data in the old instances will be left untouched. The -old instances must be shutdown first to ensure that the databases are -copied safely. The new instances will not be started by migration, -but can be started after running migration by doing - - service $pkgname start - -WARNINGS - -You will not be able to use the console or Admin Express to manage -instances that have been migrated. You will be able to use the web -applications such as the Directory Server Gateway, Directory Express, -and Org Chart. - -If you have configured your main database or replication changelog -database to use separate partitions for log files and index files, -this configuration will not be migrated. All of your data -will be copied to the standard FHS location -@localstatedir@/lib/$pkgname/slapd-INSTANCE/db (or cldb). - -OPTIONS - --v Increase the verbosity - you can specify this more than once - (e.g. -vvvv) for more output --o The old server root directory (default $oldsroot) --i Instance to migrate - by default, all instances in $oldsroot - will be migrated, but you can specify one or more if you do - not want all of them (e.g. -i slapd-inst1 -i slapd-inst2) --h This message - -EOF - - exit 1; -} - -################################################################# -# Main script begins here -################################################################# - -my @instances; # the instances to migrate - -# process command line options -Getopt::Long::Configure(qw(bundling)); # bundling allows -vvvvvv -GetOptions('verbose|v+' => \$debuglevel, - 'instance|i=s' => \@instances, - 'oldsroot|o=s' => \$oldsroot, - 'help|h' => sub { &usage }); - - -# get list of instances to migrate -if (! @instances) { - # an instance must be a directory called $oldsroot/slapd-something and the file - # $oldsroot/slapd-something/config/dse.ldif must exist - @instances = grep { -d && -f "$_/config/dse.ldif" && ($_ =~ s,$oldsroot/,,) } glob("$oldsroot/slapd-*"); -} - -die "No instances found to migrate" unless (@instances); - -# find ds_newinst.pl - in same directory as this script or in PATH -my $ds_newinst; -($ds_newinst = $0) =~ s|/[^/]+$|/ds_newinst.pl|; -if (! -x $ds_newinst) { - $ds_newinst = "ds_newinst.pl"; # just get from path -} - -# for each instance -foreach my $inst (@instances) { -# set instance specific defaults - my $newdbdir = "@localstatedir@/lib/$pkgname/$inst/db"; - my $newcertdir = "@instconfigdir@/$inst"; - my $newcldbdir = "@localstatedir@/lib/$pkgname/$inst/cldb"; - -# extract the information needed for ds_newinst.pl - my $inffile = createInfFileFromDseLdif($oldsroot, $inst); - debug(2, "Using inffile $inffile created from $oldsroot/$inst\n"); - -# create the new instance - makeNewInst($ds_newinst, $inffile); - unlink($inffile); - -# copy over the files/directories -# copy the databases - copyDatabases($oldsroot, $inst, $newdbdir); - -# copy the security related files - copySecurityFiles($oldsroot, $inst, $newcertdir); - -# copy the repl changelog database - copyChangelogDB($oldsroot, $inst, $newcldbdir); - -# merge the old info into the new dse.ldif - my $tmpdse = mergeDseLdif($oldsroot, $inst); - -# get user/group of new dse - my ($dev, $ino, $mode, $uid, $gid, @rest) = stat "@instconfigdir@/$inst/dse.ldif"; -# save the original new dse.ldif - system("cp -p @instconfigdir@/$inst/dse.ldif @instconfigdir@/$inst/dse.ldif.premigrate"); -# copy the new one - system("cp $tmpdse @instconfigdir@/$inst/dse.ldif"); -# change owner/group - chmod $mode, "@instconfigdir@/$inst/dse.ldif"; - chown $uid, $gid, "@instconfigdir@/$inst/dse.ldif"; - -# remove the temp one - unlink($tmpdse); -} - -debug(0, "\n\nDone! Migration is complete.\n"); -debug(0, "You can start your new servers with: service fedora-ds start\n"); - -# the server automagically upgrades the databases, so these are not needed for now -# sub upgradeDatabase { -# my $newdbdir = shift; -# # now, recover the database to flush the data from the log file(s) -# # into the .db4 (index) files -# debug(0, "Recovering and flushing log files in $newdbdir . . .\n"); -# my $vflag = ""; -# if ($debuglevel > 2) { -# $vflag = "-v"; -# } -# system("db42_recover $vflag -h $newdbdir") == 0 or -# die "Error: could not recover the db files in $newdbdir: $!"; -# # then, remove the log file(s) (log.xxxxx) and the old memory region files (__db.XXX files) -# debug(0, "Removing old log and memory region files in $newdbdir . . .\n"); -# system("rm -f $newdbdir/log.* $newdbdir/__db.*") == 0 or -# die "Error: could not remove log and mem region files in $newdbdir: $!"; -# # finally, upgrade the index files -# debug(0, "Upgrading all database files in $newdbdir . . .\n"); -# for my $dbfile (<$newdbdir/*/*.db4>) { -# debug(2, "Upgrading database file $dbfile . . .\n"); -# system("db_upgrade -h $newdbdir $dbfile") == 0 or -# die "Error: could not upgrade database file $dbfile: $!"; -# } -# for my $dbfile (<$newdbdir/*.db4>) { -# debug(2, "Upgrading database file $dbfile . . .\n"); -# system("db_upgrade -h $newdbdir $dbfile") == 0 or -# die "Error: could not upgrade database file $dbfile: $!"; -# } -# } - -# sub updateDBVERSION { -# my $newdbdir = shift; -# my $fname = "$newdbdir/DBVERSION"; -# my @flist = ($fname); -# push @flist, glob("$newdbdir/*/DBVERSION"); -# for $fname (@flist) { -# if (-f $fname) { -# debug(2, "Updating $fname to $db_verstr\n"); -# open(FNAME, ">$fname") or die "Can't write $fname: $!"; -# print FNAME $db_verstr, "\n"; -# close FNAME; -# } else { -# debug(0, "No $fname - skipping\n"); -# } -# } -# } - -# sub updateDBguardian { -# my $newdbdir = shift; -# my $fname = "$newdbdir/guardian"; -# my @flist = ($fname); -# push @flist, glob("$newdbdir/*/guardian"); -# for $fname (@flist) { -# if (-f $fname) { -# debug(2, "Updating $fname to $db_verstr\n"); -# open(FNAME, "$fname") or die "Can't read $fname: $!"; -# my @lines = <FNAME>; -# close FNAME; -# open(FNAME, ">$fname") or die "Can't write $fname: $!"; -# for (@lines) { -# if (/^version:/) { -# print FNAME "version:$db_verstr\n"; -# } else { -# print FNAME; -# } -# } -# close FNAME; -# } else { -# debug(0, "No $fname - skipping\n"); -# } -# } -# } diff --git a/ldap/admin/src/migrateTo4 b/ldap/admin/src/migrateTo4 deleted file mode 100644 index ca8e3d14..00000000 --- a/ldap/admin/src/migrateTo4 +++ /dev/null @@ -1,1618 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -BEGIN { - require 'uname.lib'; - $isNT = -d '\\'; - @INC = ( '.', '../../../admin/admin/bin' ); - grep { s@/@\\@g } @INC if $isNT; - $PATHSEP = $isNT ? '\\' : '/'; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; - - # If this variable is set, all file/directory creation will make sure the mode - # and ownership of the destination is the same as the source - $PRESERVE = 1 if (!$isNT); - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - if ($isNT) { - $os = "WINNT"; - } else { - $os = &uname("-s"); - } - - if ($isNT) { - # we have to pass batch files directly to the NT command interpreter - $com_spec = $ENV{ComSpec}; - if (!$com_spec) { - $com_spec = $ENV{COMSPEC}; - } - if (!$com_spec || ! -f $com_spec) { - # find the first available command interpreter - foreach $drive (c..z) { - $com_spec = "$drive:\\winnt\\system32\\cmd.exe"; - last if (-f $com_spec); - $com_spec = undef; - } - if (! $com_spec) { - # punt and pray - $com_spec = 'c:\winnt\system32\cmd.exe'; - } - } - } - - # dll suffix for shared libraries in old instance; note that the dll suffix - # may have changed for the new instance e.g. AIX now uses .so - if ( $os eq "AIX" ) { - $dll_suffix = "_shr.a"; - } - elsif ( $os eq "HP-UX" ) { - $arch = &uname("-p"); - if ( $arch eq "ia64" ) { - $dll_suffix = ".so"; - } else { - $dll_suffix = ".sl"; - } - } - elsif ( $os eq "WINNT" ) { - $dll_suffix = ".dll"; - } - else { - $dll_suffix = ".so"; - } - $slapdExecName = $isNT ? 'slapd.exe' : 'ns-slapd'; - # if this flag is set, we will migrate the 3.0 and 3.1 databases - # by doing a db2ldif -> ldif2db; if this is not set, we will just - # copy the directories; right now, we cannot copy the directories, - # because the database format has changed for 4.0, and the new - # code does not recognize the old db format. It is hoped that it - # will by RTM . . . - $convertToLDIF = 1; - select STDERR; - $| = 1; - select STDOUT; - $| = 1; - - # if the old value for dbcachesize is less than this, make it this - $MIN_DBCACHESIZE = '500000'; -} - -sub getCwd { - my $command = $isNT ? "cd" : "/bin/pwd"; - open(PWDCMD, "$command 2>&1 |") or - die "Error: could not execute $command: $!"; - # without the following sleep, reading from the pipe will - # return nothing; I guess it gives the pwd command time - # to get some data to read . . . - sleep(1); - my $curdir; - while (<PWDCMD>) { - if (!$curdir) { - chomp($curdir = $_); - } - } - my $code = close(PWDCMD); -# if ($code || $?) { -# print "$command returned code=$code status=$? dir=$curdir\n"; -# } -# print "getCwd curdir=\[$curdir\]\n"; - return $curdir; -} - -sub fixBinaryAttr { - my $foo = shift; - $foo =~ s/;binary//ig; - return $foo; -} - -$type = "slapd"; -$root = $ARGV[0]; -$oldDir = $ARGV[1]; -$newname = $ARGV[2]; -$oldname = $ARGV[3]; -$savedMDLdif = $ARGV[4]; -$savedLdif = $ARGV[5]; -$sieName = $ARGV[6]; -$secPwd = $ARGV[7]; - -if (($root =~ m#/$#) || ($root =~ m#\\$#)) { - chop $root; -} - -if (($oldDir =~ m#/$#) || ($oldDir =~ m#\\$#)) { - chop $oldDir; -} - -sub basename { - my @list = split(/[\\\/]/, $_[0]); - return $list[@list - 1]; -} - -# this is used to strip html formatting from output to user -sub localprint { - # arg 1 is string to print - # arg 2 is beginning html directive - # arg 3 is closing html directive - my ($str, $begin, $end) = @_; - print $str; -} - -# this is used to run the system() call, capture exit and signal codes, -# and die() upon badness; the first argument is a directory to change -# dir to, if any, and the rest are passed to system() -sub mySystem { - my $rc = &mySystemNoDie(@_); - my ($dir, @args) = @_; - if ($rc == 0) { -# success - } elsif ($rc == 0xff00) { - die "Error executing @args: error code $rc: $!"; - } elsif ($rc > 0x80) { - $rc >>= 8; - die "Error executing @args: error code $rc: $!"; - } else { - if ($rc & 0x80) { - $rc &= ~0x80; - } - die "Error executing @args: received signal $rc: $!"; - } - - # usually won't get return value - return $rc; -} - -# This version does not die but just returns the error code -sub mySystemNoDie { - my ($dir, @args) = @_; - if ($dir && ($dir ne "")) { - chdir($dir) or die "Could not change directory to $dir: $!"; - } - my $cmd = $args[0]; - # the system {$cmd} avoids some NT shell quoting problems if the $cmd - # needs to be quoted e.g. contains spaces; the map puts double quotes - # around the arguments on NT which are stripped by the command - # interpreter cmd.exe; but don't quote things which are already quoted - my @fixargs = map { /^[\"].*[\"]$/ ? $_ : $quote . $_ . $quote } @args; - my $rc = 0; - if ($cmd =~ /[.](bat|cmd)$/) { - # we have to pass batch files directly to the NT command interpreter - $cmd = $com_spec; -# print "system $cmd /c \"@fixargs\"\n"; - $rc = 0xffff & system {$cmd} '/c', "\"@fixargs\""; - } else { -# print "system $cmd @fixargs\n"; - $rc = 0xffff & system {$cmd} @fixargs; - } - return $rc; -} - -$serverHome = "$root${PATHSEP}$type-$newname"; - -$oldHome = "$oldDir${PATHSEP}slapd-$oldname"; - -# these are the default values used by the 4.0 installer -$DEFAULT_CHANGELOG_DIR = $serverHome . $PATHSEP . 'logs' . $PATHSEP . 'changelogdb'; -$DEFAULT_CHANGELOG_SUFFIX = "cn=changelog"; - -# get some information from the new slapd.conf file -open(INPUT, "$serverHome${PATHSEP}config${PATHSEP}slapd.conf") or - die "Could not open file $serverHome${PATHSEP}config${PATHSEP}slapd.conf"; -while (<INPUT>) { - if (/^port\s+/i) { chomp($newport = $'); } - elsif (/^localhost\s+/i) { chomp($newlocalhost = $'); } - elsif (/^localuser\s+/i) { chomp($newuser = $'); } -} -close INPUT; - -# get some information from the new slapd.ldbm.conf file -open(INPUT, "$serverHome${PATHSEP}config${PATHSEP}slapd.ldbm.conf") or - die "Could not open file $serverHome${PATHSEP}config${PATHSEP}slapd.ldbm.conf"; -while (<INPUT>) { - if (/^directory\s+[\"]?(.*?)[\"]?\s*$/i) { - # " - $newDbDir = $1; - # paths are stored in unix format in the config files . . . - $newDbDir =~ s#/#\\#g if ($isNT); - } -} -close INPUT; - -# get some information from the old slapd.conf file -open(INPUT, "$oldHome${PATHSEP}config${PATHSEP}slapd.conf") or - die "Could not open file $oldHome${PATHSEP}config${PATHSEP}slapd.conf"; -while (<INPUT>) { - if (/^changelogdir\s+[\"]?(.*?)[\"]?\s*$/i) { - # " - $oldChangeLogDir = $1; - # paths are stored in unix format in the config files . . . - $oldChangeLogDir =~ s#/#\\#g if ($isNT); - } - elsif (/^changelogsuffix\s+[\"]?(.*?)[\"]?\s*$/i) { - # " - $oldChangeLogSuffix = $1; - } - elsif (/^directory\s+[\"]?(.*?)[\"]?\s*$/i) { - # " - $oldDbDir = $1; - # paths are stored in unix format in the config files . . . - $oldDbDir =~ s#/#\\#g if ($isNT); - } - elsif (/^localuser\s+/i) { chomp($olduser = $'); } - elsif (/^encryption-alias\s+/i) { chomp($encryption_alias = $'); } - # the user may have given us a network mounted old home directory, but in the - # old instance's config files, the root directory referred to is usually - # a local directory. For example, suppose there is an automounter map for - # hosts which maps onto /h e.g. /h/oldhost would contain all directories - # exported via NFS. Similarly, for NT, you could do \\oldhost\c to look - # at the C: drive on the old host. Or the user may have network mounted - # the old server root some other way. Anyway, we need to determine what - # the old server root was local to the original host because that is what - # will be referred to it the old config files. So, we look at the errorlog - # directive in slapd.conf and use whatever comes before the slapd-oldname - elsif (/^errorlog\s+[\"]?(.*)$type-$oldname/i) { - # there may be leading " - chop($realOldDir = $1); - } -} -close INPUT; - -if (! $realOldDir) { - $realOldDir = $oldDir; -} - -$realOldHome = $realOldDir . $PATHSEP . $type . '-' . $oldname; - -# the oldDbDir is stored as a local dir, but we may need a network dir -($networkDbDir = $oldDbDir) =~ s/^$realOldDir/$oldDir/ig; - -# list of standard plugins configured out of the box in version 3 -# all of these paths are in unix format . . . -$oldLibDir = lc("$realOldDir/lib/"); -$oldConfDir = lc("$realOldHome/config/"); -$oldLogsDir = lc("$realOldHome/logs/"); -$oldLibDir =~ s#\\#/#g if ($isNT); -$oldConfDir =~ s#\\#/#g if ($isNT); -$oldLogsDir =~ s#\\#/#g if ($isNT); - -# note that all of these should be lower case, since NT does not distinguish case -# and we don't really care about case for plugin directives anyway . . . -%stdPlugins = ( - "plugin syntax \"${oldLibDir}syntax-plugin${dll_suffix}\" cis_init", "\n", - "plugin syntax \"${oldLibDir}syntax-plugin${dll_suffix}\" ces_init", "\n", - "plugin syntax \"${oldLibDir}syntax-plugin${dll_suffix}\" bin_init", "\n", - "plugin syntax \"${oldLibDir}syntax-plugin${dll_suffix}\" tel_init", "\n", - "plugin syntax \"${oldLibDir}syntax-plugin${dll_suffix}\" int_init", "\n", - "plugin syntax \"${oldLibDir}syntax-plugin${dll_suffix}\" dn_init", "\n", - "plugin matchingrule \"${oldLibDir}liblcoll${dll_suffix}\" orderingrule_init ${quote}${oldConfDir}slapd-collations.conf$quote", "\n", - "plugin database \"${oldLibDir}libback-ldbm${dll_suffix}\" ldbm_back_init", "\n", - "plugin postoperation ${quote}${oldLibDir}referint-plugin${dll_suffix}${quote} referint_postop_init 0 ${quote}${oldLogsDir}referint${quote} member uniquemember owner seealso", "\n", - "plugin postoperation ${quote}${oldLibDir}referint-plugin${dll_suffix}${quote} referint_postop_init 0 ${quote}${oldLogsDir}referint${quote} 0 member uniquemember owner seealso", "\n", - "plugin preoperation ${quote}${oldLibDir}libntsynch${dll_suffix}${quote} libntsynch_plugin_preop_init", "\n", - "plugin postoperation ${quote}${oldLibDir}libntsynch${dll_suffix}${quote} libntsynch_plugin_postop_init", "\n" -); - -# list of standard indexes configured out of the box in version 3 -%stdIndex = ( - 'index aci pres', "\n", - 'index cn pres,eq,sub', "\n", - 'index sn pres,eq,sub', "\n", - 'index givenName pres,eq,sub', "\n", - 'index mail pres,eq,sub', "\n", - 'index telephoneNumber pres,eq,sub', "\n", - 'index ntUserDomainId pres,eq,sub', "\n", - 'index uid eq', "\n", - 'index changenumber eq', "\n", - 'index uniquemember eq', "\n", - 'index member eq', "\n", - 'index owner eq', "\n", - 'index seeAlso eq', "\n" -); - -# These are files included into slapd.conf, slapd.dynamic-ldbm.conf and -# slapd.ldbm.conf by default in earlier releases. We use this hash to -# determine if there are user defined files which have been included -# into the slapd.conf e.g. for user defined attributes, object classes, -# indexes, etc. -%stdIncludes = ( - "${oldConfDir}slapd.at.conf", "\n", - "${oldConfDir}slapd.oc.conf", "\n", - "${oldConfDir}ns-schema.conf", "\n", - "${oldConfDir}ns-globopt.conf", "\n", -); - - -# list of parameters that we don't care about; these are usually just parameters -# which hold paths relative to this instance and server root, which change anyway -%oldParametersToSkip = ( - 'userat', "\n", # use the new one - 'useroc', "\n", # use the new one - 'instancedir', "\n", # must be the new one - 'dynamicconf', "\n", # use the new one - 'directory', "\n", # use the new one - 'access', "\n", # obsolete - 'defaultaccess', "\n", # obsolete - 'security-path', "\n", # obsolete - 'localuser', "\n", # use the newly configured suitespot user - 'port', "\n", # the new port must already be set either as determined from - # the old config or because we are migrating into the MC - # instance and cannot change the port number - 'rootdn', "\n", # the new rootdn must already be set either as determined from - # the old config or because we are migrating into the MC - # instance and cannot change it - 'rootpw', "\n", # the new rootpw must already be set either as determined from - # the old config or because we are migrating into the MC - # instance and cannot change it -); - -# list of old ldbm specific parameters. These parameters may be present in the -# old slapd.conf, but have been moved to the new slapd.ldbm.conf -%oldLdbmParameters = ( - 'database', "\n", - 'lookthroughlimit', "\n", - 'mode', "\n", - 'cachesize', "\n", - 'dbcachesize', "\n", - 'allidsthreshold', "\n", - 'parentcheck', "\n", -); - -# list of old slapd.conf parameters which have been moved to the new dse.ldif -%oldDSEParameters = ( - 'encryption-alias', "\n", - 'sslclientauth', "\n" -); - -($oldversion,$oldminor) = &getVersion($oldDir); -($newversion,$newminor) = &getVersion($root); - -# if there was no old user specified -if (! $isNT && ! $olduser) { - # get the olduid and oldgid from doing a stat of the db directory - ($olduid, $oldgid) = (stat($networkDbDir))[4..5]; -} -# convert the user names to numeric uids -if ($PRESERVE) { - if (! $olduid && $olduser) { - ($login,$pass,$olduid,$oldgid) = getpwnam($olduser); - } - ($login,$pass,$newuid,$newgid) = getpwnam($newuser); -} - -# copy the old config files -©Dir("$oldHome${PATHSEP}config", "$serverHome${PATHSEP}migrate_config"); - -print "Migrating log files . . .\n"; -# copy the log files -$srcdir = "$oldHome${PATHSEP}logs"; -opendir(LOGDIR, $srcdir) or - die "Error: could not open log file dir $srcdir : $!"; -foreach (readdir(LOGDIR)) { - if (! /[.][.]?/ && -f "$srcdir${PATHSEP}$_") { - ©BinFile("$srcdir${PATHSEP}$_", - "$serverHome${PATHSEP}logs${PATHSEP}${_}.migrate"); - } -} -closedir(LOGDIR); - -# copy the ssl directory -©Dir("$oldHome${PATHSEP}ssl", "$serverHome${PATHSEP}ssl"); - -# copy the cert db and key files -if ( -d "$oldDir${PATHSEP}alias" && $encryption_alias ) { - $aliasDir = "$root${PATHSEP}alias"; - if (! -d $aliasDir) { - mkdir($aliasDir, 0750); - } - $adminDir = $root . $PATHSEP . 'bin' . $PATHSEP . 'admin' . $PATHSEP . - 'admin' . $PATHSEP . 'bin'; - print "Migrating the key and certificate databases . . .\n"; - mySystem($adminDir, $adminDir . $PATHSEP . 'sec-migrate', - $oldDir, $encryption_alias, $root, $sieName, $secPwd); - # copy the old password file - if (-f "$oldDir${PATHSEP}alias${PATHSEP}$encryption_alias-password.txt") { - ©BinFile( - "$oldDir${PATHSEP}alias${PATHSEP}$encryption_alias-password.txt", - "$aliasDir${PATHSEP}$type-$newname-password.txt" - ); - if ($newversion >= 4 && $newminor >= 1) { - # need to convert the old format to new pin format - print "Converting password file to new pin format . . .\n"; - $script = "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}admin${PATHSEP}bin${PATHSEP}migratePwdFile"; - mySystem($aliasDir, $, $script, $root, "$type-$newname"); - } - } - - # get the new key/cert db filenames - opendir(CERTDIR, $aliasDir) or - die "Error: could not open cert dir $aliasDir: $!"; - foreach (readdir(CERTDIR)) { - if (/^$sieName/i) { - if (/[-]cert/) { - $newcertdb = $_; - } elsif (/[-]key/) { - $newkeydb = $_; - } - } - } - closedir(CERTDIR); -} - -$needAclUpg = 0; -if ($oldversion == 1) { - $needAclUpg = 1; - $convertToLDIF = 1; # always need this for conversion from 1.X db -} - -# Copy/Convert ldif files in ldif/ -print "Migrating old LDIF files . . .\n"; -©Ldif; - -if ($convertToLDIF) { - # Converting database - print "Migrating database to LDIF . . .\n"; - $oldLdif = "$oldHome${PATHSEP}ldif${PATHSEP}old.ldif"; - &db2ldif($networkDbDir, $oldLdif); - if ($needAclUpg) { - print "Converting ACLs in old data . . .\n"; - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}" . - "aclupg$exe_suffix", '-d', '-i', - $oldLdif, '-o', - "$oldHome${PATHSEP}ldif${PATHSEP}aclupg.ldif"); - unlink($oldLdif); - rename("$oldHome${PATHSEP}ldif${PATHSEP}aclupg.ldif", $oldLdif); - } - chown $newuid, $newgid, $oldLdif if (!$isNT); -# copy the changelogdb directory -# how to handle a 1.0 change log? -# ©Dir($changelogdir, "$serverHome${PATHSEP}changelogdb") if ($changelogdir); -} - -# Compare each configuration file against its default version. If it has changed, -# notify the user that the file has changed and will need to be checked by the -# user. This should be safe to do because there should be no path information -# stored in these conf files, which are just schema stuff. -print "Migrating configuration files . . .\n"; -$origFilePath = "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}install${PATHSEP}version${oldversion}"; -$srcdir = "$serverHome${PATHSEP}migrate_config"; -opendir(CONFDIR, $srcdir) or - die "Error: could not open migrated config dir $srcdir: $!"; -foreach $file (readdir(CONFDIR)) { - $origFile = $origFilePath . $file; - if (-f $origFile) { - $diffs = &diff("$srcdir${PATHSEP}$file", $origFile); - if ($diffs) { - print "File $srcdir${PATHSEP}$file could not be migrated\n"; - print "because it is different than\n"; - print "the standard installed version. You will need to check this\n"; - print "file and make sure its changes are compatible with the new\n"; - print "directory server. Here are the differences:\n"; - print $diffs, "\n"; - } else { -# print "No changes to old config file $srcdir${PATHSEP}$file\n"; - } - } -} -closedir(CONFDIR); - -# make a backup of the current user_at and user_oc files, and copy the old ones -# into the config directory - -©BinFile("$serverHome${PATHSEP}config${PATHSEP}slapd.user_at.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.user_at.conf.bak"); -©BinFile("$serverHome${PATHSEP}config${PATHSEP}slapd.user_oc.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.user_oc.conf.bak"); - -if (-f "$serverHome${PATHSEP}migrate_config${PATHSEP}slapd.user_at.conf") { - ©AndEditTextFile( - "$serverHome${PATHSEP}migrate_config${PATHSEP}slapd.user_at.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.user_at.conf", - \&fixBinaryAttr); -} - -if (-f "$serverHome${PATHSEP}migrate_config${PATHSEP}slapd.user_oc.conf") { - ©AndEditTextFile( - "$serverHome${PATHSEP}migrate_config${PATHSEP}slapd.user_oc.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.user_oc.conf", - \&fixBinaryAttr); -} - -# parse the parameters from the old configuration files and put them into -# the new configuration files -&fixConf("$serverHome${PATHSEP}migrate_config${PATHSEP}slapd.conf", - "$serverHome${PATHSEP}migrate_config${PATHSEP}slapd.dynamic_ldbm.conf", - "$serverHome${PATHSEP}migrate_config${PATHSEP}dse.ldif", - "$serverHome${PATHSEP}config${PATHSEP}slapd.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.ldbm.conf", - "$serverHome${PATHSEP}config${PATHSEP}dse.ldif"); - -# copy in old data and any data we wanted to save -if ($convertToLDIF) { - print "Migrating old database to new database . . .\n"; - &manyLdif2db($savedMDLdif, $oldLdif, $savedLdif); - unlink $savedMDLdif, $savedLdif; -} - -if ($oldChangeLogDir && -e $oldChangeLogDir) { - print "Migrating changelog database . . .\n"; - my $realDir = $oldChangeLogDir; - $realDir =~ s/^$realOldDir/$oldDir/ig; - if ($convertToLDIF) { - $srcDir = $realDir; - $destDir = $DEFAULT_CHANGELOG_DIR; - $srcLDIF = "$oldHome${PATHSEP}ldif${PATHSEP}changelog.ldif"; - $destLDIF = "$serverHome${PATHSEP}ldif${PATHSEP}changelog.ldif"; - mkdir( $destDir , 0755 ) if !( -e $destDir); - # Converting database - if ( !$isNT && $newuser ) { - chown($newuid, $newgid, $destDir); - } - &other_db2ldif($srcDir, $srcLDIF); - if ($needAclUpg) { - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}aclupg$exe_suffix", '-d', '-i', - $srcLDIF, '-o', $destLDIF); - } else { - ©BinFile($srcLDIF, $destLDIF); - } - &other_ldif2db($destLDIF, $destDir, 'slapd.ldbm.conf', - "suffix \"$oldChangeLogSuffix\""); - } else { - # the dir is stored as a local dir, but we may need a network dir here - ©Dir($realDir, $DEFAULT_CHANGELOG_DIR, '\.share$'); - } -} - -if ($convertToLDIF) { - # Convert the db backup, bak/ - print "Migrating database backups . . .\n"; - ©Bak; -} else { - # just copy the directories over - ©Dir($networkDbDir, "$serverHome${PATHSEP}db", '\.share$'); - ©Dir("$oldHome${PATHSEP}bak", "$serverHome${PATHSEP}bak", '\.share$'); -} - -if (-f $oldLdif) { - unlink($oldLdif); -} - -exit(0); - -############# END OF PROCESSING; SUBROUTINES FOLLOW - -# This subroutine merges the old and new source files into the new destination file -sub fixConf { - my $oldsrc = shift; - my $oldldbmsrc = shift; - my $olddseldif = shift; - my $newsrc = shift; - my $newldbmsrc = shift; - my $newdseldif = shift; - - # read the old conf file into a hash table - open( OLDSRC, $oldsrc ) || - die "Can't open $oldsrc: $!: "; - LINE: while ( <OLDSRC> ) { - if (/^\s*#/) { # skip comments - next LINE; - } - if (/^\s*$/) { # skip blank lines - next LINE; - } elsif (/^plugin/i) { - chomp($_); - if (! &isAStandardPlugin($_)) { - push @badPlugins, $_; - } - } elsif (/^index/i) { - chomp($_); - if (! &isAStandardIndex($_)) { - push @newIndex, $_; - } - } elsif (/^include\s+[\"]?(.*?)[\"]?\s*$/i) { - # strip leading and trailing " - if (! &isAStandardInclude($1)) { - push @newInclude, $1; - } - } elsif (/^dbcachesize\s+[\"]?(.*?)[\"]?\s*$/i) { - # strip leading and trailing " - $param = 'dbcachesize'; - $value = $1; - if ($value < $MIN_DBCACHESIZE) { - $value = $MIN_DBCACHESIZE; - } - - if ($oldLdbmParameters{lc($param)}) { - $oldldbmhash{lc($param)} = $value; - } else { - $oldhash{lc($param)} = $value; - - } - } elsif (/^errorlog/i) { - $oldhash{'errorlog-logging-enabled'} = "on"; - } elsif (/^accesslog/i) { - $oldhash{'accesslog-logging-enabled'} = "on"; - } elsif (/^auditlog/i) { - $oldhash{'auditlog-logging-enabled'} = "on"; - } elsif (/^replogfile/i) { - # replogfile was only used in 1.X, and it had no suffix - $oldhash{'changelogdir'} = $DEFAULT_CHANGELOG_DIR; - $oldhash{'changelogsuffix'} = $DEFAULT_CHANGELOG_SUFFIX; - } elsif (/^changelogdir/i) { - # force use of default - $oldhash{'changelogdir'} = $DEFAULT_CHANGELOG_DIR; - } elsif (/^\s*(\S+)\s+[\"]?(.*?)[\"]?\s*$/i) { - # strip leading and trailing " - $param = $1; - $value = $2; - if ($oldParametersToSkip{lc($param)}) { - next LINE; - } elsif (lc($param) eq 'suffix') { - if (lc($value) cmp 'cn=schema') { - $oldsuffix{lc($value)} = $value; - } - } else { - if ($oldLdbmParameters{lc($param)}) { - $oldldbmhash{lc($param)} = $value; - } elsif ($oldDSEParameters{lc($param)}) { - if (lc($param) eq 'encryption-alias') { - if ($newcertdb) { - $olddsehash{'nscertfile'} = "alias/$newcertdb"; - } else { - $olddsehash{'nscertfile'} = "alias/$type-$newname-cert.db"; - } - if ($newkeydb) { - $olddsehash{'nskeyfile'} = "alias/$newkeydb"; - } else { - $olddsehash{'nskeyfile'} = "alias/$type-$newname-key.db"; - } - } elsif (lc($param) eq 'sslclientauth') { - $olddsehash{'nssslclientauth'} = $value; - } else { - $olddsehash{lc($param)} = $value; - } - } elsif (($param eq 'passwdhash') && - ((! $value) || ($value eq ""))) { - # 3.X used "" as an alias for "clear" - $oldhash{lc($param)} = 'clear'; - } else { - $oldhash{lc($param)} = $value; - } - } - } - } - close(OLDSRC); - - $oldhash{'errorlog-logging-enabled'} = "off" - if (! $oldhash{'errorlog-logging-enabled'}); - $oldhash{'accesslog-logging-enabled'} = "off" - if (! $oldhash{'accesslog-logging-enabled'}); - $oldhash{'auditlog-logging-enabled'} = "off" - if (! $oldhash{'auditlog-logging-enabled'}); - - # read the old ldbm conf file into a hash table; note that there may not be - # one, so don't complain - open( OLDSRC, $oldldbmsrc ); - LINE2: while ( <OLDSRC> ) { - if (/^\s*#/) { # skip comments - next LINE2; - } - if (/^\s*$/) { # skip blank lines - next LINE2; - } - if (/^index/i) { - chomp($_); - if (! &isAStandardIndex($_)) { - push @newIndex, $_; - } - next LINE2; - } - if (/^plugin/i) { - chomp($_); - if (! &isAStandardPlugin($_)) { - push @badLdbmPlugins, $_; - } - next LINE2; - } - if (/^include\s+/i) { - chomp($inc = $'); - $inc =~ s/\"//g; - # strip " characters - if (! &isAStandardInclude($inc)) { - push @newLdbmInclude, $inc; - } - next LINE2; - } - if (/^dbcachesize\s+[\"]?(.*?)[\"]?\s*$/i) { - # strip leading and trailing " - $param = 'dbcachesize'; - $value = $1; - if ($value < $MIN_DBCACHESIZE) { - $value = $MIN_DBCACHESIZE; - } - - $oldldbmhash{lc($param)} = $value; - next LINE2; - } - - if (/^\s*(\S+)\s+[\"]?(.*?)[\"]?\s*$/) { - # strip leading and trailing " - $param = $1; - $value = $2; - if ($oldParametersToSkip{lc($param)}) { - next LINE2; - } elsif (lc($param) eq 'suffix') { - if (lc($value) cmp 'cn=schema') { - $oldsuffix{lc($value)} = $value; - } - } else { - $oldldbmhash{lc($param)} = $value; - } - } - } - close(OLDSRC); - - # read the old dse.ldif file into a hash table; note that there may not be - # one, so don't complain - open(OLDSRC, $olddseldif); - while ( <OLDSRC> ) { - chomp($_); - if ( /^passwordchange:\s*/i ) { - if ($' eq "must") { - $oldhash{'pw_change'} = "on"; - $oldhash{'pw_must_change'} = "on"; - } elsif ($' eq "may") { - $oldhash{'pw_change'} = "on"; - $oldhash{'pw_must_change'} = "off"; - } else { - $oldhash{'pw_change'} = "off"; - $oldhash{'pw_must_change'} = "off"; - } - } elsif ( /^passwordchecksyntax:\s*/i ) { - if ($' > 0) { - $oldhash{'pw_syntax'} = "on"; - } else { - $oldhash{'pw_syntax'} = "off"; - } - } elsif ( /^passwordminlength:\s*/i ) { - $oldhash{'pw_minlength'} = $'; - } elsif ( /^passwordexp:\s*/i ) { - if ($' > 0) { - $oldhash{'pw_exp'} = "on"; - } else { - $oldhash{'pw_exp'} = "off"; - } - } elsif ( /^passwordmaxage:\s*/i ) { - $oldhash{'pw_maxage'} = $'; - } elsif ( /^passwordwarning:\s*/i ) { - $oldhash{'pw_warning'} = $'; - } elsif ( /^passwordkeephistory:\s*/i ) { - if ($' > 0) { - $oldhash{'pw_history'} = "on"; - } else { - $oldhash{'pw_history'} = "off"; - } - } elsif ( /^passwordinhistory:\s*/i ) { - $oldhash{'pw_inhistory'} = $'; - } elsif ( /^passwordlockoutduration:\s*/i ) { - $oldhash{'pw_lockduration'} = $'; - } elsif ( /^passwordlockout:\s*/i ) { - if ($' > 0) { - $oldhash{'pw_lockout'} = "on"; - } else { - $oldhash{'pw_lockout'} = "off"; - } - } elsif ( /^passwordmaxfailure:\s*/i ) { - $oldhash{'pw_maxfailure'} = $'; - } elsif ( /^passwordunlock:\s*/i ) { - if ($' > 0) { - $oldhash{'pw_unlock'} = "on"; - } else { - $oldhash{'pw_unlock'} = "off"; - } - } elsif ( /^passwordresetduration:\s*/i ) { - $oldhash{'pw_resetfailurecount'} = $'; - } - } - close(OLDSRC); - - open(NEWSRC, $newsrc ) || die "Can't open $newsrc: $!: "; - open(NEWDEST, ">$newsrc.tmp" ) || die "Can't create $newsrc.tmp: $!: "; - while ( <NEWSRC> ) { - # make sure the dynamicconf parameter is the last one in the file - if (/^dynamicconf/i) { - # print the parameters which exist in the old file but do not - # exist in the new file; these are the parameters we have not - # deleted from oldhash - print NEWDEST "#These additional parameters have been migrated\n"; - foreach $param (sort keys %oldhash) { - if (lc($param) eq 'passwdhash') { - $pwhash = $oldhash{lc($param)}; - # if the old value was not set, don't set the new value either - # just have the server use the default value - if ($pwhash && $pwhash ne "" && $pwhash ne '""') { - print NEWDEST 'pw_storagescheme', "\t", $pwhash, "\n"; - } - } elsif (lc($param) eq 'ntsynchusessl') { - print NEWDEST 'NTSynchUseSSL', "\t", $oldhash{lc($param)}, "\n"; - } else { - print NEWDEST $param, "\t", "\"$oldhash{lc($param)}\"", - "\n"; - } - } - print NEWDEST "#End of additional migrated parameters\n\n"; - # use the temp one for now until we have the real one in place, then - # we will change this back - print NEWDEST "dynamicconf\t\"$newldbmsrc.tmp\"\n"; - } elsif (/^\s*#/) { - print NEWDEST $_; - } elsif (/^include/ && @newInclude) { - my $newConfDir = $serverHome . '/' . 'config' . '/'; - $newConfDir =~ s#\\#/#g if ($isNT); - print NEWDEST "# These non standard includes were migrated:\n"; - print "These non standard includes were migrated:\n"; - while (@newInclude) { - my $oldPath = shift @newInclude; - # oldPath is a local path; we need a network path here because - # we will be copying the file - $oldPath =~ s/^$realOldDir/$oldDir/ig; - my $base = &basename($oldPath); - my $newone = $newConfDir . $base; - # convert to new path - print NEWDEST "include ", $quote, $newone, $quote, "\n"; - print $newone, "\n"; - # now, change path separators back to the correct ones for - # the os - $oldPath =~ s#/#\\#g if ($isNT); - $newone =~ s#/#\\#g if ($isNT); - ©AndEditTextFile($oldPath, $newone, \&fixBinaryAttr); - } - print NEWDEST "# end of migrated includes\n"; - print "Be sure to check the new slapd.conf file to make sure the order\n"; - print "is correct and there are no conflicts with new config files,\n"; - print "object classes, attributes, etc.\n"; - print NEWDEST $_; - } elsif (/^\s*(\S+)\s+[\"]?(.*?)[\"]?\s*$/) { - $param = $1; - $value = $2; - # see if the parameter is set in the old config file - if ($oldhash{lc($param)}) { - # only set the parameter if the old value is different than - # the new value - if ($value cmp $oldhash{lc($param)}) { - print NEWDEST "#This parameter was migrated: the original value was $value\n"; - print NEWDEST $param, "\t", "\"$oldhash{lc($param)}\"", "\n"; - } else { - print NEWDEST $_; - } - delete $oldhash{lc($param)}; - } else { - # just print the parameter - print NEWDEST $_; - } - } else { - print NEWDEST $_; - } - } - close (NEWSRC); - - # print the bad plugins, commented out, at the end of the file - if (@badPlugins) { - print NEWDEST "#The following non standard plugins were detected:\n"; - print "The following non standard plugins were detected:\n"; - foreach (@badPlugins) { - print NEWDEST "#", $_, "\n"; - print $_, "\n"; - } - print NEWDEST "#These plugins will probably need to be recompiled for this release\n"; - print "These plugins will probably need to be recompiled for this release\n"; - print NEWDEST "#of directory server, or at the very least, reconfigured.\n"; - print "of directory server, or at the very least, reconfigured.\n"; - } - - close( NEWDEST ); - - open(NEWSRC, $newldbmsrc ) || die "Can't open $newldbmsrc: $!: "; - open(NEWDEST, ">$newldbmsrc.tmp" ) || die "Can't create $newldbmsrc.tmp: $!: "; - while ( <NEWSRC> ) { - if (/^\s*#/) { - print NEWDEST $_; - } elsif (/^include/ && @newLdbmInclude) { - my $newConfDir = $serverHome . '/' . 'config' . '/'; - $newConfDir =~ s#\\#/#g if ($isNT); - print NEWDEST "# These non standard ldbm includes were migrated:\n"; - print "These non standard includes were migrated:\n"; - while (@newLdbmInclude) { - my $oldPath = shift @newInclude; - # oldPath is a local path; we need a network path here because - # we will be copying the file - $oldPath =~ s/^$realOldDir/$oldDir/ig; - my $base = &basename($oldPath); - my $newone = $newConfDir . $base; - # convert to new path - print NEWDEST "include ", $quote, $newone, $quote, "\n"; - print $newone, "\n"; - # now, change path separators back to the correct ones for - # the os - $oldPath =~ s#/#\\#g if ($isNT); - $newone =~ s#/#\\#g if ($isNT); - ©BinFile($oldPath, $newone); - } - print NEWDEST "# end of migrated includes\n"; - print "Be sure to check the new slapd.ldbm.conf file to make sure the order\n"; - print "is correct and there are no conflicts with new config files,\n"; - print "object classes, attributes, etc.\n"; - print NEWDEST $_; - } elsif (/^\s*(\S+)\s+[\"]?(.*?)[\"]?\s*$/) { - # strip " characters - $param = $1; - $value = $2; - if (lc($param) eq 'suffix') { - if ($oldsuffix{lc($value)}) { - delete $oldsuffix{lc($value)}; - } - print NEWDEST $_; - } elsif ($oldhash{lc($param)}) { - # only set the parameter if the old value is different than - # the new value - if ($value cmp $oldhash{lc($param)}) { - print NEWDEST "#This parameter was migrated: the original value was $value\n"; - print NEWDEST $param, "\t", "\"$oldhash{lc($param)}\"", "\n"; - } else { - print NEWDEST $_; - } - delete $oldhash{lc($param)}; - } elsif ($oldldbmhash{lc($param)}) { - # only set the parameter if the old value is different than - # the new value - if ($value cmp $oldldbmhash{lc($param)}) { - print NEWDEST "#This parameter was migrated: the original value was $value\n"; - print NEWDEST $param, "\t", "\"$oldldbmhash{lc($param)}\"", "\n"; - } else { - print NEWDEST $_; - } - delete $oldldbmhash{lc($param)}; - } else { - # just print the parameter - print NEWDEST $_; - } - } else { - print NEWDEST $_; - } - } - close (NEWSRC); - - # add the suffixes we didn't already have - if (%oldsuffix) { - print NEWDEST "#These suffixes were migrated\n"; - foreach (values %oldsuffix) { - print NEWDEST 'suffix', "\t", "\"$_\"", "\n"; - } - } - - # add the user defined indexes - if (@newIndex) { - print NEWDEST "#These indexes were migrated\n"; - while (@newIndex) { - print NEWDEST shift(@newIndex), "\n"; - } - } - - # print the bad plugins, commented out, at the end of the file - if (@badLdbmPlugins) { - print NEWDEST "#The following non standard plugins were detected:\n"; - print "The following non standard ldbm plugins were detected:\n"; - foreach (@badLdbmPlugins) { - print NEWDEST "#", $_, "\n"; - print $_, "\n"; - } - print NEWDEST "#These plugins will probably need to be recompiled for this release\n"; - print "These plugins will probably need to be recompiled for this release\n"; - print NEWDEST "#of directory server, or at the very least, reconfigured.\n"; - print "of directory server, or at the very least, reconfigured.\n"; - } - - close( NEWDEST ); - - open(NEWSRC, $newdseldif ) || die "Can't open $newdseldif: $!: "; - open(NEWDEST, ">$newdseldif.tmp" ) || die "Can't create $newdseldif.tmp: $!: "; - $inEncryptionConfig = 0; - while ( <NEWSRC> ) { - if (/^\s*#/) { - print NEWDEST $_; - } elsif (/^\s*$/) { - if ($inEncryptionConfig) { # end of entry - $inEncryptionConfig = 0; - # if attributes were present in the old config but not - # in the new one, add them to the end of the entry - foreach $key (keys %olddsehash) { - print NEWDEST $key, ': ', $olddsehash{$key}, "\n"; - } - } - print NEWDEST $_; - } elsif (/cn=encryption\s*,\s*cn=config/) { - $inEncryptionConfig = 1; - print NEWDEST $_; - } elsif (/^\s*(\S+):\s*(.*)$/) { - $param = $1; - $value = $2; - if ($olddsehash{lc($param)}) { - # only set the parameter if the old value is different than - # the new value - if ($value cmp $olddsehash{lc($param)}) { - print NEWDEST $param, "\t", $olddsehash{lc($param)}, "\n"; - } else { - print NEWDEST $_; - } - delete $olddsehash{lc($param)}; - } else { - # just print the parameter - print NEWDEST $_; - } - } else { - print NEWDEST $_; - } - } - close (NEWSRC); - close( NEWDEST ); - - # final step: use the slapd_config program to check the new config file - my $rc = &mySystemNoDie("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}slapd_config${exe_suffix}", - '-c', '-f', "$newsrc.tmp"); - - # if the check failed, run slapd_config again in verbose mode to provide - # more information to the user; this will die and abort processing - if ($rc) { - print "The following problems were found with the new configuration:\n"; - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}slapd_config${exe_suffix}", - '-f', "$newsrc.tmp"); - } - - # if we got here, the files were good - # save a copy of the old config files - ©BinFile("$newsrc", "$newsrc.save"); - ©BinFile("$newldbmsrc", "$newldbmsrc.save"); - - # replace the temporary dynamicconf directive with the real one - open(NEWSRC, "$newsrc.tmp") or die "Could not open file $newsrc.tmp: $!"; - open(NEWDEST, ">$newsrc") or die "Could not write file $newsrc: $!"; - while(<NEWSRC>) { - if (/^dynamicconf/i) { - print NEWDEST "dynamicconf\t\"$newldbmsrc\"\n"; - } else { - print NEWDEST; - } - } - close NEWSRC; - close NEWDEST; - - ©BinFile("$newldbmsrc.tmp", "$newldbmsrc"); - ©BinFile("$newdseldif.tmp", "$newdseldif"); -} - -sub copyDir { - my $src = shift; - my $dest = shift; - my $exclude = shift; - - opendir( SRC, $src ) or die "Can't open directory $src: $!: "; - my $mode; - my $uid; - my $gid; - mkdir ( $dest , 0755 ) if !( -e $dest ); - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - local ( @files ) = readdir ( SRC ); - closedir( SRC ); - for ( @files ) { - if ( $_ eq "." || $_ eq ".." ) { - next; - } elsif ( $exclude && /$exclude/ ) { - next; - } elsif( -d "$src${PATHSEP}$_") { - ©Dir ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_" ); - } else { - ©BinFile ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_"); - } - } -} - -sub copyBinFile { - my $src = shift; - my $dest = shift; - my $buf = ""; - my $bufsize = 8192; - - open( SRC, $src ) || die "Can't open $src: $!\n"; - # if we are given a directory destination instead of a file, extract the - # filename portion of the source to use as the destination filename - if (-d $dest) { - $dest = $dest . $PATHSEP . &basename($src); - } - open( DEST, ">$dest" ) || die "Can't create $dest: $!\n"; - binmode SRC; - binmode DEST; - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - while (read(SRC, $buf, $bufsize)) { - print DEST $buf; - } - close( SRC ); - close( DEST ); -} - -sub isAStandardPlugin { - my $line = shift; - - chomp($line); - return $stdPlugins{lc($line)}; -} - -sub isAStandardIndex { - my $line = shift; - - chomp($line); - return $stdIndex{$line}; -} - -sub isAStandardInclude { - my $line = shift; - - chomp($line); - return $stdIncludes{lc($line)}; -} - -# Do a file copy, but convert path names as the file gets copied -# Don't convert paths that don't point anywere, except for log files -# push non-converted paths to the results list -# If you are xlating paths that contain one another, the long paths must come -# first -sub xlatePath { - my $src = shift; - my $dest = shift; - - open( SRC, $src ) || die "Can't open $src: $!: "; - open( DEST, ">$dest" ) || die "Can't create $dest: $!: "; - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - while ( <SRC> ) { - print DEST &xlatePaths( $_, @_ ); - } - close( SRC ); - close( DEST ); -} - -# translate paths in the string -sub xlatePaths { - my $line = shift; - my @otherParams = @_; - my $numXs = shift; - my @srcPaths = splice( @_, 0, $numXs ); - my @destPaths = splice( @_, 0, $numXs ); - my @allowedEmpty = @_; - my @pathLengths = map { length( $_ ) } @srcPaths; - my $i; - my $pre; - my $post; - my $allowed; - my $path; - my $destPath; - - # replace the src paths with the dest paths - # NOTE: this algorithm will only work if the longest paths - # are replaced first e.g. strlen(srcPath[N]) > strlen(srcPath[N+1]) - # and none of the destpaths match any of the srcpaths - for ( $i = 0 ; $i < $numXs ; ++$i ) { - if ($srcPaths[$i] ne $destPaths[$i]) { - $line =~ s/$srcPaths[$i]/$destPaths[$i]/g; - } - } - - return $line; -} - -sub copyBak { - opendir( OLDBAK, "$oldHome${PATHSEP}bak" ) || - die "Can't open directory $oldHome${PATHSEP}bak: $!: "; - local ( @dirs ) = readdir( OLDBAK ); - closedir ( OLDBAK ); - for ( @dirs ) { - if ( $_ eq "." || $_ eq ".." ) { - next; - } elsif ( -d "$oldHome${PATHSEP}bak${PATHSEP}$_" ) { - $srcDir = "$oldHome${PATHSEP}bak${PATHSEP}$_"; - $destDir = "$serverHome${PATHSEP}bak${PATHSEP}$_"; - $srcLDIF = "$oldHome${PATHSEP}ldif${PATHSEP}bak.ldif"; - $destLDIF = "$serverHome${PATHSEP}ldif${PATHSEP}bak.ldif"; - mkdir( $destDir , 0755 ) if !( -e $destDir); - # Converting database - if ( !$isNT && $newuser ) { - chown($newuid, $newgid, - "$serverHome${PATHSEP}bak", $destDir); - } - &other_db2ldif($srcDir, $srcLDIF); - if ($needAclUpg) { - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}aclupg$exe_suffix", '-d', '-i', - $srcLDIF, '-o', $destLDIF); - } else { - ©BinFile($srcLDIF, $destLDIF); - } - &other_ldif2db($destLDIF, $destDir); - } - } -} - -sub other_db2ldif { - my $srcDbDir = shift; - my $ldif = shift; - - if ($oldversion == 1) { - &db2ldif($srcDbDir, $ldif); - } else { - # make a dummy version of the current slapd.conf and tell it that - # the db directory is really the back up directory so that we can - # trick ns-slapd db2ldif to do the right thing; Oh how I wish there - # were a simple ldbmcat utility for 3.X and 4.0 . . . - &xlatePath("$oldHome${PATHSEP}config${PATHSEP}slapd.conf", - "$oldHome${PATHSEP}config${PATHSEP}slapd.conf.bak", - 3, - "$realOldHome", - "$oldDbDir", - "slapd.dynamic_ldbm.conf", - "$oldHome", - "$srcDbDir", - "slapd.dynamic_ldbm.conf.bak", - '/logs/'); - &xlatePath("$oldHome${PATHSEP}config${PATHSEP}slapd.dynamic_ldbm.conf", - "$oldHome${PATHSEP}config${PATHSEP}slapd.dynamic_ldbm.conf.bak", - 2, - "$realOldHome", - "$oldDbDir", - "$oldHome", - "$srcDbDir", - '/logs/'); - # now do the ldif2db with our munged conf files . . . - &db2ldif($srcDbDir, $ldif, - "$oldHome${PATHSEP}config${PATHSEP}slapd.conf.bak"); - unlink("$oldHome${PATHSEP}config${PATHSEP}slapd.conf.bak"); - unlink("$oldHome${PATHSEP}config${PATHSEP}slapd.dynamic_ldbm.conf.bak"); - } -} - -sub other_ldif2db { - my $ldif = shift; - my $destDbDir = shift; - my $confFile = shift; - my $directiveToAdd = shift; - - # make a dummy version of the current slapd.conf and slapd.ldbm.conf - # to point to the database directory we want to populate instead of - # the standard - &xlatePath("$serverHome${PATHSEP}config${PATHSEP}slapd.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.conf.bak", - 3, - "$newDbDir", - "slapd.ldbm.conf", - "slapd.dynamic_ldbm.conf", - "$destDbDir", - "slapd.ldbm.conf.bak", - "slapd.ldbm.conf.bak", - '/logs/'); - &xlatePath("$serverHome${PATHSEP}config${PATHSEP}slapd.ldbm.conf", - "$serverHome${PATHSEP}config${PATHSEP}slapd.ldbm.conf.bak", - 1, - "$newDbDir", - "$destDbDir", - '/logs/'); - - # we may need to add something to a config file e.g. when migrating the change - # log, we need to add suffix $changeLogSuffix to slapd.ldbm.conf in order to - # ldif2db it without error - if ($confFile && $directiveToAdd) { - open(CONFADD, ">>$serverHome${PATHSEP}config${PATHSEP}${confFile}.bak") or - die "Could not append to $serverHome${PATHSEP}config${PATHSEP}${confFile}.bak: $!"; - print CONFADD $directiveToAdd, "\n"; - close(CONFADD); - } - - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}$slapdExecName", - "ldif2db", '-C', '-f', - "$serverHome${PATHSEP}config${PATHSEP}slapd.conf.bak", '-i', - "$ldif"); - unlink("$serverHome${PATHSEP}config${PATHSEP}slapd.conf.bak"); - unlink("$serverHome${PATHSEP}config${PATHSEP}slapd.ldbm.conf.bak"); - unlink($ldif); -} - -sub manyLdif2db { - my @args = (); - while (@_) { - push @args, '-i', shift(@_); - } - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}$slapdExecName", "ldif2db", '-C', '-f', - "$serverHome${PATHSEP}config${PATHSEP}slapd.conf", @args); -} - -sub copyLdif { - opendir (LDIFDIR, "$oldHome${PATHSEP}ldif" ); - local ( @files ) = readdir ( LDIFDIR ); - closedir(LDIFDIR); - for ( @files ) { - if ( $_ eq "." || $_ eq ".." || $_ eq "demo.ldif" ) { - next; - } - - if ($needAclUpg) { - &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", - "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}" . - "aclupg$exe_suffix", '-d', '-i', - "$oldHome${PATHSEP}ldif${PATHSEP}$_", '-o', - "$serverHome${PATHSEP}ldif${PATHSEP}$_"); - } else { - ©BinFile("$oldHome${PATHSEP}ldif${PATHSEP}$_", - "$serverHome${PATHSEP}ldif${PATHSEP}$_"); - } - } -} - -sub genAcl { - my $filename = "$root${PATHSEP}httpacl${PATHSEP}generated.$type-$newname.acl"; - - open( S, ">$filename" ) || die "Can't create file $filename: $!: "; - print S "version $newversion.0;\n"; - print S "acl agents;\n"; - print S "authenticate (user, group) {\n"; - print S " prompt = \"Agent Service\";\n"; - print S "};\n"; - print S "deny absolute (all) (user != all);\n"; - print S "allow absolute (all) (user = all);\n"; - print S "\n"; - print S "acl \"default\";\n"; - print S "allow (read, list, execute,info) user = \"anyone\";\n"; - print S "allow (write, delete) user = \"all\";\n"; - close( S ); -} - -sub getVersion { - my $rootDir = shift; - my $version = 0; - my $minor = 0; - my $progDir = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - my $progDir2 = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}"; - # get the current directory so we can go back to it - my $curdir = &getCwd; - - # find the slapd executable - $prog = $rootDir . $progDir . $slapdExecName; - if (! -f $prog) { - $prog = $rootDir . $progDir2 . $slapdExecName; - if (-f $prog && $isNT) { - # if slapd is in bin/slapd and we're on NT, just assume version 1; - # apparently, slapd.exe doesn't like the -v argument . . . - return ( '1', $minor ); - } - } - - # read the old version from the old slapd program - chdir($rootDir . $progDir) or - die "Could not chdir to $rootDir${progDir}: $!: "; - open(F, "${quote}${quote}$prog${quote} -v${quote} 2>&1 |") or - die "Could not run slapd program $prog: $!"; - sleep(1); # allow some data to accumulate in the pipe -# print "Output from $prog -v:\n"; - while (<F>) { -# print; - if (/^Netscape-Directory\/(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - last; - } - } - $code = close(F); -# print "$prog returned code=$code status=$?\n"; - - # done determining versions; go back to orig directory - chdir($curdir) or die "Could not chdir to $curdir: $!: "; - - $version == 0 and - die "Could not determine version of the directory server in $rootDir: "; - - return ( $version, $minor ); -} - -# this subroutine implements a very stupid version of diff -sub diff { - my $f1 = shift; - my $f2 = shift; - my $retval = ""; - - open(F1, "$f1") or die "Could not open file $f1"; - open(F2, "$f2") or close(F1), die "Could not open file $f2"; - - while (defined($l1 = <F1>) && defined($l2 = <F2>)) { - if (!($l1 eq $l2)) { - # ignore comments - if (($l1 =~ /^#/) && ($l2 =~ /^#/)) { - next; - } - # ignore whitespace - $l1 =~ s/\s//g; - $l2 =~ s/\s//g; - - if (!($l1 eq $l2)) { - $retval .= "< ${l1}> $l2"; - } - } - } - - close(F1); - close(F2); - - if ($retval eq "") { - return undef; - } - - return $retval; -} - -# unfortunately, we can't use the shell script/batch file because it may -# not have been updated if the user changed the database directory -sub db2ldif { - my ($srcDbDir, $ldif, $conf) = @_; - - if ($oldversion == 1) { - my $dir = "$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - chdir($dir) or die "Error: could not change directory to $dir: $!"; - my @cmd = ("${quote}$dir${PATHSEP}ldbmcat${exe_suffix}${quote}", '-n', - "${quote}$srcDbDir${PATHSEP}id2entry.dbb${quote}"); - open(LDBMCAT, "${quote}@cmd${quote}|") or - die "Error: could not execute @cmd: $!"; - open(OUTLDIF, "> $ldif") or - die "Error: could not write to $ldif: $!"; - sleep(1); # allow pipe to fill with data - $ii = 0; # counter - while (<LDBMCAT>) { - print OUTLDIF; - ++$ii; - if (($ii % 250) == 0) { - print " Processed ", $ii, " lines\n"; - } - } - close(LDBMCAT); - close(OUTLDIF); - } else { - if (!$conf) { - $conf = "$oldHome${PATHSEP}config${PATHSEP}slapd.conf"; - } - my $baseldif = &basename($ldif); - if ($baseldif eq $ldif) { - $ldif = "$oldHome${PATHSEP}ldif${PATHSEP}$ldif"; - } - my $dir = "$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - chdir($dir) or - die "Error: could not change directory to $dir: $!"; - - my @cmd = - ( "${quote}$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}$slapdExecName${quote}", "db2ldif", '-n', '-f', - "${quote}$conf${quote}", '-a', "${quote}$ldif${quote}", - '-d', '1' ); - open(DB2LDIF, "${quote}@cmd${quote} 2>&1|") or - die "Error: could not execute @cmd: $!"; - sleep(1); # allow pipe to fill with data - $ii = 0; # counter - while (<DB2LDIF>) { - ++$ii; - if (($ii % 250) == 0) { - print " Processing...\n"; - } - } - close(DB2LDIF); - } - print " Done.\n"; -} - -# this subroutine works like sed in that it will create another version -# of the input file with some editing done -# the file should be a text file -sub copyAndEditTextFile { - my $srcFile = shift; - my $destFile = shift; - my $sub = shift; - - open(SRCFILE, "$srcFile") or die "Error: could not open file $srcFile: $!"; - open(DESTFILE, ">$destFile") or die "Error: could not write file $destFile: -$!"; - - while (<SRCFILE>) { - my $newline = &$sub($_); - if ($newline cmp $_) { - print "The line: $_"; - print "Was converted to: $newline"; - print "File: $srcFile\n"; - } - print DESTFILE $newline; - } - - close(SRCFILE); - close(DESTFILE); -} diff --git a/ldap/admin/src/migratedsgw b/ldap/admin/src/migratedsgw deleted file mode 100755 index 9801788c..00000000 --- a/ldap/admin/src/migratedsgw +++ /dev/null @@ -1,477 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# print begin message -$now_time = gmtime; -print "BEGIN DSGW migration at ", $now_time, " GMT\n"; - -# get the commandline options -if (!getopts('s:d:h:') || !$opt_s || !$opt_d || !$opt_h ) { - print "usage: dsgwmig options\n"; - print "\noptions:\n"; - print " -s directory\tdirectory containing the 3.0 Gateway\n"; - print " -d directory\tdirectory containing the 4.1 Gateway\n"; - print " -h host[:port]\tthe host and port of the directory server\n"; - print " \t\t\tto which the migrated gateway will query\n"; - print "\nexample:\n dsgwmig -s /usr/tmp/ds30/slapd-host/dsgw -d /usr/tmp/ds40/dsgw -h gargoyle:1974\n"; - - exit; -} - -sub reportAndExit { - my $now_time = gmtime; - print "END DSGW migration at ", $now_time, " GMT\n"; - print "DSGW Exit status is ", $exitCode, "\n"; - if ($? == 0 && $exitCode == 0) { - print "NMC_STATUS: 0\n"; - } else { - print '$?=', $?+0, ' $!=', $!+0, ' $exitCode=', $exitCode, "\n"; - print shift, "\n"; - print "NMC_STATUS: $exitCode\n"; - } - - print "###DSGW MIGRATION FINISHED###\n"; - - exit($exitCode); -} - -$SIG{__DIE__} = 'exit'; -$SIG{'QUIT'} = 'exit'; -$SIG{'INT'} = 'exit'; -$SIG{'TERM'} = 'exit'; - -# the atexit handler -END { - $! = 0; - $? = $exitCode; - &reportAndExit; -} - -# setup the path separator -$isNT = -d '\\'; -$PS = $isNT ? "\\" : "/"; - -#make sure that the target directory exists -if (! -e $opt_d) { - print "$opt_d does not exist\n"; - exit; -} - -print "Migrating the config directory...\n"; -# First migrate the config directory -migrate_html("config"); - -print "Migrating the html directory...\n"; -# Then migrate the html directory -migrate_html("html"); - -print "Migrating the dsgw.conf...\n"; -# Then migrate dsgw.conf -migrate_config(); - -# Then copy over certain files like alert.html, confirm.html and emptyFrame from -# the regular *4.1* DSGW to the newly migrated *4.1* gateway. -if (! -e "$opt_d"."$PS"."html-30"."$PS"."alert.html") { - print "copy ", "$opt_d"."$PS"."html"."$PS"."alert.html", " $opt_d"."$PS"."html-30"."$PS"."alert.html", "\n"; - copyFile("$opt_d"."$PS"."html"."$PS"."alert.html", "$opt_d"."$PS"."html-30"."$PS"."alert.html"); -} - -if (! -e "$opt_d"."$PS"."html-30"."$PS"."confirm.html") { - print "copy ", "$opt_d"."$PS"."html"."$PS"."confirm.html", " $opt_d"."$PS"."html-30"."$PS"."confirm.html", "\n"; - copyFile("$opt_d"."$PS"."html"."$PS"."confirm.html", "$opt_d"."$PS"."html-30"."$PS"."confirm.html"); -} - -if (! -e "$opt_d"."$PS"."html-30"."$PS"."confirm.gif") { - copyFile("$opt_d"."$PS"."html"."$PS"."confirm.gif", "$opt_d"."$PS"."html-30"."$PS"."confirm.gif"); -} - -if (! -e "$opt_d"."$PS"."html-30"."$PS"."alert.gif") { - copyFile("$opt_d"."$PS"."html"."$PS"."alert.gif", "$opt_d"."$PS"."html-30"."$PS"."alert.gif"); -} - -if (! -e "$opt_d"."$PS"."html-30"."$PS"."emptyFrame.html") { - copyFile("$opt_d"."$PS"."html"."$PS"."emptyFrame.html", "$opt_d"."$PS"."html-30"."$PS"."emptyFrame.html"); -} - -print "end of migratedsgw\n"; -$exitCode = 0; -exit $exitCode; - -sub migrate_html -{ - my $target_dir = shift(@_); - my $orig_target = "$target_dir"; - my $full_target_dir; - my @subdirlist; - my @dsgwfiles; - -# cd into the source directory - chdir "$opt_s"."$PS"."$target_dir" or die "Unable to cd to $opt_s$PS$target_dir: $!\n"; - -# read the files - opendir DSGW_OLD, "." or die "$!"; - @dsgwfiles = grep !/^\.\.?$/, readdir DSGW_OLD; - closedir DSGW_OLD; - -# Before we go on, we need to make the directory -# in the 4.1 space. If we're working on the config -# or html directory, then we have to rename them. - $target_dir =~ s/^(config|html)/$1\-30/; - $full_target_dir = "$opt_d". "$PS". "$target_dir"; - if (! -d $full_target_dir) { - mkdir $full_target_dir, 0755 or - die "can't create $opt_d$PS$target_dir. $!\n"; - } - -# foreach file in the current directory, -# either skip it (if it's a subdir) -# copy it to the new directory -# copy and modify it to the new directory - foreach $file (@dsgwfiles){ # - #Skip directories - if (-d $file) { -# print "Skipping Directory $file\n"; - push @subdirlist, $file; - next; - } - - if ($file =~ m/.*?\.html/) { -# open the old file - open(OLDFILE, "$file") or die "Cannot read $file. $!\n"; - -# open the new file - open(NEWFILE, ">"."$full_target_dir"."$PS"."$file") or die "Cannot write $full_target_dir$PS$file. $!\n"; - - for ($line=<OLDFILE>; $line ; $line=<OLDFILE>) { - -# replace all ACTION=/ds/cgi with ACTION=/dsgw/bin/cgi - $line =~ s:(?i)(action\s*=\s*("){0,1}\s*(http(s){0,1}\://.*?){0,1})/ds/(\w*):$1/dsgw/bin/$5:g; #")) - -# Langify the gifs, but not those that are already langified. Look for ="blah.gif" - $line =~ s:(?i)=\s*("){0,1}\s*([\w|\-|_]*)\.(gif|jpg|jpeg):=$1/dsgw/bin/lang?\<!-- GCONTEXT --\>\&file=$2\.$3:g; #") - -# And html files. Look for SRC|HREF="blah.html" - $line =~ s:(?i)(HREF|SRC)(\s*=\s*("){0,1}\s*)([\w|\-|_]*)\.(html):$1$2/dsgw/bin/lang?\<!-- GCONTEXT --\>\&file=$4\.$5:g; #") - -# Any javascript files should become /dsgw/html-30/blah.js - $line =~ s:(?i)=\s*("){0,1}\s*([\w|\-|_]*)\.(js):=$1/dsgw/html-30/$2\.$3:g; #") - -# Look for /dshtml/ to langify the .gifs and .html. This rule can't -# precede the first langify rule. That would be bad because it looks for ="blah.gif" - $line =~ s:(?i)/dshtml/([\w|\-|_]*)\.(gif|jpg|jpeg|html):/dsgw/bin/lang?\<!-- GCONTEXT --\>\&file=$1\.$2:g; #") - -# GETs on the CGIs .... -# auth - dn is passed either as QUERY_STRING or PATH_INFO, but not both. - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))auth(/|\?dn=)([\w|%]*):$3$4/dsgw/bin/auth?dn=$9\&\<!-- GCONTEXT --\>:g; - -# auth - by itself - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))auth:$3$4/dsgw/bin/auth\?\<!-- GCONTEXT --\>:g; - - -# lang - The argument is always PATH_INFO and it is either a filename -# or a file name and "info=blah". No QUERY_STRING. - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))lang/([=|\w|\&|\.|\-|_]*):$3$4/dsgw/bin/lang?\<!-- GCONTEXT --\>\&file=$8:g; - -# lang could be called without an argument, although it's silly to do so. - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))lang:$3$4/dsgw/bin/lang\?\<!-- GCONTEXT --\>:g; - -# search - take one word arguments with PATH_INFO only. No QUERY_STRING - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))search/(\w*):$3$4/dsgw/bin/search?\<!-- GCONTEXT --\>\&file=$8:g; - - -# search could exist without an argument on a GET - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))search:$3$4/dsgw/bin/search?\<!-- GCONTEXT --\>:g; - - -# csearch - take one word arguments with PATH_INFO only. No QUERY_STRING - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))csearch/(\w*):$3$4/dsgw/bin/csearch?\<!-- GCONTEXT --\>\&file=$8:g; - - -# csearch could exist without an argument on a GET - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))csearch:$3$4/dsgw/bin/csearch?\<!-- GCONTEXT --\>:g; - - -# unauth - doesn't take any arguments - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))unauth:$3$4/dsgw/bin/unauth?\<!-- GCONTEXT --\>:g; - -# dnedit and edit - must always have a dn specified, so /ds/dnedit will -# never exist by itself on a GET. If it's PATH_INFO, then it's just the dn. -# If it's QUERY_STRING it's a bunch of stuff. Could be both. dnedit must -# have a QUERY_STRING. - -# PATH_INFO and QUERY_STRING - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))(dn){0,1}edit/([\w|%]*)\?([\&|=|\w|\-|_|\.]*):$3$4/dsgw/bin/$8edit?\<!-- GCONTEXT --\>\&dn=$9\&$10:g; - -# PATH_INFO only - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))(dn){0,1}edit/([\w|%]*):$3$4/dsgw/bin/$8edit?\<!-- GCONTEXT --\>\&dn=$9:g; - - -# QUERY_STRING only - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))(dn){0,1}edit\?:$3$4/dsgw/bin/$8edit\?\<!-- GCONTEXT --\>\&:g; - - -# doauth and domodify - No GET, only POST - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))do(auth|modify):$3$4/dsgw/bin/do$8\?\<!-- GCONTEXT --\>:g; - - -# newentry - takes PATH_INFO only or nothing. If there is a PATH_INFO, -# then it's 1 word: type or name - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))newentry/(type|name):$3$4/dsgw/bin/newentry?\<!-- GCONTEXT --\>\&file=$8:g; - - -# newentry - could exist on its own - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))newentry:$3$4/dsgw/bin/newentry?\<!-- GCONTEXT --\>:g; - -# tutor - hasn't changed. - -# dosearch - From .../dosearch[/host[:port]][?[dn=baseDN&][LDAPquery]] Or -# ../dosearch/host[:port]/[baseDN][?LDAPquery] - -# To: dosearch?context=BLAH[&hp=host[:port]][&dn=baseDN][&ldq=LDAPquery]] - -# dosearch - Everything there, except maybe the port. Rule 1 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch(/){0,1}(\w+)(\:\d+){0,1}(/|\?)((dn=){0,1}([\w|%]+))(\?|\&)(.*?)(\s|"):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&hp=$9$10&dn=$14&ldq=$16$17:g; #") - - -# dosearch - no ldapquery -# current version rule 2 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch/(\w+)(\:\d+){0,1}\?((dn=)([\w|%]+)):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&hp=$8$9&dn=$12:g; - -# older version (always needs host specified) rule 3 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch/(\w+)(\:\d+){0,1}/([\w|%]+):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&hp=$8$9&dn=$10:g; - - -# dosearch - no basedn -# current version rule 4 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch/(\w+)(\:\d+){0,1}\?(.*?)(\s|"):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&hp=$8$9&ldq=$10$11:g; #") - - -# older version (always needs host specified) rule 5 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch/(\w+)(\:\d+){0,1}/\?(.*?)(\s|"):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&hp=$8$9&ldq=$10$11:g; #") - - -# dosearch - no host/port and ldapquery and dn rule 7 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch\?(dn=[\w|%]+\&)(.*?)(\s|"):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&$8ldq=$9$10:g; #") - # - -# dosearch - no host/port and no ldapquery rule 6 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch\?(dn=[\w|%]+):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&$8:g; - -# dosearch - host/port nothing else rule 9 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch/(\w+)(\:\d+){0,1}(/){0,1}:$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&hp=$8$9:g; - - -# dosearch - no host/port and no DN (current version only) rule 8 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch\?(.*?)(\s|"):$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>&ldq=$8$9:g; #") - -# dosearch - Just by itself rule 10 - $line =~ s:(?i)(((FRAME\s*SRC|HREF)(\s*=\s*("){0,1}\s*)(/ds/){0,1})|(/ds/))dosearch:$3$4/dsgw/bin/dosearch?\<!-- GCONTEXT --\>:g; - -# For 3.0 (not 3.1), we need to update the advanced search page -# to use the csearch CGI instead of javascript. - $line =~ s:SRC\s*=\s*"\s*javascript\:parent.emptyFrame\s*"\s*NAME\s*=\s*"\s*searchTypeFrame":SRC="/dsgw/bin/csearch\?\<!-- GCONTEXT --\>\&file=type" NAME="searchTypeFrame":g; - - $line =~ s:SRC\s*=\s*"\s*javascript\:parent.emptyFrame\s*"\s*NAME\s*=\s*"\s*searchAttrFrame":SRC="/dsgw/bin/csearch\?\<!-- GCONTEXT --\>\&file=attr" NAME="searchAttrFrame":g; - - $line =~ s:SRC\s*=\s*"\s*javascript\:parent.emptyFrame\s*"\s*NAME\s*=\s*"\s*searchMatchFrame":SRC="/dsgw/bin/csearch\?\<!-- GCONTEXT --\>\&file=match" NAME="searchMatchFrame":g; - - $line =~ s:SRC\s*=\s*"\s*javascript\:parent.emptyFrame\s*"\s*NAME\s*=\s*"\s*searchBaseFrame":SRC="/dsgw/bin/csearch\?\<!-- GCONTEXT --\>\&file=base" NAME="searchBaseFrame":g; - - -# Now for the POSTS -# Replace all FORM directives (except the form ending ones) with -# that same directive plus the pcontext directive on a newline - $line =~ s:(?i)(^\<\!\-\- DS_(AUTH|CSEARCH|BEGIN|NEWENTRY|SEARCH)[\w|_]*FORM .*?\-\-\>):$1\n\<!-- PCONTEXT --\>\n:g; - -# Some people might put a form-writing javascript function in their HTML. -# This rule will keep that from getting crippled because otherwise -# the next rule would insert a newline in the middle of a javascript string. - $line =~ s:(?i)\'(.*?)(\<FORM\s*.*?\>)(.*?)\':'$1$2\\n\<!-- PCONTEXT --\>\\n$3':g; - -# Now replace all the explicit <FORM> tags with that same tag -# and the pcontext directive. But don't do it if it already -# has been done by the previous rule - $line =~ s:(?i)(\<FORM\s*.*?\>)(?!\\n):$1\n\<!-- PCONTEXT --\>\n:g;#") - - - print NEWFILE $line; - - } - - close(OLDFILE); - close(NEWFILE); - - -# } elsif ( ($file =~ m/.*?\.js/) && !( -e "$opt_d"."$PS"."bin"."$PS"."$file")) { -# copyFile ("$file", "$opt_d"."$PS"."bin". "$PS". "$file"); - } else { -# print "copy this file $file\n"; - copyFile ("$file","$full_target_dir"."$PS"."$file"); - } - - } - - - - # After we've copied over all the files in this - # directory, then it's time to recurse on all the - # directories below. - - foreach $subdir (@subdirlist) { -# print "recursing on $orig_target $subdir\n"; - migrate_html("$orig_target"."$PS"."$subdir"); - } - -} - - -sub copyFile -{ - my $src = shift; - my $dest = shift; - my $buf = ""; - my $bufsize = 8192; - - open( SRC, $src ) || die "Can't open $src: $!\n"; - # if we are given a directory destination instead of a file, extract the - # filename portion of the source to use as the destination filename - if (-d $dest ) { - $dest = $dest . $PS . &basename($src); - } - open( DEST, ">$dest" ) || die "Can't create $dest: $!\n"; - binmode SRC; - binmode DEST; - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - while (read(SRC, $buf, $bufsize)) { - print DEST $buf; - } - close( SRC ); - close( DEST ); -} - - -sub migrate_config -{ - #open a new dsgw-30.conf in the NS-HOME/dsgw/context directory - open (NEWCONF, ">"."$opt_d"."$PS"."context". "$PS". "dsgw-30.conf") or die "Can't open $opt_d${PS}context${PS}dsgw-30.conf. $!\n"; - print NEWCONF "# Used by Netscape Directory Server Gateway\n\n"; - print NEWCONF "# The htmldir directive tells the CGIs where to find the html files\n"; - print NEWCONF "htmldir\t../html-30\n\n"; - print NEWCONF "# The configdir directive tells the CGIs where to find the\n"; - print NEWCONF "# templates/configuration files\n"; - print NEWCONF "configdir\t../config-30\n\n"; - print NEWCONF "# The gwnametrans directive tells the CGIs what url to output\n"; - print NEWCONF "# for http redirection. It should be the same nameTrans set\n"; - print NEWCONF "# in the webserver, if any is being is used.\n"; - print NEWCONF "gwnametrans\t/dsgw/html-30/\n\n"; - - # now open the old dsgw.conf and start copying it over, line by line - # to the new config file, replacing the NLS directive and the securityPath - # directive with the correct values. Also replace the old host:port with the - # new host:port - open (OLDCONF, "$opt_d"."$PS"."config-30"."$PS"."dsgw.conf") or die "Can't open $opt_d${PS}config-30${PS}dsgw.conf. $!\n";; - - for ($line=<OLDCONF>; $line ; $line=<OLDCONF>) { - $line =~ s:^NLS\s*../../../nls:NLS\t../../lib/nls:g; - $line =~ s:^securitypath\s*(.*?)/slapd\-.*?/dsgw/ssl:securitypath\t$1/alias/dsgw-cert.db:g; - $line =~ s:^baseurl\s*("){0,1}\s*ldap(s){0,1}\://.*?/:baseurl\t$1ldap$2\://$opt_h/:og; - - print NEWCONF "$line"; - - } - - - close (NEWCONF); - close (OLDCONF); -} - -sub basename { - my @list = split(/[\\\/]/, $_[0]); - return $list[@list - 1]; -} - -sub getopts { - local($argumentative) = @_; - local(@args,$_,$first,$rest); - local($errs) = 0; - local($[) = 0; - - @args = split( / */, $argumentative ); - while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) { - ($first,$rest) = ($1,$2); - $pos = index($argumentative,$first); - if($pos >= $[) { - if($args[$pos+1] eq ':') { - shift(@ARGV); - if($rest eq '') { - ++$errs unless @ARGV; - $rest = shift(@ARGV); - } - eval "\$opt_$first = \$rest;"; - } - else { - eval "\$opt_$first = 1"; - if($rest eq '') { - shift(@ARGV); - } - else { - $ARGV[0] = "-$rest"; - } - } - } - else { - print STDERR "Unknown option: $first\n"; - ++$errs; - if($rest ne '') { - $ARGV[0] = "-$rest"; - } - else { - shift(@ARGV); - } - } - } - $errs == 0; -} diff --git a/ldap/admin/src/namegen.c b/ldap/admin/src/namegen.c deleted file mode 100644 index c35c3eda..00000000 --- a/ldap/admin/src/namegen.c +++ /dev/null @@ -1,147 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* namegen.c - utility program to generate name * - * of backup files in the format YYYY_MM_DD_HMS * - * and set it up as an environment variable to * - * be used by batch files on NT * - * * - * to use it do the following in your batch file* - * namegen * - * call bstart * - * ....... * - * call bend * - * rm end.bat * - * * - * start and end are batch files generated by * - * name gen. * - * Example: ldif2db.bat */ - -#include <stdlib.h> -#include <stdio.h> -#include <time.h> -#include <string.h> - -#define STARTFILE "bstart.bat" -#define ENDFILE "bend.bat" -#define CMD "set DATESTR=%0\n" - - -int main (int argc, char **argv) -{ - char szDate [64]; - char szDateFile [64]; - char szCmd [256]; - struct tm *sCurTime; - long lCurTime; - int rt; - FILE *fBatch; - - time( &lCurTime ); - - sCurTime = localtime( &lCurTime ); - - strftime(szDate, sizeof (szDateFile), "%Y_%m_%d_%H%M%S", - sCurTime); - - _snprintf (szDateFile, sizeof(szDateFile), "%s.bat", szDate); - szDateFile[sizeof(szDateFile)-1] = (char)0; - - /* create date batch file */ - fBatch = fopen (szDateFile, "w"); - if (fBatch == NULL) - { - perror ("Unable to create date file!"); - exit (1); - } - - rt = fwrite (CMD, strlen (CMD), 1, fBatch); - if (rt != 1) - { - perror ("Unable to write date file\n"); - exit (1); - } - - fclose (fBatch); - - /* create bstart.bat that executest date batch file */ - fBatch = fopen (STARTFILE, "w"); - if (fBatch == NULL) - { - perror ("Unable to bstart file!"); - exit (1); - } - - _snprintf (szCmd, sizeof(szCmd), "call %s", szDate); - szCmd[sizeof(szCmd)-1] = (char)0; - - rt = fwrite (szCmd, strlen (szCmd), 1, fBatch); - if (rt != 1) - { - perror ("Unable to write bstart file\n"); - exit (1); - } - - fclose (fBatch); - - /* create bstart.bat that executest date batch file */ - fBatch = fopen (ENDFILE, "w"); - if (fBatch == NULL) - { - perror ("Unable to bend file!"); - exit (1); - } - - _snprintf (szCmd, sizeof(szCmd), "del %s\ndel bstart.bat\nset DATESTR=", szDateFile); - szCmd[sizeof(szCmd)-1] = (char)0; - - rt = fwrite (szCmd, strlen(szCmd), 1, fBatch); - if (rt != 1) - { - perror ("Unable to write bend file\n"); - exit (1); - } - - fclose (fBatch); - - return 0; -} diff --git a/ldap/admin/src/script-gen.c b/ldap/admin/src/script-gen.c deleted file mode 100644 index 0b17eb03..00000000 --- a/ldap/admin/src/script-gen.c +++ /dev/null @@ -1,147 +0,0 @@ -/** BEGIN COPYRIGHT BLOCK - * This Program is free software; you can redistribute it and/or modify it under - * the terms of the GNU General Public License as published by the Free Software - * Foundation; version 2 of the License. - * - * This Program is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS - * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License along with - * this Program; if not, write to the Free Software Foundation, Inc., 59 Temple - * Place, Suite 330, Boston, MA 02111-1307 USA. - * - * In addition, as a special exception, Red Hat, Inc. gives You the additional - * right to link the code of this Program with code not covered under the GNU - * General Public License ("Non-GPL Code") and to distribute linked combinations - * including the two, subject to the limitations in this paragraph. Non-GPL Code - * permitted under this exception must only link to the code of this Program - * through those well defined interfaces identified in the file named EXCEPTION - * found in the source code files (the "Approved Interfaces"). The files of - * Non-GPL Code may instantiate templates or use macros or inline functions from - * the Approved Interfaces without causing the resulting work to be covered by - * the GNU General Public License. Only Red Hat, Inc. may make changes or - * additions to the list of Approved Interfaces. You must obey the GNU General - * Public License in all respects for all of the Program code and other code used - * in conjunction with the Program except the Non-GPL Code covered by this - * exception. If you modify this file, you may extend this exception to your - * version of the file, but you are not obligated to do so. If you do not wish to - * provide this exception without modification, you must delete this exception - * statement from your version and license this file solely under the GPL without - * exception. - * - * - * Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. - * Copyright (C) 2005 Red Hat, Inc. - * All rights reserved. - * END COPYRIGHT BLOCK **/ - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -/* - * this is used for generating the (large) scripts during create_instance. - */ - -#include <stdio.h> -#include <stdlib.h> -#include <string.h> -#include <sys/types.h> -#include <sys/stat.h> -#include "portable.h" -#if defined( XP_WIN32 ) -#include <io.h> -#endif - -/* reads the file on inpath, and rewrites it on outpath. - * 'table' is a list of string-pairs (terminated by a pair of NULLs) that - * indicate substitution pairs. for example, the pair: - * "SERVER-ROOT", "/export/home/slapd-bastille" - * means to substitute any occurance of "{{SERVER-ROOT}}" in the file with - * "/export/home/slapd-bastille". - * - * returns 0 on success, -1 if it had trouble opening or reading/writing - * the two files. - */ -#define GS_BUFLEN 256 -int generate_script(const char *inpath, const char *outpath, int mode, - const char *table[][2]) -{ - FILE *fin, *fout; - char buffer[GS_BUFLEN], save_buffer[GS_BUFLEN]; - char *p, *q; - int i; - - fin = fopen(inpath, "r"); - if (fin == NULL) { - return -1; - } - fout = fopen(outpath, "w"); - if (fout == NULL) { - fclose(fin); - return -1; - } - - while (!feof(fin)) { - fgets(buffer, GS_BUFLEN, fin); - if (feof(fin)) { - break; - } - buffer[GS_BUFLEN-1] = 0; - if (buffer[strlen(buffer)-1] == '\n') { - buffer[strlen(buffer)-1] = 0; - } - if (buffer[strlen(buffer)-1] == '\r') { - buffer[strlen(buffer)-1] = 0; - } - - p = buffer; - while ((p = strstr(p, "{{")) != NULL) { - q = strstr(p+2, "}}"); - if (q == NULL) { - /* skip this one then */ - p += 2; - continue; - } - - /* key between {{ }} is now in [p+2, q-1] */ - for (i = 0; table[i][0] != NULL; i++) { - if ((strlen(table[i][0]) == (q-(p+2))) && - (strncasecmp(table[i][0], p+2, q-(p+2)) == 0)) { - /* match! ...but is there room for the subtitution? */ - int extra = strlen(table[i][1]) - (q+2-p); - - if (strlen(buffer) + extra > GS_BUFLEN-1) { - /* not enough room, scratch it */ - continue; - } - strncpy(save_buffer, q+2, sizeof(save_buffer)-1); - save_buffer[sizeof(save_buffer)-1] = (char)0; - strcpy(p, table[i][1]); - strcat(p, save_buffer); - q = p; - break; /* out of the for loop */ - } - } - - /* move on... */ - p = q; - } - - fprintf(fout, "%s\n", buffer); - } - -#if defined( XP_UNIX ) - fchmod(fileno(fout), mode); -#endif - - fclose(fin); - fclose(fout); - -#if defined( XP_WIN32 ) - chmod(outpath, mode); -#endif - - return 0; -} diff --git a/ldap/admin/src/scripts/Setup.pm.in b/ldap/admin/src/scripts/Setup.pm.in index 93d53291..512b5aa9 100644 --- a/ldap/admin/src/scripts/Setup.pm.in +++ b/ldap/admin/src/scripts/Setup.pm.in @@ -215,8 +215,17 @@ sub msg { sub doExit { my $self = shift; - $self->msg($FATAL, 'setup_exiting', $self->{log}->{filename}); - exit 1; + my $code = shift; + if (!defined($code)) { + $code = 1; + } + + if ($code) { + $self->msg($FATAL, 'setup_exiting', $self->{log}->{filename}); + } else { + $self->msg($SUCCESS, 'setup_exiting', $self->{log}->{filename}); + } + exit $code; } # get a list of the directory servers in configdir @@ -238,3 +247,10 @@ sub getDirServers { # Mandatory TRUE return value. # 1; + +# emacs settings +# Local Variables: +# mode:perl +# indent-tabs-mode: nil +# tab-width: 4 +# End: diff --git a/ldap/admin/src/scripts/migrate-ds.pl.in b/ldap/admin/src/scripts/migrate-ds.pl.in index 7c5ea83d..bd718d58 100644 --- a/ldap/admin/src/scripts/migrate-ds.pl.in +++ b/ldap/admin/src/scripts/migrate-ds.pl.in @@ -62,16 +62,15 @@ my $mig = new Migration($res); $mig->msg('begin_ds_migration', $mig->{oldsroot}); if (!migrateDS($mig)) { - exit 1; + $mig->doExit(1); } $mig->msg('end_ds_migration'); +$mig->doExit(0); END { if ($mig) { if (!$mig->{keep}) { unlink $mig->{inffile}; } - - $mig->doExit(); } } diff --git a/ldap/admin/src/scripts/setup-ds.pl.in b/ldap/admin/src/scripts/setup-ds.pl.in index 99969a22..32cb0c34 100644 --- a/ldap/admin/src/scripts/setup-ds.pl.in +++ b/ldap/admin/src/scripts/setup-ds.pl.in @@ -76,17 +76,18 @@ if (@errs) { $setup->msg(@errs); $setup->msg($FATAL, 'error_creating_dsinstance', $setup->{inf}->{slapd}->{ServerIdentifier}); + $setup->doExit(1); } else { $setup->msg('created_dsinstance', $setup->{inf}->{slapd}->{ServerIdentifier}); } +$setup->doExit(0); + END { if ($setup) { if (!$setup->{keep}) { unlink $setup->{inffile}; } - - $setup->doExit(); } } diff --git a/ldap/admin/src/scripts/template-migrate5to7 b/ldap/admin/src/scripts/template-migrate5to7 deleted file mode 100644 index f2e10e2a..00000000 --- a/ldap/admin/src/scripts/template-migrate5to7 +++ /dev/null @@ -1,3091 +0,0 @@ -#{{PERL-EXEC}} -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# enable the use of our bundled perldap with our bundled ldapsdk libraries -# all of this nonsense can be omitted if the mozldapsdk and perldap are -# installed in the operating system locations (e.g. /usr/lib /usr/lib/perl5) -BEGIN { - my $sroot = "{{DS-ROOT}}"; - push @INC, "$sroot/lib/perl/arch", "$sroot/lib/perl"; - if ($ENV{LD_LIBRARY_PATH}) { - $ENV{LD_LIBRARY_PATH} .= ":"; - } - $ENV{LD_LIBRARY_PATH} .= "$sroot/shared/lib"; - # this is only needed for HP/ux PA-RISC, but it doesn't hurt other platforms - if ($ENV{SHLIB_PATH}) { - $ENV{SHLIB_PATH} .= ":"; - } - $ENV{SHLIB_PATH} .= "$sroot/shared/lib"; -} -# Migrate a 5.x directory server to a 7.0 directory server - -####################################################################################################### -# enable the use of Perldap functions -require DynaLoader; - -use Getopt::Std; -use Mozilla::LDAP::Conn; -use Mozilla::LDAP::Entry; -use Mozilla::LDAP::LDIF; -use Mozilla::LDAP::Utils qw(:all); -use Mozilla::LDAP::API qw(:api :ssl :apiv3 :constant); # Direct access to C API -use Time::localtime; -use File::Basename; -use Class::Struct ; - -####################################################################################################### - -sub usage { - print(STDERR "\nUsage: $0 -D rootdn { -w password | -w - | -j filename } -p port \n"); - print(STDERR " -o oldInstancePath -n newInstancePath [-t tracelevel] [-L logfile]\n"); - print(STDERR "************** parameters in brackets are optionals, others are required **************\n"); - print(STDERR " Opts: -D rootdn - new 7.0 Directory Manager\n"); - print(STDERR " : -w password - new 7.0 Directory Manager's password\n"); - print(STDERR " : -w - - Prompt for new 7.0 Directory Manager's password\n"); - print(STDERR " : -j filename - Read new 7.0 Directory Manager's password from file\n"); - print(STDERR " : -p port - new 7.0 Directory Server port\n"); - print(STDERR " : -o oldInstancePath - Path of the old instance to migrate \n"); - print(STDERR " : -n newInstancePath - Path of the new 7.0 instance\n"); - print(STDERR " : [-d dataPath] - Path to directory containing data files to import into new instance\n"); - print(STDERR " : [-v oldVersion] - Version of old instance (obtained by running $slapdExecName -v\n"); - print(STDERR " : [-t tracelevel] - (optional) specify the level of trace (0..3)\n"); - print(STDERR " : [-L logfile] - (optional) specify the file to log the migration report \n"); - } -######################################################################################################## - -BEGIN { - - require 'uname.lib' ; - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - ${SEP} = $isNT ? ";" : ":" ; - @INC = ( '.', '../../../admin/admin/bin'); - grep { s@/@\\@g } @INC if $isNT; - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; - - # If this variable is set, all file/directory creation will make sure the mode - # and ownership of the destination is the same as the source - $PRESERVE = 1 if (!$isNT); - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - if ($isNT) { - $os = "WINNT"; - } else { - $os = &uname("-s"); - } - if ($isNT) { - # we have to pass batch files directly to the NT command interpreter - $com_spec = $ENV{ComSpec}; - if (!$com_spec) { - $com_spec = $ENV{COMSPEC}; - } - if (!$com_spec || ! -f $com_spec) { - # find the first available command interpreter - foreach $drive (c..z) { - $com_spec = "$drive:\\winnt\\system32\\cmd.exe"; - last if (-f $com_spec); - $com_spec = undef; - } - if (! $com_spec) { - # punt and pray - $com_spec = 'c:\winnt\system32\cmd.exe'; - } - } - } - if ( $os eq "AIX" ) { - $dll_suffix = "_shr.a"; - } - elsif ( $os eq "HP-UX" ) { - $dll_suffix = ".sl"; - } - elsif ( $os eq "WINNT" ) { - $dll_suffix = ".dll"; - } - else { - $dll_suffix = ".so"; - } - $slapdExecName = $isNT ? 'slapd.exe' : './ns-slapd'; - select STDERR; - $| = 1; - select STDOUT; - $| = 1; -} - -SWITCH: { - if ($os eq "AIX") { - $LIB_PATH = "LIBPATH" ; - last SWITCH ; - } - if ($os eq "HP-UX") { - $LIB_PATH = "SHLIB_PATH" ; - last SWITCH ; - } - if ($isNT) { - $LIB_PATH = "PATH" ; - last SWITCH ; - } - else { - $LIB_PATH = "LD_LIBRARY_PATH" ; - last SWITCH ; - } - } - - # old parameters - ${oldDir} = "" ; - ${oldname} = "" ; - ${oldHome} = "" ; - ${oldConfDir} = "" ; - ${oldlocaluser} ; - ${olduid} ; - ${oldgid} ; - - # new parameters - ${root} = "{{DS-ROOT}}" ; - ${type} = "" ; - ${newname} = "" ; - ${newport} = "" ; - ${rootDN} = "" ; - ${rootpwd} = "" ; - ${localhost} = "" ; - ${LogFileReport} = "" ; - ${newuid} ; - ${localuser} ; - ${newgid} ; - $NO_INPUT_USER = 0 ; # by default user can give inputs during the migration process - ${curdir} = getCwd(); - ${slapdExecDir} = "${root}${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - # in 7.0 the replica Id is setup to a static value - $replicaIdvalue = 65535; - - # specify the level of trace - $TRACELEVEL=1; - - $LDAP_SERVER_UNREACHABLE = 81; - - # get input users - &getParameters() ; - ${oldDir} = &normalizeDir("${oldDir}"); - ${oldHome} = "${oldDir}${PATHSEP}$type-$oldname" ; - ${oldConfDir} = "${oldHome}${PATHSEP}config${PATHSEP}" ; - ${oldSchemaDir} = "${oldConfDir}schema${PATHSEP}"; - ${oldDSEldif} = "${oldConfDir}dse.ldif"; - ${serverHome} = "${root}${PATHSEP}$type-$newname" ; - ${schemaDir} = "$serverHome${PATHSEP}config${PATHSEP}schema${PATHSEP}"; - ${DSEldif} = "$serverHome${PATHSEP}config${PATHSEP}dse.ldif"; - ${ldif_rep} = "${oldConfDir}ldif${PATHSEP}" ; - ${oldSlapdExecDir} = "${oldDir}${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - - open(LOGFILE, ">> $LogFileReport"); - - printTrace("\noldDir: $oldDir, oldHome: $oldHome, \noldConfDir: $oldConfDir, \nldif_rep: $ldif_rep, \nrootDN: $rootDN, \nPort: $newport, \nNewname: $newname\n",3); - printTrace("\nLIB_PATH: $LIB_PATH",4); - - if (!(-d $serverHome)) { - printMsg("\n$serverHome doesn't exist\n"); - exit(1); - } - if (!(-d $oldHome)) { - printMsg("\n$oldHome doesn't exist\n"); - exit(1); - } - - if ($olddatadir && !(-d $olddatadir)) { - print("\n$olddatadir doesn't exist\n"); - exit(1); - } - - -%HashParametersName = (); - -# The following hash displays only general server parameters to migrate under cn=config -%GeneralSrvParamToMigrate = ( - 'nsslapd-accesscontrol'=> '\n', - 'nsslapd-errorlog-logging-enabled'=> '\n', - 'nsslapd-accesslog-logging-enabled'=> '\n', - 'nsslapd-auditlog-logging-enabled'=> '\n', - 'nsslapd-accesslog-level'=> '\n', - 'nsslapd-accesslog-logbuffering'=> '\n', - 'nsslapd-accesslog-logexpirationtime'=> '\n', - 'nsslapd-accesslog-logexpirationtimeunit'=> '\n', - 'nsslapd-accesslog-logmaxdiskspace'=> '\n', - 'nsslapd-accesslog-logminfreediskspace'=> '\n', - 'nsslapd-accesslog-logrotationtime'=> '\n', - 'nsslapd-accesslog-logrotationtimeunit'=> '\n', - 'nsslapd-accesslog-maxlogsize'=> '\n', - 'nsslapd-accesslog-maxLogsPerDir'=> '\n', - 'nsslapd-attribute-name-exceptions'=> '\n', - 'nsslapd-auditlog-logexpirationtime'=> '\n', - 'nsslapd-auditlog-logexpirationtimeunit'=> '\n', - 'nsslapd-auditlog-logmaxdiskspace'=> '\n', - 'nsslapd-auditlog-logminfreediskspace'=> '\n', - 'nsslapd-auditlog-logrotationtime'=> '\n', - 'nsslapd-auditlog-logrotationtimeunit'=> '\n', - 'nsslapd-auditlog-maxlogsize'=> '\n', - 'nsslapd-auditlog-maxLogsPerDir'=> '\n', - 'nsslapd-certmap-basedn'=> '\n', - 'nsslapd-ds4-compatible-schema'=> '\n', - 'nsslapd-enquote-sup-oc'=> '\n', - 'nsslapd-errorlog-level'=> '\n', - 'nsslapd-errorlog-logexpirationtime'=> '\n', - 'nsslapd-errorlog-logexpirationtimeunit'=> '\n', - 'nsslapd-errorlog-logmaxdiskspace'=> '\n', - 'nsslapd-errorlog-logminfreediskspace'=> '\n', - 'nsslapd-errorlog-logrotationtime'=> '\n', - 'nsslapd-errorlog-logrotationtimeunit'=> '\n', - 'nsslapd-errorlog-maxlogsize'=> '\n', - 'nsslapd-errorlog-maxlogsperdir'=> '\n', - 'nsslapd-groupevalnestlevel'=> '\n', - 'nsslapd-idletimeout'=> '\n', - 'nsslapd-ioblocktimeout'=> '\n', - 'nsslapd-lastmod'=> '\n', - 'nsslapd-listenhost'=> '\n', - 'nsslapd-maxdescriptors'=> '\n', - 'nsslapd-nagle'=> '\n', - 'nsslapd-readonly'=> '\n', - 'nsslapd-referralmode'=> '\n', - 'nsslapd-plugin-depends-on-name'=> '\n', - 'nsslapd-plugin-depends-on-type'=> '\n', - 'nsslapd-referral'=> '\n', - 'nsslapd-reservedescriptors'=> '\n', - 'nsslapd-rootpwstoragescheme'=> '\n', - 'nsslapd-schemacheck'=> '\n', - 'nsslapd-secureport'=> '\n', - 'nsslapd-security'=> '\n', - 'nsslapd-sizelimit'=> '\n', - 'nsslapd-ssl3ciphers'=> '\n', - 'nsslapd-timelimit'=> '\n', - 'passwordchange'=> '\n', - 'passwordchecksyntax'=> '\n', - 'passwordexp'=> '\n', - 'passwordhistory'=> '\n', - 'passwordinhistory'=> '\n', - 'passwordlockout'=> '\n', - 'passwordlockoutduration'=> '\n', - 'passwordmaxage'=> '\n', - 'passwordmaxfailure'=> '\n', - 'passwordminage'=> '\n', - 'passwordminlength'=> '\n', - 'passwordmustchange'=> '\n', - 'passwordresetfailurecount' => '\n', - 'passwordstoragescheme' => '\n', - 'passwordunlock' => '\n', - 'passwordwarning' => '\n' -); - -# the following hash displays global parameters related to database stored under cn=config,cn=ldbm database,cn=plugins,cn=config -%GlobalConfigLDBMparamToMigrate = ( - 'nsslapd-allidsthreshold' => '\n', - 'nsslapd-lookthroughlimit' => '\n', - 'nsslapd-mode' => '\n', - 'nsslapd-dbcachesize' => '\n', - 'nsslapd-cache-autosize' => '\n', - 'nsslapd-cache-autosize-split' => '\n', - 'nsslapd-db-transaction-logging' => '\n', - 'nsslapd-import-cachesize' => '\n' -); - -# the following hash displays specific parameters to each backends and stored under cn=DBname,cn=ldbm database,cn=plugins,cn=config -%LDBMparamToMigrate = ( - 'nsslapd-cachesize' => '\n', - 'nsslapd-cachememsize' => '\n', - 'nsslapd-readonly' => '\n', - 'nsslapd-require-index' => '\n' -); - - -%ChainingConfigParams = ( - 'nsactivechainingcomponents' => '\n', - 'nstransmittedcontrols' => '\n' - ); - -%ChainingDefaultInstanceConfigParams = ( - 'nsabandonedsearchcheckinterval' => '\n', - 'nsbindconnectionslimit' => '\n', - 'nsbindtimeout' => '\n', - 'nsbindretrylimit' => '\n', - 'nshoplimit' => '\n', - 'nsmaxresponsedelay' => '\n', - 'nsmaxtestresponsedelay' => '\n', - 'nschecklocalaci' => '\n', - 'nsconcurrentbindlimit' => '\n', - 'nsconcurrentoperationslimit' => '\n', - 'nsconnectionlife' => '\n', - 'nsoperationconnectionslimit' => '\n', - 'nsproxiedauthorization' => '\n', - 'nsreferralonscopedsearch' => '\n', - 'nsslapd-sizelimit' => '\n', - 'nsslapd-timelimit' => '\n' -); - -%changelog5params = ( - 'nsslapd-changelogmaxage' => '\n', - 'nsslapd-changelogmaxentries' => '\n' - ); - -@SNMPparams = ( - 'nssnmpenabled', - 'nssnmporganization', - 'nssnmplocation', - 'nssnmpcontact', - 'nssnmpdescription', - 'nssnmpmasterhost', - 'nssnmpmasterport', - 'nssnmpenabled', - 'aci' - ); - -%stdIncludes = ( - "." => "\n", - ".." => "\n", - "30ns-common.ldif " => "\n", - "50ns-mail.ldif " => "\n", - "50ns-news.ldif" => "\n", - "50iplanet-servicemgt.ldif"=> "\n", - "50netscape-servicemgt.ldif"=> "\n", - "50ns-mcd-browser.ldif" => "\n", - "50ns-proxy.ldif" => "\n", - "00core.ldif" => "\n", - "50ns-admin.ldif" => "\n", - "50ns-mcd-config.ldif " => "\n", - "50ns-value.ldif" => "\n", - "05rfc2247.ldif" => "\n", - "50ns-calendar.ldif" => "\n", - "50ns-mcd-li.ldif" => "\n", - "50ns-wcal.ldif" => "\n", - "05rfc2927.ldif" => "\n", - "50ns-certificate.ldif" => "\n", - "50ns-mcd-mail.ldif" => "\n", - "50ns-web.ldif" => "\n", - "10rfc2307.ldif" => "\n", - "50ns-compass.ldif" => "\n", - "50ns-media.ldif" => "\n", - "20subscriber.ldif" => "\n", - "50ns-delegated-admin.ldif"=> "\n", - "50ns-mlm.ldif" => "\n", - "25java-object.ldif" => "\n", - "50ns-directory.ldif" => "\n", - "50ns-msg.ldif" => "\n", - "28pilot.ldif" => "\n", - "50ns-legacy.ldif" => "\n", - "50ns-netshare.ldif" => "\n" -); - - -# Backends migrated (Backend CN attribute value) -@BACKENDS = () ; -# All pairs of suffix-backend are registered in this hashtable -%oldBackends = () ; - -#store the backend instances to migrate -@LDBM_backend_instances = (); - -#store the mapping tree -@Mapping_tree_entries = (); - -#store the suffix and the associated chaining backend -%oldChainingBackends = (); - -#store the multiplexor bind entries to migrate -%MultiplexorBindDNEntriesToMigrate = (); - -#store the Replica bind DN entries to migrate -%ReplicaBindDNEntriesToMigrate = (); - -# list of standard plugins -%stdPlugins = ( - "7-bit check" => "\n", - "acl plugin" => "\n", - "acl preoperation" => "\n", - "binary syntax" => "\n", - "case exact string syntax" => "\n", - "case ignore string syntax" => "\n", - "chaining database" => "\n", - "class of service" => "\n", - "country string syntax" => "\n", - "distinguished name syntax" => "\n", - "generalized time syntax" => "\n", - "integer syntax" => "\n", - "internationalization plugin" => "\n", - "ldbm database" => "\n", - "legacy replication plugin" => "\n", - "multimaster replication plugin" => "\n", - "octet string syntax" => "\n", - "clear" => "\n", - "crypt" => "\n", - "ns-mta-md5" => "\n", - "sha" => "\n", - "ssha" => "\n", - "postal address syntax" => "\n", - "referential integrity postoperation" => "\n", - "retro changelog plugin" => "\n", - "roles plugin" => "\n", - "telephone syntax" => "\n", - "uid uniqueness" => "\n", - "uri syntax" => "\n" - ); - -# list of indexes that have disappeared from the new schema compared to 5.0 -%deniedIndexes = ( - 'dncomp' => "\n" -); - -@default_indexes = (); -@indexes = (); - -# list of user added Plugin's. In 7.0, they 'll need to be recompiled -@badPlugins = () ; - -@pluginAttrs = ( - "objectclass", - "cn", - "nsslapd-pluginpath", - "nsslapd-plugininitfunc", - "nsslapd-plugintype", - "nsslapd-pluginenabled", - "nsslapd-plugin-depends-on-type", - "nsslapd-pluginid", - "nsslapd-pluginversion", - "nsslapd-pluginvendor" - ); - -@nsds5replicaAttrs = ( - 'objectclass', - 'nsDS5ReplicaRoot', - 'nsDS5ReplicaType', - 'nsDS5ReplicaLegacyConsumer', - 'nsDS5flags', - 'nsDS5ReplicaId', - 'nsDS5ReplicaPurgeDelay', - 'nsDS5ReplicaBinddn', - 'cn', - 'nsDS5ReplicaReferral' - ); - -# array of replicas to migrate -@new6replicas = (); - -# array of replication agreements to migrate -@replicationAgreements = (); - -# compare LDIF standard config files with standard ones -CompareStdConfigFiles() ; -die "\n\n The version of product you want to migrate is not a 5.x Directory Server\n" unless ($oldVersion == 5) ; - -# Shutdown the legacy Directory instance -printTrace("\nShutdown the legacy Directory Server instance: ${oldHome}",0); -&stopServer($oldDir, 'slapd-'.$oldname); - -# get the hostname of the new LDAP server -my $LDAPservername = &getLDAPservername(); - -# get the uid and gid of the 7.0 slapd user -($localuser, $newuid, $newgid) = getuid_gid(); -# get the uid and gid of the 5.x slapd user -($oldlocaluser, $olduid, $oldgid) = getolduid_gid(); -printTrace("\n7.0 localuser: $localuser, uid: $newuid, gid: $newgid",2); -printTrace("\n5.x localuser: $oldlocaluser, uid: $olduid, gid: $oldgid",2); - -# backup 7.0 configuration files in <6server_root>/slapd-instancename/config -printTrace("\nBackup $serverHome${PATHSEP}config on $serverHome${PATHSEP}config_backup ...",0); -&backupConfigFiles(); - -# migrate the schema (need to stop and start the 7.0 server) -printTrace("\nMigrate the schema...",0); -MigrateSchema(); - -# start the server unless it is already started -&startServer() unless (isDirectoryAlive()); - -############### Connect to the 7.0 LDAP Directory Server ###################### -$ENV{"$LIB_PATH"} = $new_libpath; - -die "\n Migration aborted. Make sure your old and new Directory Server are installed on the same machine \n" if ( $LDAPservername == -1 ); -$conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - -# Cconnection to 7.0 LDAP server is successful ! -printTrace("\nConnected to $Version.$Minor LDAP server",0) ; - -# Parse the main configuration file: dse.ldif -printTrace("\n\nParse the old DSE ldif file: $oldDSEldif *****",0, 1); -printTrace("\nThis may take a while ...\n",0); -&MigrateDSEldif(); - -#migrate LDBM backend instances -printTrace("\n\nMigrate LDBM backend instances...",0,1); -&migrateLDBM_backend_instances(); - -#migrate mapping tree entries -printTrace("\n\nMigrate mapping tree...",0,1); -&migrateMappingTree(); - -#migrate default indexes -printTrace("\n\nMigrate default indexes...",0,1); -migrateDefaultIndexes(); - -#migrate indexes -printTrace("\n\nMigrate indexes...",0,1); -migrateIndexes(); - -#migrate replicas -printTrace("\n\nMigrate replicas...",0,1); -&MigrateNSDS5_replica(); - -#migrate replication agreements -printTrace("\n\nMigrate replication agreements...",0,1); -&MigrateNSDS_replication_agreement(); - -#migrate key/cert databases -printTrace("\n\nMigrate key/cert databases...",0,1); -&MigrateSSL(); - -# migrate certmap.conf -printTrace("\n\nMigrate Certmap.conf...",0,1); -&MigrateCertmap() ; - -################## Close the connection to 7.0 LDAP Server ##################### -printTrace("\n\n***** Close the LDAP connection to the new Directory Server instance ***** ",0); -$conn->close; - - -################## stop the new instance and Export/Import the data, restart the server ################## -if (@BACKENDS) { - &stopServer($root,'slapd-'.$newname); - if ($olddatadir) { - printTrace("\nData already contained in $olddatadir...\n",0,1) ; - $ldif_rep = "$olddatadir${PATHSEP}"; - } else { - printTrace("\nData processing...\n",0,1) ; - # migrate data for each backend: 5.x -> LDIF files - &manydb2Ldif($ldif_rep); - } - - # migrate LDIF data to the new database: LDIF -> New - &manyLdif2db($ldif_rep); - &migrateChangelog(); - printTrace("\n***** Migrate ReplicaBindDN entries...\n",0,1); - &importReplicaBindDNEntries(); - printTrace("\n***** Migrate MultiplexorBindDN entries...\n",0,1); - &importMultiplexorBindDNEntries(); - &startServer() unless (isDirectoryAlive()); -} -else { - printTrace("\nINFORMATION - There are no non-standard or non-already existing suffixes to migrate\n",0); - &migrateChangelog(); - printTrace("\n***** Migrate ReplicaBindDN entries...\n",0,1); - &importReplicaBindDNEntries(); - printTrace("\n***** Migrate MultiplexorBindDN entries...\n",0,1); - &importMultiplexorBindDNEntries(); -} - -printMsg("\n\n ****** End of migration ******\n\n"); - -close(LOGFILE); - - -########################################################################################### -# get input users -sub getParameters { - my $exit = 0 ; - my $i = 0; - my $pwdfile= ""; - - while ($i <= $#ARGV) { - if ( "$ARGV[$i]" eq "-D" ) { # directory manager - if (! $rootDN) { - $rootDN = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-w") { # password - if (! $rootpwd) { - $rootpwd = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-j") { # password file - if (! $pwdfile) { - $pwdfile = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-o") { # old instance path - if (! $oldHome ) { - $oldHome = $ARGV[++$i] ; - grep { s@\\@/@g } $oldHome if $isNT ; - if ($oldHome =~ /[\"]?(.*)?[\"]?/) { $oldHome = $1 ; } - if ($oldHome =~ m@^(.*)/([^-/]*)-([^/]*)[/]?$@) { - $oldDir = $1 ; - $type = $2 ; - $oldname = $3 ; - if ($isNT) { - $oldDir = lc($oldDir) ; - $type = lc($type) ; - $oldname = lc($oldname) ; - $oldHome = lc($oldHome) ; - grep { s@/@\\@g } $oldDir ; - grep { s@/@\\@g } $oldHome ; - } - } - else { - print("\nThe old instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-n") { # new instance path - if (! $serverHome ) { - $serverHome = $ARGV[++$i] ; - grep { s@\\@/@g } $root if $isNT ; - grep { s@\\@/@g } $serverHome if $isNT ; - if ($serverHome =~ /[\"]?(.*)?[\"]?/) { $serverHome = $1 ; } - if ($serverHome =~ m@^(.*?)/?([^/-]*)-([^/]*)[/]?$@) { - $root = $1 if ($1); - $type = $2 ; - $newname = $3 ; - if ($isNT) { - $root = lc($root) ; - $type = lc($type) ; - $newname = lc($newname) ; - $serverHome = lc($serverHome) ; - grep { s@/@\\@g } $root ; - grep { s@/@\\@g } $serverHome ; - } - } - else { - print("\nThe new instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-p") { # new DS port - if (! $newport ) { - $newport = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-d") { # old instance LDIF data dir - if (! $olddatadir ) { - $olddatadir = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-v") { # old version - if (! $oldversionstr ) { - $oldversionstr = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-t") { # TRACELEVEL - my $value = $ARGV[++$i] ; - if ($value =~ /[0-3]/) { - $TRACELEVEL = $value ; - } - else { - print("\nThe tracelevel must belong to 0..3 interval"); - &usage(); - exit(); - } - } elsif ("$ARGV[$i]" eq "-noinput") { # no user interventions during processing - $NO_INPUT_USER = 1 ; - } elsif ("$ARGV[$i]" eq "-L") { # migration logfile - $LogFileReport = $ARGV[++$i] ; - } - else { - print("\nThe option $ARGV[$i] is not recognized"); - &usage() ; - exit(1); - } - $i++; - } - if (! $rootDN) { - print("\nThe rootDN is missing"); - $exit = 1; - } - if ($pwdfile ne "") { - # Open file and get the password - unless (open (RPASS, $pwfile)) { - die "Error, cannot open password file $passwdfile\n"; - } - $rootpwd = <RPASS>; - chomp($rootpwd); - close(RPASS); - } elsif ($rootpwd eq "-"){ - # Read the password from terminal - die "The '-w -' option requires an extension library (Term::ReadKey) which is not\n", - "part of the standard perl distribution. If you want to use it, you must\n", - "download and install the module. You can find it at\n", - "http://www.perl.com/CPAN/CPAN.html\n"; - # Remove the previous line and uncomment the following 6 lines once you have installed Term::ReadKey module. -# use Term::ReadKey; -# print "Bind Password: "; -# ReadMode('noecho'); -# $rootpwd = ReadLine(0); -# chomp($rootpwd); -# ReadMode('normal'); - } - if (! $rootpwd) { - print("\nThe rootpwd is missing"); - $exit = 1 ; - } - if (! $newport) { - print("\nThe port is missing"); - $exit = 1; - } - if (! $serverHome) { - print("\nThe new instance path is missing"); - $exit = 1; - } - if (! $oldHome) { - print("\nThe old instance path is missing"); - $exit = 1; - } - if ((! $LogFileReport) && $serverHome) { - ($sec, $min, $hour, $dd, $mm, $yy) = &GetTime(); - $LogFileReport = "${serverHome}${PATHSEP}logs${PATHSEP}Migration_${dd}${mm}${yy}_${hour}${min}${sec}.log"; - } - if ($exit) { - &usage() ; - exit(1); - } - -} - -################################################################################################### - -sub MigrateSchema{ - my $FilesChanged = ""; - my $AllDiffs = ""; - my $NoChanges = "" ; - my $lineToBegin = 0 ; - opendir(SCHEMADIR, $oldSchemaDir) or - die "Error: could not open migrated config dir $oldSchemaDir: $!"; - - foreach $file (readdir(SCHEMADIR)) { - if (! exists($stdIncludes{lc($file)})) { - my $newSchemaFile = $schemaDir . $file; - if (-f $newSchemaFile ) { - # The ldif file already exists. Make a diff and warn the user if different. - if (diff($newSchemaFile, $oldSchemaDir.$file)) { - &stopServer($root,'slapd-'.$newname) if (isDirectoryAlive()); - $AllDiffs .= "\n$file"; - copyBinFile("$oldSchemaDir$file", $newSchemaFile); - } - } - else { - &stopServer($root,'slapd-'.$newname) if (isDirectoryAlive()); - $AllDiffs .= "\n$file"; - copyBinFile("$oldSchemaDir$file", $newSchemaFile); - } - } - } - closedir(SCHEMADIR); - if ($AllDiffs) { - printMsg("\n\n***********************************************************************"); - printMsg("\nThe following LDIF files have been migrated:"); - printMsg("$AllDiffs"); - printMsg("\n*************************************************************************\n\n"); - } - &startServer() if (! isDirectoryAlive()); -} - - -################################################################################################### -# This subroutine is used to parse the dse.ldif file and call specific routines to act with entries -sub MigrateDSEldif { - printTrace("\nMigrate DSE entries...",1); - my $tempoAlreadyDone = 0; - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - SWITCH: { - if ($typeOfEntry eq "LDBM_BACKEND_INSTANCE"){ - parseLDBM_backend_instance($entry); - last SWITCH; - } - if ($typeOfEntry eq "MAPPING_TREE"){ - parseMapping_tree($entry); - last SWITCH; - } - if ($typeOfEntry eq "DEFAULT_INDEX"){ - parseDefaultIndex($entry); - last SWITCH; - } - if ($typeOfEntry eq "INDEX"){ - parseIndex($entry); - last SWITCH; - } - if ($typeOfEntry eq "STANDARD_PLUGIN"){ - migrateStdPlugin($entry); - last SWITCH; - } - if ($typeOfEntry eq "CONFIG_NODE"){ - migrateConfig_Node($entry); - last SWITCH; - } - if ($typeOfEntry eq "CONFIG_LDBM_DATABASE"){ - migrateConfig_LDBM_database($entry); - last SWITCH; - } - if ($typeOfEntry eq "CHAINING_BACKEND_CONFIG"){ - migrateChainingBE_config($entry); - last SWITCH; - } - if ($typeOfEntry eq "CHAINING_BACKEND_INSTANCE"){ - migrateChainingBE_instance($entry); - last SWITCH; - } - if ($typeOfEntry eq "NSDS5_REPLICA"){ - parseNSDS5_replica($entry); - last SWITCH; - } - if ($typeOfEntry eq "NSDS_REPLICATION_AGREEMENT"){ - parseNSDS_replication_agreement($entry); - last SWITCH; - } - if ($typeOfEntry eq "CHANGELOG5"){ - migrateChangelog5($entry); - last SWITCH; - } - if ($typeOfEntry eq "REPLICATION"){ - migrateReplication($entry); - last SWITCH; - } - if ($typeOfEntry eq "SECURITY"){ - migrateSecurity($entry); - last SWITCH; - } - if ($typeOfEntry eq "SNMP"){ - migrateSNMP($entry); - last SWITCH; - } - } - - } - close(DSELDIF); -} - -############################################################################# -# returns the "type of an entry". If the entry is not to be migrated its type is "NOT_MIGRATED_TYPE" - -sub getTypeOfEntry{ - my $entry = shift; - my $DN = $entry->getDN(1) ; # 1 is to normalize the returned DN - if (($DN =~ /cn=ldbm database,cn=plugins,cn=config$/i) && (isObjectclass($entry,"nsBackendInstance"))) { - return "LDBM_BACKEND_INSTANCE"; - } - if (($DN =~ /cn=mapping tree,cn=config$/i) && (isObjectclass($entry,"nsMappingTree"))) { - return "MAPPING_TREE"; - } - if (($DN =~ /cn=default indexes,cn=config,cn=ldbm database,cn=plugins,cn=config$/i) && (isObjectclass($entry,"nsIndex"))) { - return "DEFAULT_INDEX"; - } - if (isObjectclass($entry,"nsIndex")) { - return "INDEX"; - } - if ((isObjectclass($entry,"nsSlapdPlugin")) && (isStdPlugin($entry))) { - return "STANDARD_PLUGIN"; - } - if ($DN =~ /^cn=config$/i) { - return "CONFIG_NODE"; - } - if ($DN =~ /^cn=config,cn=ldbm database,cn=plugins,cn=config$/i) { - return "CONFIG_LDBM_DATABASE"; - } - if (($DN =~ /^cn=config,cn=chaining database,cn=plugins,cn=config$/i) || ($DN =~ /^cn=default instance config,cn=chaining database,cn=plugins,cn=config$/i)){ - return "CHAINING_BACKEND_CONFIG"; - } - if (($DN =~ /cn=chaining database,cn=plugins,cn=config$/i) && (isObjectclass($entry,"nsBackendInstance"))) { - return "CHAINING_BACKEND_INSTANCE"; - } - if (isObjectclass($entry,"nsDS5Replica")) { - return "NSDS5_REPLICA"; - } - if (isObjectclass($entry,"nsDS5ReplicationAgreement")) { - return "NSDS_REPLICATION_AGREEMENT"; - } - if ($DN =~ /^cn=changelog5,cn=config$/i) { - return "CHANGELOG5"; - } - if (($DN =~ /cn=replication,cn=config$/i) && ($DN !~ /^cn=replication,cn=config$/i)) { - return "REPLICATION"; - } - if ($DN =~ /cn=encryption,cn=config$/i) { - return "SECURITY"; - } - if ($DN =~ /^cn=SNMP,cn=config$/i) { - return "SNMP"; - } - return "NOT_MIGRATED_TYPE"; -} - -############################################################################# - - - -############################################################################# -# returns 1 if the objectclass given in parameter is present in the objectclasses values of the entry -# given in parameter, 0 else - -sub isObjectclass { - my $entry = shift; - my $objectclass = shift; - return ($entry->hasValue("objectclass",$objectclass,1)); -} - -############################################################################# - -sub isStdPlugin { - my $entry = shift; - my $CN = $entry->{cn}[0]; - if (isObjectclass($entry,"nsSlapdPlugin")) { - return 1 if ($stdPlugins{lc($CN)}); - } - return 0; -} - - -############################################################################# - -sub alreadyExistsInNew{ - my $entry = shift; - my $mustExist = shift; - my $DN = $entry->getDN(1); # 1 to normalize the DN - # We have a name change of "uid uniqueness" plugin in DS6.x - # to "attribute uniqueness" - $DN =~ s/uid\ uniqueness/attribute\ uniqueness/ if ($DN =~ /uid\ uniqueness/); - return searchEntry($DN, $mustExist); -} - -############################################################################# -sub searchEntry { - my $DN = shift; - my $mustExist = shift; - my $res = $conn->search($DN, "base", "objectclass=*"); - my $cpt = 5; - if ($res) { - return $res; - } - else { - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && cpt && (! $res)) { - printMsg("\ntry to reconnect to search $DN"); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $res = $conn->search($DN, "base", "objectclass=*"); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - if ($res){ - return $res ; - } - elsif (($errorCode eq $LDAP_SERVER_UNREACHABLE) || ($mustExist)) { - my $msg = $conn->getErrorString(); - printMsg("\n\n*** Failed to search: $DN"); - printMsg("\n*** Error Msg: $msg, Error code: $errorCode"); - } - return 0; - } -} - - -############################################################################# - -sub addEntryToNew{ - my $entry = shift; - my $typeOfEntry = shift; - my $trace = shift; - my $res = $conn->add($entry); - my $DN = $entry->getDN(1); - my $cpt = 5; - if ($res) { - printTrace("\n$typeOfEntry - Add successfull: $DN",$trace); - return 1; - } - else { - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && cpt && (! $res)) { - printMsg("\ntry to reconnect to add $DN"); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $res = $conn->add($entry); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - if ($res){ - printTrace("\n$typeOfEntry - Add successfull: $DN",$trace); - return 1; - } - else { - my $msg = $conn->getErrorString(); - printMsg("\n\n*** $typeOfEntry: Add Failed: $DN"); - printMsg("\n*** Error Msg: $msg, Error code: $errorCode"); - return 0; - } - } -} - -############################################################################# - -sub updateEntry{ - my $entry = shift; - my $typeOfEntry = shift; - my $CHECK = shift; - my $trace = shift; - my $cpt = 5; - if ($CHECK) { - if (! hasChanged($entry, $typeOfEntry)) { - return 1; - } - } - my $res = $conn->update($entry); - my $DN = $entry->getDN(1); - if ($res) { - printTrace("\n$typeOfEntry - Update successfull: $DN",$trace); - return 1 ; - } - else { - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && cpt && (! $res)) { - printMsg("\ntry to reconnect to update $DN"); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $res = $conn->update($entry); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - if ($res){ - printTrace("\n$typeOfEntry - Update successfull: $DN",$trace); - return 1; - } - else { - my $msg = $conn->getErrorString(); - printMsg("\n\n*** $typeOfEntry - Update Failed: $DN"); - printMsg("\n*** Error Msg: $msg, Error code: $errorCode"); - return 0; - } - } -} - - -############################################################################# -# returns 1 if the entry to migrate and the current entry are different one another - -sub hasChanged { - my $entry = shift; - my $typeOfEntry = shift; - my $DN = $entry->getDN(1); - my $newEntry = searchEntry($DN,1); - return 1 if (! $newEntry); # we shoudn't be in that case ... - # do the stuff to check wether the entry has changed or not given its type - if (($typeOfEntry eq "DEFAULT_INDEX") || ($typeOfEntry eq "INDEX")){ - my @indexTypes = $entry->getValues("nsIndexType"); - my @newIndexTypes = $newEntry->getValues("nsIndexType"); - my @nsmatchingrules = $entry->getValues("nsmatchingrule"); - my @newMatchingRules = $newEntry->getValues("nsmatchingrule"); - return 1 if (Diffs(\@indexTypes, \@newIndexTypes)); - return 1 if (Diffs(\@nsmatchingrules,\@newMatchingRules)); - return 0; - } - if ($typeOfEntry eq "CHANGELOG5"){ - printTrace("\nCheck wether changelog has changed or not",3); - my @params = keys(%changelog5params); - foreach $param (@params){ - my @values = $entry->getValues($param); - my @newValues = $newEntry->getValues($param); - return 1 if (Diffs(\@values,\@newValues)); - } - return 0; - } - if ($typeOfEntry eq "SNMP"){ - foreach $param (@SNMPparams){ - my @values = $entry->getValues($param); - my @newValues = $newEntry->getValues($param); - return 1 if (Diffs(\@values,\@newValues)); - } - return 0; - } - # we don't know how to compare such type of entry => just return 1 - return 1 ; -} - -sub isAsystemIndex { - my $index = shift; - return ($index->hasValue("nsSystemIndex","true",1)); -} - - -sub updatePathInPluginArgs { - my $plugin = shift; - my $argNum = 0; - my $argPrefix = "nsslapd-pluginarg"; - my $cont = 1; - my $Unix_oldDir = ${oldDir} ; - my $Unix_root = ${root} ; - grep { s@\\@/@g } $Unix_oldDir if $isNT; - grep { s@\\@/@g } $Unix_root if $isNT; - while ($cont) { - my $arg = $argPrefix . $argNum ; - if ($plugin->exists($arg)) { - $_ = $plugin->{$arg}[0] ; - s@$Unix_oldDir@$Unix_root@ig ; - s/$type-$oldname/$type-$newname/ig ; - $plugin->setValues($arg, $_) ; - } - else { - $cont = 0 ; - } - $argNum++; - } - return $plugin; -} - - -sub Diffs { - my $valuesToMigrate = shift; - my $currentValues = shift; - return 1 if (getDiff(\@{$valuesToMigrate},\@{$currentValues})); - return 1 if (getDiff(\@{$currentValues},\@{$valuesToMigrate})); - return 0 ; -} - -sub getDiff { - # we get references to arrays - my $elements = shift ; - my $existing_elements = shift ; - my %count = () ; - my %countEE = () ; - @diff = () ; - foreach $e (@{$elements}, @{$existing_elements}) { $count{$e}++ ;} - foreach $e (@{existing_elements}) { $countEE{$e}++ ;} - foreach $e (@{$elements}) { - # if $e is only present in @$elements, we push it to the diff array - if (($count{$e} == 1) && ($countEE{$e} == 0)) { - push @diff, $e ; - } - } - return @diff ; -} - -sub registerSuffix_Backend { - my $ldbmDatabase = shift; - my $CN = $ldbmDatabase->{cn}[0]; - my $suffixArg = "nsslapd-suffix"; - my $suffix = $ldbmDatabase->{$suffixArg}[0]; - $oldBackends{$suffix} = $CN; -} - - -############################################################################# -# # -# # -# # -############################################################################# -sub migrateLDBM_backend_instances { - foreach $entry (@LDBM_backend_instances) { - my $DN = $entry->getDN(1); # 1 is to normalize the DN - my $CN = $entry->{cn}[0]; - my $expLdif; - my $confirm = "No"; - my $dest = "$serverHome${PATHSEP}db_backup" ; - my $newSlapdExecDir = "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - - if ($DN =~/cn=netscaperoot,cn=ldbm database/i){ - printTrace("\n\n*** INFORMATION - NetscapeRoot is NOT migrated",0); - } - else { - if(alreadyExistsInNew($entry)){ - printMsg("\n\n*** LDBM_BACKEND_INSTANCE - $DN already exists"); - printMsg("\n*** Migration will overwrite existing database"); - printMsg("\nDo you want to continue Yes/No [No] ?") ; - my $answer = <STDIN> ; - if ($answer =~ /y|yes/i) { - printMsg("Do you want to export the existing data Yes/No [Yes] ?"); - my $answer = <STDIN> ; - if (!($answer =~ /n|no/i)) { - mkdir $dest, 0700 unless (-d $dest); - $expLdif = "$dest${PATHSEP}$CN.ldif"; - while (!($confirm =~ /y|yes/i)) { - printMsg("\nEnter the full pathname of the file [$expLdif]:") ; - $answer = <STDIN> ; - chomp($expLdif = $answer) unless ($answer eq "\n"); - printMsg("\nExisting data will be exported under $expLdif"); - printMsg("\nContinue Yes/No [No] ?"); - $confirm = <STDIN>; - } - $ENV{"$LIB_PATH"}=$new_libpath; - chdir($newSlapdExecDir) or die "\nCould not change directory to $newSlapdExecDir: $!\n"; - printTrace("\nNow backing up database $CN in $expLdif\n",0); - &stopServer($root,'slapd-'.$newname); - &db2Ldif($expLdif, $CN, $serverHome); - &startServer() unless (isDirectoryAlive()); - } - push @BACKENDS, $CN; - } else { - printMsg("\n*** Migration will not update it"); - break; - } - } else { - printTrace("\nWe should add the backend instance $DN",3); - my $suffixarg = "nsslapd-suffix" ; - my $suffixname= $entry->{$suffixarg}[0] ; - my $newEntry = $conn->newEntry() ; - $newEntry->setDN($DN); - $newEntry->setValues("objectclass", "top", "extensibleObject", "nsBackendInstance" ); - $newEntry->setValues("cn", $CN ); - $newEntry->setValues($suffixarg, $suffixname); - my @params = keys(%LDBMparamToMigrate); - foreach $param (@params) { - my @values = $entry->getValues($param); - $newEntry->setValues($param, @values) if (@values); - } - if (addEntryToNew($newEntry, "LDBM_BACKEND_INSTANCE",1)) { - push @BACKENDS, $CN; - } - } - } - } -} - -sub parseLDBM_backend_instance { - my $entry = shift; - ®isterSuffix_Backend($entry); - push @LDBM_backend_instances, $entry; -} - -############################################################################# -sub migrateMappingTree { - foreach $entry (@Mapping_tree_entries) { - my $DN = $entry->getDN(1); # 1 si to normalize the DN - if ($DN =~/cn=\"o=netscaperoot\",cn=mapping tree,cn=config/i){ - # DO NOTHING - } - else { - if(alreadyExistsInNew($entry)){ - printMsg("\n\n*** MAPPING_TREE - $DN already exists"); - printMsg("\n*** Migration will not add the suffix"); - } - else { - addEntryToNew($entry, "MAPPING_TREE",1); - } - } - } -} - - -sub parseMapping_tree{ - my $entry = shift; - push @Mapping_tree_entries, $entry; -} - -############################################################################# -sub migrateDefaultIndexes { - foreach $index (@default_indexes) { - my $CN = $index->{cn}[0]; - my $newIndex ; - if ((! isAsystemIndex($index)) && (! $deniedIndexes{lc($CN)})) { - if ($newIndex = alreadyExistsInNew($index)) { - if (! isAsystemIndex($newIndex)) { - updateEntry($index, "DEFAULT_INDEX", 1, 2); - } - } - else { - addEntryToNew($index, "DEFAULT_INDEX", 2); - } - } - } -} - - -sub parseDefaultIndex{ - my $index = shift; - push @default_indexes, $index; -} - -############################################################################# - -sub migrateIndexes { - foreach $index (@indexes) { - my $CN = $index->{cn}[0]; - my $newIndex; - if ((! isAsystemIndex($index)) && (! $deniedIndexes{lc($CN)}) && (DN !~ /cn=netscaperoot,cn=index/i)){ - if ($newIndex = alreadyExistsInNew($index)) { - if (! isAsystemIndex($newIndex)) { - updateEntry($index, "INDEX", 1, 2); - } - } - else { - addEntryToNew($index, "INDEX", 2); - } - } - } -} - -sub parseIndex{ - my $index = shift; - push @indexes, $index; -} - -############################################################################# - -sub newLDIFplugin { - my $currentPlugin = shift; - my $DN = $currentPlugin->getDN(1); - my $newPlugin = $conn->newEntry() ; - $newPlugin->setDN($DN); - foreach $Attr (@pluginAttrs) { - my @values = $currentPlugin->getValues($Attr); - $newPlugin->setValues($Attr, @values) if (@values); - } - return $newPlugin; -} - -sub migrateStdPlugin{ - my $plugin = shift; - my $DN = $plugin->getDN(1); - my $pluginEnable = "nsslapd-pluginEnabled"; - my $argNum = 0; - my $argPrefix = "nsslapd-pluginarg"; - my $currentPlugin ; - if ($currentPlugin = alreadyExistsInNew($plugin, 1)) { - $plugin = updatePathInPluginArgs($plugin); - my $pluginEnableValue = $plugin->{$pluginEnable}[0]; - my $cont = 1; - my $pluginHasChanged = 0; - my $newPlugin = &newLDIFplugin($currentPlugin); - if (! $currentPlugin->hasValue($pluginEnable,$pluginEnableValue,1)){ - $newPlugin->setValues($pluginEnable, $pluginEnableValue); - $pluginHasChanged = 1 unless ($pluginHasChanged); - } - while($cont){ - my $arg = $argPrefix . $argNum ; - if ($plugin->exists($arg)) { - my @values = $plugin->getValues($arg); - my $value = $values[0] ; - $newPlugin->setValues($arg, $value) if (@values); - if ($currentPlugin->exists($arg)) { - if (! $currentPlugin->hasValue($arg,$value,1)) { - $pluginHasChanged = 1 unless ($pluginHasChanged); - } - } - else { - $pluginHasChanged = 1 unless ($pluginHasChanged); - } - } - else { - if ($currentPlugin->exists($arg)) { - # Just Warn the user. Do nothing. - printTrace("\nCompared to the old instance, the current new plugin $DN belongs this attribute: $arg",2); - } - else { - $cont = 0 ; - } - } - $argNum++; - } - updateEntry($newPlugin, "STANDARD_PLUGIN", 0, 1) if ($pluginHasChanged); - } -} - -############################################################################# - -sub migrateConfig_Node{ - my $config_node = shift; - my @params = keys(%GeneralSrvParamToMigrate); - my $hasChanged = 0; - my $newConfigNode; - if ($newConfigNode = alreadyExistsInNew($config_node, 1)){ - foreach $param (@params) { - if ($config_node->exists($param)){ - my @valuesToMigrate = $config_node->getValues($param); - if (@valuesToMigrate){ - if ($newConfigNode->exists($param)){ - my @currentValues = $newConfigNode->getValues($param); - if (Diffs(\@valuesToMigrate, \@currentValues)) { - $newConfigNode->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - printTrace("\nParam to update: $param with value @valuesToMigrate",3); - } - } - else { - $newConfigNode->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - printTrace("\nParam to update: $param with value @valuesToMigrate",3); - } - } - } - } - updateEntry($newConfigNode, "CONFIG_NODE", 0, 1) if ($hasChanged); - } -} - -############################################################################# - -sub migrateConfig_LDBM_database{ - my $config_ldbm = shift; - my @params = keys(%GlobalConfigLDBMparamToMigrate); - my $hasChanged = 0; - my $newConfigLdbm ; - if ($newConfigLdbm = alreadyExistsInNew($config_ldbm, 1)) { - foreach $param (@params) { - if ($config_ldbm->exists($param)){ - my @valuesToMigrate = $config_ldbm->getValues($param); - if (@valuesToMigrate){ - if ($newConfigLdbm->exists($param)){ - my @currentValues = $newConfigLdbm->getValues($param); - if (Diffs(\@valuesToMigrate, \@currentValues)) { - $newConfigLdbm->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - else { - $newConfigLdbm->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - } - } - updateEntry($newConfigLdbm, "CONFIG_LDBM_DATABASE", 0, 1) if ($hasChanged); - } -} - -############################################################################# - -sub migrateChainingBE_config{ - my $chaining_config = shift; - my $DN = $chaining_config->getDN(1); - my @params = (); - my $hasChanged = 0; - my $newChainingConfig; - if ($DN =~ /^cn=config,cn=chaining database,cn=plugins,cn=config$/i){ - $newChainingConfig = searchEntry("cn=config,cn=chaining database,cn=plugins,cn=config"); - @params = keys(%ChainingConfigParams); - } - if ($DN =~ /^cn=default instance config,cn=chaining database,cn=plugins,cn=config$/i){ - $newChainingConfig = searchEntry("cn=default instance config,cn=chaining database,cn=plugins,cn=config"); - @params = keys(%ChainingDefaultInstanceConfigParams); - } - foreach $param (@params) { - if ($chaining_config->exists($param)){ - my @valuesToMigrate = $chaining_config->getValues($param); - if (@valuesToMigrate){ - printTrace("\nParam: $param values To migrate: @valuesToMigrate",3); - if ($newChainingConfig->exists($param)){ - my @currentValues = $newChainingConfig->getValues($param); - printTrace("\nParam: $param new current values: @currentValues",3); - if (Diffs(\@valuesToMigrate, \@currentValues)) { - $newChainingConfig->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - else { - $newChainingConfig->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - } - } - updateEntry($newChainingConfig, "CHAINING_BACKEND_CONFIG", 0, 1) if ($hasChanged); -} - -############################################################################# - -sub registerSuffix_ChainingBE { - my $ldbmDatabase = shift; - my $CN = $ldbmDatabase->{cn}[0]; - my $suffixArg = "nsslapd-suffix"; - my $suffix = $ldbmDatabase->{$suffixArg}[0]; - $oldChainingBackends{$suffix} = $CN; -} - -sub storeMultiplexorBindDN { - my $chaining_instance = shift; - my $DN = $chaining_instance->getDN(1); - if ($chaining_instance->exists("nsMultiplexorBindDN")){ - my $bindDN = $chaining_instance->{nsMultiplexorBindDN}[0]; - my $newBindDN = searchEntry($bindDN); - if (! $newBindDN){ - # the bindDN entry doesn't yet exist in new => it will have to be migrated - $MultiplexorBindDNEntriesToMigrate{$bindDN}="\n" ; - printTrace("\nThe bindDN: $bindDN need to be migrated",3); - } - else { - # do nothing as the entry already exists in new - } - } - -} - -sub importMultiplexorBindDNEntries { - # import all entries present in @MultiplexorBindDNEntriesToMigrate in new - my @MultiplexorBindDNs = keys (%MultiplexorBindDNEntriesToMigrate); - my $ldif_dir = $ldif_rep; - foreach $bindDN (@MultiplexorBindDNs) { - printTrace("\nimportMultiplexorBindDNEntries: bindDN to migrate: $bindDN",3); - # get the backend in which is stored the bind DN entry - my $backendtoExportFrom = getBackendtoExportFrom($bindDN); - printTrace("\nbackendtoExportFrom is: $backendtoExportFrom",3); - # check wether the backend has been imported in new or not - if (! alreadyMigrated($backendtoExportFrom)) { - if ($backendtoExportFrom ne $NULL) { - # if not imported => we need to import the binf DN entry - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - &ExportAndAddEntry($bindDN, $backendtoExportFrom, $ldif_dir); - } - else { - # do nothing - } - } - } - # remove the empty ldif directory - rmdir($ldif_dir) if (-d $ldif_dir); - # close the LDAP connection to new - $conn->close if ($conn); -} - -sub migrateChainingBE_instance{ - my $chaining_instance = shift; - my $DN = $chaining_instance->getDN(1); - ®isterSuffix_ChainingBE($chaining_instance); - if (alreadyExistsInNew($chaining_instance)) { - # already exists - printMsg("\n\n*** CHAINING_BACKEND_INSTANCE - $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - &migrate_credential($chaining_instance, "nsmultiplexorcredentials"); - addEntryToNew($chaining_instance, "CHAINING_BACKEND_INSTANCE", 1); - storeMultiplexorBindDN($chaining_instance); - } -} - -############################################################################# - -# create a new LDIF representation of a new replica consumer -sub newLDIFreplica { - my $replica = shift; - my $DN = $replica->getDN(1); - my $newReplica = $conn->newEntry() ; - my $MASTER_OR_MULTIMASTER = "3" ; - $newReplica->setDN($DN); - foreach $Attr (@nsds5replicaAttrs) { - my @values = $replica->getValues($Attr); - $newReplica->setValues($Attr, @values) if (@values); - } - my $replicaType = $replica->{nsDS5ReplicaType}[0]; - if ($replicaType eq $MASTER_OR_MULTIMASTER) { - my @nsState = $replica->getValues("nsState"); - $newReplica->setValues("nsState", @nsState); - } - else { - $newReplica->setValues("nsDS5ReplicaId", $replicaIdvalue); - } - return $newReplica; -} - -sub MigrateNSDS5_replica{ - foreach $replica (@new6replicas) { - my $DN = $replica->getDN(1); - my $newReplica; - my @removeAttrs = qw(nsstate nsds5replicaname nsds5replicachangecount); - for (@removeAttrs) { - $replica->remove($_); - } - if (alreadyExistsInNew($replica)) { - # replica already exists - printMsg("\n\n*** NSDS5_REPLICA - $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - $newReplica = &newLDIFreplica($replica); - addEntryToNew($newReplica, "NSDS5_REPLICA", 1); - } - storeReplicaBindDN($replica); - } -} - -sub parseNSDS5_replica{ - my $replica = shift; - push @new6replicas, $replica; -} - -sub storeReplicaBindDN { - my $replica = shift; - my $DN = $replica->getDN(1); - if ($replica->exists("nsDS5ReplicaBindDN")){ - my $bindDN = $replica->{nsDS5ReplicaBindDN}[0]; - my $newBindDN = searchEntry($bindDN); - if (! $newBindDN){ - # the bindDN entry doesn't yet exist in new => it will have to be migrated - $ReplicaBindDNEntriesToMigrate{$bindDN}="\n" ; - printTrace("\nThe bindDN: $bindDN need to be migrated",3); - } - else { - # do nothing as the entry already exists in new - } - } -} - - -sub importReplicaBindDNEntries { - # import all entries present in @ReplicaBindDNEntriesToMigrate in new - my @ReplicaBindDNs = keys (%ReplicaBindDNEntriesToMigrate); - my $ldif_dir = $ldif_rep; - my $replBind_entry = ""; - my @bindDN_elements = ""; - my $bindDN_parent = ""; - my $parentBind_entry = ""; - foreach $bindDN (@ReplicaBindDNs) { - printTrace("\nimportReplicaBindDNEntries: bindDN to migrate: $bindDN",3); - # get the backend in which is stored the bind DN entry - my $backendtoExportFrom = getBackendtoExportFrom($bindDN); - printTrace("\nbackendtoExportFrom is: $backendtoExportFrom",3); - # If backend is from config, read the entry from dse.ldif and add to new - NGK - if ($backendtoExportFrom eq "cn=config") { - my $norm_bindDN = normalizeDN($bindDN); - @bindDN_elements = ldap_explode_dn($norm_bindDN, 0); -# @bindDN_elements = split(/,/,$norm_bindDN); - my $junk = shift(@bindDN_elements); - if ($#bindDN_elements >= 1) { - $bindDN_parent = normalizeDN(join(",", @bindDN_elements)); - } - printTrace("\nOpening DSE.ldif",3); - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF); - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN(1); - if ($DN eq $norm_bindDN) { - $replBind_entry = $entry; - } - if ($bindDN_parent ne "") { - if ($DN eq $bindDN_parent) { - $parentBind_entry = $entry; - } - } - } - close(DSELDIF); - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - if ($bindDN_parent ne "") { - addEntryToNew($parentBind_entry, BINDDN_PARENT, 0); - } - printTrace("\nAdding BindDN with addEntryToNew",3); - addEntryToNew($replBind_entry, BINDDN, 0); - } else { - # check wether the backend has been imported in new or not - if (! alreadyMigrated($backendtoExportFrom)) { - if ($backendtoExportFrom ne $NULL) { - # if not imported => we need to import the bind DN entry - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - &ExportAndAddEntry($bindDN, $backendtoExportFrom, $ldif_dir); - } - else { - # do nothing - } - } - } - } - # remove the empty ldif directory - rmdir($ldif_dir) if (-d $ldif_dir); - # close the LDAP connection to new - $conn->close if ($conn); -} - -sub alreadyMigrated { - my $backendToCheck = shift; - foreach $backend (@BACKENDS) { - return 1 if ($backend eq $backendToCheck); - } - return 0 ; -} - -sub belongsSuffix { - my $suffix = shift; - my $bindDN = shift; - return ($bindDN =~ /$suffix\s*$/i); -} - -sub length { - my $suffix = shift; - my $count = 0; - while ($suffix =~ /./g) { - $count++; - } - return $count ; -} - -sub getBackendtoExportFrom { - my $bindDN = shift ; - my $sizeOfSuffix = 0 ; - my $NULL = ""; - my @oldSuffixes = keys(%oldBackends); - my @oldChainingSuffixes = keys(%oldChainingBackends); - my $bindDN_backend = $NULL; - my $config = "cn=config"; - - my $norm_bindDN = normalizeDN($bindDN); - # Check if bindDN exists in cn=config - NGK - if (belongsSuffix($config,$norm_bindDN)) { - $bindDN_backend = $config; - printTrace("\ngetBackendtoExportFrom: bindDN_backend: $bindDN_backend",3); - } else { - foreach $suffix (@oldSuffixes){ - printTrace("\ngetBackendtoExportFrom: suffix to compare with is: $suffix",3); - if ((belongsSuffix($suffix,$norm_bindDN)) && (length($suffix) > $sizeOfSuffix)) { - $sizeOfSuffix = length($suffix); - $bindDN_backend = $oldBackends{$suffix}; - printTrace("\ngetBackendtoExportFrom: bindDN_backend: $bindDN_backend, sizeOfSuffix: $sizeOfSuffix",3); - } - } - foreach $suffix (@oldChainingSuffixes){ - printTrace("\ngetBackendtoExportFrom: suffix to compare with is a chained suffix: $suffix",3); - if ((belongsSuffix($suffix,$norm_bindDN)) && (length($suffix) > $sizeOfSuffix)) { - printMsg("\n\n*** Entry stored on a remote backend - $norm_bindDN"); - printMsg("\n*** We don't migrate it"); - return $NULL; - } - } - } - return $bindDN_backend; -} - - -sub getBackendtoImportTo { - my $bindDN = shift; - my $sizeOfSuffix = 0; - my $NULL = ""; - my $suffixArg = "nsslapd-suffix"; - my $bindDN_backend = $NULL; - open( DSELDIF, "< $DSEldif" ) || die "Can't open $DSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - if ($typeOfEntry eq "LDBM_BACKEND_INSTANCE"){ - my $suffix = $entry->{$suffixArg}[0]; - if ((belongsSuffix($suffix,$bindDN)) && (length($suffix) > $sizeOfSuffix)) { - $sizeOfSuffix = length($suffix); - $bindDN_backend = $entry->{cn}[0]; - } - } - } - close(DSELDIF); - return $bindDN_backend ; -} - - -sub ExportAndAddEntry { - my $DN = shift; - my $backendtoExportFrom = shift; - my $ldif_dir = shift; - my $ldif = "$ldif_dir${PATHSEP}$backendtoExportFrom.ldif" ; - # first: export entry pointed out by the $DN to $ldif file - $ENV{"$LIB_PATH"}=$old_libpath; - if (! $ldif_dir) { $ldif_dir = $ldif_rep ;} - if (!(-d $ldif_dir)) { - mkdir($ldif_dir,0777) or die "\ncan't create $ldif_dir to store temporary ldif files\n"; - } - chdir($oldSlapdExecDir) or die "\nCould not change directory to $oldSlapdExecDir: $!\n"; - &db2Ldif($ldif, $backendtoExportFrom, $oldHome, $DN); - chdir($curdir) or die "\nCould not change directory to $curdir: $!\n"; - - # then: Add it to new - if (! $conn) { - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - } - open( BINDDNLDIF, "< $ldif" ) || die "\nCan't open $ldif: $!: \n"; - my $in = new Mozilla::LDAP::LDIF(*BINDDNLDIF) ; - while ($entry = readOneEntry $in) { - my $entryDN = $entry->getDN(1); - if ($DN eq $entryDN) { - addEntryToNew($entry, "nsds5ReplicaBindDN", 0); - } - } - close(BINDDNLDIF); - # remove the ldif file after the import - unlink($ldif) ; -} - -############################################################################# -sub MigrateNSDS_replication_agreement { - foreach $replicationAgreement (@replicationAgreements) { - my $DN = $replicationAgreement->getDN(1); - if (alreadyExistsInNew($replicationAgreement)){ - # replication agreement already exists - printMsg("\n\n*** NSDS_REPLICATION_AGREEMENT - $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - &migrate_credential($replicationAgreement, "nsDS5ReplicaCredentials"); - addEntryToNew($replicationAgreement, "NSDS_REPLICATION_AGREEMENT", 1); - } - } -} - - -sub parseNSDS_replication_agreement{ - my $replicationAgreement = shift; - push @replicationAgreements, $replicationAgreement ; -} - -############################################################################# - -sub migrateChangelog5{ - my $changelog = shift; - my $DN = $changelog->getDN(1); - my $changelogdir = "nsslapd-changelogdir"; - if (alreadyExistsInNew($changelog)){ - # cn=changelog5,cn=config already exists in new - my $newChangelog = searchEntry($DN); - my @newChangelogdir = $newChangelog->getValues($changelogdir); - $changelog->setValues($changelogdir, @newChangelogdir); - updateEntry($changelog, "CHANGELOG5", 0, 1); - } - else { - # cn=changelog5,cn=config need to be created in new. - # the changelogdir value must be setup to <new_root_server>/slapd-instance/changelogdb - $changelog->setValues($changelogdir,"${serverHome}${PATHSEP}changelogdb"); - addEntryToNew($changelog, "CHANGELOG5", 1); - } -} - - -sub migrateChangelog { - my $oldchangelogdir = ""; - my $newchangelogdir = ""; - my $changelogdir = "nsslapd-changelogdir"; - my $CL5DN = "cn=changelog5,cn=config"; - printTrace("\n\n***** Migrate Changelog...",0,1); - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF); - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - if ($typeOfEntry eq "CHANGELOG5"){ - $oldchangelogdir = ($entry->getValues($changelogdir))[0]; - } - } - close(DSELDIF); - if ($oldchangelogdir) { - # If using olddatadir to migrate from, the path of the changelogdb - # from the dse.ldif may not match the path where the old server - # root was archived. We may need to modify oldchangelogdir so the - # copy of the changelog files succeeds. - unless(-e $oldchangelogdir) { - if($olddatadir) { - my @cldbpath = split(/\//,$oldchangelogdir); - until($cldbpath[0] =~/^slapd-/) { - shift(@cldbpath); - } - my $tmpcldbpath = join(${PATHSEP}, @cldbpath); - $oldchangelogdir = "$oldDir${PATHSEP}$tmpcldbpath"; - } - # If oldchangelogdir still looks to be wrong, prompt for the - # location instead of just failing on the copydir operation - # and bombing out of the migration. - unless(-e $oldchangelogdir) { - print("\n\nThe old changelog directory \"$oldchangelogdir\" doesn't exist. Please enter the correct path: "); - $oldchangelogdir = <STDIN>; - } - } - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - my $newChangelog = searchEntry($CL5DN); - $newchangelogdir = ($newChangelog->getValues($changelogdir))[0]; - stopServer($root,'slapd-'.$newname); - printTrace("\ncopying $oldchangelogdir${PATHSEP}* to $newchangelogdir",3); - copyDir("$oldchangelogdir","$newchangelogdir"); - - # We need to modify the DBVERSION file for a new verision of the db - open(DBVERSION,">$newchangelogdir${PATHSEP}DBVERSION") || die "Can't overwrite $newchangelogdir${PATHSEP}DBVERSION: $! "; - print DBVERSION "Changelog5/NSMMReplicationPlugin/3.0"; - close(DBVERSION); - - &startServer() unless (isDirectoryAlive()); - } -} - -############################################################################# - -sub migrateReplication{ - my $replication = shift; - my $DN = $replication->getDN(1); - if (alreadyExistsInNew($replication)){ - # replication agreement already exists - printMsg("\n\n*** $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - addEntryToNew($replication, "REPLICATION", 1); - } -} - -############################################################################# - -sub migrateSecurity{ - my $security = shift; - if ($entry->hasValue("objectClass", "nsEncryptionConfig")) { - my $certfile = "alias/slapd-" . $newname . "-cert8.db"; - my $keyfile = "alias/slapd-" . $newname. "-key3.db"; - $entry->setValues("nsCertfile",$certfile) if ! $entry->hasValue("nsCertfile",$certfile); - $entry->setValues("nsKeyfile",$keyfile) if ! $entry->hasValue("nsKeyfile",$keyfile); - } - if (alreadyExistsInNew($security)){ - # already exists in new - updateEntry($security, "SECURITY", 0, 1); - } - else { - addEntryToNew($security, "SECURITY", 1); - } -} - -############################################################################# - -sub migrateSNMP{ - my $snmp = shift; - if (alreadyExistsInNew($snmp)){ - # already exists in new - updateEntry($snmp, "SNMP", 0, 1); - } - else { - addEntryToNew($snmp, "SNMP", 1); - } -} - -############################################################################# -# printMsg print message to the user standard output. - -sub printMsg { - - my $TypeMsg = shift ; - my $Msg = shift ; - my $LineNb = shift ; - if ($LineNb) { - printTrace("Line: $LineNb, $TypeMsg, $Msg"); - } - else { - printTrace("$TypeMsg $Msg"); - } -} - -############################################################################# -# print message error to the user standard output. - -sub printTrace { - - my $Msg = shift ; - my $level = shift ; - my $sep = shift ; - - if ($sep) { - print "\n-------------------------------------------------------------------------"; - print LOGFILE "\n-------------------------------------------------------------------------"; - } - - if ($level <= $TRACELEVEL) { - print($Msg); - print LOGFILE $Msg ; - } -} - -############################################################################# -# this subroutine implements a very stupid version of diff - -sub diff { - my $f1 = shift; - my $f2 = shift; - my $lineToBeginWith = shift; - my $NULL = "" ; - my $diff_f1 = $NULL ; - my $diff_f2 = $NULL ; - my $retval = $NULL ; - my $ret; - open(F1, "$f1") or die "Could not open file $f1"; - open(F2, "$f2") or close(F1), die "Could not open file $f2"; - - while (defined($l1 = <F1>)) { - if ($lineToBeginWith){ - $lineToBeginWith -- ; - next ; - } - next if ($l1 =~ /^\#/); - $ret = defined($l2 = <F2>); - if ($ret) { - $ret = defined($l2 = <F2>) while ($ret && ($l2 =~ /^\#/)) ; - if ($ret) { - if (!($l1 eq $l2)) { - - # ignore whitespace - $l1_clean = $l1 ; - $l2_clean = $l2 ; - $l1_clean =~ s/\s//g; - $l2_clean =~ s/\s//g; - - if (!($l1_clean eq $l2_clean)) { - $diff_f1 .= "${l1}" unless ($l1_clean eq $NULL); - $diff_f2 .= "${l2}" unless ($l2_clean eq $NULL); - } - } - } - else { - next if ($l1 =~ /^\s*$/) ; - $diff_f1 .= "${l1}"; - } - } - else { - next if ($l1 =~ /^\s*$/) ; - $diff_f1 .= "${l1}"; - } - } - - while (defined($l2 = <F2>)) { - if (($l2 =~ /^\#/) || ($l2 =~ /^\s*$/)) { - next ; - } - else { - $diff_f2 .= "${l2}" ; - } - } - - close(F1); - close(F2); - - $retval .= "- differences present in your config file but not in standard file:\n\n". "$diff_f1\n" if ($diff_f1) ; - $retval .= "- differences present in standard file but not in your config file:\n\n" . "$diff_f2" if ($diff_f2) ; - return $retval ; -} - -sub CompareStdConfigFiles { - # Compare each configuration file against its default version. If it has changed, - # notify the user that the file has changed and will need to be checked by the - # user. This should be safe to do because there should be no path information - # stored in these conf files, which are just schema stuff. - # printTrace("\nCheck if standard configuration files have changed",3); - - # get the version of the DS to migrate - ($oldVersion, $oldMinor) = &getVersion($oldDir, $oldversionstr); - # get the version of the new DS - ($Version, $Minor) = &getVersion($root); - - # get old LIB_PATH - $old_libpath = &getLibPath($oldDir, $oldVersion, $oldMinor); - # get new LIB_PATH - $new_libpath = &getLibPath($root, $Version, $Minor); - - my $origFilePath = "$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}install${PATHSEP}schema${PATHSEP}" ; - my $FilesChanged = ""; - my $AllDiffs = "***********************************************************************"; - my $NoChanges = "" ; - my $lineToBegin = 0 ; - opendir(CONFDIR, $oldSchemaDir) or - die "Error: could not open migrated config dir $oldConfDir: $!"; - - foreach $file (readdir(CONFDIR)) { - $origFile = $origFilePath . $file ; - $configFile = $oldSchemaDir . $file ; - if (( exists($stdIncludes{lc($file)})) && (-f $origFile)) { - $diffs = &diff($configFile, $origFile, $lineToBegin); - $lineToBegin = 0 if $lineToBegin ; - if ($diffs) { - $FilesChanged .= "\n$configFile"; - $AllDiffs .= "\n$configFile is different than the standard configuration file" ; - $AllDiffs .= "\nYou will need to check this file and make sure its changes are compatible "; - $AllDiffs .= "with the new directory server\nHere are the differences:\n"; - $AllDiffs .= "$diffs \n\n"; - $AllDiffs .= "***********************************************************************"; - } - else { - $NoChanges .= "\n$configFile"; - } - } - } - closedir(CONFDIR); - -if ($FilesChanged) { - printTrace("\nNo changes to old configuration files:$NoChanges",3) ; - printTrace("\n***********************************************************************",3) ; - printMsg("\nThe following standard files have been modified: $FilesChanged"); - if ($NO_INPUT_USER) { - # do nothing - } - else { - printMsg("\nDo you want to see the differences Yes/No [No] ?") ; - my $answer = <STDIN> ; - if ($answer =~ /y|yes/i) { - printMsg("$AllDiffs"); - } - printMsg("\nDo you want to continue the migration Yes/No [No] ?"); - $answer = <STDIN> ; - if (! ($answer =~ /y|yes/i)) { - exit(1); - } - } - } -} - - - -############################################################################# - -# this is used to run the system() call, capture exit and signal codes, -# and die() upon badness; the first argument is a directory to change -# dir to, if any, and the rest are passed to system() -sub mySystem { - my $rc = &mySystemNoDie(@_); - my ($dir, @args) = @_; - if ($rc == 0) { -# success - } elsif ($rc == 0xff00) { - die "Error executing @args: error code $rc: $!"; - } elsif ($rc > 0x80) { - $rc >>= 8; - die "Error executing @args: error code $rc: $!"; - } else { - if ($rc & 0x80) { - $rc &= ~0x80; - } - die "Error executing @args: received signal $rc: $!"; - } - - # usually won't get return value - return $rc; -} - -# This version does not die but just returns the error code -sub mySystemNoDie { - my ($dir, @args) = @_; - if ($dir && ($dir ne "")) { - chdir($dir) or die "Could not change directory to $dir: $!"; - } - my $cmd = $args[0]; - # the system {$cmd} avoids some NT shell quoting problems if the $cmd - # needs to be quoted e.g. contains spaces; the map puts double quotes - # around the arguments on NT which are stripped by the command - # interpreter cmd.exe; but don't quote things which are already quoted - my @fixargs = map { /^[\"].*[\"]$/ ? $_ : $quote . $_ . $quote } @args; - my $rc = 0; - if ($cmd =~ /[.](bat|cmd)$/) { - # we have to pass batch files directly to the NT command interpreter - $cmd = $com_spec; -# print "system $cmd /c \"@fixargs\"\n"; - $rc = 0xffff & system {$cmd} '/c', "\"@fixargs\""; - } else { -# print "system $cmd @fixargs\n"; - $rc = 0xffff & system {$cmd} @fixargs; - } - chdir(${curdir}) or die "Could not change directory to $curdir: $!"; - return $rc; -} - -########################################################################################### -# # -# Export/Import of the backends in @BACKENDS # -# # -########################################################################################### - -sub manydb2Ldif { - my $ldif_dir = shift; - $ENV{"$LIB_PATH"}=$old_libpath; - if (! $ldif_dir) { $ldif_dir = $ldif_rep ;} - if (!(-d $ldif_dir)) { - mkdir($ldif_dir,0777) or die "can't create $ldif_dir to store temporary ldif files"; - } - chdir($oldSlapdExecDir) or die "Could not change directory to $oldSlapdExecDir: $!"; - foreach $backend (@BACKENDS) { - my $ldif = "${ldif_dir}$backend.ldif" ; - &db2Ldif($ldif, $backend, $oldHome); - } - print " Done.\n"; - chdir($curdir) or die "Could not change directory to $curdir: $!"; -} - -sub db2Ldif { - my $ldif = shift ; - my $backend = shift ; - my $home = shift ; - my $include_suffix = shift ; - my $db2ldif_param ; - if ($include_suffix) { - $db2ldif_param = "db2ldif -r -D $home -n $backend -a $ldif -s \"$include_suffix\""; - } - else { - $db2ldif_param = "db2ldif -r -D $home -n $backend -a $ldif"; - } - open(DB2LDIF, "${quote}${quote}$slapdExecName${quote} $db2ldif_param${quote} 2>&1 |") or die "Could not run ns-slapd program $ldif2db_exe\n"; - sleep(1); # allow some data to accumulate in the pipe - my $ii = 0; - while (<DB2LDIF>) { - ++$ii; - if (($ii % 250) == 0) { - printMsg(" Processing...\n"); - } - printMsg($_); - } - close(DB2LDIF); - # set the ownership of the ldif file; should be the same as the 5.x slapd user id - if ((! $isNt) && ($oldlocaluser ne $localuser)) { - if (-f $ldif) { - chown( $newuid, $newgid, $ldif) or printMsg("\nUnable to change the ownership of $ldif to $localuser") ; - } - } -} - -sub manyLdif2db { - my $ldif_dir = shift; - $ENV{"$LIB_PATH"}=$new_libpath; - chdir($slapdExecDir) or die "Could not change directory to $slapdExecDir: $!"; - foreach $backend (@BACKENDS) { - my $ldif = "${ldif_dir}$backend.ldif" ; - &Ldif2db($ldif, $backend); - } - # remove the empty ldif directory - # but not if using the data dir - if (!$olddatadir) { - rmdir($ldif_dir); - } - chdir($curdir) or die "Could not change directory to $curdir: $!"; -} - - -sub Ldif2db { - my $ldif = shift ; - my $backend = shift ; - my $ldif2db_param = "ldif2db -D $serverHome -n $backend -i $ldif"; - open(LDIF2DB, "${quote}${quote}$slapdExecName${quote} $ldif2db_param${quote} 2>&1 |") or die "Could not run ns-slapd program $ldif2db_exe\n"; - sleep(1); # allow some data to accumulate in the pipe - while (<LDIF2DB>) { - printMsg($_); - } - close(LDIF2DB); - # remove the ldif file after the import - # but not if using the data dir - if (!$olddatadir) { - unlink($ldif) ; - } -} - - -########################################################################################### -# # -# Running/Stopping the Server # -# # -########################################################################################### - - - -sub isDirectoryAlive { - die "\n Migration aborted. Make sure your old and new Directory Servers are installed on the same machine \n" if ( $LDAPservername == -1 ); - my $test_conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd); - if ($test_conn) { - $test_conn->close(); - return 1; - } - else { - return 0 ; - } -} - - -sub startServer { - my $instanceDir = ${serverHome} ; - my $errLog = $instanceDir . $PATHSEP . 'logs' . $PATHSEP . 'errors'; - # emulate tail -f - # if the last line we see does not contain "slapd started", try again - my $done = 0; - my $started = 0; - my $code = 0; - my $lastLine = ""; - my $timeout = time + 240; # 4 minutes - $ENV{"$LIB_PATH"}=$new_libpath; - - my $startCmd = $instanceDir . $PATHSEP . 'start' . $script_suffix; - if (! -f $startCmd) { - $startCmd = $instanceDir . $PATHSEP . 'start-slapd' . $script_suffix; - } - $code = &mySystem($instanceDir,$startCmd); - open(IN, $errLog) or die "Could not open error log $errLog: $!"; - my $pos = tell(IN); - while (($done == 0) && (time < $timeout)) { - for (; ($done == 0) && ($_ = <IN>); $pos = tell(IN)) { - $lastLine = $_; - # print; - # the server has already been started and shutdown once . . . - if (/slapd started\./) { - $started++; - if ($started == 2) { - $done = 1; - } - # sometimes the server will fail to come up; in that case, restart it - } elsif (/Initialization Failed/) { - # print "Server failed to start: $_"; - $code = &mySystem($instanceDir, $startCmd); - # sometimes the server will fail to come up; in that case, restart it - } elsif (/exiting\./) { - # print "Server failed to start: $_"; - #$code = &mySystem($startCmd); - $code = &mySystem($instanceDir, $startCmd); - } - } - if ($lastLine =~ /PR_Bind/) { - # server port conflicts with another one, just report and punt - print $lastLine; - print "This server cannot be started until the other server on this\n"; - print "port is shutdown.\n"; - $done = 1; - } - if ($done == 0) { - # rest a bit, then . . . - sleep(2); - # . . . reset the EOF status of the file desc - seek(IN, $pos, 0); - } - } - close(IN); - - sleep(5); - die "\nUnable to start the $Version.$Minor Directory Server\n" unless (isDirectoryAlive()); - - return 0; -} - -sub stopServer { - my $root = shift; - my $name = shift; - $maxStopIterations = 5; - print "\nShutting down server $name . . .\n"; - $ENV{"$LIB_PATH"}=$new_libpath; - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop' . $script_suffix . $quote; - if (! -f $stopCmd) { - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop-slapd' . $script_suffix . $quote; - } - - if (! -f $stopCmd) { - # no stop command, probably a 1.X system; for NT, we'll try net stop - # for unix, we'll get the pid and kill it - if ($isNT) { - $stopCmd = 'net stop ' . $name; - } else { - # see if there is a pid file - $pidfile = $root . $PATHSEP . $name . $PATHSEP . 'logs' . - $PATHSEP . 'pid'; - if (open(PIDFILE, $pidfile)) { - chomp($pid = <PIDFILE>); - close(PIDFILE); - while ($maxStopIterations-- && !$exitCode) { - $exitCode = kill(15, $pid); - } - $stopCmd = undef; - } - } - } - - # keep looping until the stop cmd returns an error code, which usually - # means that what ever we want to stop is stopped, or some other error - # occurred e.g. permission, or no such service - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - while ($stopCmd && $maxStopIterations-- && $exitCode) { - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - } - - if (!$maxStopIterations) { - print "Warning: could not shutdown the server: $!\n"; - } - sleep(10) ; - $exitCode = 0; -} - - -sub runAndIgnoreOutput { - my $cmd = shift; - printMsg("."); - open(RUNCMD, "${quote}$cmd${quote} 2>&1 |") or die "Error: could not run $cmd: $!"; - printMsg("."); - sleep(1); # allow pipe to fill with data - printMsg("."); - while (<RUNCMD>) { -# print; - } - my $code = close(RUNCMD); -# print "runAndIgnore: code=$code status=$?\n"; - return $?; -} - -############################################################################# -# migrate SSL info - -sub MigrateSSL { - my $secPwd = 'bidon' ; - # copy the SSL directory - ©Dir("$oldHome${PATHSEP}ssl","$serverHome${PATHSEP}ssl") if (-d "$oldHome${PATHSEP}ssl"); - # copy the cert db and key files - if ( -d "$oldDir${PATHSEP}alias") { - $aliasDir = "$root${PATHSEP}alias"; - if (! -d $aliasDir) { - mkdir($aliasDir, 0750); - } - &stopServer($root,'slapd-'.$newname); - my $keydb = "$aliasDir${PATHSEP}slapd-$newname-key3.db" ; - my $certdb = "$aliasDir${PATHSEP}slapd-$newname-cert8.db" ; - my $certdb7 = "$aliasDir${PATHSEP}slapd-$newname-cert7.db" ; - my $old_keydb = "$oldDir${PATHSEP}alias${PATHSEP}slapd-$oldname-key3.db" ; - my $old_certdb = "$oldDir${PATHSEP}alias${PATHSEP}slapd-$oldname-cert7.db"; - my $keydb_backup = "$aliasDir${PATHSEP}slapd-$newname-key3.db_backup" ; - my $certdb_backup = "$aliasDir${PATHSEP}slapd-$newname-cert7.db_backup" ; - if (-f $old_keydb) { - if (-f $keydb) { - if ($NO_INPUT_USER) { - printMsg("\n$keydb already exists. backup in $keydb_backup ..."); - ©BinFile($keydb,$keydb_backup); - ©BinFile($old_keydb,$keydb); - } - else { - print("\n\n$keydb already exists. Do you want to overwrite it ? [no]: "); - my $answer = <STDIN> ; - if ($answer =~ /^y|yes$/i) { - ©BinFile($old_keydb,$keydb); - } - } - } - else { - ©BinFile($old_keydb,$keydb); - } - } - if (-f $old_certdb) { - $mode = (stat($old_certdb))[2] if $PRESERVE; - if (-f $certdb) { - if ($NO_INPUT_USER) { - printMsg("\n$certdb already exists. backup in $certdb_backup ..."); - ©BinFile($certdb,$certdb_backup); - unlink($certdb) || print "Couldn't delete $certdb : $!\n"; - ©BinFile($old_certdb,$certdb7); - } - else { - print("\n\n$certdb already exists. Do you want to overwrite it ? [no]: "); - my $answer = <STDIN> ; - if ($answer =~ /^y|yes$/i) { - unlink($certdb) || print "Couldn't delete $certdb : $!\n"; - ©BinFile($old_certdb,$certdb7); - } - } - } - else { - ©BinFile($old_certdb,$certdb7); - } - } - # copy the old password file - if (-f "$oldDir${PATHSEP}alias${PATHSEP}$type-$oldname-pin.txt") { - ©BinFile( - "$oldDir${PATHSEP}alias${PATHSEP}$type-$oldname-pin.txt", - "$aliasDir${PATHSEP}$type-$newname-pin.txt" - ); - } - &startServer(); - if ($PRESERVE) { - chown($newuid,$newgid,$certdb) || print "Failed to set uid $newuid gid $newgid on $certdb : $!\n"; - chmod($mode,$certdb) || print "Failed to set mode $mode on $certdb : $!\n"; - } - } - -} - -sub DisableSSL { - my $entry = $conn->search("cn=config","base","objectclass=*"); - my $LDAPparam = "nsslapd-security" ; - my $Value = "off" ; - if ($entry->{$LDAPparam}[0] ne $Value) { - printTrace("\nDisable SSL...",1); - $entry->setValues($LDAPparam, $Value); - } - my $res = $conn->update($entry); - if ($res) { - printTrace("\nSSL disabled",2); - } - else { - printMsg("\nCan't disabled SSL. The server may have problems to start"); - } -} - -# enable the migration of client authentication informations -sub MigrateCertmap { - # backup the old certmap.conf and replace it with the new one - my $oldCertmap = "$oldDir${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf"; - my $newCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf" ; - my $backupCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf_backup" ; - if (-f $oldCertmap) { - if ($NO_INPUT_USER) { - printMsg("\n$newCertmap has been backup in $backupCertmap"); - ©BinFile($newCertmap,$backupCertmap); - ©BinFile($oldCertmap,$newCertmap); - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\n\nWhere do you want to back up the file $newCertmap [$backupCertmap] ?") ; - my $Answer = <STDIN> ; - $backupCertmap = $Answer if ($Answer ne "\n"); - chomp($backupCertmap); - printTrace("\nDest: .$backupCertmap.",4); - if (-e $backupCertmap) { - printMsg("\n\n$backupCertmap already exists. Do you want to overwrite it Yes/No [No] ?") ; - if (<STDIN> =~ /yes|y/i) { - $Ask = 0 ; - } - else { - $backupCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf_backup" ; - } - } - else { - $Ask = 0 ; - } - } - printTrace("\nBackup file: $newCertmap in $backupCertmap",4); - ©BinFile($newCertmap,$backupCertmap); - ©BinFile($oldCertmap,$newCertmap); - } - } - else { - } -} - -sub hasChangedoldCertmap { - my $certmapfile = shift ; - my @reference = ("certmap default default", - "default:DNComps", - "default:FilterComps e") ; - my $cpt = 0 ; - printTrace("\nhasChangedoldCertmap",3); - open(CERTMAP,"< $certmapfile"); - while (<CERTMAP>) { - if ((! /^\s*#/) && (! /^\s*$/)) { - my $ref = $reference[$cpt] ; - printTrace("\nValue: $_, ref: $ref",4); - if (! /^\s*$ref\s*$/) { - return 1 ; - } - else { - $cpt++ ; - } - } - } - close (CERTMAP); - printTrace("\ncpt: $cpt",4); - if ($cpt < $#reference) { - return 1 ; - } - else { - return 0 ; - } -} - - -########################################################################################### -# # -# Copy directory and files functions # -# # -########################################################################################### - - -sub copyDir { - my $src = shift; - my $dest = shift; - my $exclude = shift; - - opendir( SRC, $src ) or die "Can't open directory $src: $!: "; - my $mode; - my $uid; - my $gid; - mkdir ( $dest , 0755 ) or die "\nCan't create directory $dest. \nPlease check you have enough rights to create it and/or check that your parent directory exists.\n" if !( -e $dest ); - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - local ( @files ) = readdir ( SRC ); - closedir( SRC ); - for ( @files ) { - if ( $_ eq "." || $_ eq ".." ) { - next; - } elsif ( $exclude && /$exclude/ ) { - next; - } elsif( -d "$src${PATHSEP}$_") { - ©Dir ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_" ); - } else { - ©BinFile ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_"); - } - } -} - -sub copyBinFile { - my $src = shift; - my $dest = shift; - my $buf = ""; - my $bufsize = 8192; - - open( SRC, $src ) || die "Can't open $src: $!\n"; - # if we are given a directory destination instead of a file, extract the - # filename portion of the source to use as the destination filename - if (-d $dest) { - $dest = $dest . $PATHSEP . &basename($src); - } - open( DEST, ">$dest" ) || die "Can't create $dest: $!\n"; - binmode SRC; - binmode DEST; - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - while (read(SRC, $buf, $bufsize)) { - print DEST $buf; - } - close( SRC ); - close( DEST ); -} - -############################################################################################################# -# backup 5.x configuration files # -# backup the directory <root_server5>/slapd-instance/config dans <root_server5>/slapd-instance/BackupConfig # # -# # -############################################################################################################# - - -sub backupConfigFiles { - # backup the 5.x config files - my $src = "$serverHome${PATHSEP}config" ; - my $dest = "$serverHome${PATHSEP}config_backup" ; - if ($NO_INPUT_USER) { - printMsg("\n$src has been backup in $dest"); - ©Dir($src,$dest); - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\n\nWhere do you want to back up your configuration directory [$dest] ?") ; - my $Answer = <STDIN> ; - $dest = $Answer if ($Answer ne "\n"); - chomp($dest); - printTrace("\nDest: .$dest.",4); - if (-e $dest) { - printMsg("\n\n$dest already exists. Do you want to overwrite it Yes/No [No] ?") ; - if (<STDIN> =~ /yes|y/i) { - $Ask = 0 ; - } - else { - $dest = "$serverHome${PATHSEP}config_backup" ; - } - } - else { - $Ask = 0 ; - } - } - printTrace("\nBackup Directory: $src in $dest",4); - ©Dir($src,$dest); - } -} -############################################################################# - -sub getLDAPservername { - my $oldLDAPservername; - my $LDAPservername; - my $localhost = "nsslapd-localhost"; - open(OLDDSELDIF, "< $oldDSEldif") or die "\nError: could not open old config file $oldDSEldif \n"; - my $in = new Mozilla::LDAP::LDIF(*OLDDSELDIF) ; - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN(1) ; - if ($DN =~ /^cn=config$/i) { - my @values = $entry->getValues($localhost); - if ($entry->size($localhost)) { - $oldLDAPservername = $values[0]; - printTrace("\nName of the old LDAP server: $oldLDAPservername",3); - } - break; - } - } - close(OLDSELDIF); - - open( DSELDIF, "< $DSEldif" ) || die "\nCan't open $DSEldif \n"; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN(1) ; - if ($DN =~ /^cn=config$/i) { - my @values = $entry->getValues($localhost); - if ($entry->size($localhost)) { - $LDAPservername = $values[0]; - printTrace("\nName of the new LDAP server: $LDAPservername",3); - } - break; - } - } - close(DSELDIF); - # check ol and new Directory Instance are installed on the same physical machine. - if (lc($oldLDAPservername) ne lc($LDAPservername)) { - # warn the user he tries to migrate a 4.x server installed on a different machine from the 5.x one - printMsg("\n\nYour old instance is on $oldLDAPservername, whereas your new instance is on $LDAPservername. Migration on different machines is not supported. Do you want to continue ? Yes/No [No]:") ; - if (! (<STDIN> =~ /yes|y/i)) { - return -1; - } - } - return $LDAPservername ; -} - -############################################################################# - -sub getLibPath { - my $myDir = shift; - my $myVersion = shift; - my $myMinor = shift; - - if ($isNT) { - return $ENV{"$LIB_PATH"}; - } - if (($myVersion >= 6) && ($myMinor >= 2)) { - return - "$myDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$myDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - } else { - return "$myDir${PATHSEP}lib${SEP}".$ENV{"$LIB_PATH"}; - } -} - -############################################################################# - -sub getVersion { - my $dir = shift; - my $versionstr = shift; - my $version = 0; - my $minor = 0; - my $buildNumber = 0; - my $progDir = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - my $progDir2 = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}"; - - # find the slapd executable - if (!$versionstr) { # version not specified on cmd line - find it - $prog = $dir . $progDir . $slapdExecName; - if (! -f $prog) { - $prog = $dir . $progDir2 . $slapdExecName; - if (-f $prog && $isNT) { - # if slapd is in bin/slapd and we're on NT, just assume version 1; - # apparently, slapd.exe doesn't like the -v argument . . . - return ( '1', $minor ); - } - else{ - die "Could not run slapd program $prog: $!"; - } - } - else { - chdir($dir . $progDir); - } - $cur_libpath=$ENV{"$LIB_PATH"}; - $ENV{"$LIB_PATH"}= - "$dir${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - # read the old version from the old slapd program - - open(F, "${quote}${quote}$prog${quote} -v${quote} 2>&1 |") or - die "Could not run slapd program $prog: $!"; - sleep(1); # allow some data to accumulate in the pipe -# print "Output from $prog -v:\n"; - while (<F>) { - if (/^Netscape-Directory/ || /^iPlanet-Directory/i) { - $versionstr = $_; - last; - } - } - $code = close(F); - # print "$prog returned code=$code status=$?\n"; - $ENV{"$LIB_PATH"}=$cur_libpath; - } - - if ($versionstr =~ /^Netscape-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\(restrict?ed-mode\)\/(\d+)\.(\d+)\s+(\S+)/) { # we can have restricted-mode or restriced-mode ... - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^iPlanet-Directory\/(\d+)\.(\d+)\s+(\S+)/i) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } elsif ($versionstr =~ /(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - } - - if ($version == 0) { - die "\nCould not determine version of the directory server in $dir: \n"; - } - - # distinguish the 4.1 and the 4.11 thanks to the buildNumber - if (($version == 4) && ($minor == 1)){ - if (! ($buildNumber =~ /^B99\.16/)) { - # it's not a 4.1 Netscape Directory Server => it's a 4.11 - $minor = 11 ; - } - } - chdir($curdir) or die "Could not change directory to $curdir: $!" ; - return ( $version, $minor ); -} - -############################################################################################### -sub normalizeDir { - my $dir = shift ; - my $dir_prec = "" ; - while ($dir_prec ne $dir) { - $dir_prec = $dir ; - if ($isNT) { - grep { s@\\\\@\\@g } $dir ; - } - else { - grep { s@//@/@g } $dir ; - } - } - return $dir ; -} - - -############################################################################################### - -sub GetTime { - my $tm = localtime; - (my $sec, my $min, my $hour, my $dd, my $mm, my $yy) = ($tm->sec, $tm->min, $tm->hour, $tm->mday, ($tm->mon)+1, ($tm->year)+1900); - $sec = "0$sec" unless $sec > 9 ; - $min = "0$min" unless $min > 9 ; - $hour = "0$hour" unless $hour > 9 ; - $dd = "0$dd" unless $dd > 9 ; - $mm = "0$mm" unless $mm > 9 ; - return ($sec, $min, $hour, $dd, $mm, $yy); -} - -############################################################################################### -# get uid and group id of the 5.x slapd server. -# The uid is done through the nsslapd-localuser attribute - -sub getuid_gid { - my $newuid ; - my $newgid ; - my $localuser ; - my $localuser_attr = "nsslapd-localuser" ; - if (! $isNT) { - &startServer() unless (isDirectoryAlive()); - my $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Can't contact the $Version.$Minor LDAP server: $LDAPservername\n"; - my $entry = $conn->search("cn=config ", "base","objectclass=*", 0, ($localuser_attr)) ; - # Tests wether we succeed to get the entry cn=config - die "\nCan't get the entry cn=config \n" unless ($entry); - my @values = $entry->getValues($localuser_attr); - $conn->close(); - if ($#values == -1 || ($values[0] eq "") ) { # tests wether the nsslapd-localuser attribute has a value - printMsg("\nNo localuser has been found in the configuration of the directory. "); - if ($NO_INPUT_USER) { - printMsg("\nWe considered nobody as the localuser"); - $localuser = "nobody" ; - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\nUnder what user does your $Version.$Minor directory server run [nobody] ? ") ; - $localuser = <STDIN> ; - chomp($localuser); - $localuser = "nobody" if ($localuser eq ""); - ($newuid, $newgid) = (getpwnam("$localuser"))[2..3] ; - if ($newuid) { - $Ask = 0 ; - } - else { - printMsg("\nError: $localuser is unknown from the system "); - } - } - } - } - else { - $localuser = $values[0]; # returns the first value (we should only have one localuser) - my $size = $#values ; - } - ($newuid, $newgid) = (getpwnam("$localuser"))[2..3] ; - return ($localuser, $newuid, $newgid) ; - } - else { - return () ; - } -} - -sub getolduid_gid { - my $oldlocaluser ; - my $localuserAttr = "nsslapd-localuser"; - my $entry ; - if (! $isNT) { - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - if ($typeOfEntry eq "CONFIG_NODE") { - $oldlocaluser = $entry->{$localuserAttr}[0] if ($entry->exists($localuserAttr)); - break ; - } - } - close(DSE); - ($olduid, $oldgid) = (getpwnam("$oldlocaluser"))[2..3] ; - return ($oldlocaluser, $olduid, $oldgid) ; - } - else { - return (); - } -} -############################################################################################### -# get current directory - -sub getCwd { - my $command = $isNT ? "cd" : "/bin/pwd"; - open(PWDCMD, "$command 2>&1 |") or - die "Error: could not execute $command: $!"; - # without the following sleep, reading from the pipe will - # return nothing; I guess it gives the pwd command time - # to get some data to read . . . - sleep(1); - my $currentdir; - while (<PWDCMD>) { - if (!$currentdir) { - chomp($currentdir = $_); - } - } - my $code = close(PWDCMD); -# if ($code || $?) { -# print "$command returned code=$code status=$? dir=$curdir\n"; -# } -# print "getCwd curdir=\[$curdir\]\n"; - return $currentdir; -} - -################################ -# Need to migrate the credential. -# If the credential can not be migrated, leave it at it is -################################ -sub migrate_credential{ - my $entry_to_modify = shift; - my $credentials_attr = shift; - my @old_value = $entry_to_modify->getValues($credentials_attr); - my $migratecredExecName = 'migratecred'; - my $credOldHome = $oldHome; - my $credServerHome = $serverHome; - - if ($isNT) { - # oldHome may be pointing to the archived copy of the - # instance dir which may be different than the path that - # the instance was originally installed as on Windows. If - # this path is not the original install path, then the - # credential will not be migrated correctly. We should - # prompt the user on Windows for the correct path. - - print "\n\nThe old instance path must be the same as where it was"; - print "\ninitially installed, not where it was archived in order"; - print "\nfor this step to succeed. Please verify that the path"; - print "\nis correct. Note that case sensitivity is important here."; - print "\n\nOld Instance Directory: $credOldHome"; - print "\nIs this correct? (y/n): "; - chomp(my $answer = <STDIN>); - if (!($answer =~ /y|yes/i)) { - print "\nPlease enter the correct path for the old instance directory: "; - chomp($credOldHome = <STDIN>); - } - - print "\n\nThe new instance path must also be correct for this step"; - print "\nto succeed. Please verify that the path is correct. Note"; - print "\nthat case sensitivity is important here."; - print "\n\nNew Instance Directory: $credServerHome"; - print "\nIs this correct? (y/n): "; - chomp(my $answer = <STDIN>); - if (!($answer =~ /y|yes/i)) { - print "\nPlease enter the correct path for the new instance directory: "; - chomp($credServerHome = <STDIN>); - } - } -# print "\nMigratecred command is: ${quote}$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}$migratecredExecName${quote} -o $credOldHome -n $credServerHome -c @old_value\n"; - - my @new_cred = `${quote}$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}$migratecredExecName${quote} -o $credOldHome -n $credServerHome -c @old_value`; - - if ( $? == 0 ) - { - $entry_to_modify->setValues($credentials_attr, @new_cred); - } -} - diff --git a/ldap/admin/src/scripts/template-migrate6to7 b/ldap/admin/src/scripts/template-migrate6to7 deleted file mode 100644 index 284fac9e..00000000 --- a/ldap/admin/src/scripts/template-migrate6to7 +++ /dev/null @@ -1,3127 +0,0 @@ -#{{PERL-EXEC}} -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# enable the use of our bundled perldap with our bundled ldapsdk libraries -# all of this nonsense can be omitted if the mozldapsdk and perldap are -# installed in the operating system locations (e.g. /usr/lib /usr/lib/perl5) -BEGIN { - my $sroot = "{{DS-ROOT}}"; - push @INC, "$sroot/lib/perl/arch", "$sroot/lib/perl"; - if ($ENV{LD_LIBRARY_PATH}) { - $ENV{LD_LIBRARY_PATH} .= ":"; - } - $ENV{LD_LIBRARY_PATH} .= "$sroot/shared/lib"; - # this is only needed for HP/ux PA-RISC, but it doesn't hurt other platforms - if ($ENV{SHLIB_PATH}) { - $ENV{SHLIB_PATH} .= ":"; - } - $ENV{SHLIB_PATH} .= "$sroot/shared/lib"; -} -# Migrate a 6.x directory server to a 7.0 directory server - -####################################################################################################### -# enable the use of Perldap functions -require DynaLoader; - -use Getopt::Std; -use Mozilla::LDAP::Conn; -use Mozilla::LDAP::Entry; -use Mozilla::LDAP::LDIF; -use Mozilla::LDAP::Utils qw(:all); -use Mozilla::LDAP::API qw(:api :ssl :apiv3 :constant); # Direct access to C API -use Time::localtime; -use File::Basename; -use Class::Struct ; - -####################################################################################################### - -sub usage { - print(STDERR "\nUsage: $0 -D rootdn { -w password | -w - | -j filename } -p port \n"); - print(STDERR " -o oldInstancePath -n newInstancePath [-t tracelevel] [-L logfile]\n"); - print(STDERR "************** parameters in brackets are optionals, others are required **************\n"); - print(STDERR " Opts: -D rootdn - new 7.0 Directory Manager\n"); - print(STDERR " : -w password - new 7.0 Directory Manager's password\n"); - print(STDERR " : -w - - Prompt for new 7.0 Directory Manager's password\n"); - print(STDERR " : -j filename - Read new 7.0 Directory Manager's password from file\n"); - print(STDERR " : -p port - new 7.0 Directory Server port\n"); - print(STDERR " : -o oldInstancePath - Path of the old instance to migrate \n"); - print(STDERR " : -n newInstancePath - Path of the new 7.0 instance\n"); - print(STDERR " : [-d dataPath] - Path to directory containing data files to import into new instance\n"); - print(STDERR " : [-v oldVersion] - Version of old instance (obtained by running $slapdExecName -v\n"); - print(STDERR " : [-t tracelevel] - (optional) specify the level of trace (0..3)\n"); - print(STDERR " : [-L logfile] - (optional) specify the file to log the migration report \n"); - } -######################################################################################################## - -BEGIN { - - require 'uname.lib' ; - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - ${SEP} = $isNT ? ";" : ":" ; - @INC = ( '.', '../../../admin/admin/bin'); - grep { s@/@\\@g } @INC if $isNT; - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; - - # If this variable is set, all file/directory creation will make sure the mode - # and ownership of the destination is the same as the source - $PRESERVE = 1 if (!$isNT); - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - if ($isNT) { - $os = "WINNT"; - } else { - $os = &uname("-s"); - } - if ($isNT) { - # we have to pass batch files directly to the NT command interpreter - $com_spec = $ENV{ComSpec}; - if (!$com_spec) { - $com_spec = $ENV{COMSPEC}; - } - if (!$com_spec || ! -f $com_spec) { - # find the first available command interpreter - foreach $drive (c..z) { - $com_spec = "$drive:\\winnt\\system32\\cmd.exe"; - last if (-f $com_spec); - $com_spec = undef; - } - if (! $com_spec) { - # punt and pray - $com_spec = 'c:\winnt\system32\cmd.exe'; - } - } - } - if ( $os eq "AIX" ) { - $dll_suffix = "_shr.a"; - } - elsif ( $os eq "HP-UX" ) { - $dll_suffix = ".sl"; - } - elsif ( $os eq "WINNT" ) { - $dll_suffix = ".dll"; - } - else { - $dll_suffix = ".so"; - } - $slapdExecName = $isNT ? 'slapd.exe' : './ns-slapd'; - select STDERR; - $| = 1; - select STDOUT; - $| = 1; -} - -SWITCH: { - if ($os eq "AIX") { - $LIB_PATH = "LIBPATH" ; - last SWITCH ; - } - if ($os eq "HP-UX") { - $LIB_PATH = "SHLIB_PATH" ; - last SWITCH ; - } - if ($isNT) { - $LIB_PATH = "PATH" ; - last SWITCH ; - } - else { - $LIB_PATH = "LD_LIBRARY_PATH" ; - last SWITCH ; - } - } - - # old parameters - ${oldDir} = "" ; - ${oldname} = "" ; - ${oldHome} = "" ; - ${oldConfDir} = "" ; - ${oldlocaluser} ; - ${olduid} ; - ${oldgid} ; - - # new parameters - ${root} = "{{DS-ROOT}}" ; - ${type} = "" ; - ${newname} = "" ; - ${newport} = "" ; - ${rootDN} = "" ; - ${rootpwd} = "" ; - ${localhost} = "" ; - ${LogFileReport} = "" ; - ${newuid} ; - ${localuser} ; - ${newgid} ; - $NO_INPUT_USER = 0 ; # by default user can give inputs during the migration process - ${curdir} = getCwd(); - ${slapdExecDir} = "${root}${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - # in 7.0 the replica Id is setup to a static value - $replicaIdvalue = 65535; - - # specify the level of trace - $TRACELEVEL=1; - - $LDAP_SERVER_UNREACHABLE = 81; - - # get input users - &getParameters() ; - ${oldDir} = &normalizeDir("${oldDir}"); - ${oldHome} = "${oldDir}${PATHSEP}$type-$oldname" ; - ${oldConfDir} = "${oldHome}${PATHSEP}config${PATHSEP}" ; - ${oldSchemaDir} = "${oldConfDir}schema${PATHSEP}"; - ${oldDSEldif} = "${oldConfDir}dse.ldif"; - ${serverHome} = "${root}${PATHSEP}$type-$newname" ; - ${schemaDir} = "$serverHome${PATHSEP}config${PATHSEP}schema${PATHSEP}"; - ${DSEldif} = "$serverHome${PATHSEP}config${PATHSEP}dse.ldif"; - ${ldif_rep} = "${oldConfDir}ldif${PATHSEP}" ; - ${oldSlapdExecDir} = "${oldDir}${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - - open(LOGFILE, ">> $LogFileReport"); - - printTrace("\noldDir: $oldDir, oldHome: $oldHome, \noldConfDir: $oldConfDir, \nldif_rep: $ldif_rep, \nrootDN: $rootDN, \nPort: $newport, \nNewname: $newname\n",3); - printTrace("\nLIB_PATH: $LIB_PATH",4); - - if (!(-d $serverHome)) { - printMsg("\n$serverHome doesn't exist\n"); - exit(1); - } - if (!(-d $oldHome)) { - printMsg("\n$oldHome doesn't exist\n"); - exit(1); - } - - if ($olddatadir && !(-d $olddatadir)) { - print("\n$olddatadir doesn't exist\n"); - exit(1); - } - - -%HashParametersName = (); - -# The following hash displays only general server parameters to migrate under cn=config -%GeneralSrvParamToMigrate = ( - 'nsslapd-accesscontrol'=> '\n', - 'nsslapd-errorlog-logging-enabled'=> '\n', - 'nsslapd-accesslog-logging-enabled'=> '\n', - 'nsslapd-auditlog-logging-enabled'=> '\n', - 'nsslapd-accesslog-level'=> '\n', - 'nsslapd-accesslog-logbuffering'=> '\n', - 'nsslapd-accesslog-logexpirationtime'=> '\n', - 'nsslapd-accesslog-logexpirationtimeunit'=> '\n', - 'nsslapd-accesslog-logmaxdiskspace'=> '\n', - 'nsslapd-accesslog-logminfreediskspace'=> '\n', - 'nsslapd-accesslog-logrotationtime'=> '\n', - 'nsslapd-accesslog-logrotationtimeunit'=> '\n', - 'nsslapd-accesslog-maxlogsize'=> '\n', - 'nsslapd-accesslog-maxLogsPerDir'=> '\n', - 'nsslapd-attribute-name-exceptions'=> '\n', - 'nsslapd-auditlog-logexpirationtime'=> '\n', - 'nsslapd-auditlog-logexpirationtimeunit'=> '\n', - 'nsslapd-auditlog-logmaxdiskspace'=> '\n', - 'nsslapd-auditlog-logminfreediskspace'=> '\n', - 'nsslapd-auditlog-logrotationtime'=> '\n', - 'nsslapd-auditlog-logrotationtimeunit'=> '\n', - 'nsslapd-auditlog-maxlogsize'=> '\n', - 'nsslapd-auditlog-maxLogsPerDir'=> '\n', - 'nsslapd-certmap-basedn'=> '\n', - 'nsslapd-ds4-compatible-schema'=> '\n', - 'nsslapd-enquote-sup-oc'=> '\n', - 'nsslapd-errorlog-level'=> '\n', - 'nsslapd-errorlog-logexpirationtime'=> '\n', - 'nsslapd-errorlog-logexpirationtimeunit'=> '\n', - 'nsslapd-errorlog-logmaxdiskspace'=> '\n', - 'nsslapd-errorlog-logminfreediskspace'=> '\n', - 'nsslapd-errorlog-logrotationtime'=> '\n', - 'nsslapd-errorlog-logrotationtimeunit'=> '\n', - 'nsslapd-errorlog-maxlogsize'=> '\n', - 'nsslapd-errorlog-maxlogsperdir'=> '\n', - 'nsslapd-groupevalnestlevel'=> '\n', - 'nsslapd-idletimeout'=> '\n', - 'nsslapd-ioblocktimeout'=> '\n', - 'nsslapd-lastmod'=> '\n', - 'nsslapd-listenhost'=> '\n', - 'nsslapd-maxdescriptors'=> '\n', - 'nsslapd-nagle'=> '\n', - 'nsslapd-readonly'=> '\n', - 'nsslapd-referralmode'=> '\n', - 'nsslapd-plugin-depends-on-name'=> '\n', - 'nsslapd-plugin-depends-on-type'=> '\n', - 'nsslapd-referral'=> '\n', - 'nsslapd-reservedescriptors'=> '\n', - 'nsslapd-rootpwstoragescheme'=> '\n', - 'nsslapd-schemacheck'=> '\n', - 'nsslapd-secureport'=> '\n', - 'nsslapd-security'=> '\n', - 'nsslapd-sizelimit'=> '\n', - 'nsslapd-ssl3ciphers'=> '\n', - 'nsslapd-timelimit'=> '\n', - 'passwordchange'=> '\n', - 'passwordchecksyntax'=> '\n', - 'passwordexp'=> '\n', - 'passwordhistory'=> '\n', - 'passwordinhistory'=> '\n', - 'passwordlockout'=> '\n', - 'passwordlockoutduration'=> '\n', - 'passwordmaxage'=> '\n', - 'passwordmaxfailure'=> '\n', - 'passwordminage'=> '\n', - 'passwordminlength'=> '\n', - 'passwordmustchange'=> '\n', - 'passwordresetfailurecount' => '\n', - 'passwordstoragescheme' => '\n', - 'passwordunlock' => '\n', - 'passwordwarning' => '\n' -); - -# the following hash displays global parameters related to database stored under cn=config,cn=ldbm database,cn=plugins,cn=config -%GlobalConfigLDBMparamToMigrate = ( - 'nsslapd-allidsthreshold' => '\n', - 'nsslapd-lookthroughlimit' => '\n', - 'nsslapd-mode' => '\n', - 'nsslapd-dbcachesize' => '\n', - 'nsslapd-cache-autosize' => '\n', - 'nsslapd-cache-autosize-split' => '\n', - 'nsslapd-db-transaction-logging' => '\n', - 'nsslapd-import-cachesize' => '\n' -); - -# the following hash displays specific parameters to each backends and stored under cn=DBname,cn=ldbm database,cn=plugins,cn=config -%LDBMparamToMigrate = ( - 'nsslapd-cachesize' => '\n', - 'nsslapd-cachememsize' => '\n', - 'nsslapd-readonly' => '\n', - 'nsslapd-require-index' => '\n' -); - - -%ChainingConfigParams = ( - 'nsactivechainingcomponents' => '\n', - 'nstransmittedcontrols' => '\n' - ); - -%ChainingDefaultInstanceConfigParams = ( - 'nsabandonedsearchcheckinterval' => '\n', - 'nsbindconnectionslimit' => '\n', - 'nsbindtimeout' => '\n', - 'nsbindretrylimit' => '\n', - 'nshoplimit' => '\n', - 'nsmaxresponsedelay' => '\n', - 'nsmaxtestresponsedelay' => '\n', - 'nschecklocalaci' => '\n', - 'nsconcurrentbindlimit' => '\n', - 'nsconcurrentoperationslimit' => '\n', - 'nsconnectionlife' => '\n', - 'nsoperationconnectionslimit' => '\n', - 'nsproxiedauthorization' => '\n', - 'nsreferralonscopedsearch' => '\n', - 'nsslapd-sizelimit' => '\n', - 'nsslapd-timelimit' => '\n' -); - -%changelog5params = ( - 'nsslapd-changelogmaxage' => '\n', - 'nsslapd-changelogmaxentries' => '\n' - ); - -@SNMPparams = ( - 'nssnmpenabled', - 'nssnmporganization', - 'nssnmplocation', - 'nssnmpcontact', - 'nssnmpdescription', - 'nssnmpmasterhost', - 'nssnmpmasterport', - 'nssnmpenabled', - 'aci' - ); - -%stdIncludes = ( - "." => "\n", - ".." => "\n", - "30ns-common.ldif " => "\n", - "50ns-mail.ldif " => "\n", - "50ns-news.ldif" => "\n", - "50iplanet-servicemgt.ldif"=> "\n", - "50netscape-servicemgt.ldif"=> "\n", - "50ns-mcd-browser.ldif" => "\n", - "50ns-proxy.ldif" => "\n", - "00core.ldif" => "\n", - "50ns-admin.ldif" => "\n", - "50ns-mcd-config.ldif " => "\n", - "50ns-value.ldif" => "\n", - "05rfc2247.ldif" => "\n", - "50ns-calendar.ldif" => "\n", - "50ns-mcd-li.ldif" => "\n", - "50ns-wcal.ldif" => "\n", - "05rfc2927.ldif" => "\n", - "50ns-certificate.ldif" => "\n", - "50ns-mcd-mail.ldif" => "\n", - "50ns-web.ldif" => "\n", - "10rfc2307.ldif" => "\n", - "50ns-compass.ldif" => "\n", - "50ns-media.ldif" => "\n", - "20subscriber.ldif" => "\n", - "50ns-delegated-admin.ldif"=> "\n", - "50ns-mlm.ldif" => "\n", - "25java-object.ldif" => "\n", - "50ns-directory.ldif" => "\n", - "50ns-msg.ldif" => "\n", - "28pilot.ldif" => "\n", - "50ns-legacy.ldif" => "\n", - "50ns-netshare.ldif" => "\n" -); - - -# Backends migrated (Backend CN attribute value) -@BACKENDS = () ; -# All pairs of suffix-backend are registered in this hashtable -%oldBackends = () ; - -#store the backend instances to migrate -@LDBM_backend_instances = (); - -#store the mapping tree -@Mapping_tree_entries = (); - -#store the suffix and the associated chaining backend -%oldChainingBackends = (); - -#store the multiplexor bind entries to migrate -%MultiplexorBindDNEntriesToMigrate = (); - -#store the Replica bind DN entries to migrate -%ReplicaBindDNEntriesToMigrate = (); - -# list of standard plugins -%stdPlugins = ( - "7-bit check" => "\n", - "acl plugin" => "\n", - "acl preoperation" => "\n", - "binary syntax" => "\n", - "case exact string syntax" => "\n", - "case ignore string syntax" => "\n", - "chaining database" => "\n", - "class of service" => "\n", - "country string syntax" => "\n", - "distinguished name syntax" => "\n", - "generalized time syntax" => "\n", - "integer syntax" => "\n", - "internationalization plugin" => "\n", - "ldbm database" => "\n", - "legacy replication plugin" => "\n", - "multimaster replication plugin" => "\n", - "octet string syntax" => "\n", - "clear" => "\n", - "crypt" => "\n", - "ns-mta-md5" => "\n", - "sha" => "\n", - "ssha" => "\n", - "postal address syntax" => "\n", - "referential integrity postoperation" => "\n", - "retro changelog plugin" => "\n", - "roles plugin" => "\n", - "telephone syntax" => "\n", - "uid uniqueness" => "\n", - "uri syntax" => "\n" - ); - -# list of indexes that have disappeared from the new schema compared to 6.x -%deniedIndexes = ( - 'dncomp' => "\n" -); - -@default_indexes = (); -@indexes = (); - -# list of user added Plugin's. In 7.0, they 'll need to be recompiled -@badPlugins = () ; - -@pluginAttrs = ( - "objectclass", - "cn", - "nsslapd-pluginpath", - "nsslapd-plugininitfunc", - "nsslapd-plugintype", - "nsslapd-pluginenabled", - "nsslapd-plugin-depends-on-type", - "nsslapd-pluginid", - "nsslapd-pluginversion", - "nsslapd-pluginvendor" - ); - -@nsds5replicaAttrs = ( - 'objectclass', - 'nsDS5ReplicaName', - 'nsDS5ReplicaRoot', - 'nsDS5ReplicaType', - 'nsDS5ReplicaLegacyConsumer', - 'nsDS5flags', - 'nsDS5ReplicaId', - 'nsDS5ReplicaPurgeDelay', - 'nsDS5ReplicaBinddn', - 'cn', - 'nsDS5ReplicaReferral' - ); - -# array of replicas to migrate -@new6replicas = (); - -# array of replication agreements to migrate -@replicationAgreements = (); - -# compare LDIF standard config files with standard ones -CompareStdConfigFiles() ; -die "\n\n The version of product you want to migrate is not a 6.x Directory Server\n" unless ($oldVersion == 6) ; - -# Shutdown the legacy Directory instance -printTrace("\nShutdown the legacy Directory Server instance: ${oldHome}",0); -&stopServer($oldDir, 'slapd-'.$oldname); - -# get the hostname of the new LDAP server -my $LDAPservername = &getLDAPservername(); - -# get the uid and gid of the 7.0 slapd user -($localuser, $newuid, $newgid) = getuid_gid(); -# get the uid and gid of the 6.x slapd user -($oldlocaluser, $olduid, $oldgid) = getolduid_gid(); -printTrace("\n7.0 localuser: $localuser, uid: $newuid, gid: $newgid",2); -printTrace("\n6.x localuser: $oldlocaluser, uid: $olduid, gid: $oldgid",2); - -# backup 7.0 configuration files in <6server_root>/slapd-instancename/config -printTrace("\nBackup $serverHome${PATHSEP}config on $serverHome${PATHSEP}config_backup ...",0); -&backupConfigFiles(); - -# migrate the schema (need to stop and start the 7.0 server) -printTrace("\nMigrate the schema...",0); -MigrateSchema(); - -#migrate key/cert databases -# We will migrate the key/cert databases before the dse file because the -# dse migration may cause SSL to be enabled. -printTrace("\n\nMigrate key/cert databases...",0,1); -&MigrateSSL(); - -# start the server unless it is already started -&startServer() unless (isDirectoryAlive()); - -############### Connect to the 7.0 LDAP Directory Server ###################### -$ENV{"$LIB_PATH"} = $new_libpath; - -die "\n Migration aborted. Make sure your old and new Directory Server are installed on the same machine \n" if ( $LDAPservername == -1 ); -$conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - -# Cconnection to 7.0 LDAP server is successful ! -printTrace("\nConnected to $Version.$Minor LDAP server",0) ; - -# Parse the main configuration file: dse.ldif -printTrace("\n\nParse the old DSE ldif file: $oldDSEldif *****",0, 1); -printTrace("\nThis may take a while ...\n",0); -&MigrateDSEldif(); - -#migrate LDBM backend instances -printTrace("\n\nMigrate LDBM backend instances...",0,1); -&migrateLDBM_backend_instances(); - -#migrate mapping tree entries -printTrace("\n\nMigrate mapping tree...",0,1); -&migrateMappingTree(); - -#migrate default indexes -printTrace("\n\nMigrate default indexes...",0,1); -migrateDefaultIndexes(); - -#migrate indexes -printTrace("\n\nMigrate indexes...",0,1); -migrateIndexes(); - -#migrate replicas -printTrace("\n\nMigrate replicas...",0,1); -&MigrateNSDS5_replica(); - -#migrate replication agreements -printTrace("\n\nMigrate replication agreements...",0,1); -&MigrateNSDS_replication_agreement(); - -# migrate certmap.conf -printTrace("\n\nMigrate Certmap.conf...",0,1); -&MigrateCertmap() ; - -################## Close the connection to 7.0 LDAP Server ##################### -printTrace("\n\n***** Close the LDAP connection to the new Directory Server instance ***** ",0); -$conn->close; - - -################## stop the new instance and Export/Import the data, restart the server ################## -if (@BACKENDS) { - &stopServer($root,'slapd-'.$newname); - if ($olddatadir) { - printTrace("\nData already contained in $olddatadir...\n",0,1) ; - $ldif_rep = "$olddatadir${PATHSEP}"; - } else { - printTrace("\nData processing...\n",0,1) ; - # migrate data for each backend: 6.x -> LDIF files - &manydb2Ldif($ldif_rep); - } - - # migrate LDIF data to the new database: LDIF -> New - &manyLdif2db($ldif_rep); - &migrateChangelog(); - printTrace("\n***** Migrate ReplicaBindDN entries...\n",0,1); - &importReplicaBindDNEntries(); - printTrace("\n***** Migrate MultiplexorBindDN entries...\n",0,1); - &importMultiplexorBindDNEntries(); - &startServer() unless (isDirectoryAlive()); -} -else { - printTrace("\nINFORMATION - There are no non-standard or non-already existing suffixes to migrate\n",0); - &migrateChangelog(); - printTrace("\n***** Migrate ReplicaBindDN entries...\n",0,1); - &importReplicaBindDNEntries(); - printTrace("\n***** Migrate MultiplexorBindDN entries...\n",0,1); - &importMultiplexorBindDNEntries(); -} - -printMsg("\n\n ****** End of migration ******\n\n"); - -close(LOGFILE); - - -########################################################################################### -# get input users -sub getParameters { - my $exit = 0 ; - my $i = 0; - my $pwdfile= ""; - - while ($i <= $#ARGV) { - if ( "$ARGV[$i]" eq "-D" ) { # directory manager - if (! $rootDN) { - $rootDN = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-w") { # password - if (! $rootpwd) { - $rootpwd = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-j") { # password file - if (! $pwdfile) { - $pwdfile = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-o") { # old instance path - if (! $oldHome ) { - $oldHome = $ARGV[++$i] ; - grep { s@\\@/@g } $oldHome if $isNT ; - if ($oldHome =~ /[\"]?(.*)?[\"]?/) { $oldHome = $1 ; } - if ($oldHome =~ m@^(.*)/([^-/]*)-([^/]*)[/]?$@) { - $oldDir = $1 ; - $type = $2 ; - $oldname = $3 ; - if ($isNT) { - $oldDir = lc($oldDir) ; - $type = lc($type) ; - $oldname = lc($oldname) ; - $oldHome = lc($oldHome) ; - grep { s@/@\\@g } $oldDir ; - grep { s@/@\\@g } $oldHome ; - } - } - else { - print("\nThe old instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-n") { # new instance path - if (! $serverHome ) { - $serverHome = $ARGV[++$i] ; - grep { s@\\@/@g } $root if $isNT ; - grep { s@\\@/@g } $serverHome if $isNT ; - if ($serverHome =~ /[\"]?(.*)?[\"]?/) { $serverHome = $1 ; } - if ($serverHome =~ m@^(.*?)/?([^/-]*)-([^/]*)[/]?$@) { - $root = $1 if ($1); - $type = $2 ; - $newname = $3 ; - if ($isNT) { - $root = lc($root) ; - $type = lc($type) ; - $newname = lc($newname) ; - $serverHome = lc($serverHome) ; - grep { s@/@\\@g } $root ; - grep { s@/@\\@g } $serverHome ; - } - } - else { - print("\nThe new instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-p") { # new DS port - if (! $newport ) { - $newport = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-d") { # old instance LDIF data dir - if (! $olddatadir ) { - $olddatadir = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-v") { # old version - if (! $oldversionstr ) { - $oldversionstr = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-t") { # TRACELEVEL - my $value = $ARGV[++$i] ; - if ($value =~ /[0-3]/) { - $TRACELEVEL = $value ; - } - else { - print("\nThe tracelevel must belong to 0..3 interval"); - &usage(); - exit(); - } - } elsif ("$ARGV[$i]" eq "-noinput") { # no user interventions during processing - $NO_INPUT_USER = 1 ; - } elsif ("$ARGV[$i]" eq "-L") { # migration logfile - $LogFileReport = $ARGV[++$i] ; - } - else { - print("\nThe option $ARGV[$i] is not recognized"); - &usage() ; - exit(1); - } - $i++; - } - if (! $rootDN) { - print("\nThe rootDN is missing"); - $exit = 1; - } - if ($pwdfile ne "") { - # Open file and get the password - unless (open (RPASS, $pwfile)) { - die "Error, cannot open password file $passwdfile\n"; - } - $rootpwd = <RPASS>; - chomp($rootpwd); - close(RPASS); - } elsif ($rootpwd eq "-"){ - # Read the password from terminal - die "The '-w -' option requires an extension library (Term::ReadKey) which is not\n", - "part of the standard perl distribution. If you want to use it, you must\n", - "download and install the module. You can find it at\n", - "http://www.perl.com/CPAN/CPAN.html\n"; - # Remove the previous line and uncomment the following 6 lines once you have installed Term::ReadKey module. -# use Term::ReadKey; -# print "Bind Password: "; -# ReadMode('noecho'); -# $rootpwd = ReadLine(0); -# chomp($rootpwd); -# ReadMode('normal'); - } - if (! $rootpwd) { - print("\nThe rootpwd is missing"); - $exit = 1 ; - } - if (! $newport) { - print("\nThe port is missing"); - $exit = 1; - } - if (! $serverHome) { - print("\nThe new instance path is missing"); - $exit = 1; - } - if (! $oldHome) { - print("\nThe old instance path is missing"); - $exit = 1; - } - if ((! $LogFileReport) && $serverHome) { - ($sec, $min, $hour, $dd, $mm, $yy) = &GetTime(); - $LogFileReport = "${serverHome}${PATHSEP}logs${PATHSEP}Migration_${dd}${mm}${yy}_${hour}${min}${sec}.log"; - } - if ($exit) { - &usage() ; - exit(1); - } - -} - -################################################################################################### - -sub MigrateSchema{ - my $FilesChanged = ""; - my $AllDiffs = ""; - my $NoChanges = "" ; - my $lineToBegin = 0 ; - opendir(SCHEMADIR, $oldSchemaDir) or - die "Error: could not open migrated config dir $oldSchemaDir: $!"; - - foreach $file (readdir(SCHEMADIR)) { - if (! exists($stdIncludes{lc($file)})) { - my $newSchemaFile = $schemaDir . $file; - if (-f $newSchemaFile ) { - # The ldif file already exists. Make a diff and warn the user if different. - if (diff($newSchemaFile, $oldSchemaDir.$file)) { - &stopServer($root,'slapd-'.$newname) if (isDirectoryAlive()); - $AllDiffs .= "\n$file"; - copyBinFile("$oldSchemaDir$file", $newSchemaFile); - } - } - else { - &stopServer($root,'slapd-'.$newname) if (isDirectoryAlive()); - $AllDiffs .= "\n$file"; - copyBinFile("$oldSchemaDir$file", $newSchemaFile); - } - } - } - closedir(SCHEMADIR); - if ($AllDiffs) { - printMsg("\n\n***********************************************************************"); - printMsg("\nThe following LDIF files have been migrated:"); - printMsg("$AllDiffs"); - printMsg("\n*************************************************************************\n\n"); - } - &startServer() if (! isDirectoryAlive()); -} - - -################################################################################################### -# This subroutine is used to parse the dse.ldif file and call specific routines to act with entries -sub MigrateDSEldif { - printTrace("\nMigrate DSE entries...",1); - my $tempoAlreadyDone = 0; - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - SWITCH: { - if ($typeOfEntry eq "LDBM_BACKEND_INSTANCE"){ - parseLDBM_backend_instance($entry); - last SWITCH; - } - if ($typeOfEntry eq "MAPPING_TREE"){ - parseMapping_tree($entry); - last SWITCH; - } - if ($typeOfEntry eq "DEFAULT_INDEX"){ - parseDefaultIndex($entry); - last SWITCH; - } - if ($typeOfEntry eq "INDEX"){ - parseIndex($entry); - last SWITCH; - } - if ($typeOfEntry eq "STANDARD_PLUGIN"){ - migrateStdPlugin($entry); - last SWITCH; - } - if ($typeOfEntry eq "CONFIG_NODE"){ - migrateConfig_Node($entry); - last SWITCH; - } - if ($typeOfEntry eq "CONFIG_LDBM_DATABASE"){ - migrateConfig_LDBM_database($entry); - last SWITCH; - } - if ($typeOfEntry eq "CHAINING_BACKEND_CONFIG"){ - migrateChainingBE_config($entry); - last SWITCH; - } - if ($typeOfEntry eq "CHAINING_BACKEND_INSTANCE"){ - migrateChainingBE_instance($entry); - last SWITCH; - } - if ($typeOfEntry eq "NSDS5_REPLICA"){ - parseNSDS5_replica($entry); - last SWITCH; - } - if ($typeOfEntry eq "NSDS_REPLICATION_AGREEMENT"){ - parseNSDS_replication_agreement($entry); - last SWITCH; - } - if ($typeOfEntry eq "CHANGELOG5"){ - migrateChangelog5($entry); - last SWITCH; - } - if ($typeOfEntry eq "REPLICATION"){ - migrateReplication($entry); - last SWITCH; - } - if ($typeOfEntry eq "SECURITY"){ - migrateSecurity($entry); - last SWITCH; - } - if ($typeOfEntry eq "SNMP"){ - migrateSNMP($entry); - last SWITCH; - } - } - - } - close(DSELDIF); -} - -############################################################################# -# returns the "type of an entry". If the entry is not to be migrated its type is "NOT_MIGRATED_TYPE" - -sub getTypeOfEntry{ - my $entry = shift; - my $DN = $entry->getDN(1) ; # 1 is to normalize the returned DN - if (($DN =~ /cn=ldbm database,cn=plugins,cn=config$/i) && (isObjectclass($entry,"nsBackendInstance"))) { - return "LDBM_BACKEND_INSTANCE"; - } - if (($DN =~ /cn=mapping tree,cn=config$/i) && (isObjectclass($entry,"nsMappingTree"))) { - return "MAPPING_TREE"; - } - if (($DN =~ /cn=default indexes,cn=config,cn=ldbm database,cn=plugins,cn=config$/i) && (isObjectclass($entry,"nsIndex"))) { - return "DEFAULT_INDEX"; - } - if (isObjectclass($entry,"nsIndex")) { - return "INDEX"; - } - if ((isObjectclass($entry,"nsSlapdPlugin")) && (isStdPlugin($entry))) { - return "STANDARD_PLUGIN"; - } - if ($DN =~ /^cn=config$/i) { - return "CONFIG_NODE"; - } - if ($DN =~ /^cn=config,cn=ldbm database,cn=plugins,cn=config$/i) { - return "CONFIG_LDBM_DATABASE"; - } - if (($DN =~ /^cn=config,cn=chaining database,cn=plugins,cn=config$/i) || ($DN =~ /^cn=default instance config,cn=chaining database,cn=plugins,cn=config$/i)){ - return "CHAINING_BACKEND_CONFIG"; - } - if (($DN =~ /cn=chaining database,cn=plugins,cn=config$/i) && (isObjectclass($entry,"nsBackendInstance"))) { - return "CHAINING_BACKEND_INSTANCE"; - } - if (isObjectclass($entry,"nsDS5Replica")) { - return "NSDS5_REPLICA"; - } - if (isObjectclass($entry,"nsDS5ReplicationAgreement")) { - return "NSDS_REPLICATION_AGREEMENT"; - } - if ($DN =~ /^cn=changelog5,cn=config$/i) { - return "CHANGELOG5"; - } - if (($DN =~ /cn=replication,cn=config$/i) && ($DN !~ /^cn=replication,cn=config$/i)) { - return "REPLICATION"; - } - if ($DN =~ /cn=encryption,cn=config$/i) { - return "SECURITY"; - } - if ($DN =~ /^cn=SNMP,cn=config$/i) { - return "SNMP"; - } - return "NOT_MIGRATED_TYPE"; -} - -############################################################################# - - - -############################################################################# -# returns 1 if the objectclass given in parameter is present in the objectclasses values of the entry -# given in parameter, 0 else - -sub isObjectclass { - my $entry = shift; - my $objectclass = shift; - return ($entry->hasValue("objectclass",$objectclass,1)); -} - -############################################################################# - -sub isStdPlugin { - my $entry = shift; - my $CN = $entry->{cn}[0]; - if (isObjectclass($entry,"nsSlapdPlugin")) { - return 1 if ($stdPlugins{lc($CN)}); - } - return 0; -} - - -############################################################################# - -sub alreadyExistsInNew{ - my $entry = shift; - my $mustExist = shift; - my $DN = $entry->getDN(1); # 1 to normalize the DN - # We have a name change of "uid uniqueness" plugin in DS6.x - # to "attribute uniqueness" - $DN =~ s/uid\ uniqueness/attribute\ uniqueness/ if ($DN =~ /uid\ uniqueness/); - return searchEntry($DN, $mustExist); -} - -############################################################################# -sub searchEntry { - my $DN = shift; - my $mustExist = shift; - my $res = $conn->search($DN, "base", "objectclass=*"); - my $cpt = 5; - if ($res) { - return $res; - } - else { - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && cpt && (! $res)) { - printMsg("\ntry to reconnect to search $DN"); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $res = $conn->search($DN, "base", "objectclass=*"); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - if ($res){ - return $res ; - } - elsif (($errorCode eq $LDAP_SERVER_UNREACHABLE) || ($mustExist)) { - my $msg = $conn->getErrorString(); - printMsg("\n\n*** Failed to search: $DN"); - printMsg("\n*** Error Msg: $msg, Error code: $errorCode"); - } - return 0; - } -} - - -############################################################################# - -sub addEntryToNew{ - my $entry = shift; - my $typeOfEntry = shift; - my $trace = shift; - my $res = $conn->add($entry); - my $DN = $entry->getDN(1); - my $cpt = 5; - if ($res) { - printTrace("\n$typeOfEntry - Add successfull: $DN",$trace); - return 1; - } - else { - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && cpt && (! $res)) { - printMsg("\ntry to reconnect to add $DN"); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $res = $conn->add($entry); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - if ($res){ - printTrace("\n$typeOfEntry - Add successfull: $DN",$trace); - return 1; - } - else { - my $msg = $conn->getErrorString(); - printMsg("\n\n*** $typeOfEntry: Add Failed: $DN"); - printMsg("\n*** Error Msg: $msg, Error code: $errorCode"); - return 0; - } - } -} - -############################################################################# - -sub updateEntry{ - my $entry = shift; - my $typeOfEntry = shift; - my $CHECK = shift; - my $trace = shift; - my $cpt = 5; - if ($CHECK) { - if (! hasChanged($entry, $typeOfEntry)) { - return 1; - } - } - my $res = $conn->update($entry); - my $DN = $entry->getDN(1); - if ($res) { - printTrace("\n$typeOfEntry - Update successfull: $DN",$trace); - return 1 ; - } - else { - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && cpt && (! $res)) { - printMsg("\ntry to reconnect to update $DN"); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $res = $conn->update($entry); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - if ($res){ - printTrace("\n$typeOfEntry - Update successfull: $DN",$trace); - return 1; - } - else { - my $msg = $conn->getErrorString(); - printMsg("\n\n*** $typeOfEntry - Update Failed: $DN"); - printMsg("\n*** Error Msg: $msg, Error code: $errorCode"); - return 0; - } - } -} - - -############################################################################# -# returns 1 if the entry to migrate and the current entry are different one another - -sub hasChanged { - my $entry = shift; - my $typeOfEntry = shift; - my $DN = $entry->getDN(1); - my $newEntry = searchEntry($DN,1); - return 1 if (! $newEntry); # we shoudn't be in that case ... - # do the stuff to check wether the entry has changed or not given its type - if (($typeOfEntry eq "DEFAULT_INDEX") || ($typeOfEntry eq "INDEX")){ - my @indexTypes = $entry->getValues("nsIndexType"); - my @newIndexTypes = $newEntry->getValues("nsIndexType"); - my @nsmatchingrules = $entry->getValues("nsmatchingrule"); - my @newMatchingRules = $newEntry->getValues("nsmatchingrule"); - return 1 if (Diffs(\@indexTypes, \@newIndexTypes)); - return 1 if (Diffs(\@nsmatchingrules,\@newMatchingRules)); - return 0; - } - if ($typeOfEntry eq "CHANGELOG5"){ - printTrace("\nCheck wether changelog has changed or not",3); - my @params = keys(%changelog5params); - foreach $param (@params){ - my @values = $entry->getValues($param); - my @newValues = $newEntry->getValues($param); - return 1 if (Diffs(\@values,\@newValues)); - } - return 0; - } - if ($typeOfEntry eq "SNMP"){ - foreach $param (@SNMPparams){ - my @values = $entry->getValues($param); - my @newValues = $newEntry->getValues($param); - return 1 if (Diffs(\@values,\@newValues)); - } - return 0; - } - # we don't know how to compare such type of entry => just return 1 - return 1 ; -} - -sub isAsystemIndex { - my $index = shift; - return ($index->hasValue("nsSystemIndex","true",1)); -} - - -sub updatePathInPluginArgs { - my $plugin = shift; - my $argNum = 0; - my $argPrefix = "nsslapd-pluginarg"; - my $cont = 1; - my $Unix_oldDir = ${oldDir} ; - my $Unix_root = ${root} ; - grep { s@\\@/@g } $Unix_oldDir if $isNT; - grep { s@\\@/@g } $Unix_root if $isNT; - while ($cont) { - my $arg = $argPrefix . $argNum ; - if ($plugin->exists($arg)) { - $_ = $plugin->{$arg}[0] ; - s@$Unix_oldDir@$Unix_root@ig ; - s/$type-$oldname/$type-$newname/ig ; - $plugin->setValues($arg, $_) ; - } - else { - $cont = 0 ; - } - $argNum++; - } - return $plugin; -} - - -sub Diffs { - my $valuesToMigrate = shift; - my $currentValues = shift; - return 1 if (getDiff(\@{$valuesToMigrate},\@{$currentValues})); - return 1 if (getDiff(\@{$currentValues},\@{$valuesToMigrate})); - return 0 ; -} - -sub getDiff { - # we get references to arrays - my $elements = shift ; - my $existing_elements = shift ; - my %count = () ; - my %countEE = () ; - @diff = () ; - foreach $e (@{$elements}, @{$existing_elements}) { $count{$e}++ ;} - foreach $e (@{existing_elements}) { $countEE{$e}++ ;} - foreach $e (@{$elements}) { - # if $e is only present in @$elements, we push it to the diff array - if (($count{$e} == 1) && ($countEE{$e} == 0)) { - push @diff, $e ; - } - } - return @diff ; -} - -sub registerSuffix_Backend { - my $ldbmDatabase = shift; - my $CN = $ldbmDatabase->{cn}[0]; - my $suffixArg = "nsslapd-suffix"; - my $suffix = $ldbmDatabase->{$suffixArg}[0]; - $oldBackends{$suffix} = $CN; -} - - -############################################################################# -# # -# # -# # -############################################################################# -sub migrateLDBM_backend_instances { - foreach $entry (@LDBM_backend_instances) { - my $DN = $entry->getDN(1); # 1 is to normalize the DN - my $CN = $entry->{cn}[0]; - my $expLdif; - my $confirm = "No"; - my $dest = "$serverHome${PATHSEP}db_backup" ; - my $newSlapdExecDir = "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - - if ($DN =~/cn=netscaperoot,cn=ldbm database/i){ - printTrace("\n\n*** INFORMATION - NetscapeRoot is NOT migrated",0); - } - else { - if(alreadyExistsInNew($entry)){ - printMsg("\n\n*** LDBM_BACKEND_INSTANCE - $DN already exists"); - printMsg("\n*** Migration will overwrite existing database"); - printMsg("\nDo you want to continue Yes/No [No] ?") ; - my $answer = <STDIN> ; - if ($answer =~ /y|yes/i) { - printMsg("Do you want to export the existing data Yes/No [Yes] ?"); - my $answer = <STDIN> ; - if (!($answer =~ /n|no/i)) { - mkdir $dest, 0700 unless (-d $dest); - $expLdif = "$dest${PATHSEP}$CN.ldif"; - while (!($confirm =~ /y|yes/i)) { - printMsg("\nEnter the full pathname of the file [$expLdif]:") ; - $answer = <STDIN> ; - chomp($expLdif = $answer) unless ($answer eq "\n"); - printMsg("\nExisting data will be exported under $expLdif"); - printMsg("\nContinue Yes/No [No] ?"); - $confirm = <STDIN>; - } - $ENV{"$LIB_PATH"}=$new_libpath; - chdir($newSlapdExecDir) or die "\nCould not change directory to $newSlapdExecDir: $!\n"; - printTrace("\nNow backing up database $CN in $expLdif\n",0); - &stopServer($root,'slapd-'.$newname); - &db2Ldif($expLdif, $CN, $serverHome); - &startServer() unless (isDirectoryAlive()); - } - push @BACKENDS, $CN; - } else { - printMsg("\n*** Migration will not update it"); - break; - } - } else { - printTrace("\nWe should add the backend instance $DN",3); - my $suffixarg = "nsslapd-suffix" ; - my $suffixname= $entry->{$suffixarg}[0] ; - my $newEntry = $conn->newEntry() ; - $newEntry->setDN($DN); - $newEntry->setValues("objectclass", "top", "extensibleObject", "nsBackendInstance" ); - $newEntry->setValues("cn", $CN ); - $newEntry->setValues($suffixarg, $suffixname); - my @params = keys(%LDBMparamToMigrate); - foreach $param (@params) { - my @values = $entry->getValues($param); - $newEntry->setValues($param, @values) if (@values); - } - if (addEntryToNew($newEntry, "LDBM_BACKEND_INSTANCE",1)) { - push @BACKENDS, $CN; - } - } - } - } -} - -sub parseLDBM_backend_instance { - my $entry = shift; - ®isterSuffix_Backend($entry); - push @LDBM_backend_instances, $entry; -} - -############################################################################# -sub migrateMappingTree { - foreach $entry (@Mapping_tree_entries) { - my $DN = $entry->getDN(1); # 1 si to normalize the DN - if ($DN =~/cn=\"o=netscaperoot\",cn=mapping tree,cn=config/i){ - # DO NOTHING - } - else { - if(alreadyExistsInNew($entry)){ - printMsg("\n\n*** MAPPING_TREE - $DN already exists"); - printMsg("\n*** Migration will not add the suffix"); - } - else { - addEntryToNew($entry, "MAPPING_TREE",1); - } - } - } -} - - -sub parseMapping_tree{ - my $entry = shift; - push @Mapping_tree_entries, $entry; -} - -############################################################################# -sub migrateDefaultIndexes { - foreach $index (@default_indexes) { - my $CN = $index->{cn}[0]; - my $newIndex ; - if ((! isAsystemIndex($index)) && (! $deniedIndexes{lc($CN)})) { - if ($newIndex = alreadyExistsInNew($index)) { - if (! isAsystemIndex($newIndex)) { - updateEntry($index, "DEFAULT_INDEX", 1, 2); - } - } - else { - addEntryToNew($index, "DEFAULT_INDEX", 2); - } - } - } -} - - -sub parseDefaultIndex{ - my $index = shift; - push @default_indexes, $index; -} - -############################################################################# - -sub migrateIndexes { - foreach $index (@indexes) { - my $CN = $index->{cn}[0]; - my $newIndex; - if ((! isAsystemIndex($index)) && (! $deniedIndexes{lc($CN)}) && (DN !~ /cn=netscaperoot,cn=index/i)){ - if ($newIndex = alreadyExistsInNew($index)) { - if (! isAsystemIndex($newIndex)) { - updateEntry($index, "INDEX", 1, 2); - } - } - else { - addEntryToNew($index, "INDEX", 2); - } - } - } -} - -sub parseIndex{ - my $index = shift; - push @indexes, $index; -} - -############################################################################# - -sub newLDIFplugin { - my $currentPlugin = shift; - my $DN = $currentPlugin->getDN(1); - my $newPlugin = $conn->newEntry() ; - $newPlugin->setDN($DN); - foreach $Attr (@pluginAttrs) { - my @values = $currentPlugin->getValues($Attr); - $newPlugin->setValues($Attr, @values) if (@values); - } - return $newPlugin; -} - -sub migrateStdPlugin{ - my $plugin = shift; - my $DN = $plugin->getDN(1); - my $pluginEnable = "nsslapd-pluginEnabled"; - my $argNum = 0; - my $argPrefix = "nsslapd-pluginarg"; - my $currentPlugin ; - if ($currentPlugin = alreadyExistsInNew($plugin, 1)) { - $plugin = updatePathInPluginArgs($plugin); - my $pluginEnableValue = $plugin->{$pluginEnable}[0]; - my $cont = 1; - my $pluginHasChanged = 0; - my $newPlugin = &newLDIFplugin($currentPlugin); - if (! $currentPlugin->hasValue($pluginEnable,$pluginEnableValue,1)){ - $newPlugin->setValues($pluginEnable, $pluginEnableValue); - $pluginHasChanged = 1 unless ($pluginHasChanged); - } - while($cont){ - my $arg = $argPrefix . $argNum ; - if ($plugin->exists($arg)) { - my @values = $plugin->getValues($arg); - my $value = $values[0] ; - $newPlugin->setValues($arg, $value) if (@values); - if ($currentPlugin->exists($arg)) { - if (! $currentPlugin->hasValue($arg,$value,1)) { - $pluginHasChanged = 1 unless ($pluginHasChanged); - } - } - else { - $pluginHasChanged = 1 unless ($pluginHasChanged); - } - } - else { - if ($currentPlugin->exists($arg)) { - # Just Warn the user. Do nothing. - printTrace("\nCompared to the old instance, the current new plugin $DN belongs this attribute: $arg",2); - } - else { - $cont = 0 ; - } - } - $argNum++; - } - updateEntry($newPlugin, "STANDARD_PLUGIN", 0, 1) if ($pluginHasChanged); - } -} - -############################################################################# - -sub migrateConfig_Node{ - my $config_node = shift; - my @params = keys(%GeneralSrvParamToMigrate); - my $hasChanged = 0; - my $newConfigNode; - if ($newConfigNode = alreadyExistsInNew($config_node, 1)){ - foreach $param (@params) { - if ($config_node->exists($param)){ - my @valuesToMigrate = $config_node->getValues($param); - if (@valuesToMigrate){ - if ($newConfigNode->exists($param)){ - my @currentValues = $newConfigNode->getValues($param); - if (Diffs(\@valuesToMigrate, \@currentValues)) { - $newConfigNode->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - printTrace("\nParam to update: $param with value @valuesToMigrate",3); - } - } - else { - $newConfigNode->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - printTrace("\nParam to update: $param with value @valuesToMigrate",3); - } - } - } - } - updateEntry($newConfigNode, "CONFIG_NODE", 0, 1) if ($hasChanged); - } -} - -############################################################################# - -sub migrateConfig_LDBM_database{ - my $config_ldbm = shift; - my @params = keys(%GlobalConfigLDBMparamToMigrate); - my $hasChanged = 0; - my $newConfigLdbm ; - if ($newConfigLdbm = alreadyExistsInNew($config_ldbm, 1)) { - foreach $param (@params) { - if ($config_ldbm->exists($param)){ - my @valuesToMigrate = $config_ldbm->getValues($param); - if (@valuesToMigrate){ - if ($newConfigLdbm->exists($param)){ - my @currentValues = $newConfigLdbm->getValues($param); - if (Diffs(\@valuesToMigrate, \@currentValues)) { - $newConfigLdbm->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - else { - $newConfigLdbm->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - } - } - updateEntry($newConfigLdbm, "CONFIG_LDBM_DATABASE", 0, 1) if ($hasChanged); - } -} - -############################################################################# - -sub migrateChainingBE_config{ - my $chaining_config = shift; - my $DN = $chaining_config->getDN(1); - my @params = (); - my $hasChanged = 0; - my $newChainingConfig; - if ($DN =~ /^cn=config,cn=chaining database,cn=plugins,cn=config$/i){ - $newChainingConfig = searchEntry("cn=config,cn=chaining database,cn=plugins,cn=config"); - @params = keys(%ChainingConfigParams); - } - if ($DN =~ /^cn=default instance config,cn=chaining database,cn=plugins,cn=config$/i){ - $newChainingConfig = searchEntry("cn=default instance config,cn=chaining database,cn=plugins,cn=config"); - @params = keys(%ChainingDefaultInstanceConfigParams); - } - foreach $param (@params) { - if ($chaining_config->exists($param)){ - my @valuesToMigrate = $chaining_config->getValues($param); - if (@valuesToMigrate){ - printTrace("\nParam: $param values To migrate: @valuesToMigrate",3); - if ($newChainingConfig->exists($param)){ - my @currentValues = $newChainingConfig->getValues($param); - printTrace("\nParam: $param new current values: @currentValues",3); - if (Diffs(\@valuesToMigrate, \@currentValues)) { - $newChainingConfig->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - else { - $newChainingConfig->setValues($param, @valuesToMigrate); - $hasChanged = 1 unless ($hasChanged); - } - } - } - } - updateEntry($newChainingConfig, "CHAINING_BACKEND_CONFIG", 0, 1) if ($hasChanged); -} - -############################################################################# - -sub registerSuffix_ChainingBE { - my $ldbmDatabase = shift; - my $CN = $ldbmDatabase->{cn}[0]; - my $suffixArg = "nsslapd-suffix"; - my $suffix = $ldbmDatabase->{$suffixArg}[0]; - $oldChainingBackends{$suffix} = $CN; -} - -sub storeMultiplexorBindDN { - my $chaining_instance = shift; - my $DN = $chaining_instance->getDN(1); - if ($chaining_instance->exists("nsMultiplexorBindDN")){ - my $bindDN = $chaining_instance->{nsMultiplexorBindDN}[0]; - my $newBindDN = searchEntry($bindDN); - if (! $newBindDN){ - # the bindDN entry doesn't yet exist in new => it will have to be migrated - $MultiplexorBindDNEntriesToMigrate{$bindDN}="\n" ; - printTrace("\nThe bindDN: $bindDN need to be migrated",3); - } - else { - # do nothing as the entry already exists in new - } - } - -} - -sub importMultiplexorBindDNEntries { - # import all entries present in @MultiplexorBindDNEntriesToMigrate in new - my @MultiplexorBindDNs = keys (%MultiplexorBindDNEntriesToMigrate); - my $ldif_dir = $ldif_rep; - foreach $bindDN (@MultiplexorBindDNs) { - printTrace("\nimportMultiplexorBindDNEntries: bindDN to migrate: $bindDN",3); - # get the backend in which is stored the bind DN entry - my $backendtoExportFrom = getBackendtoExportFrom($bindDN); - printTrace("\nbackendtoExportFrom is: $backendtoExportFrom",3); - # check wether the backend has been imported in new or not - if (! alreadyMigrated($backendtoExportFrom)) { - if ($backendtoExportFrom ne $NULL) { - # if not imported => we need to import the binf DN entry - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - &ExportAndAddEntry($bindDN, $backendtoExportFrom, $ldif_dir); - } - else { - # do nothing - } - } - } - # remove the empty ldif directory - rmdir($ldif_dir) if (-d $ldif_dir); - # close the LDAP connection to new - $conn->close if ($conn); -} - -sub migrateChainingBE_instance{ - my $chaining_instance = shift; - my $DN = $chaining_instance->getDN(1); - ®isterSuffix_ChainingBE($chaining_instance); - if (alreadyExistsInNew($chaining_instance)) { - # already exists - printMsg("\n\n*** CHAINING_BACKEND_INSTANCE - $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - &migrate_credential($chaining_instance, "nsmultiplexorcredentials"); - addEntryToNew($chaining_instance, "CHAINING_BACKEND_INSTANCE", 1); - storeMultiplexorBindDN($chaining_instance); - } -} - -############################################################################# - -# create a new LDIF representation of a new replica consumer -sub newLDIFreplica { - my $replica = shift; - my $DN = $replica->getDN(1); - my $newReplica = $conn->newEntry() ; - my $MASTER_OR_MULTIMASTER = "3" ; - $newReplica->setDN($DN); - foreach $Attr (@nsds5replicaAttrs) { - my @values = $replica->getValues($Attr); - $newReplica->setValues($Attr, @values) if (@values); - } - my $replicaType = $replica->{nsDS5ReplicaType}[0]; - if ($replicaType eq $MASTER_OR_MULTIMASTER) { - my @nsState = $replica->getValues("nsState"); - # nsState omitted because it is incomatible between 32 and 64 bit - # servers. Bug 624441 - # $newReplica->setValues("nsState", @nsState); - } - else { - $newReplica->setValues("nsDS5ReplicaId", $replicaIdvalue); - } - return $newReplica; -} - -sub MigrateNSDS5_replica{ - foreach $replica (@new6replicas) { - my $DN = $replica->getDN(1); - my $newReplica; - my @removeAttrs = qw(nsstate nsds5replicachangecount); - for (@removeAttrs) { - $replica->remove($_); - } - if (alreadyExistsInNew($replica)) { - # replica already exists - printMsg("\n\n*** NSDS5_REPLICA - $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - $newReplica = &newLDIFreplica($replica); - addEntryToNew($newReplica, "NSDS5_REPLICA", 1); - } - storeReplicaBindDN($replica); - } -} - -sub parseNSDS5_replica{ - my $replica = shift; - push @new6replicas, $replica; -} - -sub storeReplicaBindDN { - my $replica = shift; - my $DN = $replica->getDN(1); - if ($replica->exists("nsDS5ReplicaBindDN")){ - my $bindDN = $replica->{nsDS5ReplicaBindDN}[0]; - my $newBindDN = searchEntry($bindDN); - if (! $newBindDN){ - # the bindDN entry doesn't yet exist in new => it will have to be migrated - $ReplicaBindDNEntriesToMigrate{$bindDN}="\n" ; - printTrace("\nThe bindDN: $bindDN need to be migrated",3); - } - else { - # do nothing as the entry already exists in new - } - } -} - - -sub importReplicaBindDNEntries { - # import all entries present in @ReplicaBindDNEntriesToMigrate in new - my @ReplicaBindDNs = keys (%ReplicaBindDNEntriesToMigrate); - my $ldif_dir = $ldif_rep; - my $replBind_entry = ""; - my @bindDN_elements = ""; - my $bindDN_parent = ""; - my $parentBind_entry = ""; - foreach $bindDN (@ReplicaBindDNs) { - printTrace("\nimportReplicaBindDNEntries: bindDN to migrate: $bindDN",3); - # get the backend in which is stored the bind DN entry - my $backendtoExportFrom = getBackendtoExportFrom($bindDN); - printTrace("\nbackendtoExportFrom is: $backendtoExportFrom",3); - # If backend is from config, read the entry from dse.ldif and add to new - NGK - if ($backendtoExportFrom eq "cn=config") { - my $norm_bindDN = normalizeDN($bindDN); - @bindDN_elements = ldap_explode_dn($norm_bindDN, 0); -# @bindDN_elements = split(/,/,$norm_bindDN); - my $junk = shift(@bindDN_elements); - if ($#bindDN_elements >= 1) { - $bindDN_parent = normalizeDN(join(",", @bindDN_elements)); - } - printTrace("\nOpening DSE.ldif",3); - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF); - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN(1); - if ($DN eq $norm_bindDN) { - $replBind_entry = $entry; - } - if ($bindDN_parent ne "") { - if ($DN eq $bindDN_parent) { - $parentBind_entry = $entry; - } - } - } - close(DSELDIF); - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - if ($bindDN_parent ne "") { - addEntryToNew($parentBind_entry, BINDDN_PARENT, 0); - } - printTrace("\nAdding BindDN with addEntryToNew",3); - addEntryToNew($replBind_entry, BINDDN, 0); - } else { - # check wether the backend has been imported in new or not - if (! alreadyMigrated($backendtoExportFrom)) { - if ($backendtoExportFrom ne $NULL) { - # if not imported => we need to import the bind DN entry - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - &ExportAndAddEntry($bindDN, $backendtoExportFrom, $ldif_dir); - } - else { - # do nothing - } - } - } - } - # remove the empty ldif directory - rmdir($ldif_dir) if (-d $ldif_dir); - # close the LDAP connection to new - $conn->close if ($conn); -} - -sub alreadyMigrated { - my $backendToCheck = shift; - foreach $backend (@BACKENDS) { - return 1 if ($backend eq $backendToCheck); - } - return 0 ; -} - -sub belongsSuffix { - my $suffix = shift; - my $bindDN = shift; - return ($bindDN =~ /$suffix\s*$/i); -} - -sub length { - my $suffix = shift; - my $count = 0; - while ($suffix =~ /./g) { - $count++; - } - return $count ; -} - -sub getBackendtoExportFrom { - my $bindDN = shift ; - my $sizeOfSuffix = 0 ; - my $NULL = ""; - my @oldSuffixes = keys(%oldBackends); - my @oldChainingSuffixes = keys(%oldChainingBackends); - my $bindDN_backend = $NULL; - my $config = "cn=config"; - - my $norm_bindDN = normalizeDN($bindDN); - # Check if bindDN exists in cn=config - NGK - if (belongsSuffix($config,$norm_bindDN)) { - $bindDN_backend = $config; - printTrace("\ngetBackendtoExportFrom: bindDN_backend: $bindDN_backend",3); - } else { - foreach $suffix (@oldSuffixes){ - printTrace("\ngetBackendtoExportFrom: suffix to compare with is: $suffix",3); - if ((belongsSuffix($suffix,$norm_bindDN)) && (length($suffix) > $sizeOfSuffix)) { - $sizeOfSuffix = length($suffix); - $bindDN_backend = $oldBackends{$suffix}; - printTrace("\ngetBackendtoExportFrom: bindDN_backend: $bindDN_backend, sizeOfSuffix: $sizeOfSuffix",3); - } - } - foreach $suffix (@oldChainingSuffixes){ - printTrace("\ngetBackendtoExportFrom: suffix to compare with is a chained suffix: $suffix",3); - if ((belongsSuffix($suffix,$norm_bindDN)) && (length($suffix) > $sizeOfSuffix)) { - printMsg("\n\n*** Entry stored on a remote backend - $norm_bindDN"); - printMsg("\n*** We don't migrate it"); - return $NULL; - } - } - } - return $bindDN_backend; -} - - -sub getBackendtoImportTo { - my $bindDN = shift; - my $sizeOfSuffix = 0; - my $NULL = ""; - my $suffixArg = "nsslapd-suffix"; - my $bindDN_backend = $NULL; - open( DSELDIF, "< $DSEldif" ) || die "Can't open $DSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - if ($typeOfEntry eq "LDBM_BACKEND_INSTANCE"){ - my $suffix = $entry->{$suffixArg}[0]; - if ((belongsSuffix($suffix,$bindDN)) && (length($suffix) > $sizeOfSuffix)) { - $sizeOfSuffix = length($suffix); - $bindDN_backend = $entry->{cn}[0]; - } - } - } - close(DSELDIF); - return $bindDN_backend ; -} - - -sub ExportAndAddEntry { - my $DN = shift; - my $backendtoExportFrom = shift; - my $ldif_dir = shift; - my $ldif = "$ldif_dir${PATHSEP}$backendtoExportFrom.ldif" ; - # first: export entry pointed out by the $DN to $ldif file - $ENV{"$LIB_PATH"}=$old_libpath; - if (! $ldif_dir) { $ldif_dir = $ldif_rep ;} - if (!(-d $ldif_dir)) { - mkdir($ldif_dir,0777) or die "\ncan't create $ldif_dir to store temporary ldif files\n"; - } - chdir($oldSlapdExecDir) or die "\nCould not change directory to $oldSlapdExecDir: $!\n"; - &db2Ldif($ldif, $backendtoExportFrom, $oldHome, $DN); - chdir($curdir) or die "\nCould not change directory to $curdir: $!\n"; - - # then: Add it to new - if (! $conn) { - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - } - open( BINDDNLDIF, "< $ldif" ) || die "\nCan't open $ldif: $!: \n"; - my $in = new Mozilla::LDAP::LDIF(*BINDDNLDIF) ; - while ($entry = readOneEntry $in) { - my $entryDN = $entry->getDN(1); - if ($DN eq $entryDN) { - addEntryToNew($entry, "nsds5ReplicaBindDN", 0); - } - } - close(BINDDNLDIF); - # remove the ldif file after the import - unlink($ldif) ; -} - -############################################################################# -sub MigrateNSDS_replication_agreement { - foreach $replicationAgreement (@replicationAgreements) { - my $DN = $replicationAgreement->getDN(1); - if (alreadyExistsInNew($replicationAgreement)){ - # replication agreement already exists - printMsg("\n\n*** NSDS_REPLICATION_AGREEMENT - $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - &migrate_credential($replicationAgreement, "nsDS5ReplicaCredentials"); - addEntryToNew($replicationAgreement, "NSDS_REPLICATION_AGREEMENT", 1); - } - } -} - - -sub parseNSDS_replication_agreement{ - my $replicationAgreement = shift; - push @replicationAgreements, $replicationAgreement ; -} - -############################################################################# - -sub migrateChangelog5{ - my $changelog = shift; - my $DN = $changelog->getDN(1); - my $changelogdir = "nsslapd-changelogdir"; - if (alreadyExistsInNew($changelog)){ - # cn=changelog5,cn=config already exists in new - my $newChangelog = searchEntry($DN); - my @newChangelogdir = $newChangelog->getValues($changelogdir); - $changelog->setValues($changelogdir, @newChangelogdir); - updateEntry($changelog, "CHANGELOG5", 0, 1); - } - else { - # cn=changelog5,cn=config need to be created in new. - # the changelogdir value must be setup to <new_root_server>/slapd-instance/changelogdb - $changelog->setValues($changelogdir,"${serverHome}${PATHSEP}changelogdb"); - addEntryToNew($changelog, "CHANGELOG5", 1); - } -} - - -sub migrateChangelog { - my $oldchangelogdir = ""; - my $newchangelogdir = ""; - my $changelogdir = "nsslapd-changelogdir"; - my $CL5DN = "cn=changelog5,cn=config"; - printTrace("\n\n***** Migrate Changelog...",0,1); - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF); - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - if ($typeOfEntry eq "CHANGELOG5"){ - $oldchangelogdir = ($entry->getValues($changelogdir))[0]; - } - } - close(DSELDIF); - if ($oldchangelogdir) { - # If using olddatadir to migrate from, the path of the changelogdb - # from the dse.ldif may not match the path where the old server - # root was archived. We may need to modify oldchangelogdir so the - # copy of the changelog files succeeds. - unless(-e $oldchangelogdir) { - if($olddatadir) { - my @cldbpath = split(/\//,$oldchangelogdir); - until($cldbpath[0] =~/^slapd-/) { - shift(@cldbpath); - } - my $tmpcldbpath = join(${PATHSEP}, @cldbpath); - $oldchangelogdir = "$oldDir${PATHSEP}$tmpcldbpath"; - } - # If oldchangelogdir still looks to be wrong, prompt for the - # location instead of just failing on the copydir operation - # and bombing out of the migration. - unless(-e $oldchangelogdir) { - print("\n\nThe old changelog directory \"$oldchangelogdir\" doesn't exist. Please enter the correct path: "); - $oldchangelogdir = <STDIN>; - } - } - &startServer() unless (isDirectoryAlive()); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - my $newChangelog = searchEntry($CL5DN); - $newchangelogdir = ($newChangelog->getValues($changelogdir))[0]; - stopServer($root,'slapd-'.$newname); - printTrace("\ncopying $oldchangelogdir${PATHSEP}* to $newchangelogdir",3); - - # Clean destination changelog directory - opendir(NEWCLDIR, "$newchangelogdir"); - while($delfile = readdir(NEWCLDIR)) { - if ( -f "$newchangelogdir/$delfile" ) { - unlink "$newchangelogdir/$delfile" or die "Can't delete $newchangelogdir/$delfile: $!\n"; - } - } - - copyDir("$oldchangelogdir","$newchangelogdir"); - - # We need to modify the DBVERSION file for a new verision of the db - # For 6.21 to 7.0, leave it as 4.0. For 6.11 to 7.0 we want the server - # to perform the migration at startup, so set it to 3.0. - if(substr($oldMinor,0,1) < 2) { - open(DBVERSION,">$newchangelogdir${PATHSEP}DBVERSION") || die "Can't overwrite $newchangelogdir${PATHSEP}DBVERSION: $! "; - print DBVERSION "Changelog5/NSMMReplicationPlugin/3.0"; - close(DBVERSION); - } - &startServer() unless (isDirectoryAlive()); - } -} - -############################################################################# - -sub migrateReplication{ - my $replication = shift; - my $DN = $replication->getDN(1); - if (alreadyExistsInNew($replication)){ - # replication agreement already exists - printMsg("\n\n*** $DN already exists"); - printMsg("\n*** Migration will not update it"); - } - else { - addEntryToNew($replication, "REPLICATION", 1); - } -} - -############################################################################# - -sub migrateSecurity{ - my $security = shift; - if ($entry->hasValue("objectClass", "nsEncryptionConfig")) { - my $certfile = "alias/slapd-" . $newname . "-cert8.db"; - my $keyfile = "alias/slapd-" . $newname. "-key3.db"; - $entry->setValues("nsCertfile",$certfile) if ! $entry->hasValue("nsCertfile",$certfile); - $entry->setValues("nsKeyfile",$keyfile) if ! $entry->hasValue("nsKeyfile",$keyfile); - } - if (alreadyExistsInNew($security)){ - # already exists in new - updateEntry($security, "SECURITY", 0, 1); - } - else { - addEntryToNew($security, "SECURITY", 1); - } -} - -############################################################################# - -sub migrateSNMP{ - my $snmp = shift; - if (alreadyExistsInNew($snmp)){ - # already exists in new - updateEntry($snmp, "SNMP", 0, 1); - } - else { - addEntryToNew($snmp, "SNMP", 1); - } -} - -############################################################################# -# printMsg print message to the user standard output. - -sub printMsg { - - my $TypeMsg = shift ; - my $Msg = shift ; - my $LineNb = shift ; - if ($LineNb) { - printTrace("Line: $LineNb, $TypeMsg, $Msg"); - } - else { - printTrace("$TypeMsg $Msg"); - } -} - -############################################################################# -# print message error to the user standard output. - -sub printTrace { - - my $Msg = shift ; - my $level = shift ; - my $sep = shift ; - - if ($sep) { - print "\n-------------------------------------------------------------------------"; - print LOGFILE "\n-------------------------------------------------------------------------"; - } - - if ($level <= $TRACELEVEL) { - print($Msg); - print LOGFILE $Msg ; - } -} - -############################################################################# -# this subroutine implements a very stupid version of diff - -sub diff { - my $f1 = shift; - my $f2 = shift; - my $lineToBeginWith = shift; - my $NULL = "" ; - my $diff_f1 = $NULL ; - my $diff_f2 = $NULL ; - my $retval = $NULL ; - my $ret; - open(F1, "$f1") or die "Could not open file $f1"; - open(F2, "$f2") or close(F1), die "Could not open file $f2"; - - while (defined($l1 = <F1>)) { - if ($lineToBeginWith){ - $lineToBeginWith -- ; - next ; - } - next if ($l1 =~ /^\#/); - $ret = defined($l2 = <F2>); - if ($ret) { - $ret = defined($l2 = <F2>) while ($ret && ($l2 =~ /^\#/)) ; - if ($ret) { - if (!($l1 eq $l2)) { - - # ignore whitespace - $l1_clean = $l1 ; - $l2_clean = $l2 ; - $l1_clean =~ s/\s//g; - $l2_clean =~ s/\s//g; - - if (!($l1_clean eq $l2_clean)) { - $diff_f1 .= "${l1}" unless ($l1_clean eq $NULL); - $diff_f2 .= "${l2}" unless ($l2_clean eq $NULL); - } - } - } - else { - next if ($l1 =~ /^\s*$/) ; - $diff_f1 .= "${l1}"; - } - } - else { - next if ($l1 =~ /^\s*$/) ; - $diff_f1 .= "${l1}"; - } - } - - while (defined($l2 = <F2>)) { - if (($l2 =~ /^\#/) || ($l2 =~ /^\s*$/)) { - next ; - } - else { - $diff_f2 .= "${l2}" ; - } - } - - close(F1); - close(F2); - - $retval .= "- differences present in your config file but not in standard file:\n\n". "$diff_f1\n" if ($diff_f1) ; - $retval .= "- differences present in standard file but not in your config file:\n\n" . "$diff_f2" if ($diff_f2) ; - return $retval ; -} - -sub CompareStdConfigFiles { - # Compare each configuration file against its default version. If it has changed, - # notify the user that the file has changed and will need to be checked by the - # user. This should be safe to do because there should be no path information - # stored in these conf files, which are just schema stuff. - # printTrace("\nCheck if standard configuration files have changed",3); - - # get the version of the DS to migrate - ($oldVersion, $oldMinor) = &getVersion($oldDir, $oldversionstr); - # get the version of the new DS - ($Version, $Minor) = &getVersion($root); - - # get old LIB_PATH - $old_libpath = &getLibPath($oldDir, $oldVersion, $oldMinor); - # get new LIB_PATH - $new_libpath = &getLibPath($root, $Version, $Minor); - - my $origFilePath = "$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}install${PATHSEP}schema${PATHSEP}" ; - my $FilesChanged = ""; - my $AllDiffs = "***********************************************************************"; - my $NoChanges = "" ; - my $lineToBegin = 0 ; - opendir(CONFDIR, $oldSchemaDir) or - die "Error: could not open migrated config dir $oldConfDir: $!"; - - foreach $file (readdir(CONFDIR)) { - $origFile = $origFilePath . $file ; - $configFile = $oldSchemaDir . $file ; - if (( exists($stdIncludes{lc($file)})) && (-f $origFile)) { - $diffs = &diff($configFile, $origFile, $lineToBegin); - $lineToBegin = 0 if $lineToBegin ; - if ($diffs) { - $FilesChanged .= "\n$configFile"; - $AllDiffs .= "\n$configFile is different than the standard configuration file" ; - $AllDiffs .= "\nYou will need to check this file and make sure its changes are compatible "; - $AllDiffs .= "with the new directory server\nHere are the differences:\n"; - $AllDiffs .= "$diffs \n\n"; - $AllDiffs .= "***********************************************************************"; - } - else { - $NoChanges .= "\n$configFile"; - } - } - } - closedir(CONFDIR); - -if ($FilesChanged) { - printTrace("\nNo changes to old configuration files:$NoChanges",3) ; - printTrace("\n***********************************************************************",3) ; - printMsg("\nThe following standard files have been modified: $FilesChanged"); - if ($NO_INPUT_USER) { - # do nothing - } - else { - printMsg("\nDo you want to see the differences Yes/No [No] ?") ; - my $answer = <STDIN> ; - if ($answer =~ /y|yes/i) { - printMsg("$AllDiffs"); - } - printMsg("\nDo you want to continue the migration Yes/No [No] ?"); - $answer = <STDIN> ; - if (! ($answer =~ /y|yes/i)) { - exit(1); - } - } - } -} - - - -############################################################################# - -# this is used to run the system() call, capture exit and signal codes, -# and die() upon badness; the first argument is a directory to change -# dir to, if any, and the rest are passed to system() -sub mySystem { - my $rc = &mySystemNoDie(@_); - my ($dir, @args) = @_; - if ($rc == 0) { -# success - } elsif ($rc == 0xff00) { - die "Error executing @args: error code $rc: $!"; - } elsif ($rc > 0x80) { - $rc >>= 8; - die "Error executing @args: error code $rc: $!"; - } else { - if ($rc & 0x80) { - $rc &= ~0x80; - } - die "Error executing @args: received signal $rc: $!"; - } - - # usually won't get return value - return $rc; -} - -# This version does not die but just returns the error code -sub mySystemNoDie { - my ($dir, @args) = @_; - if ($dir && ($dir ne "")) { - chdir($dir) or die "Could not change directory to $dir: $!"; - } - my $cmd = $args[0]; - # the system {$cmd} avoids some NT shell quoting problems if the $cmd - # needs to be quoted e.g. contains spaces; the map puts double quotes - # around the arguments on NT which are stripped by the command - # interpreter cmd.exe; but don't quote things which are already quoted - my @fixargs = map { /^[\"].*[\"]$/ ? $_ : $quote . $_ . $quote } @args; - my $rc = 0; - if ($cmd =~ /[.](bat|cmd)$/) { - # we have to pass batch files directly to the NT command interpreter - $cmd = $com_spec; -# print "system $cmd /c \"@fixargs\"\n"; - $rc = 0xffff & system {$cmd} '/c', "\"@fixargs\""; - } else { -# print "system $cmd @fixargs\n"; - $rc = 0xffff & system {$cmd} @fixargs; - } - chdir(${curdir}) or die "Could not change directory to $curdir: $!"; - return $rc; -} - -########################################################################################### -# # -# Export/Import of the backends in @BACKENDS # -# # -########################################################################################### - -sub manydb2Ldif { - my $ldif_dir = shift; - $ENV{"$LIB_PATH"}=$old_libpath; - if (! $ldif_dir) { $ldif_dir = $ldif_rep ;} - if (!(-d $ldif_dir)) { - mkdir($ldif_dir,0777) or die "can't create $ldif_dir to store temporary ldif files"; - } - chdir($oldSlapdExecDir) or die "Could not change directory to $oldSlapdExecDir: $!"; - foreach $backend (@BACKENDS) { - my $ldif = "${ldif_dir}$backend.ldif" ; - &db2Ldif($ldif, $backend, $oldHome); - } - print " Done.\n"; - chdir($curdir) or die "Could not change directory to $curdir: $!"; -} - -sub db2Ldif { - my $ldif = shift ; - my $backend = shift ; - my $home = shift ; - my $include_suffix = shift ; - my $db2ldif_param ; - if ($include_suffix) { - $db2ldif_param = "db2ldif -r -D $home -n $backend -a $ldif -s \"$include_suffix\""; - } - else { - $db2ldif_param = "db2ldif -r -D $home -n $backend -a $ldif"; - } - open(DB2LDIF, "${quote}${quote}$slapdExecName${quote} $db2ldif_param${quote} 2>&1 |") or die "Could not run ns-slapd program $ldif2db_exe\n"; - sleep(1); # allow some data to accumulate in the pipe - my $ii = 0; - while (<DB2LDIF>) { - ++$ii; - if (($ii % 250) == 0) { - printMsg(" Processing...\n"); - } - printMsg($_); - } - close(DB2LDIF); - # set the ownership of the ldif file; should be the same as the 6.x slapd user id - if ((! $isNt) && ($oldlocaluser ne $localuser)) { - if (-f $ldif) { - chown( $newuid, $newgid, $ldif) or printMsg("\nUnable to change the ownership of $ldif to $localuser") ; - } - } -} - -sub manyLdif2db { - my $ldif_dir = shift; - $ENV{"$LIB_PATH"}=$new_libpath; - chdir($slapdExecDir) or die "Could not change directory to $slapdExecDir: $!"; - foreach $backend (@BACKENDS) { - my $ldif = "${ldif_dir}$backend.ldif" ; - &Ldif2db($ldif, $backend); - } - # remove the empty ldif directory - # but not if using the data dir - if (!$olddatadir) { - rmdir($ldif_dir); - } - chdir($curdir) or die "Could not change directory to $curdir: $!"; -} - - -sub Ldif2db { - my $ldif = shift ; - my $backend = shift ; - my $ldif2db_param = "ldif2db -D $serverHome -n $backend -i $ldif"; - open(LDIF2DB, "${quote}${quote}$slapdExecName${quote} $ldif2db_param${quote} 2>&1 |") or die "Could not run ns-slapd program $ldif2db_exe\n"; - sleep(1); # allow some data to accumulate in the pipe - while (<LDIF2DB>) { - printMsg($_); - } - close(LDIF2DB); - # remove the ldif file after the import - # but not if using the data dir - if (!$olddatadir) { - unlink($ldif) ; - } -} - - -########################################################################################### -# # -# Running/Stopping the Server # -# # -########################################################################################### - - - -sub isDirectoryAlive { - die "\n Migration aborted. Make sure your old and new Directory Servers are installed on the same machine \n" if ( $LDAPservername == -1 ); - my $test_conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd); - if ($test_conn) { - $test_conn->close(); - return 1; - } - else { - return 0 ; - } -} - - -sub startServer { - my $instanceDir = ${serverHome} ; - my $errLog = $instanceDir . $PATHSEP . 'logs' . $PATHSEP . 'errors'; - # emulate tail -f - # if the last line we see does not contain "slapd started", try again - my $done = 0; - my $started = 0; - my $code = 0; - my $lastLine = ""; - my $timeout = time + 240; # 4 minutes - $ENV{"$LIB_PATH"}=$new_libpath; - - my $startCmd = $instanceDir . $PATHSEP . 'start' . $script_suffix; - if (! -f $startCmd) { - $startCmd = $instanceDir . $PATHSEP . 'start-slapd' . $script_suffix; - } - $code = &mySystem($instanceDir,$startCmd); - open(IN, $errLog) or die "Could not open error log $errLog: $!"; - my $pos = tell(IN); - while (($done == 0) && (time < $timeout)) { - for (; ($done == 0) && ($_ = <IN>); $pos = tell(IN)) { - $lastLine = $_; - # print; - # the server has already been started and shutdown once . . . - if (/slapd started\./) { - $started++; - if ($started == 2) { - $done = 1; - } - # sometimes the server will fail to come up; in that case, restart it - } elsif (/Initialization Failed/) { - # print "Server failed to start: $_"; - $code = &mySystem($instanceDir, $startCmd); - # sometimes the server will fail to come up; in that case, restart it - } elsif (/exiting\./) { - # print "Server failed to start: $_"; - #$code = &mySystem($startCmd); - $code = &mySystem($instanceDir, $startCmd); - } - } - if ($lastLine =~ /PR_Bind/) { - # server port conflicts with another one, just report and punt - print $lastLine; - print "This server cannot be started until the other server on this\n"; - print "port is shutdown.\n"; - $done = 1; - } - if ($done == 0) { - # rest a bit, then . . . - sleep(2); - # . . . reset the EOF status of the file desc - seek(IN, $pos, 0); - } - } - close(IN); - - sleep(5); - die "\nUnable to start the $Version.$Minor Directory Server\n" unless (isDirectoryAlive()); - - return 0; -} - -sub stopServer { - my $root = shift; - my $name = shift; - $maxStopIterations = 5; - print "\nShutting down server $name . . .\n"; - $ENV{"$LIB_PATH"}=$new_libpath; - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop' . $script_suffix . $quote; - if (! -f $stopCmd) { - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop-slapd' . $script_suffix . $quote; - } - - if (! -f $stopCmd) { - # no stop command, probably a 1.X system; for NT, we'll try net stop - # for unix, we'll get the pid and kill it - if ($isNT) { - $stopCmd = 'net stop ' . $name; - } else { - # see if there is a pid file - $pidfile = $root . $PATHSEP . $name . $PATHSEP . 'logs' . - $PATHSEP . 'pid'; - if (open(PIDFILE, $pidfile)) { - chomp($pid = <PIDFILE>); - close(PIDFILE); - while ($maxStopIterations-- && !$exitCode) { - $exitCode = kill(15, $pid); - } - $stopCmd = undef; - } - } - } - - # keep looping until the stop cmd returns an error code, which usually - # means that what ever we want to stop is stopped, or some other error - # occurred e.g. permission, or no such service - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - while ($stopCmd && $maxStopIterations-- && $exitCode) { - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - } - - if (!$maxStopIterations) { - print "Warning: could not shutdown the server: $!\n"; - } - sleep(10) ; - $exitCode = 0; -} - - -sub runAndIgnoreOutput { - my $cmd = shift; - printMsg("."); - open(RUNCMD, "${quote}$cmd${quote} 2>&1 |") or die "Error: could not run $cmd: $!"; - printMsg("."); - sleep(1); # allow pipe to fill with data - printMsg("."); - while (<RUNCMD>) { -# print; - } - my $code = close(RUNCMD); -# print "runAndIgnore: code=$code status=$?\n"; - return $?; -} - -############################################################################# -# migrate SSL info - -sub MigrateSSL { - my $secPwd = 'bidon' ; - # copy the SSL directory - ©Dir("$oldHome${PATHSEP}ssl","$serverHome${PATHSEP}ssl") if (-d "$oldHome${PATHSEP}ssl"); - # copy the cert db and key files - if ( -d "$oldDir${PATHSEP}alias") { - $aliasDir = "$root${PATHSEP}alias"; - if (! -d $aliasDir) { - mkdir($aliasDir, 0750); - } - &stopServer($root,'slapd-'.$newname) if (isDirectoryAlive()); - - my $old_certdb_ver = (substr($oldMinor,0,1) >= 2) ? "8" : "7"; - my $keydb = "$aliasDir${PATHSEP}slapd-$newname-key3.db" ; - my $certdb = "$aliasDir${PATHSEP}slapd-$newname-cert8.db" ; - my $certdb_target = "$aliasDir${PATHSEP}slapd-$newname-cert${old_certdb_ver}.db" ; - my $old_keydb = "$oldDir${PATHSEP}alias${PATHSEP}slapd-$oldname-key3.db" ; - my $old_certdb = "$oldDir${PATHSEP}alias${PATHSEP}slapd-$oldname-cert${old_certdb_ver}.db"; - - my $keydb_backup = "$aliasDir${PATHSEP}slapd-$newname-key3.db_backup" ; - my $certdb_backup = "$aliasDir${PATHSEP}slapd-$newname-cert7.db_backup" ; - if (-f $old_keydb) { - if (-f $keydb) { - if ($NO_INPUT_USER) { - printMsg("\n$keydb already exists. backup in $keydb_backup ..."); - ©BinFile($keydb,$keydb_backup); - ©BinFile($old_keydb,$keydb); - } - else { - print("\n\n$keydb already exists. Do you want to overwrite it ? [no]: "); - my $answer = <STDIN> ; - if ($answer =~ /^y|yes$/i) { - ©BinFile($old_keydb,$keydb); - } - } - } - else { - ©BinFile($old_keydb,$keydb); - } - } - if (-f $old_certdb) { - $mode = (stat($old_certdb))[2] if $PRESERVE; - if (-f $certdb) { - if ($NO_INPUT_USER) { - printMsg("\n$certdb already exists. backup in $certdb_backup ..."); - ©BinFile($certdb,$certdb_backup); - unlink($certdb) || print "Couldn't delete $certdb : $!\n"; - ©BinFile($old_certdb,$certdb_target); - } - else { - print("\n\n$certdb already exists. Do you want to overwrite it ? [no]: "); - my $answer = <STDIN> ; - if ($answer =~ /^y|yes$/i) { - unlink($certdb) || print "Couldn't delete $certdb : $!\n"; - ©BinFile($old_certdb,$certdb_target); - } - } - } - else { - ©BinFile($old_certdb,$certdb_target); - } - } - # copy the old password file - if (-f "$oldDir${PATHSEP}alias${PATHSEP}$type-$oldname-pin.txt") { - ©BinFile( - "$oldDir${PATHSEP}alias${PATHSEP}$type-$oldname-pin.txt", - "$aliasDir${PATHSEP}$type-$newname-pin.txt" - ); - } - &startServer(); - if ($PRESERVE && $old_certdb_ver == 7) { - chown($newuid,$newgid,$certdb) || print "Failed to set uid $newuid gid $newgid on $certdb : $!\n"; - chmod($mode,$certdb) || print "Failed to set mode $mode on $certdb : $!\n"; - } - } - -} - -sub DisableSSL { - my $entry = $conn->search("cn=config","base","objectclass=*"); - my $LDAPparam = "nsslapd-security" ; - my $Value = "off" ; - if ($entry->{$LDAPparam}[0] ne $Value) { - printTrace("\nDisable SSL...",1); - $entry->setValues($LDAPparam, $Value); - } - my $res = $conn->update($entry); - if ($res) { - printTrace("\nSSL disabled",2); - } - else { - printMsg("\nCan't disabled SSL. The server may have problems to start"); - } -} - -# enable the migration of client authentication informations -sub MigrateCertmap { - # backup the old certmap.conf and replace it with the new one - my $oldCertmap = "$oldDir${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf"; - my $newCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf" ; - my $backupCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf_backup" ; - if (-f $oldCertmap) { - if ($NO_INPUT_USER) { - printMsg("\n$newCertmap has been backup in $backupCertmap"); - ©BinFile($newCertmap,$backupCertmap); - ©BinFile($oldCertmap,$newCertmap); - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\n\nWhere do you want to back up the file $newCertmap [$backupCertmap] ?") ; - my $Answer = <STDIN> ; - $backupCertmap = $Answer if ($Answer ne "\n"); - chomp($backupCertmap); - printTrace("\nDest: .$backupCertmap.",4); - if (-e $backupCertmap) { - printMsg("\n\n$backupCertmap already exists. Do you want to overwrite it Yes/No [No] ?") ; - if (<STDIN> =~ /yes|y/i) { - $Ask = 0 ; - } - else { - $backupCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf_backup" ; - } - } - else { - $Ask = 0 ; - } - } - printTrace("\nBackup file: $newCertmap in $backupCertmap",4); - ©BinFile($newCertmap,$backupCertmap); - ©BinFile($oldCertmap,$newCertmap); - } - } - else { - } -} - -sub hasChangedoldCertmap { - my $certmapfile = shift ; - my @reference = ("certmap default default", - "default:DNComps", - "default:FilterComps e") ; - my $cpt = 0 ; - printTrace("\nhasChangedoldCertmap",3); - open(CERTMAP,"< $certmapfile"); - while (<CERTMAP>) { - if ((! /^\s*#/) && (! /^\s*$/)) { - my $ref = $reference[$cpt] ; - printTrace("\nValue: $_, ref: $ref",4); - if (! /^\s*$ref\s*$/) { - return 1 ; - } - else { - $cpt++ ; - } - } - } - close (CERTMAP); - printTrace("\ncpt: $cpt",4); - if ($cpt < $#reference) { - return 1 ; - } - else { - return 0 ; - } -} - - -########################################################################################### -# # -# Copy directory and files functions # -# # -########################################################################################### - - -sub copyDir { - my $src = shift; - my $dest = shift; - my $exclude = shift; - - opendir( SRC, $src ) or die "Can't open directory $src: $!: "; - my $mode; - my $uid; - my $gid; - mkdir ( $dest , 0755 ) or die "\nCan't create directory $dest. \nPlease check you have enough rights to create it and/or check that your parent directory exists.\n" if !( -e $dest ); - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - local ( @files ) = readdir ( SRC ); - closedir( SRC ); - for ( @files ) { - if ( $_ eq "." || $_ eq ".." ) { - next; - } elsif ( $exclude && /$exclude/ ) { - next; - } elsif ( $_ =~ /^__/ ) { - # region files are incompatible between 32 - # and 64 bit servers - next; - } elsif( -d "$src${PATHSEP}$_") { - ©Dir ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_" ); - } else { - ©BinFile ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_"); - } - } -} - -sub copyBinFile { - my $src = shift; - my $dest = shift; - my $buf = ""; - my $bufsize = 8192; - - open( SRC, $src ) || die "Can't open $src: $!\n"; - # if we are given a directory destination instead of a file, extract the - # filename portion of the source to use as the destination filename - if (-d $dest) { - $dest = $dest . $PATHSEP . &basename($src); - } - open( DEST, ">$dest" ) || die "Can't create $dest: $!\n"; - binmode SRC; - binmode DEST; - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - while (read(SRC, $buf, $bufsize)) { - print DEST $buf; - } - close( SRC ); - close( DEST ); -} - -############################################################################################################# -# backup 6.x configuration files # -# backup the directory <root_server5>/slapd-instance/config dans <root_server5>/slapd-instance/BackupConfig # # -# # -############################################################################################################# - - -sub backupConfigFiles { - # backup the 6.x config files - my $src = "$serverHome${PATHSEP}config" ; - my $dest = "$serverHome${PATHSEP}config_backup" ; - if ($NO_INPUT_USER) { - printMsg("\n$src has been backup in $dest"); - ©Dir($src,$dest); - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\n\nWhere do you want to back up your configuration directory [$dest] ?") ; - my $Answer = <STDIN> ; - $dest = $Answer if ($Answer ne "\n"); - chomp($dest); - printTrace("\nDest: .$dest.",4); - if (-e $dest) { - printMsg("\n\n$dest already exists. Do you want to overwrite it Yes/No [No] ?") ; - if (<STDIN> =~ /yes|y/i) { - $Ask = 0 ; - } - else { - $dest = "$serverHome${PATHSEP}config_backup" ; - } - } - else { - $Ask = 0 ; - } - } - printTrace("\nBackup Directory: $src in $dest",4); - ©Dir($src,$dest); - } -} -############################################################################# - -sub getLDAPservername { - my $oldLDAPservername; - my $LDAPservername; - my $localhost = "nsslapd-localhost"; - open(OLDDSELDIF, "< $oldDSEldif") or die "\nError: could not open old config file $oldDSEldif \n"; - my $in = new Mozilla::LDAP::LDIF(*OLDDSELDIF) ; - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN(1) ; - if ($DN =~ /^cn=config$/i) { - my @values = $entry->getValues($localhost); - if ($entry->size($localhost)) { - $oldLDAPservername = $values[0]; - printTrace("\nName of the old LDAP server: $oldLDAPservername",3); - } - break; - } - } - close(OLDSELDIF); - - open( DSELDIF, "< $DSEldif" ) || die "\nCan't open $DSEldif \n"; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN(1) ; - if ($DN =~ /^cn=config$/i) { - my @values = $entry->getValues($localhost); - if ($entry->size($localhost)) { - $LDAPservername = $values[0]; - printTrace("\nName of the new LDAP server: $LDAPservername",3); - } - break; - } - } - close(DSELDIF); - # check ol and new Directory Instance are installed on the same physical machine. - if (lc($oldLDAPservername) ne lc($LDAPservername)) { - # warn the user he tries to migrate a 4.x server installed on a different machine from the 6.x one - printMsg("\n\nYour old instance is on $oldLDAPservername, whereas your new instance is on $LDAPservername. Migration on different machines is not supported. Do you want to continue ? Yes/No [No]:") ; - if (! (<STDIN> =~ /yes|y/i)) { - return -1; - } - } - return $LDAPservername ; -} - -############################################################################# - -sub getLibPath { - my $myDir = shift; - my $myVersion = shift; - my $myMinor = shift; - - if ($isNT) { - return $ENV{"$LIB_PATH"}; - } - if (($myVersion >= 6) && ($myMinor >= 2)) { - return - "$myDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$myDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - } else { - return "$myDir${PATHSEP}lib${SEP}".$ENV{"$LIB_PATH"}; - } -} - -############################################################################# - -sub getVersion { - my $dir = shift; - my $versionstr = shift; - my $version = 0; - my $minor = 0; - my $buildNumber = 0; - my $progDir = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - my $progDir2 = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}"; - - # find the slapd executable - if (!$versionstr) { # version not specified on cmd line - find it - $prog = $dir . $progDir . $slapdExecName; - if (! -f $prog) { - $prog = $dir . $progDir2 . $slapdExecName; - if (-f $prog && $isNT) { - # if slapd is in bin/slapd and we're on NT, just assume version 1; - # apparently, slapd.exe doesn't like the -v argument . . . - return ( '1', $minor ); - } - else{ - die "Could not run slapd program $prog: $!"; - } - } - else { - chdir($dir . $progDir); - } - $cur_libpath=$ENV{"$LIB_PATH"}; - $ENV{"$LIB_PATH"}= - "$dir${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - # read the old version from the old slapd program - - open(F, "${quote}${quote}$prog${quote} -v${quote} 2>&1 |") or - die "Could not run slapd program $prog: $!"; - sleep(1); # allow some data to accumulate in the pipe -# print "Output from $prog -v:\n"; - while (<F>) { - if (/^Red Hat-Directory/ || /^Netscape-Directory/ || /^iPlanet-Directory/i) { - $versionstr = $_; - last; - } - } - $code = close(F); - # print "$prog returned code=$code status=$?\n"; - $ENV{"$LIB_PATH"}=$cur_libpath; - } - - if ($versionstr =~ /^Red Hat-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\(restrict?ed-mode\)\/(\d+)\.(\d+)\s+(\S+)/) { # we can have restricted-mode or restriced-mode ... - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^iPlanet-Directory\/(\d+)\.(\d+)\s+(\S+)/i) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } elsif ($versionstr =~ /(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - } - - if ($version == 0) { - die "\nCould not determine version of the directory server in $dir: \n"; - } - - # distinguish the 4.1 and the 4.11 thanks to the buildNumber - if (($version == 4) && ($minor == 1)){ - if (! ($buildNumber =~ /^B99\.16/)) { - # it's not a 4.1 Netscape Directory Server => it's a 4.11 - $minor = 11 ; - } - } - chdir($curdir) or die "Could not change directory to $curdir: $!" ; - return ( $version, $minor ); -} - -############################################################################################### -sub normalizeDir { - my $dir = shift ; - my $dir_prec = "" ; - while ($dir_prec ne $dir) { - $dir_prec = $dir ; - if ($isNT) { - grep { s@\\\\@\\@g } $dir ; - } - else { - grep { s@//@/@g } $dir ; - } - } - return $dir ; -} - - -############################################################################################### - -sub GetTime { - my $tm = localtime; - (my $sec, my $min, my $hour, my $dd, my $mm, my $yy) = ($tm->sec, $tm->min, $tm->hour, $tm->mday, ($tm->mon)+1, ($tm->year)+1900); - $sec = "0$sec" unless $sec > 9 ; - $min = "0$min" unless $min > 9 ; - $hour = "0$hour" unless $hour > 9 ; - $dd = "0$dd" unless $dd > 9 ; - $mm = "0$mm" unless $mm > 9 ; - return ($sec, $min, $hour, $dd, $mm, $yy); -} - -############################################################################################### -# get uid and group id of the 6.x slapd server. -# The uid is done through the nsslapd-localuser attribute - -sub getuid_gid { - my $newuid ; - my $newgid ; - my $localuser ; - my $localuser_attr = "nsslapd-localuser" ; - if (! $isNT) { - &startServer() unless (isDirectoryAlive()); - my $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Can't contact the $Version.$Minor LDAP server: $LDAPservername\n"; - my $entry = $conn->search("cn=config ", "base","objectclass=*", 0, ($localuser_attr)) ; - # Tests wether we succeed to get the entry cn=config - die "\nCan't get the entry cn=config \n" unless ($entry); - my @values = $entry->getValues($localuser_attr); - $conn->close(); - if ($#values == -1 || ($values[0] eq "") ) { # tests wether the nsslapd-localuser attribute has a value - printMsg("\nNo localuser has been found in the configuration of the directory. "); - if ($NO_INPUT_USER) { - printMsg("\nWe considered nobody as the localuser"); - $localuser = "nobody" ; - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\nUnder what user does your $Version.$Minor directory server run [nobody] ? ") ; - $localuser = <STDIN> ; - chomp($localuser); - $localuser = "nobody" if ($localuser eq ""); - ($newuid, $newgid) = (getpwnam("$localuser"))[2..3] ; - if ($newuid) { - $Ask = 0 ; - } - else { - printMsg("\nError: $localuser is unknown from the system "); - } - } - } - } - else { - $localuser = $values[0]; # returns the first value (we should only have one localuser) - my $size = $#values ; - } - ($newuid, $newgid) = (getpwnam("$localuser"))[2..3] ; - return ($localuser, $newuid, $newgid) ; - } - else { - return () ; - } -} - -sub getolduid_gid { - my $oldlocaluser ; - my $localuserAttr = "nsslapd-localuser"; - my $entry ; - if (! $isNT) { - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - $typeOfEntry = getTypeOfEntry($entry); - if ($typeOfEntry eq "CONFIG_NODE") { - $oldlocaluser = $entry->{$localuserAttr}[0] if ($entry->exists($localuserAttr)); - break ; - } - } - close(DSE); - ($olduid, $oldgid) = (getpwnam("$oldlocaluser"))[2..3] ; - return ($oldlocaluser, $olduid, $oldgid) ; - } - else { - return (); - } -} -############################################################################################### -# get current directory - -sub getCwd { - my $command = $isNT ? "cd" : "/bin/pwd"; - open(PWDCMD, "$command 2>&1 |") or - die "Error: could not execute $command: $!"; - # without the following sleep, reading from the pipe will - # return nothing; I guess it gives the pwd command time - # to get some data to read . . . - sleep(1); - my $currentdir; - while (<PWDCMD>) { - if (!$currentdir) { - chomp($currentdir = $_); - } - } - my $code = close(PWDCMD); -# if ($code || $?) { -# print "$command returned code=$code status=$? dir=$curdir\n"; -# } -# print "getCwd curdir=\[$curdir\]\n"; - return $currentdir; -} - -################################ -# Need to migrate the credential. -# If the credential can not be migrated, leave it at it is -################################ -sub migrate_credential{ - my $entry_to_modify = shift; - my $credentials_attr = shift; - my @old_value = $entry_to_modify->getValues($credentials_attr); - my $migratecredExecName = 'migratecred'; - my $credOldHome = $oldHome; - my $credServerHome = $serverHome; - - if ($isNT) { - # oldHome may be pointing to the archived copy of the - # instance dir which may be different than the path that - # the instance was originally installed as on Windows. If - # this path is not the original install path, then the - # credential will not be migrated correctly. We should - # prompt the user on Windows for the correct path. - - print "\n\nThe old instance path must be the same as where it was"; - print "\ninitially installed, not where it was archived in order"; - print "\nfor this step to succeed. Please verify that the path"; - print "\nis correct. Note that case sensitivity is important here."; - print "\n\nOld Instance Directory: $credOldHome"; - print "\nIs this correct? (y/n): "; - chomp(my $answer = <STDIN>); - if (!($answer =~ /y|yes/i)) { - print "\nPlease enter the correct path for the old instance directory: "; - chomp($credOldHome = <STDIN>); - } - - print "\n\nThe new instance path must also be correct for this step"; - print "\nto succeed. Please verify that the path is correct. Note"; - print "\nthat case sensitivity is important here."; - print "\n\nNew Instance Directory: $credServerHome"; - print "\nIs this correct? (y/n): "; - chomp(my $answer = <STDIN>); - if (!($answer =~ /y|yes/i)) { - print "\nPlease enter the correct path for the new instance directory: "; - chomp($credServerHome = <STDIN>); - } - } - - my $cur_dir = getCwd(); - my $migratecreddir = "${quote}$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - chdir(${migratecreddir}) or die "Could not change directory to $migratecreddir: $!"; - -# print "\nMigratecred command is: ${quote}$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}$migratecredExecName${quote} -o $credOldHome -n $credServerHome -c @old_value\n"; - - my @new_cred = `${quote}$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}$migratecredExecName${quote} -o $credOldHome -n $credServerHome -c @old_value`; - - chdir(${cur_dir}) or die "Could not change directory back to $cur_dir: $!"; - - if ( $? == 0 ) - { - $entry_to_modify->setValues($credentials_attr, @new_cred); - } -} - diff --git a/ldap/admin/src/scripts/template-migrateInstance7 b/ldap/admin/src/scripts/template-migrateInstance7 deleted file mode 100644 index acc0e987..00000000 --- a/ldap/admin/src/scripts/template-migrateInstance7 +++ /dev/null @@ -1,586 +0,0 @@ -#{{PERL-EXEC}} -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# -use Time::localtime; - -BEGIN { - require 'uname.lib'; - $| = 1; - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - $SEP = $isNT ? ";" : ":" ; - $exitCode = 0; - @INC = ( '.', '../../../admin/admin/bin'); - grep { s@/@\\@g } @INC if $isNT; - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; - if ($isNT) { - # we have to pass batch files directly to the NT command interpreter - $com_spec = $ENV{ComSpec}; - if (!$com_spec) { - $com_spec = $ENV{COMSPEC}; - } - if (!$com_spec || ! -f $com_spec) { - # find the first available command interpreter - foreach $drive (c..z) { - $com_spec = "$drive:\\winnt\\system32\\cmd.exe"; - last if (-f $com_spec); - $com_spec = undef; - } - if (! $com_spec) { - # punt and pray - $com_spec = 'c:\winnt\system32\cmd.exe'; - } - } - $os = "WINNT"; - } else { - $os = &uname("-s"); - if ($os eq "SunOS") { - $isSolaris9 = ( &uname("-r") eq "5.9" ); - } - } - - if ( ($os eq "AIX") || ($os eq "HP-UX") ) { - $sigChildHandler = 'sigChildHandler'; - } - SWITCH: { - if ($os eq "AIX") { - $LIB_PATH = "LIBPATH" ; - last SWITCH ; - } - if ($os eq "HP-UX") { - $LIB_PATH = "SHLIB_PATH" ; - last SWITCH ; - } - if ($isNT) { - $LIB_PATH = "PATH" ; - last SWITCH ; - } - else { - $LIB_PATH = "LD_LIBRARY_PATH" ; - last SWITCH ; - } - } - $slapdExecName = $isNT ? 'slapd.exe' : 'ns-slapd'; - select STDERR; - $| = 1; - select STDOUT; - $| = 1; -} - - - -$TRACELEVEL = 0; -${root} = "{{DS-ROOT}}" ; -${type} = "" ; -${newname} = "" ; -${newport} = "" ; -${rootDN} = "" ; -${rootpwd} = "" ; -${localhost} = "" ; -${LogFileReport} = "" ; - -# get input users -&getParameters() ; - - -${oldHome} = "${oldDir}${PATHSEP}$type-$oldname" ; -${oldConfDir} = "${oldHome}${PATHSEP}config${PATHSEP}" ; -${oldSlapdConf} = "${oldConfDir}slapd.conf" ; -${serverHome} = "${root}${PATHSEP}$type-$newname" ; -${ldif_rep} = "${oldConfDir}ldif${PATHSEP}" ; -${curdir} = getCwd(); - - -if (!(-d $serverHome)) { - print("\n$serverHome doesn't exist\n"); - exit(1); - } - if (!(-d $oldHome)) { - print("\n$oldHome doesn't exist\n"); - exit(1); - } -if ($olddatadir && !(-d $olddatadir)) { - print("\n$olddatadir doesn't exist\n"); - exit(1); - } -$ENV{"$LIB_PATH"} = "$root${PATHSEP}lib${SEP}".$ENV{"$LIB_PATH"} ; - -# get the version of the DS to migrate -($oldVersion, $oldMinor) = &getVersion($oldDir, $oldversionstr); -# get the version of the new DS -($Version, $Minor) = &getVersion($root); - -if ($Version >= 7) { - if ($oldVersion == 4) { - $myscript = "migrateTo7" ; - printMsg("\n******* Migration from $oldVersion.$oldMinor to $Version.$Minor Directory Server *********\n"); - } - elsif ($oldVersion == 5 ) { - printMsg("\nWarning. You may experience some problems if the version of directory server you want to migrate is not a 5.0 or 5.1") if ($oldMinor > 1); - $myscript = "migrate5to7" ; - printMsg("\n******* Migration from $oldVersion.$oldMinor to $Version.$Minor Directory Server *********\n"); - } - elsif ($oldVersion == 6 ) { - $myscript = "migrate6to7" ; - printMsg("\n******* Migration from $oldVersion.$oldMinor to $Version.$Minor Directory Server *********\n"); - } - else { - - die "We don't support the version of directory server you want to migrate"; - } -} -else { - die "\n\nThe version of directory you want to upgrade is not a 7.x product\nMigration aborted\n"; -} - -my $start_time = gmtime ; -@args = ($^X, $myscript, @ARGV, '-L', $LogFileReport); -$exitCode = &mySystem(@args); -#die "Error: @args: $!" if ($exitCode != 0); - -open(LOGFILE,">> $LogFileReport") or die "\nCan't write to $LogFileReport\n$!\n"; -if (! $exitCode) { - my $end_time = gmtime ; - printMsg("-> Migration started at $start_time\n"); - printMsg("-> Migration ended at $end_time\n\n"); -} -printMsg("***********************************************\n\n"); -print("-> The migration report file is available at: $LogFileReport\n\n"); - -close(LOGFILE); - -####################################################################################################################### -sub usage { - print(STDERR "\nUsage: $0 -D rootdn { -w password | -w - | -j filename } -p port \n"); - print(STDERR " -o oldInstancePath -n newInstancePath [-t tracelevel] \n"); - print(STDERR " [-L logfile] [-noinput]\n"); - print(STDERR "************** parameters in brackets are optionals, others are required **************\n"); - print(STDERR " Opts: -D rootdn - new Directory Manager\n"); - print(STDERR " : -w password - new Directory Manager's password\n"); - print(STDERR " : -w - - Prompt for new Directory Manager's password\n"); - print(STDERR " : -j filename - Read new Directory Manager's password from file\n"); - print(STDERR " : -p port - new Directory Server port\n"); - print(STDERR " : -o oldInstancePath - Path of the old instance to migrate \n"); - print(STDERR " : -n newInstancePath - Path of the new instance\n"); - print(STDERR " : [-d dataPath] - Path to directory containing data files to import into new instance\n"); - print(STDERR " : [-v oldVersion] - Version of old instance (obtained by running $slapdExecName -v\n"); - print(STDERR " : [-t tracelevel] - specify the level of trace (0..3) by default setup to 1\n"); - print(STDERR " : [-L logfile] - specify the file to log the migration report \n"); - print(STDERR " : [-noinput] - no user interventions during migration processing to solve conflicts\n"); - - } - - -####################################################################################################################### -# get input users - -sub getParameters { - my $exit = 0 ; - my $i = 0; - my $pwdfile= ""; - - while ($i <= $#ARGV) { - if ( "$ARGV[$i]" eq "-D" ) { # directory manager - if (! $rootDN) { - $rootDN = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-w") { # password - if (! $rootpwd) { - $rootpwd = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-j") { # password file - if (! $pwdfile) { - $pwdfile = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-o") { # old instance path - if (! $oldHome ) { - $oldHome = $ARGV[++$i] ; - grep { s@\\@/@g } $oldHome if $isNT ; - if ($oldHome =~ /[\"]?(.*)?[\"]?/) { $oldHome = $1 ; } - if ($oldHome =~ m@^(.*)/([^-/]*)-([^/]*)[/]?$@) { - $oldDir = $1 ; - $type = $2 ; - $oldname = $3 ; - if ($isNT) { - $oldDir = lc($oldDir) ; - $type = lc($type) ; - $oldname = lc($oldname) ; - $oldHome = lc($oldHome) ; - grep { s@/@\\@g } $oldDir ; - grep { s@/@\\@g } $oldHome ; - } - } - else { - print("\nThe old instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-n") { # 5.x instance path - if (! $serverHome ) { - $serverHome = $ARGV[++$i] ; - grep { s@\\@/@g } $root if $isNT ; - grep { s@\\@/@g } $serverHome if $isNT ; - if ($serverHome =~ /[\"]?(.*)?[\"]?/) { $serverHome = $1 ; } - if ($serverHome =~ m@^(.*?)/?([^/-]*)-([^/]*)[/]?$@) { - $root = $1 if ($1); - $type = $2 ; - $newname = $3 ; - if ($isNT) { - $root = lc($root) ; - $type = lc($type) ; - $newname = lc($newname) ; - $serverHome = lc($serverHome) ; - grep { s@/@\\@g } $root ; - grep { s@/@\\@g } $serverHome ; - } - } - else { - print("\nThe new instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-p") { # 5.x DS port - if (! $newport ) { - $newport = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-d") { # old instance LDIF data dir - if (! $olddatadir ) { - $olddatadir = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-v") { # old version - if (! $oldversionstr ) { - $oldversionstr = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-t") { # TRACELEVEL - my $value = $ARGV[++$i] ; - if ($value =~ /[0-3]/) { - $TRACELEVEL = $value ; - } - else { - print("\nThe tracelevel must belong to 0..3 interval"); - &usage(); - exit(); - } - } elsif ("$ARGV[$i]" eq "-noinput") { # no user interventions during processing - } elsif ("$ARGV[$i]" eq "-L") { # user defined logfile for the migration - $LogFileReport = $ARGV[++$i]; - } - else { - &usage() ; - exit(1); - } - $i++; - } - - if (! $rootDN) { - print("\nThe rootDN is missing"); - $exit = 1; - } - if ($pwdfile ne "") { - # Open file and get the password - unless (open (RPASS, $pwfile)) { - die "Error, cannot open password file $passwdfile\n"; - } - $rootpwd = <RPASS>; - chomp($rootpwd); - close(RPASS); - } elsif ($rootpwd eq "-"){ - # Read the password from terminal - die "The '-w -' option requires an extension library (Term::ReadKey) which is not\n", - "part of the standard perl distribution. If you want to use it, you must\n", - "download and install the module. You can find it at\n", - "http://www.perl.com/CPAN/CPAN.html\n"; - # Remove the previous line and uncomment the following 6 lines once you have installed Term::ReadKey module. -# use Term::ReadKey; -# print "Bind Password: "; -# ReadMode('noecho'); -# $rootpwd = ReadLine(0); -# chomp($rootpwd); -# ReadMode('normal'); - } - if (! $rootpwd) { - print("\nThe rootpwd is missing"); - $exit = 1 ; - } - if (! $newport) { - print("\nThe port is missing"); - $exit = 1; - } - if (! $serverHome) { - print("\nThe new instance path is missing"); - $exit = 1; - } - if (! $oldHome) { - print("\nThe old instance path is missing"); - $exit = 1; - } - if ((! $LogFileReport) && $serverHome) { - ($sec, $min, $hour, $dd, $mm, $yy) = &GetTime(); - $LogFileReport = "${serverHome}${PATHSEP}logs${PATHSEP}Migration_${dd}${mm}${yy}_${hour}${min}${sec}.log"; - } - if ($exit) { - &usage() ; - exit(1); - } - -} - -############################################################################# -# printMsg print message to the user standard output. - -sub printMsg { - - my $TypeMsg = shift ; - my $Msg = shift ; - my $LineNb = shift ; - if ($LineNb) { - printTrace("Line: $LineNb, $TypeMsg, $Msg"); - } - else { - printTrace("$TypeMsg $Msg"); - } -} - -############################################################################# -# print message error to the user standard output. - -sub printTrace { - - my $Msg = shift ; - my $level = shift ; - if ($level <= $TRACELEVEL) { - print($Msg); - print LOGFILE $Msg; - } - -} - -############################################################################# -sub mySystem { - my $cmd = $_[0]; - # the system {$cmd} avoids some NT shell quoting problems if the $cmd - # needs to be quoted e.g. contains spaces; the map puts double quotes - # around the arguments on NT which are stripped by the command - # interpreter cmd.exe; but don't quote things which are already quoted - my @fixargs = map { /^[\"].*[\"]$/ ? $_ : $quote . $_ . $quote } @_; - my $rc = 0; - if ($cmd =~ /[.](bat|cmd)$/) { - # we have to pass batch files directly to the NT command interpreter - $cmd = $com_spec; -# print "system $cmd /c \"@fixargs\"\n"; - $rc = system {$cmd} '/c', "\"@fixargs\""; - } else { -# print "system $cmd \"@fixargs\"\n"; - if($isNT) { - $rc = system "\"@fixargs\""; - } else { - $rc = system @fixargs; - } - } - - return $rc; -} - -############################################################################# - -sub GetTime { - my $tm = localtime; - (my $sec, my $min, my $hour, my $dd, my $mm, my $yy) = ($tm->sec, $tm->min, $tm->hour, $tm->mday, ($tm->mon)+1, ($tm->year)+1900); - $sec = "0$sec" unless $sec > 9 ; - $min = "0$min" unless $min > 9 ; - $hour = "0$hour" unless $hour > 9 ; - $dd = "0$dd" unless $dd > 9 ; - $mm = "0$mm" unless $mm > 9 ; - return ($sec, $min, $hour, $dd, $mm, $yy); -} - -############################################################################# - -sub getVersion { - my $dir = shift; - my $versionstr = shift; - my $version = 0; - my $minor = 0; - my $buildNumber = 0; - my $progDir = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - my $progDir2 = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}"; - - # find the slapd executable - if (!$versionstr) { # version not specified on cmd line - find it - $prog = $dir . $progDir . $slapdExecName; - if (! -f $prog) { - $prog = $dir . $progDir2 . $slapdExecName; - if (-f $prog && $isNT) { - # if slapd is in bin/slapd and we're on NT, just assume version 1; - # apparently, slapd.exe doesn't like the -v argument . . . - return ( '1', $minor ); - } - else{ - die "Could not run slapd program $prog: $!"; - } - } - else { - chdir($dir . $progDir); - } - $preserve_lib_path = $ENV{"$LIB_PATH"}; - $ENV{"$LIB_PATH"}= - "$dir${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - # read the old version from the old slapd program - - open(F, "${quote}${quote}$prog${quote} -v${quote} 2>&1 |") or - die "Could not run slapd program $prog: $!"; - sleep(1); # allow some data to accumulate in the pipe -# print "Output from $prog -v:\n"; - while (<F>) { - if (/^Red Hat-Directory/ || /^Netscape-Directory/ || /^iPlanet-Directory/i) { - $versionstr = $_; - last; - } - } - $code = close(F); - # print "$prog returned code=$code status=$?\n"; - $ENV{"$LIB_PATH"}="$root${PATHSEP}lib${SEP}".$ENV{"$LIB_PATH"}; - } - - if ($versionstr =~ /^Red Hat-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\(restrict?ed-mode\)\/(\d+)\.(\d+)\s+(\S+)/) { # we can have restricted-mode or restriced-mode ... - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^iPlanet-Directory\/(\d+)\.(\d+)\s+(\S+)/i) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } elsif ($versionstr =~ /(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - } - - if ($version == 0) { - die "\nCould not determine version of the directory server in $dir: \n"; - } - - # distinguish the 4.1 and the 4.11 thanks to the buildNumber - if (($version == 4) && ($minor == 1)){ - if (! ($buildNumber =~ /^B99\.16/)) { - # it's not a 4.1 Netscape Directory Server => it's a 4.11 - $minor = 11 ; - } - } - # Restore the original library path - $ENV{"$LIB_PATH"} = $preserve_lib_path; - chdir($curdir) or die "Could not change directory to $curdir: $!" ; - return ( $version, $minor ); -} - -############################################################################################### -# get current directory - -sub getCwd { - my $command = $isNT ? "cd" : "/bin/pwd"; - open(PWDCMD, "$command 2>&1 |") or - die "Error: could not execute $command: $!"; - # without the following sleep, reading from the pipe will - # return nothing; I guess it gives the pwd command time - # to get some data to read . . . - sleep(1); - my $currentdir; - while (<PWDCMD>) { - if (!$currentdir) { - chomp($currentdir = $_); - } - } - my $code = close(PWDCMD); -# if ($code || $?) { -# print "$command returned code=$code status=$? dir=$curdir\n"; -# } -# print "getCwd curdir=\[$curdir\]\n"; - return $currentdir; -} diff --git a/ldap/admin/src/scripts/template-migrateTo7 b/ldap/admin/src/scripts/template-migrateTo7 deleted file mode 100644 index 4a7b2c37..00000000 --- a/ldap/admin/src/scripts/template-migrateTo7 +++ /dev/null @@ -1,3321 +0,0 @@ -#{{PERL-EXEC}} -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -# enable the use of our bundled perldap with our bundled ldapsdk libraries -# all of this nonsense can be omitted if the mozldapsdk and perldap are -# installed in the operating system locations (e.g. /usr/lib /usr/lib/perl5) -BEGIN { - my $sroot = "{{DS-ROOT}}"; - push @INC, "$sroot/lib/perl/arch", "$sroot/lib/perl"; - if ($ENV{LD_LIBRARY_PATH}) { - $ENV{LD_LIBRARY_PATH} .= ":"; - } - $ENV{LD_LIBRARY_PATH} .= "$sroot/shared/lib"; - # this is only needed for HP/ux PA-RISC, but it doesn't hurt other platforms - if ($ENV{SHLIB_PATH}) { - $ENV{SHLIB_PATH} .= ":"; - } - $ENV{SHLIB_PATH} .= "$sroot/shared/lib"; -} -# Migrate a old directory server to a 7.0 directory server - -######################################################################################################## -# enable the use of Perldap functions -require DynaLoader; - -use Getopt::Std; -use Mozilla::LDAP::Conn; -use Mozilla::LDAP::Entry; -use Mozilla::LDAP::LDIF; -use Mozilla::LDAP::Utils qw(:all); -use Mozilla::LDAP::API qw(:api :ssl :apiv3 :constant); # Direct access to C API -use Time::localtime; - -######################################################################################################## -use Class::Struct ; # load struct-building module - -struct S_index => { - names => '@' , - types => '@' , - oids => '@' , - specific => '$' - }; - - -struct S_plugin => { - name => '$' , - type => '$' , - enable => '$' , - args => '@' - }; -##################################################################################################### - -sub usage { - print(STDERR "\nUsage: $0 -D rootdn { -w password | -w - | -j filename } -p port \n"); - print(STDERR " -o OldInstancePath -n NewInstancePath [-t tracelevel] [-L logfile]\n"); - print(STDERR "************** parameters in brackets are optionals, others are required **************\n"); - print(STDERR " Opts: -D rootdn - New Directory Manager\n"); - print(STDERR " : -w password - New Directory Manager's password\n"); - print(STDERR " : -w - - Prompt for New Directory Manager's password\n"); - print(STDERR " : -j filename - Read New Directory Manager's password from file\n"); - print(STDERR " : -p port - New Directory Server port\n"); - print(STDERR " : -o OldInstancePath - Path of the Old instance to migrate \n"); - print(STDERR " : -n NewInstancePath - Path of the new instance\n"); - print(STDERR " : [-d dataPath] - Path to directory containing data files to import into new instance\n"); - print(STDERR " : [-v oldVersion] - Old version (obtained by running $slapdExecName -v\n"); - print(STDERR " : [-t tracelevel] - specify the level of trace (0..3)\n"); - print(STDERR " : [-L logfile] - specify the file to log the migration report \n"); - - - } - - - -############# -BEGIN { - - require 'uname.lib' ; - $isNT = -d '\\'; - $PATHSEP = $isNT ? "\\" : "/"; - ${SEP} = $isNT ? ";" : ":" ; - @INC = ( '.', '../../../admin/admin/bin'); - grep { s@/@\\@g } @INC if $isNT; - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - # NT needs quotes around some things unix doesn't - $quote = $isNT ? "\"" : ""; - - # If this variable is set, all file/directory creation will make sure the mode - # and ownership of the destination is the same as the source - $PRESERVE = 1 if (!$isNT); - $script_suffix = $isNT ? ".bat" : ""; - $exe_suffix = $isNT ? ".exe" : ""; - if ($isNT) { - $os = "WINNT"; - } else { - $os = &uname("-s"); - } - if ($isNT) { - # we have to pass batch files directly to the NT command interpreter - $com_spec = $ENV{ComSpec}; - if (!$com_spec) { - $com_spec = $ENV{COMSPEC}; - } - if (!$com_spec || ! -f $com_spec) { - # find the first available command interpreter - foreach $drive (c..z) { - $com_spec = "$drive:\\winnt\\system32\\cmd.exe"; - last if (-f $com_spec); - $com_spec = undef; - } - if (! $com_spec) { - # punt and pray - $com_spec = 'c:\winnt\system32\cmd.exe'; - } - } - } - if ( $os eq "AIX" ) { - $dll_suffix = "_shr.a"; - } - elsif ( $os eq "HP-UX" ) { - $dll_suffix = ".sl"; - } - elsif ( $os eq "WINNT" ) { - $dll_suffix = ".dll"; - } - else { - $dll_suffix = ".so"; - } - $slapdExecName = $isNT ? 'slapd.exe' : './ns-slapd'; - # if this flag is set, we will migrate the old database - # by doing a db2ldif -> ldif2db; - $convertToLDIF = 1; - select STDERR; - $| = 1; - select STDOUT; - $| = 1; - # if the old value for dbcachesize is less than this, make it this - $MIN_DBCACHESIZE = '500000'; -} - -SWITCH: { - if ($os eq "AIX") { - $LIB_PATH = "LIBPATH" ; - last SWITCH ; - } - if ($os eq "HP-UX") { - $LIB_PATH = "SHLIB_PATH" ; - last SWITCH ; - } - if ($isNT) { - $LIB_PATH = "PATH" ; - last SWITCH ; - } - else { - $LIB_PATH = "LD_LIBRARY_PATH" ; - last SWITCH ; - } - } - - # Old parameters - ${oldDir} = "" ; - ${oldname} = "" ; - ${oldHome} = "" ; - ${oldConfDir} = "" ; - ${oldlocaluser} ; - ${olduid} ; - ${oldgid} ; - - # New parameters - ${root} = "{{DS-ROOT}}" ; - ${type} = "" ; - ${newname} = "" ; - ${newport} = "" ; - ${rootDN} = "" ; - ${rootpwd} = "" ; - ${localhost} = "" ; - ${LogFileReport} = "" ; - ${newuid} ; - ${localuser} ; - ${newgid} ; - $NO_INPUT_USER = 0 ; # by default user can give inputs during the migration process - ${curdir} = getCwd(); - ${slapdExecDir} = "${root}${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - - # specify the level of trace - $TRACELEVEL=1; - - $LDAP_SERVER_UNREACHABLE = 81; - - # get input users - &getParameters() ; - ${oldDir} = &normalizeDir("${oldDir}"); - ${oldHome} = "${oldDir}${PATHSEP}$type-$oldname" ; - ${oldConfDir} = "${oldHome}${PATHSEP}config${PATHSEP}" ; - ${oldSlapdConf} = "${oldConfDir}slapd.conf" ; - ${oldDSEldif} = "${oldConfDir}dse.ldif" ; - ${serverHome} = "${root}${PATHSEP}$type-$newname" ; - ${DSEldif} = "$serverHome${PATHSEP}config${PATHSEP}dse.ldif"; - ${ldif_rep} = "${oldConfDir}${PATHSEP}ldif${PATHSEP}" ; - ${oldSlapdExecDir} = "${oldDir}${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - - - - - open(LOGFILE, ">> $LogFileReport"); - - printTrace("\noldDir: $oldDir, oldHome: $oldHome, \noldConfDir: $oldConfDir, \noldSlapdConf: $oldSlapdConf, \nldif_rep: $ldif_rep, \nrootDN: $rootDN, \nPwd: ******, \nPort: $newport, \nNewname: $newname\n",3); - printTrace("\nLIB_PATH: $LIB_PATH",4); - - if (!(-d $serverHome)) { - printMsg("\n$serverHome doesn't exist\n"); - exit(1); - } - if (!(-d $oldHome)) { - printMsg("\n$oldHome doesn't exist\n"); - exit(1); - } - - if ($olddatadir && !(-d $olddatadir)) { - print("\n$olddatadir doesn't exist\n"); - exit(1); - } - -#define CONFIG_DATABASE_DIRECTIVE "database" -#define CONFIG_DATABASE_ATTRIBUTE "nsslapd-database" -#define CONFIG_PLUGIN_DIRECTIVE "plugin" -#define CONFIG_PLUGIN_ATTRIBUTE "nsslapd-plugin" -#define CONFIG_SIZELIMIT_DIRECTIVE "sizelimit" -#define CONFIG_SIZELIMIT_ATTRIBUTE "nsslapd-sizelimit" -#define CONFIG_ORCAUTO_DIRECTIVE "orcauto" -#define CONFIG_ORCAUTO_ATTRIBUTE "nsslapd-orcauto" -#define CONFIG_TIMELIMIT_DIRECTIVE "timelimit" -#define CONFIG_TIMELIMIT_ATTRIBUTE "nsslapd-timelimit" -#define CONFIG_SUFFIX_DIRECTIVE "suffix" -#define CONFIG_SUFFIX_ATTRIBUTE "nsslapd-suffix" -#define CONFIG_READONLY_DIRECTIVE "readonly" -#define CONFIG_READONLY_ATTRIBUTE "nsslapd-readonly" -#define CONFIG_REFERRAL_DIRECTIVE "referral" -#define CONFIG_REFERRAL_ATTRIBUTE "nsslapd-referral" -#define CONFIG_OBJECTCLASS_DIRECTIVE "objectclass" -#define CONFIG_OBJECTCLASS_ATTRIBUTE "nsslapd-objectclass" -#define CONFIG_ATTRIBUTE_DIRECTIVE "attribute" -#define CONFIG_ATTRIBUTE_ATTRIBUTE "nsslapd-attribute" -#define CONFIG_SCHEMACHECK_DIRECTIVE "schemacheck" -#define CONFIG_SCHEMACHECK_ATTRIBUTE "nsslapd-schemacheck" -#define CONFIG_LOGLEVEL_DIRECTIVE "loglevel" -#define CONFIG_LOGLEVEL_ATTRIBUTE "nsslapd-errorlog-level" -#define CONFIG_ACCESSLOGLEVEL_DIRECTIVE "accessloglevel" -#define CONFIG_ACCESSLOGLEVEL_ATTRIBUTE "nsslapd-accesslog-level" -#define CONFIG_ACCESSLOG_MAXNUMOFLOGSPERDIR_DIRECTIVE "accesslog-maxNumOfLogsPerDir" -#define CONFIG_ACCESSLOG_MAXNUMOFLOGSPERDIR_ATTRIBUTE "nsslapd-accesslog-maxlogsperdir" -#define CONFIG_ERRORLOG_MAXNUMOFLOGSPERDIR_DIRECTIVE "errorlog-maxNumOfLogsPerDir" -#define CONFIG_ERRORLOG_MAXNUMOFLOGSPERDIR_ATTRIBUTE "nsslapd-errorlog-maxlogsperdir" -#define CONFIG_AUDITLOG_MAXNUMOFLOGSPERDIR_DIRECTIVE "auditlog-maxNumOfLogsPerDir" -#define CONFIG_AUDITLOG_MAXNUMOFLOGSPERDIR_ATTRIBUTE "nsslapd-auditlog-maxlogsperdir" -#define CONFIG_ACCESSLOG_MAXLOGSIZE_DIRECTIVE "accesslog-maxlogsize" -#define CONFIG_ACCESSLOG_MAXLOGSIZE_ATTRIBUTE "nsslapd-accesslog-maxlogsize" -#define CONFIG_ERRORLOG_MAXLOGSIZE_DIRECTIVE "errorlog-maxlogsize" -#define CONFIG_ERRORLOG_MAXLOGSIZE_ATTRIBUTE "nsslapd-errorlog-maxlogsize" -#define CONFIG_AUDITLOG_MAXLOGSIZE_DIRECTIVE "auditlog-maxlogsize" -#define CONFIG_AUDITLOG_MAXLOGSIZE_ATTRIBUTE "nsslapd-auditlog-maxlogsize" -#define CONFIG_ACCESSLOG_LOGROTATIONTIME_DIRECTIVE "accesslog-logrotationtime" -#define CONFIG_ACCESSLOG_LOGROTATIONTIME_ATTRIBUTE "nsslapd-accesslog-logrotationtime" -#define CONFIG_ERRORLOG_LOGROTATIONTIME_DIRECTIVE "errorlog-logrotationtime" -#define CONFIG_ERRORLOG_LOGROTATIONTIME_ATTRIBUTE "nsslapd-errorlog-logrotationtime" -#define CONFIG_AUDITLOG_LOGROTATIONTIME_DIRECTIVE "auditlog-logrotationtime" -#define CONFIG_AUDITLOG_LOGROTATIONTIME_ATTRIBUTE "nsslapd-auditlog-logrotationtime" -#define CONFIG_ACCESSLOG_LOGROTATIONTIMEUNIT_DIRECTIVE "accesslog-logrotationtimeunit" -#define CONFIG_ACCESSLOG_LOGROTATIONTIMEUNIT_ATTRIBUTE "nsslapd-accesslog-logrotationtimeunit" -#define CONFIG_ERRORLOG_LOGROTATIONTIMEUNIT_DIRECTIVE "errorlog-logrotationtimeunit" -#define CONFIG_ERRORLOG_LOGROTATIONTIMEUNIT_ATTRIBUTE "nsslapd-errorlog-logrotationtimeunit" -#define CONFIG_AUDITLOG_LOGROTATIONTIMEUNIT_DIRECTIVE "auditlog-logrotationtimeunit" -#define CONFIG_AUDITLOG_LOGROTATIONTIMEUNIT_ATTRIBUTE "nsslapd-auditlog-logrotationtimeunit" -#define CONFIG_ACCESSLOG_MAXLOGDISKSPACE_DIRECTIVE "accesslog-maxlogdiskspace" -#define CONFIG_ACCESSLOG_MAXLOGDISKSPACE_ATTRIBUTE "nsslapd-accesslog-logmaxdiskspace" -#define CONFIG_ERRORLOG_MAXLOGDISKSPACE_DIRECTIVE "errorlog-maxlogdiskspace" -#define CONFIG_ERRORLOG_MAXLOGDISKSPACE_ATTRIBUTE "nsslapd-errorlog-logmaxdiskspace" -#define CONFIG_AUDITLOG_MAXLOGDISKSPACE_DIRECTIVE "auditlog-maxlogdiskspace" -#define CONFIG_AUDITLOG_MAXLOGDISKSPACE_ATTRIBUTE "nsslapd-auditlog-logmaxdiskspace" -#define CONFIG_ACCESSLOG_MINFREEDISKSPACE_DIRECTIVE "accesslog-minfreediskspace" -#define CONFIG_ACCESSLOG_MINFREEDISKSPACE_ATTRIBUTE "nsslapd-accesslog-logminfreediskspace" -#define CONFIG_ERRORLOG_MINFREEDISKSPACE_DIRECTIVE "errorlog-minfreediskspace" -#define CONFIG_ERRORLOG_MINFREEDISKSPACE_ATTRIBUTE "nsslapd-errorlog-logminfreediskspace" -#define CONFIG_AUDITLOG_MINFREEDISKSPACE_DIRECTIVE "auditlog-minfreediskspace" -#define CONFIG_AUDITLOG_MINFREEDISKSPACE_ATTRIBUTE "nsslapd-auditlog-logminfreediskspace" -#define CONFIG_ACCESSLOG_LOGEXPIRATIONTIME_DIRECTIVE "accesslog-logexpirationtime" -#define CONFIG_ACCESSLOG_LOGEXPIRATIONTIME_ATTRIBUTE "nsslapd-accesslog-logexpirationtime" -#define CONFIG_ERRORLOG_LOGEXPIRATIONTIME_DIRECTIVE "errorlog-logexpirationtime" -#define CONFIG_ERRORLOG_LOGEXPIRATIONTIME_ATTRIBUTE "nsslapd-errorlog-logexpirationtime" -#define CONFIG_AUDITLOG_LOGEXPIRATIONTIME_DIRECTIVE "auditlog-logexpirationtime" -#define CONFIG_AUDITLOG_LOGEXPIRATIONTIME_ATTRIBUTE "nsslapd-auditlog-logexpirationtime" -#define CONFIG_ACCESSLOG_LOGEXPIRATIONTIMEUNIT_DIRECTIVE "accesslog-logexpirationtimeunit" -#define CONFIG_ACCESSLOG_LOGEXPIRATIONTIMEUNIT_ATTRIBUTE "nsslapd-accesslog-logexpirationtimeunit" -#define CONFIG_ERRORLOG_LOGEXPIRATIONTIMEUNIT_DIRECTIVE "errorlog-logexpirationtimeunit" -#define CONFIG_ERRORLOG_LOGEXPIRATIONTIMEUNIT_ATTRIBUTE "nsslapd-errorlog-logexpirationtimeunit" -#define CONFIG_AUDITLOG_LOGEXPIRATIONTIMEUNIT_DIRECTIVE "auditlog-logexpirationtimeunit" -#define CONFIG_AUDITLOG_LOGEXPIRATIONTIMEUNIT_ATTRIBUTE "nsslapd-auditlog-logexpirationtimeunit" -#define CONFIG_ACCESSLOG_LOGGING_ENABLED_DIRECTIVE "accesslog-logging-enabled" -#define CONFIG_ACCESSLOG_LOGGING_ENABLED_ATTRIBUTE "nsslapd-accesslog-logging-enabled" -#define CONFIG_ERRORLOG_LOGGING_ENABLED_DIRECTIVE "errorlog-logging-enabled" -#define CONFIG_ERRORLOG_LOGGING_ENABLED_ATTRIBUTE "nsslapd-errorlog-logging-enabled" -#define CONFIG_AUDITLOG_LOGGING_ENABLED_DIRECTIVE "auditlog-logging-enabled" -#define CONFIG_AUDITLOG_LOGGING_ENABLED_ATTRIBUTE "nsslapd-auditlog-logging-enabled" -#define CONFIG_ROOTDN_DIRECTIVE "rootdn" -#define CONFIG_ROOTDN_ATTRIBUTE "nsslapd-rootdn" -#define CONFIG_ROOTPW_DIRECTIVE "rootpw" -#define CONFIG_ROOTPW_ATTRIBUTE "nsslapd-rootpw" -#define CONFIG_ROOTPWSTORAGESCHEME_DIRECTIVE "rootpwstoragescheme" -#define CONFIG_ROOTPWSTORAGESCHEME_ATTRIBUTE "nsslapd-rootpwstoragescheme" -#define CONFIG_UPDATEDN_DIRECTIVE "updatedn" -#define CONFIG_UPDATEDN_ATTRIBUTE "nsslapd-updatedn" -#define CONFIG_UPDATEPW_DIRECTIVE "updatepw" -#define CONFIG_UPDATEPW_ATTRIBUTE "nsslapd-updatepw" -#define CONFIG_UPDATESSLCLIENT_DIRECTIVE "updateSSLclient" -#define CONFIG_UPDATESSLCLIENT_ATTRIBUTE "nsslapd-updateSSLclient" -#define CONFIG_AUDITFILE_DIRECTIVE "auditfile" -#define CONFIG_AUDITFILE_ATTRIBUTE "nsslapd-auditlog" -#define CONFIG_LASTMOD_DIRECTIVE "lastmod" -#define CONFIG_LASTMOD_ATTRIBUTE "nsslapd-lastmod" -#define CONFIG_INCLUDE_DIRECTIVE "include" -#define CONFIG_INCLUDE_ATTRIBUTE "nsslapd-include" -#define CONFIG_DYNAMICCONF_DIRECTIVE "dynamicconf" -#define CONFIG_DYNAMICCONF_ATTRIBUTE "nsslapd-dynamicconf" -#define CONFIG_USEROC_DIRECTIVE "useroc" -#define CONFIG_USEROC_ATTRIBUTE "nsslapd-useroc" -#define CONFIG_USERAT_DIRECTIVE "userat" -#define CONFIG_USERAT_ATTRIBUTE "nsslapd-userat" -#define CONFIG_SVRTAB_DIRECTIVE "svrtab" -#define CONFIG_SVRTAB_ATTRIBUTE "nsslapd-svrtab" -#ifndef _WIN32 -#define CONFIG_LOCALUSER_DIRECTIVE "localuser" -#define CONFIG_LOCALUSER_ATTRIBUTE "nsslapd-localuser" -#endif /* !_WIN32 */ -#define CONFIG_LOCALHOST_DIRECTIVE "localhost" -#define CONFIG_LOCALHOST_ATTRIBUTE "nsslapd-localhost" -#define CONFIG_PORT_DIRECTIVE "port" -#define CONFIG_PORT_ATTRIBUTE "nsslapd-port" -#define CONFIG_LISTENHOST_DIRECTIVE "listenhost" -#define CONFIG_LISTENHOST_ATTRIBUTE "nsslapd-listenhost" -#define CONFIG_SECURITY_DIRECTIVE "security" -#define CONFIG_SECURITY_ATTRIBUTE "nsslapd-security" -#define CONFIG_SSL3CIPHERS_DIRECTIVE "SSL3ciphers" -#define CONFIG_SSL3CIPHERS_ATTRIBUTE "nsslapd-SSL3ciphers" -#define CONFIG_ACCESSLOG_DIRECTIVE "accesslog" -#define CONFIG_ACCESSLOG_ATTRIBUTE "nsslapd-accesslog" -#define CONFIG_ERRORLOG_DIRECTIVE "errorlog" -#define CONFIG_ERRORLOG_ATTRIBUTE "nsslapd-errorlog" -#define CONFIG_INSTANCEDIR_DIRECTIVE "instancedir" -#define CONFIG_INSTANCEDIR_ATTRIBUTE "nsslapd-instancedir" -#define CONFIG_SECUREPORT_DIRECTIVE "secure-port" -#define CONFIG_SECUREPORT_ATTRIBUTE "nsslapd-securePort" -#define CONFIG_SECURELISTENHOST_DIRECTIVE "secure-listenhost" -#define CONFIG_SECURELISTENHOST_ATTRIBUTE "nsslapd-securelistenhost" -#define CONFIG_THREADNUMBER_DIRECTIVE "threadnumber" -#define CONFIG_THREADNUMBER_ATTRIBUTE "nsslapd-threadnumber" -#define CONFIG_MAXTHREADSPERCONN_DIRECTIVE "maxthreadsperconn" -#define CONFIG_MAXTHREADSPERCONN_ATTRIBUTE "nsslapd-maxthreadsperconn" -#if !defined(_WIN32) && !defined(AIX) -#define CONFIG_MAXDESCRIPTORS_DIRECTIVE "maxdescriptors" -#define CONFIG_MAXDESCRIPTORS_ATTRIBUTE "nsslapd-maxdescriptors" -#endif /* !_WIN32 && ! AIX */ -#define CONFIG_RESERVEDESCRIPTORS_DIRECTIVE "reservedescriptors" -#define CONFIG_RESERVEDESCRIPTORS_ATTRIBUTE "nsslapd-reservedescriptors" -#define CONFIG_IDLETIMEOUT_DIRECTIVE "idletimeout" -#define CONFIG_IDLETIMEOUT_ATTRIBUTE "nsslapd-idletimeout" -#define CONFIG_IOBLOCKTIMEOUT_DIRECTIVE "ioblocktimeout" -#define CONFIG_IOBLOCKTIMEOUT_ATTRIBUTE "nsslapd-ioblocktimeout" -#define CONFIG_NTSYNCH_DIRECTIVE "ntsynch" -#define CONFIG_NTSYNCH_ATTRIBUTE "nsslapd-NTSynch" -#define CONFIG_NTSYNCHUSESSL_DIRECTIVE "ntsynchusessl" -#define CONFIG_NTSYNCHUSESSL_ATTRIBUTE "nsslapd-NTSynch-SSL" -#define CONFIG_NTSYNCHPORT_DIRECTIVE "ntsynch-port" -#define CONFIG_NTSYNCHPORT_ATTRIBUTE "nsslapd-NTSynch-port" -#define CONFIG_ACCESSCONTROL_DIRECTIVE "accesscontrol" -#define CONFIG_ACCESSCONTROL_ATTRIBUTE "nsslapd-accesscontrol" -#define CONFIG_GROUPEVALNESTLEVEL_DIRECTIVE "groupevalnestlevel" -#define CONFIG_GROUPEVALNESTLEVEL_ATTRIBUTE "nsslapd-groupevalnestlevel" -#define CONFIG_NAGLE_DIRECTIVE "nagle" -#define CONFIG_NAGLE_ATTRIBUTE "nsslapd-nagle" -#define CONFIG_PW_CHANGE_DIRECTIVE "pw_change" -#define CONFIG_PW_CHANGE_ATTRIBUTE "passwordChange" -#define CONFIG_PW_MUSTCHANGE_DIRECTIVE "pw_must_change" -#define CONFIG_PW_MUSTCHANGE_ATTRIBUTE "passwordMustChange" -#define CONFIG_PW_SYNTAX_DIRECTIVE "pw_syntax" -#define CONFIG_PW_SYNTAX_ATTRIBUTE "passwordCheckSyntax" -#define CONFIG_PW_MINLENGTH_DIRECTIVE "pw_minlength" -#define CONFIG_PW_MINLENGTH_ATTRIBUTE "passwordMinLength" -#define CONFIG_PW_EXP_DIRECTIVE "pw_exp" -#define CONFIG_PW_EXP_ATTRIBUTE "passwordExp" -#define CONFIG_PW_MAXAGE_DIRECTIVE "pw_maxage" -#define CONFIG_PW_MAXAGE_ATTRIBUTE "passwordMaxAge" -#define CONFIG_PW_MINAGE_DIRECTIVE "pw_minage" -#define CONFIG_PW_MINAGE_ATTRIBUTE "passwordMinAge" -#define CONFIG_PW_WARNING_DIRECTIVE "pw_warning" -#define CONFIG_PW_WARNING_ATTRIBUTE "passwordWarning" -#define CONFIG_PW_HISTORY_DIRECTIVE "pw_history" -#define CONFIG_PW_HISTORY_ATTRIBUTE "passwordHistory" -#define CONFIG_PW_INHISTORY_DIRECTIVE "pw_inhistory" -#define CONFIG_PW_INHISTORY_ATTRIBUTE "passwordInHistory" -#define CONFIG_PW_LOCKOUT_DIRECTIVE "pw_lockout" -#define CONFIG_PW_LOCKOUT_ATTRIBUTE "passwordLockout" -#define CONFIG_PW_STORAGESCHEME_DIRECTIVE "pw_storagescheme" -#define CONFIG_PW_STORAGESCHEME_ATTRIBUTE "passwordStorageScheme" -#define CONFIG_PW_MAXFAILURE_DIRECTIVE "pw_maxfailure" -#define CONFIG_PW_MAXFAILURE_ATTRIBUTE "passwordMaxFailure" -#define CONFIG_PW_UNLOCK_DIRECTIVE "pw_unlock" -#define CONFIG_PW_UNLOCK_ATTRIBUTE "passwordUnlock" -#define CONFIG_PW_LOCKDURATION_DIRECTIVE "pw_lockduration" -#define CONFIG_PW_LOCKDURATION_ATTRIBUTE "passwordLockoutDuration" -#define CONFIG_PW_RESETFAILURECOUNT_DIRECTIVE "pw_resetfailurecount" -#define CONFIG_PW_RESETFAILURECOUNT_ATTRIBUTE "passwordResetFailureCount" -#define CONFIG_ACCESSLOG_BUFFERING_DIRECTIVE "logbuffering" -#define CONFIG_ACCESSLOG_BUFFERING_ATTRIBUTE "nsslapd-accesslog-logbuffering" -#define CONFIG_CHANGELOG_DIR_DIRECTIVE "changelogdir" -#define CONFIG_CHANGELOG_DIR_ATTRIBUTE "nsslapd-changelogdir" -#define CONFIG_CHANGELOG_SUFFIX_DIRECTIVE "changelogsuffix" -#define CONFIG_CHANGELOG_SUFFIX_ATTRIBUTE "nsslapd-changelogsuffix" -#define CONFIG_CHANGELOG_MAXENTRIES_DIRECTIVE "changelogmaxextries" -#define CONFIG_CHANGELOG_MAXENTRIES_ATTRIBUTE "nsslapd-changelogmaxentries" -#define CONFIG_CHANGELOG_MAXAGE_DIRECTIVE "changelogmaxage" -#define CONFIG_CHANGELOG_MAXAGE_ATTRIBUTE "nsslapd-changelogmaxage" -#define CONFIG_RETURN_EXACT_CASE_DIRECTIVE "return_exact_case" -#define CONFIG_RESULT_TWEAK_DIRECTIVE "result_tweak" -#define CONFIG_REFERRAL_MODE_DIRECTIVE "referralmode" -#define CONFIG_ATTRIBUTE_NAME_EXCEPTION_DIRECTIVE "attribute_name_exceptions" -#define CONFIG_MAXBERSIZE_DIRECTIVE "maxbersize" -#define CONFIG_VERSIONSTRING_DIRECTIVE "versionstring" -#define CONFIG_ENQUOTE_SUP_OC_DIRECTIVE "enquote_sup_oc" -#define CONFIG_ENQUOTE_SUP_OC_ATTRIBUTE "nsslapd-enquote_sup_oc" -#define CONFIG_BASEDN_DIRECTIVE "certmap-basedn" -#define CONFIG_BASEDN_ATTRIBUTE "nsslapd-certmap-basedn" - -%HashParametersName = (); - -# The following hash displays only general server parameters to migrate under cn=config -%GeneralSrvParamToMigrate = ( - 'accesscontrol' => 'nsslapd-accesscontrol', - 'errorlog-logging-enabled' => 'nsslapd-errorlog-logging-enabled', - 'accesslog-logging-enabled' => 'nsslapd-accesslog-logging-enabled', - 'auditlog-logging-enabled' => 'nsslapd-auditlog-logging-enabled', - 'logbuffering' => 'nsslapd-accesslog-logbuffering', - 'accesslog-logexpirationtime' => 'nsslapd-accesslog-logexpirationtime', - 'accesslog-logexpirationtimeunit' => 'nsslapd-accesslog-logexpirationtimeunit', - 'accesslog-maxlogdiskspace' => 'nsslapd-accesslog-logmaxdiskspace', - 'accesslog-minfreediskspace' => 'nsslapd-accesslog-logminfreediskspace', - 'accesslog-logrotationtime' => 'nsslapd-accesslog-logrotationtime', - 'accesslog-logrotationtimeunit' => 'nsslapd-accesslog-logrotationtimeunit', - 'accesslog-maxlogsize' => 'nsslapd-accesslog-maxlogsize', - 'accesslog-maxnumoflogsperdir' => 'nsslapd-accesslog-maxLogsPerDir', - 'auditlog-logexpirationtime' => 'nsslapd-auditlog-logexpirationtime', - 'auditlog-logexpirationtimeunit' => 'nsslapd-auditlog-logexpirationtimeunit', - 'auditlog-maxlogdiskspace' => 'nsslapd-auditlog-logmaxdiskspace', - 'auditlog-minfreediskspace' => 'nsslapd-auditlog-logminfreediskspace', - 'auditlog-logrotationtime' => 'nsslapd-auditlog-logrotationtime', - 'auditlog-logrotationtimeunit' => 'nsslapd-auditlog-logrotationtimeunit', - 'auditlog-maxlogsize' => 'nsslapd-auditlog-maxlogsize', - 'auditlog-maxnumoflogsperdir' => 'nsslapd-auditlog-maxLogsPerDir', - 'certmap-basedn' => 'nsslapd-certmap-basedn', - 'enquote_sup_oc' => 'nsslapd-enquote-sup-oc', - 'loglevel' => 'nsslapd-errorlog-level', - 'errorlog-logexpirationtime' => 'nsslapd-errorlog-logexpirationtime', - 'errorlog-logexpirationtimeunit' => 'nsslapd-errorlog-logexpirationtimeunit', - 'errorlog-maxlogdiskspace' => 'nsslapd-errorlog-logmaxdiskspace', - 'errorlog-minfreediskspace' => 'nsslapd-errorlog-logminfreediskspace', - 'errorlog-logrotationtime' => 'nsslapd-errorlog-logrotationtime', - 'errorlog-logrotationtimeunit' => 'nsslapd-errorlog-logrotationtimeunit', - 'errorlog-maxlogsize' => 'nsslapd-errorlog-maxlogsize', - 'errorlog-maxnumoflogsperdir' => 'nsslapd-errorlog-maxlogsperdir', - 'idletimeout' => 'nsslapd-idletimeout', - 'ioblocktimeout' => 'nsslapd-ioblocktimeout', - 'lastmod' => 'nsslapd-lastmod', - 'listenhost' => 'nsslapd-listenhost', - 'maxdescriptors' => 'nsslapd-maxdescriptors', - 'referral' => 'nsslapd-referral', - 'reservedescriptors' => 'nsslapd-reservedescriptors', - 'rootpwstoragescheme' => 'nsslapd-rootpwstoragescheme', - 'schemacheck' => 'nsslapd-schemacheck', - 'secure-port' => 'nsslapd-securePort', - 'security' => 'nsslapd-security', - 'sizelimit' => 'nsslapd-sizelimit', - 'SSL3ciphers' => 'nsslapd-SSL3ciphers', - 'timelimit' => 'nsslapd-timelimit', - 'pw_change' => 'passwordChange', - 'pw_syntax' => 'passwordCheckSyntax', - 'pw_exp' => 'passwordExp', - 'pw_history' => 'passwordHistory', - 'pw_inhistory' => 'passwordInHistory', - 'pw_lockout' => 'passwordLockout', - 'pw_lockduration' => 'passwordLockoutDuration', - 'pw_maxage' => 'passwordMaxAge', - 'pw_maxfailure' => 'passwordMaxFailure', - 'pw_minage' => 'passwordMinAge', - 'pw_minlength' => 'passwordMinLength', - 'pw_must_change' => 'passwordMustChange', - 'pw_resetfailurecount' => 'passwordResetFailureCount', - 'pw_storagescheme' => 'passwordStorageScheme', - 'pw_unlock' => 'passwordUnlock', - 'pw_warning' => 'passwordWarning' -); - -# the following hash displays global parameters related to database stored under cn=config,cn=ldbm database,cn=plugins,cn=config -%GlobalConfigLDBMparamToMigrate = ( - 'allidsthreshold' => 'nsslapd-allidsthreshold', - 'lookthroughlimit' => 'nsslapd-lookthroughlimit', - 'mode' => 'nsslapd-mode', - 'dbcachesize' => 'nsslapd-dbcachesize' -); - -# the following hash displays specific parameters to each backends and stored under cn=DBname,cn=ldbm database,cn=plugins,cn=config -%LDBMparamToMigrate = ( - 'cachesize' => 'nsslapd-cachesize', - 'readonly' => 'nsslapd-readonly' -); - -%stdIncludes = ( - "${oldConfDir}slapd.at.conf", "\n", - "${oldConfDir}slapd.oc.conf", "\n", - "${oldConfDir}java-object-schema.conf", "\n", - "${oldConfDir}ns-admin-schema.conf", "\n", - "${oldConfDir}ns-calendar-schema.conf", "\n", - "${oldConfDir}ns-certificate-schema.conf", "\n", - "${oldConfDir}ns-common-schema.conf", "\n", - "${oldConfDir}ns-compass-schema.conf", "\n", - "${oldConfDir}ns-delegated-admin-schema.conf", "\n", - "${oldConfDir}ns-directory-schema.conf", "\n", - "${oldConfDir}ns-legacy-schema.conf", "\n", - "${oldConfDir}ns-mail-schema.conf", "\n", - "${oldConfDir}ns-mcd-browser-schema.conf", "\n", - "${oldConfDir}ns-mcd-config-schema.conf", "\n", - "${oldConfDir}ns-mcd-li-schema.conf", "\n", - "${oldConfDir}ns-mcd-mail-schema.conf", "\n", - "${oldConfDir}ns-media-schema.conf", "\n", - "${oldConfDir}ns-mlm-schema.conf", "\n", - "${oldConfDir}ns-msg-schema.conf", "\n", - "${oldConfDir}ns-netshare-schema.conf", "\n", - "${oldConfDir}ns-news-schema.conf", "\n", - "${oldConfDir}ns-proxy-schema.conf", "\n", - "${oldConfDir}ns-value-schema.conf", "\n", - "${oldConfDir}ns-wcal-schema.conf", "\n", - "${oldConfDir}ns-cos-schema.conf", "\n", - "${oldConfDir}ns-web-schema.conf", "\n" -); - -%userDefinedConfigFiles = ( - "slapd.conf", "\n", - "slapd.ldbm.conf", "\n", - "slapd.user_at.conf", "\n", - "slapd.user_oc.conf", "\n", - "ns-schema.conf", "\n" - ); - -$CIS_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.15" ; -$TELEPHONE_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.50" ; -$DN_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.12" ; -$CES_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.26" ; -$INT_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.27" ; -$BIN_SYNTAX_OID = "1.3.6.1.4.1.1466.115.121.1.5" ; - -%allowedPlugins = ( - "cis", $CIS_SYNTAX_OID, - "tel", $TELEPHONE_SYNTAX_OID, - "dn", $DN_SYNTAX_OID, - "ces", $CES_SYNTAX_OID, - "int", $INT_SYNTAX_OID, - "bin", $BIN_SYNTAX_OID - ); - -%allowedModifiers = ( - "single", "SINGLE-VALUE" - ); -# "override" is not supported anymore and "operational" cannot be used in user defined attribute. - -@oldSuffixes = () ; # array of old suffixes (with "o=netscaperoot" if presents) - -# link beetwen the name of the suffix and its associated DBname -%DBNAMES = () ; -%DBDirectory = () ; - -%oldhash = () ; - -# list of standard plugin's in version 4 -%stdPlugins = ( - "7-bit check" => "\n", - "binary syntax" => "\n", - "case exact string syntax" => "\n", - "case ignore string syntax" => "\n", - "distinguished name syntax" => "\n", - "integer syntax" => "\n", - "internationalization plugin" => "\n", - "referential integrity postoperation" => "\n", - "telephone syntax" => "\n", - "uid uniqueness" => "\n" - - ); - -# list of standard indexes configured out of the box in version 4 -%stdIndex = ( - 'aci', "\n", - 'changenumber', "\n", - 'copiedfrom', "\n", - 'dncomp', "\n", - 'entrydn', "\n", - 'numsubordinates', "\n", - 'objectclass', "\n", - 'parentid', "\n" -); - -# list of user added Plugin's. In the new version, they 'll need to be recompiled -@badPlugins = () ; - -%newIndex = () ; - -%User_oc = () ; -# push objectnames as they are encountered in config files. -@User_oc_names = () ; - -%User_at = () ; - - - -#Usage parameters -$USER_OC_FILE_MODIFIED = 0 ; # 0 if user don't want to modify LDIF objectclasses before processing, 1 else -$USER_AT_FILE_MODIFIED = 0 ; -$INDEX_FILE_MODIFIED = 0 ; - -# get the version of the DS to migrate -($oldVersion, $oldMinor) = &getVersion($oldDir, $oldversionstr); -# get the version of the new DS -($Version, $Minor) = &getVersion($root); - -# get old LIB_PATH -$old_libpath = &getLibPath($oldDir, $oldVersion, $oldMinor); -# get new LIB_PATH -$new_libpath = &getLibPath($root, $Version, $Minor); - -# Shutdown the legacy Directory instance -printTrace("\nShutdown the legacy Directory Server instance: ${oldHome}",0); -&stopServer($oldDir, 'slapd-'.$oldname); - -# compare configuration files with the standard ones -CompareStdConfigFiles() ; -die "\n\n The version of the product you want to migrate is not a 4.x Netscape Directory Server\n" unless ($oldVersion == 4) ; - -FillHashParametersName() ; - -############### Connect to the New LDAP Directory Server ###################### -$ENV{"$LIB_PATH"} = $new_libpath; -my $LDAPservername = &getLDAPservername(); -die "\n Migration aborted. Make sure your Old and New Directory Servers are installed on the same machine \n" if ( $LDAPservername == -1 ); -$conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Can't contact the $Version.$Minor LDAP server: $LDAPservername\n"; - -# continue if the connection to new LDAP server is successful ! -printTrace("\nConnected to $Version.$Minor LDAP server\n",0) ; - -# get the uid and gid of the new slapd user -($localuser, $newuid, $newgid) = getuid_gid(); -# get the uid and gid of the old slapd user -($oldlocaluser, $olduid, $oldgid) = getolduid_gid(); - -# backup new configuration files in <new_root_server>/slapd-instancename/config -printTrace("\nBackup $serverHome${PATHSEP}config on $serverHome${PATHSEP}config_backup ...",0); -&backupConfigFiles(); - -# Parse the main configuration file: slapd.conf -printTrace("\nParse the configuration file: $oldSlapdConf...",0); -ParseSlapdConf("< ${oldSlapdConf}"); - -#migrate key/cert databases -printTrace("\nMigrate key/cert databases...",0); -&MigrateSSL(); - -# Update parameters : general server parameters, global LDBM parameter, specific backend parameters -printTrace("\nUpdate general server parameters...",0); -$conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Can't contact the $Version.$Minor LDAP server: $LDAPservername\n"; -AddGeneralParameters(); -printTrace("\nUpdate global LDBM parameters...",0); -AddGeneralLDBMParameters(); -printTrace("\nUpdate specific backend parameters...",0); -AddSpecificLDBMParameters(); - -##### FOR TESTING PURPOSE ONLY ######## -# -#testIndexUpdating(); -# -####################################### - -# Migrate some entries contained in the old dse.ldif, and migrate certmap.conf -&MigrateDSE() ; -&MigrateCertmap() ; - -# update new attribute definitions -LDAPmodify_User_at(); - -# update new object classes definitions -LDAPmodify_User_oc(); - -# add new indexes to each backends -LDAPmodify_Indexes(); - -# migrate Plug'ins parameters (enable attribute, and arguments) -LDAPmodify_stdPlugin(); - -################## Close the connection to new LDAP Server ##################### -$conn->close; - - -################## stop the new instance and Export/Import the data, restart the server ################## -if (%DBNAMES) { - &stopServer($root,'slapd-'.$newname); - if ($olddatadir) { - printTrace("\nold data directory $olddatadir...",0) ; - $ldif_rep = "$olddatadir${PATHSEP}"; - } else { - printTrace("\ndata processing...",0) ; - # migrate data for each suffix: old -> LDIF files - &db2ldif($oldSlapdConf); - } - - # migrate LDIF data to the new database: LDIF -> new - &manyLdif2db(); - &startServer(); -} -else { - printTrace("\nThere no old non-standard suffixes to migrate",0); -} - -printMsg("\n\n ****** End of migration ******\n\n"); - -close(LOGFILE); - - -########################################################################################### -# get input users -sub getParameters { - my $exit = 0 ; - my $i = 0; - my $pwdfile= ""; - while ($i <= $#ARGV) { - if ( "$ARGV[$i]" eq "-D" ) { # directory manager - if (! $rootDN) { - $rootDN = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-w") { # password - if (! $rootpwd) { - $rootpwd = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-j") { # password file - if (! $pwdfile) { - $pwdfile = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-o") { # old instance path - if (! $oldHome ) { - $oldHome = $ARGV[++$i] ; - grep { s@\\@/@g } $oldHome if $isNT ; - if ($oldHome =~ /[\"]?(.*)?[\"]?/) { $oldHome = $1 ; } - if ($oldHome =~ m@^(.*)/([^-/]*)-([^/]*)[/]?$@) { - $oldDir = $1 ; - $type = $2 ; - $oldname = $3 ; - if ($isNT) { - $oldDir = lc($oldDir) ; - $type = lc($type) ; - $oldname = lc($oldname) ; - $oldHome = lc($oldHome) ; - grep { s@/@\\@g } $oldDir ; - grep { s@/@\\@g } $oldHome ; - } - } - else { - print("\nThe old instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-n") { # new instance path - if (! $serverHome ) { - $serverHome = $ARGV[++$i] ; - grep { s@\\@/@g } $root if $isNT ; - grep { s@\\@/@g } $serverHome if $isNT ; - if ($serverHome =~ /[\"]?(.*)?[\"]?/) { $serverHome = $1 ; } - if ($serverHome =~ m@^(.*?)/?([^/-]*)-([^/]*)[/]?$@) { - $root = $1 if ($1); - $type = $2 ; - $newname = $3 ; - if ($isNT) { - $root = lc($root) ; - $type = lc($type) ; - $newname = lc($newname) ; - $serverHome = lc($serverHome) ; - grep { s@/@\\@g } $root ; - grep { s@/@\\@g } $serverHome ; - } - } - else { - print("\nThe new instance path is not correct. It must be like slapd-instancename"); - &usage(); - exit(1); - } - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-p") { # new DS port - if (! $newport ) { - $newport = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-d") { # old instance LDIF data dir - if (! $olddatadir ) { - $olddatadir = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-v") { # old version - if (! $oldversionstr ) { - $oldversionstr = $ARGV[++$i] ; - } - else { - &usage() ; - exit(1); - } - } elsif ("$ARGV[$i]" eq "-t") { # TRACELEVEL - my $value = $ARGV[++$i] ; - if ($value =~ /[0-3]/) { - $TRACELEVEL = $value ; - } - else { - print("\nThe tracelevel must belong to 0..3 interval"); - &usage(); - exit(); - } - } elsif ("$ARGV[$i]" eq "-noinput") { # no user interventions during processing - $NO_INPUT_USER = 1 ; - } elsif ("$ARGV[$i]" eq "-L") { # migration logfile - $LogFileReport = $ARGV[++$i] ; - } - else { - print("\nThe option $ARGV[$i] is not recognized"); - &usage() ; - exit(1); - } - $i++; - } - if (! $rootDN) { - print("\nThe rootDN is missing"); - $exit = 1; - } - if ($pwdfile ne "") { - # Open file and get the password - unless (open (RPASS, $pwfile)) { - die "Error, cannot open password file $passwdfile\n"; - } - $rootpwd = <RPASS>; - chomp($rootpwd); - close(RPASS); - } elsif ($rootpwd eq "-"){ - # Read the password from terminal - die "The '-w -' option requires an extension library (Term::ReadKey) which is not\n", - "part of the standard perl distribution. If you want to use it, you must\n", - "download and install the module. You can find it at\n", - "http://www.perl.com/CPAN/CPAN.html\n"; - # Remove the previous line and uncomment the following 6 lines once you have installed Term::ReadKey module. -# use Term::ReadKey; -# print "Bind Password: "; -# ReadMode('noecho'); -# $rootpwd = ReadLine(0); -# chomp($rootpwd); -# ReadMode('normal'); - } - if (! $rootpwd) { - print("\nThe rootpwd is missing"); - $exit = 1 ; - } - if (! $newport) { - print("\nThe port is missing"); - $exit = 1; - } - if (! $serverHome) { - print("\nThe new instance path is missing"); - $exit = 1; - } - if (! $oldHome) { - print("\nThe old instance path is missing"); - $exit = 1; - } - if ((! $LogFileReport) && $serverHome) { - ($sec, $min, $hour, $dd, $mm, $yy) = &GetTime(); - $LogFileReport = "${serverHome}${PATHSEP}logs${PATHSEP}Migration_${dd}${mm}${yy}_${hour}${min}${sec}.log"; - } - - if ($exit) { - &usage() ; - exit(1); - } - -} - - -############################################################################### -# This subroutine is used to parse the slapd.conf configuration file and migrate specific parameters contained in it - - -sub ParseSlapdConf { - my $oldsrc = shift; - my $NumLine = 0 ; - # read the old conf file into a hash table - open( OLDSRC, $oldsrc ) || die "Can't open $oldsrc: $!: "; - LINE: while ( <OLDSRC> ) { - $NumLine++ ; - printTrace("\nLine: $_",4) ; - if (/^\s*\#/) { # skip comments - printTrace("\n# ",4) ; - next LINE; - } - if (/^\s*$/) { # skip blank lines - printTrace("\nBLANK LINE",4); - next LINE; - } elsif (/^suffix\s+/i) { - chomp($_) ; - CheckSuffix($_); - } elsif (/^plugin/i) { - printTrace("\nPLUGIN",4); - chomp($_); - if (! &isAStandardPlugin($_)) { - push @badPlugins, $_; - } - else { - my $Plugin = $_ ; - if (! &ParsePlugin($_,$NumLine)) { - printMsg("\nLine $NumLine, syntax error of the plugin:\n$Plugin"); - } - } - } elsif (/^include\s+[\"]?(.*?)[\"]?\s*$/i) { - # strip leading and trailing " - my $include_file = $1 ; - grep { s@/@\\@g } $include_file if $isNT; - if (! &isAStandardInclude($include_file)) { - printTrace("\nFILE: $1 NOT STANDARD",4) ; - &ParseConfigurationFile($include_file); - printTrace("\nEXIT ParseConfigurationFile: $include_file",4) ; - } - } elsif (/^userat\s+[\"]?(.*?)[\"]?\s*$/i) { - printTrace("\nuserat: $1",4); - my $at_file = $1 ; - grep { s@/@\\@g } $at_file if $isNT; - # Parse user defined attributes - &ParseAttributesFile($at_file); - } elsif (/^useroc\s+[\"]?(.*?)[\"]?\s*$/i) { - printTrace("\nuseroc: $1",4); - my $oc_file = $1 ; - grep { s@/@\\@g } $oc_file if $isNT; - # Parse user defined object classes - &ParseObjectClassesFile($oc_file); - } elsif (/^dynamicconf\s+[\"]?(.*?)[\"]?\s*$/i){ - printTrace("\ndynamicconf: $1",4); - my $dynamiconf_file = $1 ; - grep { s@/@\\@g } $dynamiconf_file if $isNT; - # Parse dynamic configuration file (e-g slapd.ldbm.conf) - &ParseConfigurationFile($dynamiconf_file); - } elsif (/^\s*(\S+)\s+[\"]?(.*?)[\"]?\s*$/) { - printTrace("\nParseParameters: $1",4); - # Parse parameters and record the associated value in %oldhash - &ParseParameters($1,$2,$NumLine); - } else { - printTrace("\nUnknown format of configuration data: $_",0); } - } - close(OLDSRC); - - } - - - -############################################################################# -# return 1 if the suffix already exists, 0 else -sub existSuffix { - my $suffixname = shift ; - my $nsuffix = normalizeDN($suffixname); - my $entry = $conn->search("cn=mapping tree,cn=config", "one", "(|(cn=\"$suffixname\")(cn=\"$nsuffix\"))"); - return 1 if ($entry) ; - my $cpt = 5; - my $errorCode = $conn->getErrorCode(); - while (($errorCode eq $LDAP_SERVER_UNREACHABLE) && $cpt && (! $entry)) { - printTrace("\ntry to reconnect to search cn=\"$suffixname\",cn=mapping tree,cn=config", 1); - $conn = new Mozilla::LDAP::Conn($LDAPservername,$newport,$rootDN,$rootpwd) or die "\n Unable to contact the $Version.$Minor LDAP server: $LDAPservername\n"; - $entry = $conn->search("cn=mapping tree,cn=config", "one", "(|(cn=\"$suffixname\")(cn=\"$nsuffix\"))"); - $errorCode = $conn->getErrorCode(); - $cpt--; - } - return 1 if ($entry) ; - return 0 ; -} - -# return the name of the backend if it has been successfully created, 0 else -sub createBackend { - my $suffixname = shift ; - my $backend = "MigratedDB_0" ; - my $NbRetry = 1 ; - my $entry = $conn->search("cn=$backend,cn=ldbm database,cn=plugins,cn=config ", "base","objectclass=*") ; - while ($entry) { - # try to find another name for the backend - $backend = "MigratedDB_$NbRetry" ; - $entry = $conn->search("cn=$backend,cn=ldbm database,cn=plugins,cn=config ", "base","objectclass=*") ; - $NbRetry++; - } - # normally I should have a unique name for the backend - my $suffixarg = "nsslapd-suffix" ; - $entry = $conn->newEntry() ; - $entry->setDN("cn=$backend,cn=ldbm database,cn=plugins,cn=config"); - $entry->setValues("objectclass", "top", "extensibleObject", "nsBackendInstance" ); - $entry->setValues("cn", $backend ); - $entry->setValues($suffixarg, $suffixname ); - my $res = $conn->add($entry) ; - if ($res) { - return $backend ; - } - else { - return 0 ; - } -} - -# return 1, if add the new entry in the mapping tree, else 0 -sub AddEntryInMappingTree { - my $backend = shift ; - my $entry = $conn->search("cn=$backend,cn=ldbm database,cn=plugins,cn=config ", "base","objectclass=*") ; - if ($entry) { - printTrace("\nAddEntry in progress ...",4) ; - my $suffixarg = "nsslapd-suffix" ; - my $statearg = "nsslapd-state" ; - my $backendarg= "nsslapd-backend"; - my $suffixname = $entry->{$suffixarg}[0]; - $entry = $conn->newEntry() ; - $entry->setDN("cn=\"$suffixname\",cn=mapping tree,cn=config") ; - $entry->setValues("objectclass", "top", "extensibleObject", "nsMappingTree" ); - $entry->setValues("cn", "\"$suffixname\""); - $entry->setValues($statearg, "backend"); - $entry->setValues($backendarg, $backend); - return $conn->add($entry); - } - else { - printTrace("\nNo AddEntry processed for $backend",4); - return 0 ; - } -} - - -# Treat the case where the suffix is "o=NetscapeRoot" -sub CheckSuffix { - my $suffix = shift ; - my $suffixname ; - my $expLdif; - my $confirm = "No"; - my $dest = "$serverHome${PATHSEP}db_backup" ; - my $newSlapdExecDir = "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - - if (!(/^suffix\s+\"?(.*?)\"?\s*$/i)) { - printMsg("Syntax error of the suffix: $suffix"); - return 0 ; - } - else { - $suffixname = $1 ; - } - if (/^suffix\s+\"?\s*o=netscaperoot\s*\"?\s*$/i) { - printTrace("\nFor the suffix o=NetscapeRoot, we do nothing",1); - # treat the case where the suffix is "o=NetscapeRoot" - } - else { - push @oldSuffixes, $_; - # check if the suffix already exists in the new DS target - if (! existSuffix($suffixname)) { - printTrace("\n\nSuffix $suffixname doesn't exist",1) ; - # create a new backend with the name of the suffix preceded by MigratedDB_ - my $backend = createBackend($suffixname) ; - if ($backend) { - printTrace("\nBackend: $backend has been created !!!",1); - # if the creation of the backend is ok, we add a new entry in the mapping tree - if (AddEntryInMappingTree($backend)) { - # We add the association dbname->suffix in the hash %DBNAMES - $DBNAMES{$suffixname} = $backend ; - # get the db filename - $entry = $conn->search("cn=$backend,cn=ldbm database,cn=plugins,cn=config ", "base","objectclass=*") ; - my $dirarg = "nsslapd-directory"; - $DBDirectory{$backend} = $entry->{$dirarg}[0]; - printTrace("\nThe relation $backend->$suffixname has been added to the mapping tree",2); - } - else { - printMsg("\nCOULD NOT ADD ENTRY: $backend->$suffixname IN MAPPINGTREE"); - } - } - else { - printMsg("\nCOULD NOT CREATE BACKEND: $backend"); - } - } - else { - printMsg("\n\nSuffix: $suffixname already exists"); - # the suffix already exists in the new DS - printMsg("\nMigration will overwrite existing database"); - printMsg("\nDo you want to continue Yes/No [No] ?") ; - my $answer = <STDIN> ; - if ($answer =~ /y|yes/i) { - my $nsuffix = normalizeDN($suffixname); - my $my_entry = $conn->search("cn=mapping tree,cn=config", "one", "(|(cn=\"$suffixname\")(cn=\"$nsuffix\"))"); - my $backend = $my_entry->{"nsslapd-backend"}[0]; - my $backend_entry = $conn->search("cn=$backend,cn=ldbm database,cn=plugins,cn=config ", "base","objectclass=*") ; - printMsg("Do you want to export the existing data Yes/No [Yes] ?"); - my $answer = <STDIN> ; - if (!($answer =~ /n|no/i)) { - mkdir $dest, 0700 unless (-d $dest); - $expLdif = "$dest${PATHSEP}$backend.ldif"; - while (!($confirm =~ /y|yes/i)) { - printMsg("\nEnter the full pathname of the file [$expLdif]:") ; - $answer = <STDIN> ; - chomp($expLdif = $answer) unless ($answer eq "\n"); - printMsg("\nExisting data will be exported under $expLdif"); - printMsg("\nContinue Yes/No [No] ?"); - $confirm = <STDIN>; - } - $ENV{"$LIB_PATH"}=$new_libpath; - chdir($newSlapdExecDir) or die "\nCould not change directory to $newSlapdExecDir: $!\n"; - printTrace("\nNow backing up database $CN in $expLdif\n",0); - &stopServer($root,'slapd-'.$newname); - &newinst_db2ldif($expLdif, $suffixname, $serverHome); - &startServer(); - } - # We add the association dbname->suffix in the hash %DBNAMES - $DBNAMES{$suffixname} = $backend ; - my $dirarg = "nsslapd-directory"; - $DBDirectory{$backend} = $backend_entry->{$dirarg}[0]; - printTrace("\nThe relation $backend->$suffixname has been added to the mapping tree",2); - } - } - return 1 ; -} -} - -############################################################################# -# Usefull to know the standard configuration -sub isAStandardPlugin { - my $line = shift; - chomp($line); - printTrace("\nStdPlugin?: $line",4); - if ($line =~ /^plugin\s+(database|extendop|preoperation|postoperation|matchingrule|syntax)\s+(on|off)\s+\"(.*?)\"\s+\"(.*?)\"\s+(\S+)(.*)$/i) { - # $1 = <type>, $2 = <on|off>, $3 = <name>, $4 = <pathname>, $5 = <init_function>, $6 = [<arg>]* - printTrace("\nName: $3, pathname: $4, init_function: $5",4); - - my $LC_line = lc($3); - my $Value = $stdPlugins{$LC_line} ; - if ($Value) { - printTrace("\nIS A STANDARD PLUGIN",4); - } - else { - printTrace("\nNOT A STANDARD PLUGIN",4); - } - return $stdPlugins{$LC_line} ; - } - else { - printTrace("\nSYNTAX ERROR PLUGIN",4); - return 0 ; - } -} - -sub isAStandardIndex { - my $line = shift ; - chomp($line); - if ($line =~ /^index\s+(\S+).*/i) { - my $LC_line = lc($1); - my $Value = $stdIndex{$LC_line} ; - printTrace("\nInclude: $LC_line \nValue: $Value", 4); - return $stdIndex{$LC_line}; - } - else { - return 0 ; - } -} - - -sub isAStandardInclude { - my $line = shift; - - chomp($line); - if ($isNT){ - return $stdIncludes{lc($line)}; - } - else { - return $stdIncludes{$line} ; - } -} - -############################################################################# -# -# Execute a Perldap command to update plugins definition in the new schema - -sub LDAPmodify_stdPlugin { - my $Filename = shift ; - my @pluginames = keys(%stdPlugins); - if (! $STDPLUGINS_FILE_MODIFIED) { - printTrace("\nLDAPmodify_plugin",4); - printTrace("\nMigrate plugin's...",1); - foreach $pluginame ( @pluginames ) { - my $update_plugin = 0 ; - my $ref_plugin = $stdPlugins{$pluginame}; - if ($ref_plugin ne "\n") { - my $name = $ref_plugin->name ; - # We have a name change of "uid uniqueness plugin" in DS7.0 - # to "attribute uniqueness" - $name = "attribute uniqueness" if ($name eq "uid uniqueness"); - my $entry = $conn->search("cn=$name,cn=plugins,cn=config", "base","objectclass=nsSlapdPlugin") ; - if ($entry) { - my $pluginenabled="nsslapd-pluginenabled" ; - if (($entry->{$pluginenabled}[0]) ne $ref_plugin->enable) { - $update_plugin = 1 ; - my $enable = $ref_plugin->enable ; - printTrace("\n$pluginame, plugin-enable: $enable",3) ; - $entry->setValues($pluginenabled, $enable ); - } - my $ArgNum = 0 ; - foreach $ArgValue (@{$ref_plugin->args}) { - my $Arg="nsslapd-pluginarg$ArgNum"; - printTrace("\n$Arg: $ArgValue",3) ; - if ($entry->{$Arg}[0] ne $ArgValue) { - printTrace("\n$pluginame, $Arg: $ArgValue",3) ; - $update_plugin = 1 ; - $entry->setValues($Arg, $ArgValue) ; - } - $ArgNum++ ; - } - if ($update_plugin) { - printTrace("\n$pluginame is being updated...",2); - my $res = $conn->update($entry) ; - if ($res) { - printTrace("\nupdated !",2); - } - else { - printMsg("\nError during update of plugin: $pluginame") ; - $MigrationErrors .= "\nError during update of plugin: $pluginame"; - } - } - else { - printTrace("\n$pluginame has not changed",4); - } - } - else { - printMsg("\ncan't access the plugin: cn=$name,cn=plugins,cn=config"); - } - } - else { - printTrace("\nPLUGIN NOT RECORDED: $pluginame",4) ; - } - } - } - else { - # treat the case where the user wants to look at these plugins before processing - } -} - -############################################################################# -# Execute Perldap command to add new indexes to the migrated instances - -sub LDAPmodify_Indexes { - my $Filename = shift ; - my @indexnames = keys(%newIndex); - my @suffixnames = keys(%DBNAMES); - if ((! $INDEX_FILE_MODIFIED) && (%DBNAMES)) { - # we update indexes only if there is at least one backend to migrate - printTrace("\nLDAPmodify_indexes",4); - printTrace("\nMigrate indexes...",1); - foreach $indexname ( @indexnames ) { - printTrace("\nIndexName: $indexname",4); - printTrace("\nIndexTypes: .@{$newIndex{$indexname}->types}.", 4) ; - printTrace("\nIndexOIDS: .@{$newIndex{$indexname}->oids}.", 4) ; - foreach $suffixname ( @suffixnames ) { - # check if the index already exists ! - printTrace("\nsearch for cn=$indexname,cn=index,cn=$DBNAMES{$suffixname},cn=ldbm database,cn=plugins,cn=config...", 3); - my $entry = $conn->search("cn=$indexname,cn=index,cn=$DBNAMES{$suffixname},cn=ldbm database,cn=plugins,cn=config","base","objectclass=nsIndex"); - if (! $entry) { - # create a new index - printTrace("index $indexname is being created under cn=index,cn=$DBNAMES{$suffixname},cn=ldbm database,cn=plugins,cn=config...",2); - my $entry = $conn->newEntry(); - $entry->setDN("cn=$indexname,cn=index,cn=$DBNAMES{$suffixname},cn=ldbm database,cn=plugins,cn=config"); - $entry->setValues("objectclass", "top", "nsIndex" ) ; - $entry->setValues("cn", $indexname) ; - $entry->setValues("nssystemindex", "false") ; - my @types = @{$newIndex{$indexname}->types} ; - my @oids = @{$newIndex{$indexname}->oids} ; - $entry->setValues("nsindextype", @types) if (@types) ; - $entry->setValues("nsmatchingrule", @oids ) if (@oids); - my $res = $conn->add($entry) ; - if ($res) { - printTrace("\nAdd index successfully: $indexname for backend: $DBNAMES{$suffixname}",2); - } - else { - printMsg("\n Failed to add the index: $indexname to backend: $DBNAMES{$suffixname}"); - $MigrationErrors .= "\n Failed to add the index: $indexname to backend: $DBNAMES{$suffixname}" ; - } - } - elsif ($entry->{nssystemindex}[0] eq "false") { - # if the index is not a system index, we update it - printTrace("\nindex $indexname is being processed under cn=index,cn=$DBNAMES{$suffixname},cn=ldbm database,cn=plugins,cn=config...",2); - my @types = @{$newIndex{$indexname}->types} ; printTrace("\ntypes: .@types.",2) ; - my @oids = @{$newIndex{$indexname}->oids} ; printTrace("\noids: .@oids.",2) ; - my @existing_types = $entry->getValues("nsindextype"); - my @existing_oids = $entry->getValues("nsmatchingrule"); - # get the elements present in @types and not present in @existing_types - my @typesToAdd = &getDiff(\@types, \@existing_types); - # same for matchingrules - my @oidsToAdd = &getDiff(\@oids, \@existing_oids); - foreach $newtype (@typesToAdd) { - $entry->addValue("nsindextype", $newtype); printTrace("\nnewtype: $newtype",2); - } - foreach $newoid (@oidsToAdd) { - $entry->addValue("nsmatchingrule", $newoid); - } - if (@typesToAdd || @oidsToAdd) { - my $res = $conn->update($entry) ; - if ($res) { - printTrace("\nUpdate index successfully: $indexname for backend: $DBNAMES{$suffixname}",2); - } - else { - printMsg("\n Failed to update the index: $indexname to backend: $DBNAMES{$suffixname}"); - $MigrationErrors .= "\n Failed to update the index: $indexname to backend: $DBNAMES{$suffixname}" ; - } - } - else { - printTrace("\nNothing to update",2); - } - } - else { - printTrace("\nThe index: $indexname is a system index. It can't be updated",2); - } - } - } - - } - else { - # treat the case where the user wants to look at these indexes before processing - } - -} - -############################################################################# -# -# Execute a Perldap command to add all user defined object classes in the new schema - -sub LDAPmodify_User_oc { - my $Filename = shift ; - if (! $USER_OC_FILE_MODIFIED) { - printTrace("\nLDAPmodify_User_oc",4); - printTrace("\nMigrate objectclasses...",1); - foreach $objectname ( @User_oc_names ) { - my $entry = $conn->search("cn=schema", "base","objectclass=*") ; - die "\ncan't connect to object: cn=schema\n" unless ($entry); - printTrace("\nObjectName: $objectname\nValue: $User_oc{$objectname}",3); - next if ($entry->hasValue("objectclasses",$User_oc{$objectname},1)) ; - $entry->addValue("objectclasses",$User_oc{$objectname},"1") ; - my $res = $conn->update($entry) ; - my $err = $conn->getErrorCode(); - if ($res) { - printTrace("\nobjectclass: $User_oc{$objectname} added",2); - } elsif ($err == 20) { # already exists - printTrace("\nobjectclass: $User_oc{$objectname} already exists",1); - } else { - printMsg("\nCan\'t add objectclass to the schema: $User_oc{$objectname}"); - my $msg = $conn->getErrorString(); - printMsg("\nMsg: $msg"); - $MigrationErrors .= "\nCan\'t add objectclass to the schema: $User_oc{$objectname}" ; - } - } - } - else { - # treat the case where the user wants to look at these objectclasses before processing - } -} - -############################################################################# -# -# Execute a Perldap command to add all user defined attributes in the new schema - -sub LDAPmodify_User_at { - my $Filename = shift ; - my @attributenames = keys(%User_at); - if (! $USER_AT_FILE_MODIFIED) { - - printTrace("\nLDAPmodify_User_at",4); - printTrace("\nMigrate attributes...",1); - foreach $attributename ( @attributenames ) { - my $entry = $conn->search("cn=schema", "base","objectclass=*") ; - printTrace("\nAtributeName: $attributename, Value: $User_at{$attributename}",3); - die "\nentry not found cn=schema\n" unless $entry ; - next if ($entry->hasValue("attributetypes",$User_at{$attributename},1) ) ; - my $res = $entry->addValue("attributetypes",$User_at{$attributename},"1") ; - if (! $res) { - printMsg("\nCan\'t add attribute to the schema: $User_at{$attributename}"); - $MigrationErrors .= "\nCan\'t add attribute to the schema: $User_at{$attributename}" ; - } - my $res = $conn->update($entry) ; - my $err = $conn->getErrorCode(); - if ($res) { - printTrace("\nattribute: $attributename added",2); - } elsif ($err == 20) { # already exists - printTrace("\nattribute: $attributename already exists",1); - } - else { - printMsg("\nCan\'t add attribute to the schema: $User_at{$attributename}"); - my $msg = $conn->getErrorString(); - printMsg("\nMsg: $msg"); - $MigrationErrors .= "\nCan\'t add attribute to the schema: $User_at{$attributename}" ; - } - } - } - else { - # treat the case where the user wants to look at these attributes before processing - } -} - -############################################################################# -# Add an object class to the user_oc hash and reset the object !!! -sub AddObjectClass { - my $ObjectClass = shift ; - my $ObjectName = $ObjectClass->{'ObjectName'} ; - my $Object_oid = $ObjectClass->{'Object_oid'} ; - my $Object_superior = $ObjectClass->{'Object_superior'} ; - my $Object_requires = $ObjectClass->{'Object_requires'} ; - my $Object_allows = $ObjectClass->{'Object_allows'} ; - my $ObjectClassDef = "( $Object_oid NAME \'$ObjectName\' DESC \'\' SUP $Object_superior STRUCTURAL MUST ($Object_requires) MAY ($Object_allows) X-ORIGIN \'user defined\' )"; - if ( (!($ObjectName =~ /^top$/i)) && ( ! $User_oc{$ObjectName} )) { - $User_oc{$ObjectName} = $ObjectClassDef ; - push @User_oc_names, $ObjectName ; - printTrace("ObjectName: $ObjectName \nObject_oid: $Object_oid \nObject_superior:$Object_superior \nObject_requires: $Object_requires \nObject_allows: $Object_allows \nObjectClassDefinition: $User_oc{$ObjectName}\n",4); - } - elsif ( ($User_oc{$ObjectName}) && ($User_oc{$ObjectName} ne $ObjectClassDef) ) { - printMsg("\nAttempt to redifine the objectclass: $ObjectName previously defined in your configuration file. Operation not allowed "); - } - else { - printMsg("\nAttempt to redifine the objectclass: top. Operation not allowed"); - } - resetObjectClass($ObjectClass); -} - -############################################################################# -# Build an LDIF attribute and add it to the user_at hash -sub AddAttribute { - my $Attr = shift ; - my $AttributeName = $Attr->{'AttributeName'}; - my $Attribute_oid = $Attr->{'Attribute_oid'}; - my $Attribute_aliases = $Attr->{'Attribute_aliases'}; - my $Attribute_syntax = $Attr->{'Attribute_syntax'}; - my $Attribute_single = $Attr->{'Attribute_single'}; - my $AttributeDef = "( $Attribute_oid NAME ( \'$AttributeName\' $Attribute_aliases) DESC \'User Defined Attribute\' SYNTAX $Attribute_syntax $Attribute_single X-ORIGIN 'user defined' )" ; - printTrace("\nAttributeDef: $AttributeDef",4); - $User_at{$AttributeName} = $AttributeDef ; -} -############################################################################# -# add the index structure to the newIndex hash -sub AddIndex { - my $ref_index = shift ; - my $state = shift ; - printTrace("\nAddIndex, last state: $state",4) ; - if ($state == 1) { - $ref_index->specific("ALL") ; - return 1 ; - } - elsif ($state == 6) { - $ref_index->specific("NONE") ; - return 1 ; - } - if (($state == 1) || ($state == 3) || ($state == 5) || ($state == 6)) { - foreach $name (@{$ref_index->names}) { - $newIndex{$name} = $ref_index ; # record the ref to the index struct in the newIndex hash - } - return 1 ; - } - else { - return 0 ; - } -} - -############################################################################# -# add the plugin structure to the stdPlugin hash - -sub AddPlugin { - my $ref_plugin = shift ; - printTrace("\nAddPlugin",4) ; - $stdPlugins{lc($ref_plugin->name)} = $ref_plugin ; - my $name = $ref_plugin->name ; - my $type = $ref_plugin->type ; - my $enable = $ref_plugin->enable ; - - printTrace("\nPluginName: $name",4); - printTrace("\nPluginType: $type",4); - printTrace("\nPluginEnable: $enable",4); - printTrace("\nPluginArgs: @{$ref_plugin->args}",4); - return 1 ; -} - - -############################################################################# -# parse a plugin definition and call the addindex - -sub ParsePlugin { - my $Plugin = shift ; - my $NumLine = shift ; - my $state = 0 ; - my $ErrorMsg = "Syntax error of a plugin definition. \n line parsed:"; - my $ref_plugin = S_plugin->new(); - printTrace("\nParsePlugin: $_",4); - if (/^plugin\s+(database|extendop|preoperation|postoperation|matchingrule|syntax)\s+(on|off)\s+\"(.*?)\"\s+\"(.*?)\"\s+(\S+)(.*)$/i) { - # $1 = <type>, $2 = <on|off>, $3 = <name>, $4 = <pathname>, $5 = <init_function>, $6 = [<arg>]* - $ref_plugin->name($3); - $ref_plugin->type($1); - $ref_plugin->enable($2); - $_ = $6 ; - my $ArgNb = 0 ; - my $prec ; - my $arg ; - my $Unix_oldDir = $oldDir ; - my $Unix_root = $root ; - grep { s@\\@/@g } $Unix_oldDir if $isNT; - grep { s@\\@/@g } $Unix_root if $isNT; - while (!(/^\s*$/)) { - if (/^\s*\".*?\"/) { - s/^\s*\"(.*?)\"(.*)/$2/i ; - $arg = $1 ; - } - elsif (/^\s*[^\"\s]+/) { - s/^\s*([^\"\s]+)(.*)/$2/i ; - $arg = $1 ; - } - $prec = $_ ; - $_ = $arg ; - - s@$Unix_oldDir@$Unix_root@ig ; - s/$type-$oldname/$type-$newname/ig ; - @{$ref_plugin->args}[$ArgNb++] = $_ ; - $_ = $prec ; - } - if (/^\s*$/) { - return AddPlugin($ref_plugin); - } - else { - return 0 ; - } - } - return 0 ; -} - -############################################################################# -# parse an index definition and call the addindex - -sub ParseIndex { - my $index = shift ; - my $NumLine = shift ; - my $ref_index = S_index->new() ; - my $Value ; - my $state = 0 ; - my $ErrorMsg = "Syntax error of an index definition.\nline parsed:"; - printTrace("\nParseIndex: $_",4) ; - s/,/, /g ; - s/\s+,/,/g ; - s/^index\s+//i ; # substitute the token index - while (!(/^\s*$/)) { - s/^\s*(\S+)(.*)$/$2/ ; - $Value = $1 ; - printTrace("\nValue: $Value",4); - printTrace("\nState: $state",4) ; - SWITCH: { - if ($state == 0) { - if ($Value =~ /[^\.]/) { - if ($Value =~ /(\S+),$/) { - push @{$ref_index->names}, $1 ; - } - else { - $state = 1 ; - push @{$ref_index->names}, $Value ; - } - } - else { - return 0 ; - } - last SWITCH ; - } - if ($state == 1) { - if ($Value =~ /^none$/i) { - $state = 6 ; # end of the index definition - } - elsif ($Value =~ /^\"\"$/) { - $state = 4 ; # we expect to have at least one OID - } - elsif ($Value =~ /(\S+),$/) { - $state = 2 ; - push @{$ref_index->types}, $1 ; - } - else { - $state = 3 ; - push @{$ref_index->types}, $Value ; - } - last SWITCH ; - } - if ($state == 2) { - if ($Value =~ /(\S+),$/) { - push @{$ref_index->types}, $1 ; - } - else { - $state = 3 ; - push @{$ref_index->types}, $Value ; - } - last SWITCH ; - } - if ($state == 3) { - if ($Value =~ /(\S+),$/) { - $state = 4 ; - push @{$ref_index->oids}, $1 ; - } - else { - $state = 5 ; - push @{$ref_index->oids}, $Value ; - } - last SWITCH ; - } - if ($state == 4) { - if ($Value =~ /(\S+),$/) { - push @{$ref_index->oids}, $1 ; - } - else { - $state = 5 ; - push @{$ref_index->oids}, $Value ; - } - last SWITCH ; - } - } - } -return AddIndex($ref_index,$state) ; - -} - -############################################################################# - -sub ParseAttribute { - - - my $Attr = shift ; - my $NumLine = shift ; - my $state = 1 ; - my $ErrorMsg = "Syntax error of an attribute definition.\nline parsed:"; - my %Attribute = ( - 'AttributeName' => "", - 'Attribute_oid' => "", - 'Attribute_aliases' => "", - 'Attribute_syntax' => "", - 'Attribute_single' => "" - ); - my $AttributeName = " "; - printTrace("\nParseAttribute",4); - while (!(/^\s*$/)) { - s/^(.*?)(\S+)\s*$/$1/ ; - printTrace("\nValue: $2",4); - printTrace("\nState: $state",4) ; - my $Value = $2 ; - SWITCH: { - if ($state == 1) { - if (isAllowedModifier($Value)) { - $state = 1 ; - $modifier = lc($Value); - $AttrVar = 'Attribute_' . $modifier ; - $Attribute{$AttrVar} = &getModifierValue($Value) ; - } - elsif (&isAllowedPlugin($Value)) { - $state = 2 ; - $Attribute{'Attribute_syntax'} = &getSyntaxOid($Value) ; - } - else { - return 0 ; - } - last SWITCH ; - } - if ($state == 2) { - if ($Value =~ /[\.]|-oid$/) { - $Attribute{'Attribute_oid'} = "$Value" ; - printTrace("\nAttribute-oid: $Attribute{'Attribute_oid'}",3); - $state = 3 ; - } - elsif ($Value =~ /[^\.]/) { - $AttributeName = $Attribute{'AttributeName'} ; - if ($AttributeName) { $Attribute{'Attribute_aliases'} .= "\'$AttributeName\' " ;} - $Attribute{'AttributeName'} = $Value ; - $state = 4 ; - } - else { - return 0 ; - } - last SWITCH ; - } - if ($state == 3) { - if ($Value =~ /[^\.]/) { - $AttributeName = $Attribute{'AttributeName'} ; - if ($AttributeName) { $Attribute{'Attribute_aliases'} .= "\'$AttributeName\' " ;} - $Attribute{'AttributeName'} = $Value ; - $state = 4 ; } - else { - return 0 ; - } - last SWITCH ; - } - if ($state == 4) { - if ($Value =~/^attribute$/i){ - $state = 5; - } - elsif ($Value =~/[^\.]/i) { - $AttributeName = $Attribute{'AttributeName'} ; - if ($AttributeName) { $Attribute{'Attribute_aliases'} .= "\'$AttributeName\' " ;} - $Attribute{'AttributeName'} = $Value ; - } - else { - return 0 ; - } - last SWITCH ; - } - if ($state == 5) { - return 0 ; - last SWITCH ; - } - } - } - $Attribute{'Attribute_oid'} = $Attribute{'AttributeName'} . '-oid' unless ($Attribute{'Attribute_oid'}) ; - return AddAttribute(\%Attribute) ; -} - - -############################################################################# -# fill in the hash HashParametersName - -sub FillHashParametersName { - my @paramnames = ( keys(%GeneralSrvParamToMigrate), keys(%GlobalConfigLDBMparamToMigrate), keys(%LDBMparamToMigrate)); - foreach $param (@paramnames) { - $HashParametersName{$param} = '\n'; - } -} - - -# Parse parameters -sub ParseParameters { - my $param = shift ; - my $value = shift ; - my $NumLine = shift ; - my $ErrorMsg = "parameter unknown, or not to be migrated: "; - if ($HashParametersName{lc($param)} && ($value !~ /^\s*$/)) { - $HashParametersName{lc($param)} = $value ; - printTrace("\nParam: $param is present",4); - } - else { - printTrace("\n$NumLine, $ErrorMsg,$param",4); - } - -} - -# add general server parameters -sub AddGeneralParameters { - my @paramnames = keys(%GeneralSrvParamToMigrate); - my $entry = $conn->search("cn=config","base","objectclass=*"); - die "\ncan't access to object: cn=config. \nMigration stopped\n" unless ($entry); - printTrace("\nAddGeneralParameters",4); - foreach $param (@paramnames) { - my $LDAPparam = $GeneralSrvParamToMigrate{$param} ; - my $Value = $HashParametersName{$param} ; - if (($Value ne '\n') && ($entry->{$LDAPparam}[0] ne $Value)) { - printTrace("\nLDAPparam: $LDAPparam, Value: $Value",4); - $entry->setValues($LDAPparam, $Value); - my $res = $conn->update($entry); - if ($res) { - printTrace("\nUpdate successfully $LDAPparam ",0); - } - else { - printMsg("\nCan't update parameter: $LDAPparam"); - } - } - } -} - - -# add general LDBM parameters -sub AddGeneralLDBMParameters { - my @paramnames = keys(%GlobalConfigLDBMparamToMigrate); - my $entry = $conn->search("cn=config,cn=ldbm database,cn=plugins,cn=config","base","objectclass=*"); - die "\ncan't access to object: cn=config,cn=ldbm database,cn=plugins,cn=config. \nMigration stopped\n" unless ($entry); - printTrace("\nAddGeneralLDBMParameters",4); - foreach $param (@paramnames) { - my $LDAPparam = $GlobalConfigLDBMparamToMigrate{$param} ; - my $Value = $HashParametersName{$param} ; - if (($Value ne '\n') && ($entry->{$LDAPparam}[0] ne $Value)) { - printTrace("\nLDAPparam: $LDAPparam, Value: $Value",4); - $entry->setValues($LDAPparam, $Value); - my $res = $conn->update($entry); - if ($res) { - printTrace("\nUpdate successfully $LDAPparam ",0); - } - else { - printMsg("\nCan't update parameter: $LDAPparam"); - } - } - } -} - -# add specific LDBM parameters -sub AddSpecificLDBMParameters { - my @paramnames = keys(%LDBMparamToMigrate); - my %REV_DBNAMES = reverse %DBNAMES ; - my @dbnames = keys(%REV_DBNAMES); - printTrace("\nAddSpecificLDBMParameters",4); - foreach $dbname (@dbnames) { - my $entry = $conn->search("cn=$dbname,cn=ldbm database,cn=plugins,cn=config","base","objectclass=*"); - die "\ncan't access to object: cn=$dbname,cn=ldbm database,cn=plugins,cn=config. \nMigration stopped\n" unless ($entry); - foreach $param (@paramnames) { - my $LDAPparam = $LDBMparamToMigrate{$param} ; - my $Value = $HashParametersName{$param} ; - if (($Value ne '\n') && ($entry->{$LDAPparam}[0] ne $Value)) { - printTrace("\nLDAPparam: $LDAPparam, Value: $Value",4); - $entry->setValues($LDAPparam, $Value); - my $res = $conn->update($entry); - if ($res) { - printTrace("\nUpdate successfully $LDAPparam",2); - } - else { - printMsg("\nCan't update parameter: $LDAPparam"); - } - } - } - } -} - -############################################################################# -# Parse a configuration file potentialy tuned by the user (different from slapd.user_oc.conf and slapd.user_at.conf) - -sub ParseConfigurationFile { - - my $FileToParse = shift; - my $NumLine = 0; - my $PARSE_OBJECTCLASSES = 0 ; # 1 if there are objectclass definitions in the file - printTrace("\nParseConfigurationFile: $FileToParse",4) ; - printTrace("\nParse $FileToParse",2); - # read each line of the configuration file - my $CONFIGFILE = "CONFIGFILE.$FileToParse" ; - open( $CONFIGFILE, $FileToParse ) || die "Can't open $FileToParsec: $!: "; - LINE: while ( <$CONFIGFILE> ) { - $NumLine++ ; - if (/^\s*\#/) { # skip comments - next LINE; - } - if (/^\s*$/) { # skip blank lines - next LINE; - } elsif (/^suffix\s+/i) { - chomp($_) ; - CheckSuffix($_) ; - } elsif (/^plugin/i) { - chomp($_); - if (! &isAStandardPlugin($_)) { - push @badPlugins, $_; - } - else { - my $Plugin = $_ ; - if (! &ParsePlugin($_,$NumLine)) { - printMsg("\nLine $NumLine, syntax error of the plugin:\n$Plugin"); - } - } - } elsif (/^index/i) { - chomp($_); - if (! &isAStandardIndex($_)) { - my $Index = $_ ; - if (! &ParseIndex($_,$NumLine)) { - printMsg("\nLine $NumLine, syntax error of index:\n$Index"); - } - } - } elsif (/^include\s+[\"]?(.*?)[\"]?\s*$/i) { - # strip leading and trailing " - my $include_file = $1 ; - grep { s@/@\\@g } $include_file if $isNT; - if (! &isAStandardInclude($include_file)) { - &ParseConfigurationFile($include_file); - } - } elsif (/^attribute\s+\S+/i) { - chomp($_); - my $Attrib = $_ ; - if (! &ParseAttribute($_,$NumLine)) { - printMsg("\nLine $NumLine, syntax error of attribute:\n$Attrib"); - } - } elsif (/^objectclass\s+(\S+)\s*$/i) { - # At least one objectclass is present in the file - $PARSE_OBJECTCLASSES = 1; - } elsif (/^\s*(\S+)\s+[\"]?(.*?)[\"]?\s*$/) { - # Parse parameters and record the associated value in %Oldhash - &ParseParameters($1,$2,$NumLine); - } - } - close($CONFIGFILE); - ParseObjectClassesFile($FileToParse) if ($PARSE_OBJECTCLASSES); # parse objectclass definition - -} - -############################################################################# -# Parse the file specified in the userat attribute - -sub ParseAttributesFile { - my $userat_file=shift ; - my $NumLine = 0; - printTrace("\nParseAttributesFile: $userat_file",4); - printTrace("\nParse user defined attributes file: $userat_file",2); - # read each line of the configuration file - open( ATTRFILE, $userat_file ) || die "Can't open $FileToParsec: $!: "; - LINE: while ( <ATTRFILE> ) { - $NumLine++ ; - if (/^\s*\#/) { # skip comments - next LINE; - } - if (/^\s*$/) { # skip blank lines - next LINE; - } elsif (/^attribute\s+\S+/i) { - chomp($_); - my $Attrib = $_ ; - if (! &ParseAttribute($_, $NumLine)) { - printMsg("\nLine $NumLine, syntax error of attribute:\n$Attrib"); - } - } - } - close(ATTRFILE); -} - -############################################################################# -# Parse the file specified in the useroc token - -sub ParseObjectClassesFile { - my $useroc_file = shift ; - my %ObjectClass = ( - 'ObjectName' => " ", - 'Object_oid' => " ", - 'Object_superior' => "top", - 'Object_requires' => " ", - 'Object_allows' => " " - ); - - my $state = 0; - my $ErrorMsg = "Syntax error of an object class definition.\nline parsed:"; - my $LineNb = 0 ; # Number of the current line parsed in the file - printTrace("ParseObjectClassesFile: $useroc_file\n",4) ; - # read each line of the configuration file - open( OBJCLASSFILE, $useroc_file ) || die "Can't open $FileToParsec: $!: "; - printTrace("Begin the parsing of the file: $useroc_file",4); - LINE: while ( <OBJCLASSFILE> ) { - printTrace("Current Line: $_",4); - $LineNb++ ; - if (/^\s*\#/) { # skip comments - next LINE; - } - if (/^\s*$/) { # skip blank lines - next LINE; - } - SWITCH: { - if ($state == 0) { resetObjectClass(\%ObjectClass); - if (/^objectclass\s+(\S+)\s*$/i) { - $ObjectClass{'ObjectName'} = $1; - $state = 1 ;} - else {} # printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - if ($state == 1) {if (/^\s+oid\s+(\S+)\s*$/i) { - $ObjectClass{'Object_oid'} = $1; - $state = 2 ;} - elsif (/^\s+superior\s+(\S+)\s*$/i) { - $ObjectClass{'Object_superior'} = $1; - $state = 3 ; - } - elsif (/^\s+requires\s*$/i) { - $state = 4; - } - elsif (/^\s+allows\s*$/i) { - $state = 5; - } - else {$state=0; printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - if ($state == 2) {if (/^\s+superior\s+(\S+)\s*$/i) { - $ObjectClass{'Object_superior'} = $1; - $state = 3 ;} - elsif (/^\s+requires\s*$/i) { - $state = 4; - } - elsif (/^\s+allows\s*$/i) { - $state = 5; - } - else { $state=0; printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - if ($state == 3) {if (/^\s+requires\s*$/i) - { $state = 4; } - elsif (/^objectclass\s+(\S+)\s*$/i) { - # run an ldap add before to continue - &AddObjectClass(\%ObjectClass); - $ObjectClass{'ObjectName'} = $1; - $state = 1 ;} - elsif (/^\s+allows\s*$/i) - { $state = 5; } - else {$state = 0; printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - if ($state == 4) {if (/^\s+([^,\s]+),\s*$/i) { - $ObjectClass{'Object_requires'}.=$1." \$ "; } - elsif (/^\s+([^,\s]+)\s*$/i) { - $ObjectClass{'Object_requires'}.=$1." "; - $state = 6; } - else {$state = 0;printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - if ($state == 5) {if (/^\s+([^,\s]+),\s*$/i) { - $ObjectClass{'Object_allows'}.=$1." \$ "; } - elsif (/^\s+([^,\s]+)\s*$/i) { - $ObjectClass{'Object_allows'}.=$1." "; - # run an ldap add before to continue - &AddObjectClass(\%ObjectClass); - $state = 0; } - else {$state = 0; printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - if ($state == 6) {if (/^objectclass\s+(\S+)\s*$/i) { - # run an ldap add before to continue - &AddObjectClass(\%ObjectClass); - $ObjectClass{'ObjectName'} = $1; - $state = 1 ;} - elsif (/^\s+allows\s*$/i) { - $state = 5;} - else {$state = 0; printMsg($ErrorMsg,$_,$LineNb);} - last SWITCH;} - } - } - close(OBJCLASSFILE); - if (($state == 3) || ($state == 4) || ($state == 5) || ($state == 6)) { - &AddObjectClass(\%ObjectClass); - } - printTrace("state: $state",4); -} - -############################################################################# -# printMsg print message to the user standard output. - -sub printMsg { - - my $TypeMsg = shift ; - my $Msg = shift ; - my $LineNb = shift ; - if ($LineNb) { - printTrace("Line: $LineNb, $TypeMsg, $Msg"); - } - else { - printTrace("$TypeMsg $Msg"); - } -} - -############################################################################# -# print message error to the user standard output. - -sub printTrace { - - my $Msg = shift ; - my $level = shift ; - if ($level <= $TRACELEVEL) { - print($Msg); - print LOGFILE $Msg ; - } -} - -############################################################################# -# reset an objectclass structure - -sub resetObjectClass { - my $ObjectClass = shift; - $ObjectClass->{'ObjectName'} = " " ; - $ObjectClass->{'Object_oid'} = " " ; - $ObjectClass->{'Object_superior'} = "top" ; - $ObjectClass->{'Object_requires'} = " " ; - $ObjectClass->{'Object_allows'} = " " ; -} - -############################################################################# -# this subroutine implements a very stupid version of diff - -sub diff { - my $f1 = shift; - my $f2 = shift; - my $lineToBeginWith = shift; - my $NULL = "" ; - my $diff_f1 = $NULL ; - my $diff_f2 = $NULL ; - my $retval = $NULL ; - my $ret; - open(F1, "$f1") or die "Could not open file $f1"; - open(F2, "$f2") or close(F1), die "Could not open file $f2"; - - while (defined($l1 = <F1>)) { - if ($lineToBeginWith){ - $lineToBeginWith -- ; - next ; - } - next if ($l1 =~ /^\#/); - $ret = defined($l2 = <F2>); - if ($ret) { - $ret = defined($l2 = <F2>) while ($ret && ($l2 =~ /^\#/)) ; - if ($ret) { - if (!($l1 eq $l2)) { - - # ignore whitespace - $l1_clean = $l1 ; - $l2_clean = $l2 ; - $l1_clean =~ s/\s//g; - $l2_clean =~ s/\s//g; - - if (!($l1_clean eq $l2_clean)) { - $diff_f1 .= "${l1}" unless ($l1_clean eq $NULL); - $diff_f2 .= "${l2}" unless ($l2_clean eq $NULL); - } - } - } - else { - next if ($l1 =~ /^\s*$/) ; - $diff_f1 .= "${l1}"; - } - } - else { - next if ($l1 =~ /^\s*$/) ; - $diff_f1 .= "${l1}"; - } - } - - while (defined($l2 = <F2>)) { - if (($l2 =~ /^\#/) || ($l2 =~ /^\s*$/)) { - next ; - } - else { - $diff_f2 .= "${l2}" ; - } - } - - close(F1); - close(F2); - - $retval .= "- differences present in your config file but not in standard file:\n\n". "$diff_f1\n" if ($diff_f1) ; - $retval .= "- differences present in standard file but not in your config file:\n\n" . "$diff_f2" if ($diff_f2) ; - return $retval ; -} - -sub CompareStdConfigFiles { - # Compare each configuration file against its default version. If it has changed, - # notify the user that the file has changed and will need to be checked by the - # user. This should be safe to do because there should be no path information - # stored in these conf files, which are just schema stuff. - # printTrace("\nCheck if standard configuration files have changed",3); - - my $origFilePath = "$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}install${PATHSEP}config${PATHSEP}" ; - my $FilesChanged = ""; - my $AllDiffs = "***********************************************************************"; - my $NoChanges = "" ; - my $lineToBegin = 0 ; - printTrace("\nVersion of the old directory server: $oldVersion.$oldMinor",0); - opendir(CONFDIR, $oldConfDir) or - die "Error: could not open migrated config dir $oldConfDir: $!"; - - foreach $file (readdir(CONFDIR)) { - $origFile = $origFilePath . $file ; - $configFile = $oldConfDir . $file ; - if ((! exists($userDefinedConfigFiles{lc($file)})) && (-f $origFile)) { - my $lineToBegin = 1 if (lc($file) eq "slapd-collations.conf"); # we ignore the first line of slapd-collations - $diffs = &diff($configFile, $origFile, $lineToBegin); - $lineToBegin = 0 if $lineToBegin ; - if ($diffs) { - $FilesChanged .= "\n$configFile"; - $AllDiffs .= "\n$configFile is different than the standard configuration file" ; - $AllDiffs .= "\nYou will need to check this file and make sure its changes are compatible "; - $AllDiffs .= "with the new directory server\nHere are the differences:\n"; - $AllDiffs .= "$diffs \n\n"; - $AllDiffs .= "***********************************************************************"; - } - else { - $NoChanges .= "\n$configFile"; - } - } - } - closedir(CONFDIR); - -if ($FilesChanged) { - printTrace("\nNo changes to old configuration files:$NoChanges",3) ; - printTrace("\n***********************************************************************",3) ; - printMsg("\nThe following standard files have been modified: $FilesChanged"); - if ($NO_INPUT_USER) { - # do nothing - } - else { - printMsg("\nDo you want to see the differences Yes/No [No] ?") ; - my $answer = <STDIN> ; - if ($answer =~ /y|yes/i) { - printMsg("$AllDiffs"); - } - printMsg("\nDo you want to continue the migration Yes/No [No] ?"); - $answer = <STDIN> ; - if (! ($answer =~ /y|yes/i)) { - exit(1); - } - } - } -} - - -############################################################################# - -sub db2ldif { - my ($conf, $ldif_dir) = @_; - $ENV{"$LIB_PATH"}=$old_libpath; - if (!$conf) { - $conf = "$oldHome${PATHSEP}config${PATHSEP}slapd.conf"; - } - if (! $ldif_dir) { $ldif_dir = $ldif_rep ;} - if (!(-d $ldif_dir)) { - mkdir($ldif_dir,0777) or die "can't create $ldif_rep to store temporary ldif files"; - } - my $dir = "$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server"; - chdir($dir) or - die "Error: could not change directory to $dir: $!"; - my @suffixnames = keys(%DBNAMES) ; - foreach $suffixname (@suffixnames) { - my $ldif_file = $ldif_dir.$DBNAMES{$suffixname}.".ldif" ; - # If we are on NT, ${quote} is setup to "\"", else it's setup to "" - # As the suffix can contain some space characters, I write the suffix parameter: "\"$suffixname\"" rather than "${quote}$suffixname${quote}" - my @cmd = - ( "${quote}$oldDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . - "${PATHSEP}$slapdExecName${quote}", "db2ldif", '-n', '-f', - "${quote}$conf${quote}", '-a', "${quote}$ldif_file${quote}", - '-d', '1','-s',"\"$suffixname\"" ); - open(DB2LDIF, "${quote}@cmd${quote} 2>&1|") or - die "Error: could not execute @cmd: $!"; - sleep(1); # allow pipe to fill with data - $ii = 0; # counter - while (<DB2LDIF>) { - ++$ii; - if (($ii % 250) == 0) { - printMsg(" Processing...\n"); - } - } - close(DB2LDIF); - # set the ownership of the ldif file; should be the same as the new slapd user id - if ((! $isNt) && ($oldlocaluser ne $localuser)) { - if (-f $ldif_file) { - chown( $newuid, $newgid, $ldif_file) or printMsg("\nUnable to change the ownership of $ldif_file to $localuser") ; - } - } - } - print " Done.\n"; - chdir($curdir) or die "Could not change directory to $curdir: $!"; -} - -############################################################################# -# This db2ldif is used to export database of the new instance - -sub newinst_db2ldif { - my $ldif = shift ; - my $include_suffix = shift ; - my $home = shift ; - my $db2ldif_param = "db2ldif -r -D $home -a $ldif -s \"$include_suffix\""; - - open(DB2LDIF, "${quote}${quote}$slapdExecName${quote} $db2ldif_param${quote} 2>&1 |") or die "Could not run ns-slapd program $ldif2db_exe\n"; - sleep(1); # allow some data to accumulate in the pipe - my $ii = 0; - while (<DB2LDIF>) { - ++$ii; - if (($ii % 250) == 0) { - printMsg(" Processing...\n"); - } - printMsg($_); - } - close(DB2LDIF); - # set the ownership of the ldif file; should be the same as the 5.x slapd user id - if ((! $isNt) && ($oldlocaluser ne $localuser)) { - if (-f $ldif) { - chown( $newuid, $newgid, $ldif) or printMsg("\nUnable to change the ownership of $ldif to $localuser") ; - } - } -} - -############################################################################# - -# this is used to run the system() call, capture exit and signal codes, -# and die() upon badness; the first argument is a directory to change -# dir to, if any, and the rest are passed to system() -sub mySystem { - my $rc = &mySystemNoDie(@_); - my ($dir, @args) = @_; - if ($rc == 0) { -# success - } elsif ($rc == 0xff00) { - die "Error executing @args: error code $rc: $!"; - } elsif ($rc > 0x80) { - $rc >>= 8; - die "Error executing @args: error code $rc: $!"; - } else { - if ($rc & 0x80) { - $rc &= ~0x80; - } - die "Error executing @args: received signal $rc: $!"; - } - - # usually won't get return value - return $rc; -} - -# This version does not die but just returns the error code -sub mySystemNoDie { - my ($dir, @args) = @_; - if ($dir && ($dir ne "")) { - chdir($dir) or die "Could not change directory to $dir: $!"; - } - my $cmd = $args[0]; - # the system {$cmd} avoids some NT shell quoting problems if the $cmd - # needs to be quoted e.g. contains spaces; the map puts double quotes - # around the arguments on NT which are stripped by the command - # interpreter cmd.exe; but don't quote things which are already quoted - my @fixargs = map { /^[\"].*[\"]$/ ? $_ : $quote . $_ . $quote } @args; - my $rc = 0; - if ($cmd =~ /[.](bat|cmd)$/) { - # we have to pass batch files directly to the NT command interpreter - $cmd = $com_spec; -# print "system $cmd /c \"@fixargs\"\n"; - $rc = 0xffff & system {$cmd} '/c', "\"@fixargs\""; - } else { -# print "system $cmd @fixargs\n"; - $rc = 0xffff & system {$cmd} @fixargs; - } - chdir(${curdir}) or die "Could not change directory to $curdir: $!"; - return $rc; -} - -############################################################################# -sub manyLdif2db { - my %rev_dbnames = reverse(%DBNAMES); - @backends = keys(%rev_dbnames); - $ENV{"$LIB_PATH"}=$new_libpath; - chdir($slapdExecDir) or die "Could not change directory to $slapdExecDir: $!"; - foreach $backend (@backends) { - my $ldif = "${ldif_rep}$backend.ldif" ; - if (! -f $ldif) { - $ldif = ${ldif_rep}."data.ldif"; - } - &Ldif2db($ldif, $backend); - } - # remove the empty ldif directory - # but not if using the data dir - if (!$olddatadir) { - rmdir($ldif_rep); - } - chdir($curdir) or die "Could not change directory to $curdir: $!"; -} - - -sub Ldif2db { - my $ldif = shift ; - my $backend = shift ; - my $ldif2db_param = "ldif2db -D $serverHome -n $backend -i $ldif"; - open(LDIF2DB, "${quote}${quote}$slapdExecName${quote} $ldif2db_param${quote} 2>&1 |") or die "Could not run ns-slapd program $ldif2db_exe\n"; - sleep(1); # allow some data to accumulate in the pipe - while (<LDIF2DB>) { - printMsg($_); - } - close(LDIF2DB); - # remove the ldif file after the import - # but not if using the data dir - if (!$olddatadir) { - unlink($ldif) ; - } -} - -############################################################################# - -#sub copyBak { -# opendir( OLDBAK, "$oldHome${PATHSEP}bak" ) || -# die "Can't open directory $oldHome${PATHSEP}bak: $!: "; -# local ( @dirs ) = readdir( OLDBAK ); -# closedir ( OLDBAK ); -# for ( @dirs ) { -# if ( $_ eq "." || $_ eq ".." ) { -# next; -# } elsif ( -d "$oldHome${PATHSEP}bak${PATHSEP}$_" ) { -# $srcDir = "$oldHome${PATHSEP}bak${PATHSEP}$_"; -# $destDir = "$serverHome${PATHSEP}bak${PATHSEP}$_"; -# $srcLDIF = "$oldHome${PATHSEP}ldif${PATHSEP}bak.ldif"; -# $destLDIF = "$serverHome${PATHSEP}ldif${PATHSEP}bak.ldif"; -# mkdir( $destDir , 0755 ) if !( -e $destDir); -# # Converting database -# if ( !$isNT && $newuser ) { -# chown($newuid, $newgid, -# "$serverHome${PATHSEP}bak", $destDir); -# } -# &other_db2ldif($srcDir, $srcLDIF); -# if ($needAclUpg) { -# &mySystem("$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server", -# "$root${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server" . -# "${PATHSEP}aclupg$exe_suffix", '-d', '-i', -# $srcLDIF, '-o', $destLDIF); -# } else { -# ©BinFile($srcLDIF, $destLDIF); -# } -# &other_ldif2db($destLDIF, $destDir); -# } -# } -#} -############################################################################# - -sub startServer { - my $instanceDir = ${serverHome} ; - my $errLog = $instanceDir . $PATHSEP . 'logs' . $PATHSEP . 'errors'; - # emulate tail -f - # if the last line we see does not contain "slapd started", try again - my $done = 0; - my $started = 0; - my $code = 0; - my $lastLine = ""; - my $timeout = time + 240; # 4 minutes - $ENV{"$LIB_PATH"}=$new_libpath; - - my $startCmd = $instanceDir . $PATHSEP . 'start' . $script_suffix; - if (! -f $startCmd) { - $startCmd = $instanceDir . $PATHSEP . 'start-slapd' . $script_suffix; - } - printTrace("\nInstanceDir: $instanceDir\n",4); - $code = &mySystem($instanceDir,$startCmd); - open(IN, $errLog) or die "Could not open error log $errLog: $!"; - my $pos = tell(IN); - while (($done == 0) && (time < $timeout)) { - for (; ($done == 0) && ($_ = <IN>); $pos = tell(IN)) { - $lastLine = $_; - # print; - # the server has already been started and shutdown once . . . - if (/slapd started\./) { - $started++; - if ($started == 2) { - $done = 1; - } - # sometimes the server will fail to come up; in that case, restart it - } elsif (/Initialization Failed/) { - # print "Server failed to start: $_"; - $code = &mySystem($instanceDir, $startCmd); - # sometimes the server will fail to come up; in that case, restart it - } elsif (/exiting\./) { - # print "Server failed to start: $_"; - #$code = &mySystem($startCmd); - - $code = &mySystem($instanceDir, $startCmd); - } - } - if ($lastLine =~ /PR_Bind/) { - # server port conflicts with another one, just report and punt - print $lastLine; - print "This server cannot be started until the other server on this\n"; - print "port is shutdown.\n"; - $done = 1; - } - if ($done == 0) { - # rest a bit, then . . . - sleep(2); - # . . . reset the EOF status of the file desc - seek(IN, $pos, 0); - } - } - close(IN); - - if ($started < 2) { - $! = $code; - # $now = time; - # if ($now > $timeout) { - # print "Possible timeout: timeout=$timeout now=$now\n"; - # } - die "Error: could not start server: $!"; - } - - return 0; -} - -sub stopServer { - my $root = shift; - my $name = shift; - $maxStopIterations = 5; - print "\nShutting down server $name . . .\n"; - - $ENV{"$LIB_PATH"}=$new_libpath; - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop' . $script_suffix . $quote; - if (! -f $stopCmd) { - $stopCmd = $quote . $root . $PATHSEP . $name . $PATHSEP . 'stop-slapd' . $script_suffix . $quote; - } - - if (! -f $stopCmd) { - # no stop command, probably a 1.X system; for NT, we'll try net stop - # for unix, we'll get the pid and kill it - if ($isNT) { - $stopCmd = 'net stop ' . $name; - } else { - # see if there is a pid file - $pidfile = $root . $PATHSEP . $name . $PATHSEP . 'logs' . - $PATHSEP . 'pid'; - if (open(PIDFILE, $pidfile)) { - chomp($pid = <PIDFILE>); - close(PIDFILE); - while ($maxStopIterations-- && !$exitCode) { - $exitCode = kill(15, $pid); - } - $stopCmd = undef; - } - } - } - - # keep looping until the stop cmd returns an error code, which usually - # means that what ever we want to stop is stopped, or some other error - # occurred e.g. permission, or no such service - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - while ($stopCmd && $maxStopIterations-- && $exitCode) { - $exitCode = &runAndIgnoreOutput($stopCmd); -# print "stopServer: exitCode=$exitCode\n"; - } - - if (!$maxStopIterations) { - print "Warning: could not shutdown the server: $!\n"; - } - - sleep(10) ; - - $exitCode = 0; - -} - - -sub runAndIgnoreOutput { - my $cmd = shift; - printMsg("."); - open(RUNCMD, "${quote}$cmd${quote} 2>&1 |") or die "Error: could not run $cmd: $!"; - printMsg("."); - sleep(1); # allow pipe to fill with data - printMsg("."); - while (<RUNCMD>) { -# print; - } - my $code = close(RUNCMD); -# print "runAndIgnore: code=$code status=$?\n"; - return $?; -} -############################################################################# -# migrate some of entries present in the old DSE.ldif like -# cn=snmp,cn=config -# cn=encryption,cn=config -# all the aci's - -sub MigrateDSE { - printTrace("\nMigrate DSE entries...",1); - open( DSELDIF, "< $oldDSEldif" ) || die "Can't open $oldDSEldif: $!: "; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($old_entry = readOneEntry $in) { - my $DN = $old_entry->getDN() ; - SWITCH: { - # migrate the entrie: cn=snmp,cn=config - if ($DN =~ /^cn=SNMP,cn=config$/i) { - my $entry = $conn->search("$DN","base","objectclass=nsSNMP"); - if ($entry) { - my $res = $conn->update($old_entry); - if ($res) { - printTrace("\n$DN updated !",2); - } - else { - printMsg("\nFailed to update $DN"); - } - } - else { - printMsg("\nUnable to get info under $DN"); - } - last SWITCH; - } - # migrate the entrie: cn=encryption,cn=config - if ($DN =~ /cn=encryption,cn=config$/i) { - if ($conn->search("$DN","base","objectclass=*")) { - if ($old_entry->hasValue("objectClass", "nsEncryptionConfig")) { - my $certfile = "alias/slapd-" . $newname . "-cert8.db"; - my $keyfile = "alias/slapd-" . $newname. "-key3.db"; - $old_entry->setValues("nsCertfile",$certfile) if ! $old_entry->hasValue("nsCertfile",$certfile); - $old_entry->setValues("nsKeyfile",$keyfile) if ! $old_entry->hasValue("nsKeyfile",$keyfile); - } - my $res = $conn->update($old_entry); - if ($res) { - printTrace("\n$DN updated !",2); - } - else { - printMsg("\nFailed to update $DN"); - } - } - else { - my $res = $conn->add($old_entry); - if ($res) { - printTrace("\n$DN added !",2); - } - else { - printMsg("\nFailed to add $DN"); - } - } - last SWITCH; - } - if (@{$old_entry->{aci}} && (! ($DN =~ /^cn=monitor$/i)) && (! ($DN =~ /^cn=schema$/i))) { - # migrate aci's - my $entry = $conn->search("$DN","base","objectclass=*"); - if ($entry) { - my $res = $conn->update($old_entry); - if ($res) { - printTrace("\n$DN updated !",2); - } - else { - printMsg("\nFailed to update $DN"); - } - } - else { - my $res = $conn->add($old_entry); - if ($res) { - printTrace("\n$DN added !",2); - } - else { - printMsg("\nFailed to add $DN"); - } - } - last SWITCH; - } - } - } - close(DSELDIF); -} -############################################################################# -# migrate SSL info - -sub MigrateSSL { - my $secPwd = 'bidon' ; - # copy the SSL directory - ©Dir("$oldHome${PATHSEP}ssl","$serverHome${PATHSEP}ssl"); - # copy the cert db and key files - if ( -d "$oldDir${PATHSEP}alias") { - $aliasDir = "$root${PATHSEP}alias"; - if (! -d $aliasDir) { - mkdir($aliasDir, 0750); - } - &stopServer($root,'slapd-'.$newname); - my $keydb = "$aliasDir${PATHSEP}slapd-$newname-key3.db" ; - my $certdb = "$aliasDir${PATHSEP}slapd-$newname-cert8.db" ; - my $certdb7 = "$aliasDir${PATHSEP}slapd-$newname-cert7.db" ; - my $old_keydb = "$oldDir${PATHSEP}alias${PATHSEP}slapd-$oldname-key3.db" ; - my $old_certdb = "$oldDir${PATHSEP}alias${PATHSEP}slapd-$oldname-cert7.db"; - my $keydb_backup = "$aliasDir${PATHSEP}slapd-$newname-key3.db_backup" ; - my $certdb_backup = "$aliasDir${PATHSEP}slapd-$newname-cert7.db_backup" ; - if (-f $old_keydb) { - if (-f $keydb) { - if ($NO_INPUT_USER) { - printMsg("\n$keydb already exists. backup in $keydb_backup ..."); - ©BinFile($keydb,$keydb_backup); - ©BinFile($old_keydb,$keydb); - } - else { - print("\n\n$keydb already exists. Do you want to overwrite it ? [no]: "); - my $answer = <STDIN> ; - if ($answer =~ /^y|yes$/i) { - ©BinFile($old_keydb,$keydb); - } - } - } - else { - ©BinFile($old_keydb,$keydb); - } - } - if (-f $old_certdb) { - $mode = (stat($old_certdb))[2] if $PRESERVE; - if (-f $certdb) { - if ($NO_INPUT_USER) { - printMsg("\n$certdb already exists. backup in $certdb_backup ..."); - ©BinFile($certdb,$certdb_backup); - unlink($certdb) || print "Couldn't delete $certdb : $!\n"; - ©BinFile($old_certdb,$certdb7); - } - else { - print("\n\n$certdb already exists. Do you want to overwrite it ? [no]: "); - my $answer = <STDIN> ; - if ($answer =~ /^y|yes$/i) { - unlink($certdb) || print "Couldn't delete $certdb : $!\n"; - ©BinFile($old_certdb,$certdb7); - } - } - } - else { - ©BinFile($old_certdb,$certdb7); - } - } - # copy the old password file - if (-f "$oldDir${PATHSEP}alias${PATHSEP}$type-$oldname-pin.txt") { - ©BinFile( - "$oldDir${PATHSEP}alias${PATHSEP}$type-$oldname-pin.txt", - "$aliasDir${PATHSEP}$type-$newname-pin.txt" - ); - } - &startServer(); - if ($PRESERVE) { - chown($newuid,$newgid,$certdb) || print "Failed to set uid $newuid gid $newgid on $certdb : $!\n"; - chmod($mode,$certdb) || print "Failed to set mode $mode on $certdb : $!\n"; - } - } - -} - -sub DisableSSL { - my $entry = $conn->search("cn=config","base","objectclass=*"); - my $LDAPparam = "nsslapd-security" ; - my $Value = "off" ; - if ($entry->{$LDAPparam}[0] ne $Value) { - printTrace("\nDisable SSL...",1); - $entry->setValues($LDAPparam, $Value); - } - my $res = $conn->update($entry); - if ($res) { - printTrace("\nSSL disabled",2); - } - else { - printMsg("\nCan't disable SSL, the server may have problems starting"); - } -} - -# enable the migration of client authentication informations -sub MigrateCertmap { - # backup the old new certmap.conf and replace it with the old certmap.conf file - my $oldCertmap = "$oldDir${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf"; - my $newCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf" ; - my $backupCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf_backup" ; - if (&hasChangedoldCertmap($oldCertmap)) { - if ($NO_INPUT_USER) { - printMsg("\n$newCertmap has been backup in $backupCertmap"); - ©BinFile($newCertmap,$backupCertmap); - ©BinFile($oldCertmap,$newCertmap); - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\n\nWhere do you want to back up the file $newCertmap [$backupCertmap] ?") ; - my $Answer = <STDIN> ; - $backupCertmap = $Answer if ($Answer ne "\n"); - chomp($backupCertmap); - printTrace("\nDest: .$backupCertmap.",4); - if (-e $backupCertmap) { - printMsg("\n\n$backupCertmap already exists. Do you want to overwrite it Yes/No [No] ?") ; - if (<STDIN> =~ /yes|y/i) { - $Ask = 0 ; - } - else { - $backupCertmap = "$root${PATHSEP}shared${PATHSEP}config${PATHSEP}certmap.conf_backup" ; - } - } - else { - $Ask = 0 ; - } - } - printTrace("\nBackup file: $newCertmap in $backupCertmap",4); - ©BinFile($newCertmap,$backupCertmap); - ©BinFile($oldCertmap,$newCertmap); - } - } - else { - } -} - -sub hasChangedoldCertmap { - my $certmapfile = shift ; - my @reference = ("certmap default default", - "default:DNComps", - "default:FilterComps e") ; - my $cpt = 0 ; - printTrace("\nhasChangedoldCertmap",3); - open(CERTMAP,"< $certmapfile"); - while (<CERTMAP>) { - if ((! /^\s*#/) && (! /^\s*$/)) { - my $ref = $reference[$cpt] ; - printTrace("\nValue: $_, ref: $ref",4); - if (! /^\s*$ref\s*$/) { - return 1 ; - } - else { - $cpt++ ; - } - } - } - close (CERTMAP); - printTrace("\ncpt: $cpt",4); - if ($cpt < $#reference) { - return 1 ; - } - else { - return 0 ; - } -} -############################################################################# -# copy a directory to another - -sub copyDir { - my $src = shift; - my $dest = shift; - my $exclude = shift; - - opendir( SRC, $src ) or die "Can't open directory $src: $!: "; - my $mode; - my $uid; - my $gid; - mkdir ( $dest , 0755 ) or die "\nCan't create directory $dest. \nPlease check you have enough rights to create it and/or check that your parent directory exists.\n" if !( -e $dest ); - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - local ( @files ) = readdir ( SRC ); - closedir( SRC ); - for ( @files ) { - if ( $_ eq "." || $_ eq ".." ) { - next; - } elsif ( $exclude && /$exclude/ ) { - next; - } elsif( -d "$src${PATHSEP}$_") { - ©Dir ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_" ); - } else { - ©BinFile ( "$src${PATHSEP}$_", "$dest${PATHSEP}$_"); - } - } -} - -sub copyBinFile { - my $src = shift; - my $dest = shift; - my $buf = ""; - my $bufsize = 8192; - - open( SRC, $src ) || die "Can't open $src: $!\n"; - # if we are given a directory destination instead of a file, extract the - # filename portion of the source to use as the destination filename - if (-d $dest) { - $dest = $dest . $PATHSEP . &basename($src); - } - open( DEST, ">$dest" ) || die "Can't create $dest: $!\n"; - binmode SRC; - binmode DEST; - if ($PRESERVE) { - $mode = (stat($src))[2]; - ($uid, $gid) = (stat(_))[4..5]; - # Make sure files owned by the old user are owned by the - # new user - if ($uid == $olduid) { - $uid = $newuid; - $gid = $newgid; - } - chown $uid, $gid, $dest; - chmod $mode, $dest; - } - while (read(SRC, $buf, $bufsize)) { - print DEST $buf; - } - close( SRC ); - close( DEST ); -} -############################################################################# -# backup new configuration files -# backup the directory <new_root_server>/slapd-instance/config in <new_root_server>/slapd-instance/BackupConfig - -sub backupConfigFiles { - # backup the new config files - my $src = "$serverHome${PATHSEP}config" ; - my $dest = "$serverHome${PATHSEP}config_backup" ; - if ($NO_INPUT_USER) { - printMsg("\n$src has been backup in $dest"); - ©Dir($src,$dest); - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\n\nWhere do you want to back up your configuration directory [$dest] ?") ; - my $Answer = <STDIN> ; - $dest = $Answer if ($Answer ne "\n"); - chomp($dest); - printTrace("\nDest: .$dest.",4); - if (-e $dest) { - printMsg("\n\n$dest already exists. Do you want to overwrite it Yes/No [No] ?") ; - if (<STDIN> =~ /yes|y/i) { - $Ask = 0 ; - } - else { - $dest = "$serverHome${PATHSEP}config_backup" ; - } - } - else { - $Ask = 0 ; - } - } - printTrace("\nBackup Directory: $src in $dest",4); - ©Dir($src,$dest); - } -} -############################################################################# - -sub getLDAPservername { - my $oldLDAPservername; - my $LDAPservername; - open(OLDSLAPDCONF, $oldSlapdConf) or - die "\nError: could not open old config file $oldSlapdConf \n"; - while(<OLDSLAPDCONF>) { - chop; - if (/^localhost\s+/i) { - ($oldLDAPservername = $') =~ s/^[\"]//;; - $oldLDAPservername =~ s/[\"]$//; - printTrace("\nName of the old LDAP server: $oldLDAPservername",3); - } - } - close(OLDSLAPDCONF); - - open( DSELDIF, "< $DSEldif" ) || die "\nCan't open $DSEldif \n"; - my $in = new Mozilla::LDAP::LDIF(*DSELDIF) ; - while ($entry = readOneEntry $in) { - my $DN = $entry->getDN() ; - if ($DN =~ /^cn=config$/i) { - my $localhost = "nsslapd-localhost"; - my @values = $entry->getValues($localhost); - if ($#values != -1) { - $LDAPservername = $values[0]; - } - break; - } - } - close(DSELDIF); - # check old and new are installed on the same physical machine. - if (lc($oldLDAPservername) ne lc($LDAPservername)) { - # warn the user he tries to migrate a old server installed on a different machine from the new one - printMsg("\n\nYour old server is on $oldLDAPservername, and your new server is on $LDAPservername. We don't support migration on different machines. Do you want to continue ? Yes/No [No]:") ; - if (! (<STDIN> =~ /yes|y/i)) { - return -1; - } - } - return $LDAPservername ; -} - -############################################################################# - -sub getLibPath { - my $myDir = shift; - my $myVersion = shift; - my $myMinor = shift; - - if ($isNT) { - return $ENV{"$LIB_PATH"}; - } - if (($myVersion >= 6) && ($myMinor >= 2)) { - return - "$myDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$myDir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - } else { - return "$myDir${PATHSEP}lib${SEP}".$ENV{"$LIB_PATH"}; - } -} - -############################################################################# - -sub getVersion { - my $dir = shift; - my $versionstr = shift; - my $version = 0; - my $minor = 0; - my $buildNumber = 0; - my $progDir = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${PATHSEP}"; - my $progDir2 = "${PATHSEP}bin${PATHSEP}slapd${PATHSEP}"; - - # find the slapd executable - if (!$versionstr) { # version not specified on cmd line - find it - $prog = $dir . $progDir . $slapdExecName; - if (! -f $prog) { - $prog = $dir . $progDir2 . $slapdExecName; - if (-f $prog && $isNT) { - # if slapd is in bin/slapd and we're on NT, just assume version 1; - # apparently, slapd.exe doesn't like the -v argument . . . - return ( '1', $minor ); - } - else{ - die "Could not run slapd program $prog: $!"; - } - } - else { - chdir($dir . $progDir); - } - $cur_libpath=$ENV{"$LIB_PATH"}; - $ENV{"$LIB_PATH"}= - "$dir${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}lib${SEP}". - "$dir${PATHSEP}bin${PATHSEP}slapd${PATHSEP}server${SEP}". - $ENV{"$LIB_PATH"}; - # read the old version from the old slapd program - - open(F, "${quote}${quote}$prog${quote} -v${quote} 2>&1 |") or - die "Could not run slapd program $prog: $!"; - sleep(1); # allow some data to accumulate in the pipe -# print "Output from $prog -v:\n"; - while (<F>) { - if (/^Red Hat-Directory/ || /^Netscape-Directory/ || /^iPlanet-Directory/i) { - $versionstr = $_; - last; - } - } - $code = close(F); - # print "$prog returned code=$code status=$?\n"; - $ENV{"$LIB_PATH"}=$cur_libpath; - } - - if ($versionstr =~ /^Red Hat-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\/(\d+)\.(\d+)(?:b\d)*\s+(\S+)/) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^Netscape-Directory\(restrict?ed-mode\)\/(\d+)\.(\d+)\s+(\S+)/) { # we can have restricted-mode or restriced-mode ... - $version = $1; - $minor = $2; - $buildNumber = $3; - } - elsif ($versionstr =~ /^iPlanet-Directory\/(\d+)\.(\d+)\s+(\S+)/i) { - $version = $1; - $minor = $2; - $buildNumber = $3; - } elsif ($versionstr =~ /(\d+)\.(\d+)/) { - $version = $1; - $minor = $2; - } - - if ($version == 0) { - die "\nCould not determine version of the directory server in $dir: \n"; - } - - # distinguish the 4.1 and the 4.11 thanks to the buildNumber - if (($version == 4) && ($minor == 1)){ - if (! ($buildNumber =~ /^B99\.16/)) { - # it's not a 4.1 Netscape Directory Server => it's a 4.11 - $minor = 11 ; - } - } - chdir($curdir) or die "Could not change directory to $curdir: $!" ; - return ( $version, $minor ); -} - -############################################################################# - -sub getDiff { - # we get references to arrays - my $elements = shift ; - my $existing_elements = shift ; - my %count = () ; - my %countEE = () ; - @diff = () ; - foreach $e (@{$elements}, @{$existing_elements}) { $count{$e}++ ;} - foreach $e (@{existing_elements}) { $countEE{$e}++ ;} - foreach $e (@{$elements}) { - # if $e is only present in @$elements, we push it to the diff array - if (($count{$e} == 1) && ($countEE{$e} == 0)) { - push @diff, $e ; - } - } - return @diff ; -} - -############################################################################################### -sub testIndexUpdating { - #my $entry = $conn->newEntry(); - #$entry->setDN("cn=djeattribute,cn=index,cn=MigratedDB_5,cn=ldbm database,cn=plugins,cn=config"); - my $entry = $conn->search("cn=mail,cn=index,cn=MigratedDB_2,cn=ldbm database,cn=plugins,cn=config","base","objectclass=nsIndex"); - my @types = ("pres", "sub", "eq") ; - my @existing_types = $entry->getValues("nsindextype"); - my @typesToAdd = &getDiff(\@types, \@existing_types); - foreach $newtype (@typesToAdd) { - $entry->addValue("nsindextype", $newtype); printTrace("\nnewtype: $newtype",2); - } - my $res = $conn->update($entry) ; - if ($res) {print("\nUpdate index mail\n");} - else { print("\ncan't update index mail");} - - $entry = $conn->search("cn=givenName,cn=index,cn=MigratedDB_2,cn=ldbm database,cn=plugins,cn=config","base","objectclass=nsIndex"); - @types = ("pres", "sub", "eq") ; - @existing_types = $entry->getValues("nsindextype"); print("\ngivenName, existing_types: @existing_types"); - @typesToAdd = &getDiff(\@types, \@existing_types); print("\nTypesToAdd: @typesToAdd"); - foreach $newtype (@typesToAdd) { - $entry->addValue("nsindextype", $newtype); printTrace("\nnewtype: $newtype",2); - } - my $res = $conn->update($entry) ; - if ($res) {print("\nUpdate index givenName\n");} - else { print("\ncan't update index givenName");} - } - - -############################################################################################### -sub normalizeDir { - my $dir = shift ; - my $dir_prec = "" ; - while ($dir_prec ne $dir) { - $dir_prec = $dir ; - if ($isNT) { - grep { s@\\\\@\\@g } $dir ; - } - else { - grep { s@//@/@g } $dir ; - } - } - return $dir ; -} - - -############################################################################################### -# return 1 if the value parameters is -sub isAllowedPlugin { - my $Value = lc(shift) ; - if ($allowedPlugins{$Value}) { - return 1 ; - } - else { - return 0 ; - } - -} - - -sub getSyntaxOid { - my $Value = lc(shift) ; - return $allowedPlugins{$Value} ; -} - -############################################################################################### -# return 1 if the value given in parameters is an allowed modifier -sub isAllowedModifier { - my $Value = lc(shift) ; - if ($allowedModifiers{$Value}) { - return 1 ; - } - else { - return 0 ; - } -} - -sub getModifierValue { - my $Value = lc(shift) ; - return $allowedModifiers{$Value} ; -} - -############################################################################################### - -sub GetTime { - my $tm = localtime; - (my $sec, my $min, my $hour, my $dd, my $mm, my $yy) = ($tm->sec, $tm->min, $tm->hour, $tm->mday, ($tm->mon)+1, ($tm->year)+1900); - $sec = "0$sec" unless $sec > 9 ; - $min = "0$min" unless $min > 9 ; - $hour = "0$hour" unless $hour > 9 ; - $dd = "0$dd" unless $dd > 9 ; - $mm = "0$mm" unless $mm > 9 ; - return ($sec, $min, $hour, $dd, $mm, $yy); -} - -############################################################################################### -# get uid and group id of the new slapd server. -# The uid is done through the nsslapd-localuser attribute - -sub getuid_gid { - my $newuid ; - my $newgid ; - my $localuser ; - my $localuser_attr = "nsslapd-localuser" ; - if (! $isNT) { - my $entry = $conn->search("cn=config ", "base","objectclass=*", 0, ($localuser_attr)) ; - # Tests wether we succeed to get the entry cn=config - die "\nCan't get the entry cn=config \n" unless ($entry); - my @values = $entry->getValues($localuser_attr); - if ($#values == -1 || ($values[0] eq "") ) { # tests wether the nsslapd-localuser attribute has a value - printMsg("\nNo localuser has been found in the configuration of the directory. "); - if ($NO_INPUT_USER) { - printMsg("\nWe considered nobody as the localuser"); - $localuser = "nobody" ; - } - else { - my $Ask = 1 ; - while ($Ask) { - printMsg("\nUnder what user does your $Version.$Minor directory server run [nobody] ? ") ; - $localuser = <STDIN> ; - chomp($localuser); - $localuser = "nobody" if ($localuser eq ""); - ($newuid, $newgid) = (getpwnam("$localuser"))[2..3] ; - if ($newuid) { - $Ask = 0 ; - } - else { - printMsg("\nError: $localuser is unknown from the system "); - } - } - } - } - else { - $localuser = $values[0]; # returns the first value (we should only have one localuser) - my $size = $#values ; - } - ($newuid, $newgid) = (getpwnam("$localuser"))[2..3] ; - return ($localuser, $newuid, $newgid) ; - } - else { - return () ; - } -} - - -############################################################################################### -# get uid and group id of the old slapd server. - -sub getolduid_gid { - my $oldlocaluser ; - if (! $isNT) { - open(CONF, $oldSlapdConf) or die "\nError: cannot open $oldSlapdConf: $!\n"; - while (<CONF>) { - if (/^localuser\s+/i) { - chomp($oldlocaluser = $'); - last; - } - } - close(CONF); - ($olduid, $oldgid) = (getpwnam("$oldlocaluser"))[2..3] ; - return ($oldlocaluser, $olduid, $oldgid) ; - } - else { - return (); - } -} - -############################################################################################### -# get current directory - -sub getCwd { - my $command = $isNT ? "cd" : "/bin/pwd"; - open(PWDCMD, "$command 2>&1 |") or - die "Error: could not execute $command: $!"; - # without the following sleep, reading from the pipe will - # return nothing; I guess it gives the pwd command time - # to get some data to read . . . - sleep(1); - my $currentdir; - while (<PWDCMD>) { - if (!$currentdir) { - chomp($currentdir = $_); - } - } - my $code = close(PWDCMD); -# if ($code || $?) { -# print "$command returned code=$code status=$? dir=$curdir\n"; -# } -# print "getCwd curdir=\[$curdir\]\n"; - return $currentdir; -} diff --git a/ldap/admin/src/sec_tools_wrapper b/ldap/admin/src/sec_tools_wrapper deleted file mode 100644 index 338a1569..00000000 --- a/ldap/admin/src/sec_tools_wrapper +++ /dev/null @@ -1,66 +0,0 @@ -#!/bin/sh -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# Copyright (C) 2006 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# -# This file is the wrapper around the security tools. It just sets the -# runtime library lookup path and invokes the actual binary with the given -# arguments. This file is copied to the actual name of the command e.g. -# we get the binary certutil program from the NSS package. When we package -# it, we rename it to certutil-bin e.g. cp $(NSS)/certutil shared/bin/certutil-bin -# This file is copied to certutil e.g. cp sec_tools_wrapper shared/bin/certutil - -# figure out where the libdir is based on the location of this shell script -savedir=`pwd` -bindir=`dirname $0` -if test -n "$bindir" ; then - cd $bindir/../lib -else -# could be running as e.g. ./certutil or certutil if current dir is in PATH - cd ../lib -fi -# assume the libdir is ../lib from the bindir e.g. sroot/shared/bin and sroot/shared/lib -libdir=`pwd` -cd $savedir - -# cover our bases on ld libpaths -SHLIB_PATH=$libdir -LIBPATH=$libdir -LD_LIBRARY_PATH=$libdir -DYLD_PATH=$libdir -export SHLIB_PATH LIBPATH LD_LIBRARY_PATH DYLD_PATH - -$0-bin ${1+"$@"} diff --git a/ldap/admin/src/uname.lib b/ldap/admin/src/uname.lib deleted file mode 100644 index c8124389..00000000 --- a/ldap/admin/src/uname.lib +++ /dev/null @@ -1,201 +0,0 @@ -#!perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -sub uname -{ - local (@CommandLine) = @_; - - local($getall) = 0; - local($getproc) = 0; - local($getosrel) = 0; - local($getosname) = 0; - local($getosver) = 0; - - while ($_ = @CommandLine[0]) { - PARSE_SWITCH: { - if (/^-a\b/i) {# show all information - $getall=1; - shift(@CommandLine); - last PARSE_SWITCH - } - if (/^-n\b/i) {# show node name - $getnodename=1; - shift(@CommandLine); - last PARSE_SWITCH - } - if (/^-p\b/i) {# show processor - $getproc=1; - shift(@CommandLine); - last PARSE_SWITCH - } - if (/^-r\b/i) {# show os release - $getosrel=1; - shift(@CommandLine); - last PARSE_SWITCH - } - if (/^-s\b/i) {# show os name - $getosname=1; - shift(@CommandLine); - last PARSE_SWITCH - } - if (/^-v\b/i) {# show os version - $getosver=1; - shift(@CommandLine); - last PARSE_SWITCH - } - print " ERROR: Unknown parameter: $_\n"; - shift(@CommandLine); - } - } - -chomp(local($os) = `uname -s`); -local($nodename) = ""; -local($proc) = ""; -local($osrel) = ""; -local($osname) = ""; -local($osver) = ""; -local($osrel1) = ""; -local($osrel2) = ""; -local($nodename1) = ""; -local($retval) = ""; -local($ret) = ""; - -if ($os eq "Windows_NT") -{ - chomp($nodename = `uname -n`); - chomp($proc = `uname -m`); lc($proc); - if ($proc =~ /^[0-9]86.*/) - { - $proc = "i386"; - } - else - { - $proc = "?"; - } - chomp($osrel1 = `uname -r`); - chomp($osrel2 = `uname -v`); - $osrel = $osrel1.".".$osrel2; - $osname = "WINNT"; - $osver = "???"; -} -if ($os eq "WINNT") -{ - chomp($nodename = `uname -n`); - chomp($proc = `uname -p`); lc($proc); - chomp($osrel = `uname -r`); - $osname = "WINNT"; - chomp($osver = `uname -v`); -} - -if ($os eq "SunOS") -{ - chomp($nodename = `uname -n`); - chomp($proc = `uname -p`); - chomp($osrel = `uname -r`); - $osname = $os; - chomp($osver = `uname -v`); -} -if ($os eq "IRIX" || $os eq "IRIX64") -{ - chomp($nodename = `uname -n`); - chomp($proc = `uname -p`); - chomp($osrel = `uname -r`); - $osname = "IRIX"; - chomp($osver = `uname -v`); -} - -if ($os eq "HP-UX") -{ - chomp($nodename = `uname -n`); -# $proc = "hppa1.1"; - chomp($proc = `uname -m`); - chomp($osrel = `uname -r`); - $osname = $os; - chomp($osver = `uname -v`); -} - -if ($os eq "OSF1") -{ - chomp($nodename1 = `uname -n`); - ($nodename) = ($nodename1 =~ /(\w+)\..*/); - chomp($proc = `uname -m`); - chomp($osrel = `uname -r`); - $osname = $os; - chomp($osver = `uname -v`); -} - -if ($os eq "AIX") -{ - chomp($nodename = `uname -n`); - $proc = "rs6000"; - chomp($osrel1 = `uname -v`); - chomp($osrel2 = `uname -r`); - $osrel = $osrel1.".".$osrel2; - $osname = $os; - $osver = "???"; -} - -if ($getall) -{ - $getosname = 1; - $getnodename = 1; - $getosrel = 1; - $getosver = 1; - $getproc = 1; -} - -$retval = ""; -$retval = $retval.($getosname ? $osname : ""); -$retval = $retval.($getnodename ? " ".$nodename : ""); -$retval = $retval.($getosrel ? " ".$osrel : ""); -$retval = $retval.($getosver ? " ".$osver : ""); -$retval = $retval.($getproc ? " ".$proc : ""); - -if ($retval eq "") -{ - $retval = $nodename; -} - -($ret) = ($retval =~ /\s*(.*)/); - -return "$ret"; -} -1 diff --git a/ldap/admin/src/updatedsgw b/ldap/admin/src/updatedsgw deleted file mode 100755 index 03efd21f..00000000 --- a/ldap/admin/src/updatedsgw +++ /dev/null @@ -1,363 +0,0 @@ -#!/usr/bin/env perl -# -# BEGIN COPYRIGHT BLOCK -# This Program is free software; you can redistribute it and/or modify it under -# the terms of the GNU General Public License as published by the Free Software -# Foundation; version 2 of the License. -# -# This Program is distributed in the hope that it will be useful, but WITHOUT -# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS -# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. -# -# You should have received a copy of the GNU General Public License along with -# this Program; if not, write to the Free Software Foundation, Inc., 59 Temple -# Place, Suite 330, Boston, MA 02111-1307 USA. -# -# In addition, as a special exception, Red Hat, Inc. gives You the additional -# right to link the code of this Program with code not covered under the GNU -# General Public License ("Non-GPL Code") and to distribute linked combinations -# including the two, subject to the limitations in this paragraph. Non-GPL Code -# permitted under this exception must only link to the code of this Program -# through those well defined interfaces identified in the file named EXCEPTION -# found in the source code files (the "Approved Interfaces"). The files of -# Non-GPL Code may instantiate templates or use macros or inline functions from -# the Approved Interfaces without causing the resulting work to be covered by -# the GNU General Public License. Only Red Hat, Inc. may make changes or -# additions to the list of Approved Interfaces. You must obey the GNU General -# Public License in all respects for all of the Program code and other code used -# in conjunction with the Program except the Non-GPL Code covered by this -# exception. If you modify this file, you may extend this exception to your -# version of the file, but you are not obligated to do so. If you do not wish to -# provide this exception without modification, you must delete this exception -# statement from your version and license this file solely under the GPL without -# exception. -# -# -# Copyright (C) 2001 Sun Microsystems, Inc. Used by permission. -# Copyright (C) 2005 Red Hat, Inc. -# All rights reserved. -# END COPYRIGHT BLOCK -# - -$nshome = $ENV{'NETSITE_ROOT'}; - -# If there is no nshome, then assume that we're running -# as a commandline script. -if (!$nshome ) { - $script_mode = 1; - -# get the commandline options - if (!getopts('h:i:d:e:s:t:n:') || !$opt_n || !$opt_h ) { - print "usage: " . $0 . " -n nshome -h current_slapd_host:current_slapd_port [options]\n"; - print "\nrequired:\n"; - print " -n directory\tthe directory where 1.0 is installed (NS-HOME)\n"; - print " -h host[:port]\tthe current host and port of the directory server\n"; - print " \tto which the gateway connects.\n"; - print "\noptions:\n"; - print " -i host[:port]\tthe new host and port of the directory server\n"; - print " -s suffix\t\tthe old suffix of the directory server\n"; - print " -t suffix\t\tthe new ESCAPED suffix of the directory server\n"; - print " -d dirmgrdn\t\tthe old manager dn of the directory server\n"; - print " -e dirmgrdn\t\tthe new manager dn of the directory server\n"; - print "\nexample:\n " . $0 . " -n /home/servers/ds10/ -h gargoyle:1974 -i brooklyn -s \"dc=example,dc=com\" -t \"o%3Ddirectory.fedora.redhat.com\" -d \"cn=directory manager\" -e \"cn=directory guru\"\n"; - - exit; - } - - # Parse the commandline options - handle_script_input(); - -} else { -# output cgi header - print "Content-type: text/plain\n\n"; - -# print "Done\n"; -# parse the input - while ( <> ) { - &parse_input( $_ ); - } - - if ( !$vars{'old_host'}) { - rpt_err( -13, "host"); -# -13 = null parameter. -# print "Invalid input for DSGW changer CGI\n\n"; - exit; - } - -# print "$nshome $vars{'old_host'} $vars{'old_port'}\n"; -} - -# setup the path separator -$isNT = -d '\\'; -$PS = $isNT ? "\\" : "/"; - -$contextdir = "$nshome"."$PS"."dsgw"."$PS"."context"; - -#make sure that the target directory exists -if (! -e "$contextdir") { - rpt_err( -16 ,"$contextdir"); -# -16 = not a directory -# print "$contextdir does not exist\n"; - exit; -} - - -# cd into NS-HOME/dsgw/context directory -chdir "$contextdir" or die "Unable to cd to $contextdir: $!\n"; - -# read the files - opendir DSGW_CONTEXT, "." or die "$!"; - @dsgwconfs = grep !/^\.\.?$/, readdir DSGW_CONTEXT; - closedir DSGW_CONTEXT; - - -# unescape the new and old suffixes -if ($vars{'old_suffix'} && $vars{'new_suffix'}) { - $escaped_suffix = $vars{'new_suffix'}; - $vars{'new_suffix'} =~ s/%(\w\w)/chr(hex($1))/eg; - $unescaped_suffix = $vars{'new_suffix'}; -# print "Normal new suffix: $unescaped_suffix\n"; -# print "Escaped new suffix: $escaped_suffix\n"; - $unescaped_oldsuffix = $vars{'old_suffix'}; - $unescaped_oldsuffix =~ s/%(\w\w)/chr(hex($1))/eg; -} - -#unescape the digmrs -if ($vars{'new_dirmgr'}){ - $vars{'new_dirmgr'} =~ s/%(\w\w)/chr(hex($1))/eg; -} - -if ($vars{'old_dirmgr'}){ - $vars{'old_dirmgr'} =~ s/%(\w\w)/chr(hex($1))/eg; -} - - - # - $changed = ""; - foreach $file (@dsgwconfs){ - -# print "working on $file\n"; - - # If it's not a .conf file, skip it. - if ( $file !~ m/.*?\.conf$/ ) { -# print "skipping $file\n\n\n\n"; - next; - } - - $relevant_conf = 0; - $relevant_suffix = 0; - - # open the old file - open(OLDFILE, "$file") or die "Cannot read $file. $!\n"; # - - # Need to test to see if this conf file has a baseurl that - # matches the old host and port - for ($line=<OLDFILE>; $line ; $line=<OLDFILE>) { # - - # If we find the matching baseurl, then set a flag and break out of the loop. - if ($line =~ m:^baseurl\s*("){0,1}\s*ldap(s){0,1}\://$vars{'old_host'}(\:$vars{'old_port'}){0,1}/:) { #") - # Also check for a matching suffix. - if ($vars{'old_suffix'} && $vars{'new_suffix'}) { - @baseurl = split("/", $line); - $curr_suff = $baseurl[3]; - - # Get rid of any double quotes. - @baseurl = split("\"", $curr_suff); - $curr_suff = $baseurl[0]; - - $unescaped_currsuffix = $curr_suff; - $unescaped_currsuffix =~ s/%(\w\w)/chr(hex($1))/eg; - -# print "curr Suffix: $curr_suff\n"; -# print "old Suffix: $vars{'old_suffix'}\n"; -# print "unescaped curr Suffix: $unescaped_currsuffix\n"; -# print "unescaped old Suffix: $unescaped_oldsuffix\n"; - - if ($unescaped_currsuffix eq $unescaped_oldsuffix) { - $relevant_suffix = 1; -# print "suffix match for $file\n"; - } - - } - # set a flag - $relevant_conf = 1; -# print "host:port match for $file\n"; - last; - } - - - } - - # If there was no match, then go on to the next file. - if (! $relevant_conf) { - close(OLDFILE); -# print "no match for $file\n"; - next; - } - - # Else, there is a match start over at the beginning of the file - seek OLDFILE, 0, 0; - if ($changed eq "") { - $changed = $file; - } - - # open the new file - open(NEWFILE, ">"."tmpcp_"."$file"."1") or die "Cannot write $contextdir$PStmpcp_$file1. $!\n"; - - # Go through each line, replacing the relevant information - for ($line=<OLDFILE>; $line ; $line=<OLDFILE>) { # - - # If there is a new host - if ($vars{'new_host'}) { - $line =~ s:^baseurl\s*("){0,1}\s*ldap(s){0,1}\://.*?(\:\d*){0,1}/:baseurl\t$1ldap$2\://$vars{'new_host'}$3/:og; #") -# print "new host for $file\n"; - - } - - # a new port - if ($vars{'new_port'}) { - $line =~ s:^baseurl\s*("){0,1}\s*ldap(s){0,1}\://(.*?)(\:\d*){0,1}/:baseurl\t$1ldap$2\://$3\:$vars{'new_port'}/:og; #") -# print "new port for $file\n"; - } - - # new dirmgr - if ($vars{'new_dirmgr'} && $vars{'old_dirmgr'}) { - $line =~ s:(?i)^dirmgr\s*("){0,1}$vars{'old_dirmgr'}("){0,1}:dirmgr\t"$vars{'new_dirmgr'}":g; -# print "new dirmgr for $file\n"; - } - - # new suffix - if ($relevant_suffix) { - $line =~ s:(^baseurl\s*("){0,1}\s*ldap(s){0,1}\://.*?(\:\d*){0,1}/)((.*?("))|(.*?)):$1$escaped_suffix$7:og; # - $line =~ s:^location-suffix.*:location-suffix\t"$unescaped_suffix":og; -# print "new suffix for $file\n"; - } - - - print NEWFILE $line; - - } - # - close(OLDFILE); - close(NEWFILE); - - rename "tmpcp_" . "$file"."1", "$file"; - - } -rpt_err(0, $changed); - - -sub parse_input -{ - local( $line ) = @_; - local($var, $value, $assign ); - - - foreach $assign ( split( /&/, $line ) ) { - ( $var, $value ) = split( /=/, $assign ); - $value =~ s/\+/ /g; - $value =~ s/ /%20/g; -# $value =~ s/%(\w\w)/chr(hex($1))/eg; - $var =~ s/\+/ /g; -# $var =~ s/%(\w\w)/chr(hex($1))/eg; - - - $vars{$var} = $value; - } -} - - -sub handle_script_input -{ - - if ($opt_h) { - @temp_array = split(":", $opt_h); - - $vars{'old_host'} = $temp_array[0]; - $vars{'old_port'} = $temp_array[1]; - -# print "host: $vars{'old_port'}\n"; -# print "port: $vars{'old_host'}\n"; - } - - if ($opt_i) { - @temp_array = split(":", $opt_i); - - $vars{'new_host'} = $temp_array[0]; - $vars{'new_port'} = $temp_array[1]; - -# print " $vars{'new_port'}\n"; -# print " $vars{'new_host'}\n"; - } - if ($opt_d) { - $vars{'old_dirmgr'} = $opt_d; - } - if ($opt_e) { - $vars{'new_dirmgr'} = $opt_e; - } - if ($opt_s) { - $vars{'old_suffix'} = $opt_s; - } - if ($opt_t) { - $vars{'new_suffix'} = $opt_t; - } - if ($opt_n) { - $nshome = $opt_n; - } - -} - - -sub rpt_err -{ - my $code = shift; - my $err_string = shift; - - print "NMC_ErrInfo: " . "$err_string" . "\n"; - print "NMC_STATUS: " . "$code"."\n"; - -} - -sub getopts { - local($argumentative) = @_; - local(@args,$_,$first,$rest); - local($errs) = 0; - local($[) = 0; - - @args = split( / */, $argumentative ); - while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) { - ($first,$rest) = ($1,$2); - $pos = index($argumentative,$first); - if($pos >= $[) { - if($args[$pos+1] eq ':') { - shift(@ARGV); - if($rest eq '') { - ++$errs unless @ARGV; - $rest = shift(@ARGV); - } - eval "\$opt_$first = \$rest;"; - } - else { - eval "\$opt_$first = 1"; - if($rest eq '') { - shift(@ARGV); - } - else { - $ARGV[0] = "-$rest"; - } - } - } - else { - print STDERR "Unknown option: $first\n"; - ++$errs; - if($rest ne '') { - $ARGV[0] = "-$rest"; - } - else { - shift(@ARGV); - } - } - } - $errs == 0; -} - |