Bug 450646, Upgrade Mozilla to NSS 3.12.1 release candidate 1
authorKai Engert <kaie@kuix.de>
Fri, 15 Aug 2008 06:12:54 +0200
changeset 16700 2e5f07e2b75b1912f843443c8a2b05d55eb81bff
parent 16699 c652d1311eec1a042db17f491d3d05c5f86207a4
child 16701 df6e6f3ac380e82ea9450157b83d852e941f2774
push idunknown
push userunknown
push dateunknown
bugs450646
milestone1.9.1a2pre
Bug 450646, Upgrade Mozilla to NSS 3.12.1 release candidate 1 r=rrelyea
dbm/tests/lots.c
security/coreconf/Linux.mk
security/coreconf/RISCOS.mk
security/coreconf/config.mk
security/coreconf/nsinstall/nsinstall.c
security/coreconf/rules.mk
security/nss/cmd/certutil/certutil.c
security/nss/cmd/crmftest/testcrmf.c
security/nss/cmd/lib/secutil.c
security/nss/cmd/lib/secutil.h
security/nss/cmd/manifest.mn
security/nss/cmd/modutil/pk11.c
security/nss/cmd/p7content/p7content.c
security/nss/cmd/p7env/p7env.c
security/nss/cmd/p7sign/p7sign.c
security/nss/cmd/p7verify/p7verify.c
security/nss/cmd/pk11mode/pk11mode.c
security/nss/cmd/pwdecrypt/pwdecrypt.c
security/nss/cmd/rsaperf/rsaperf.c
security/nss/cmd/selfserv/selfserv.c
security/nss/cmd/shlibsign/shlibsign.c
security/nss/cmd/signtool/certgen.c
security/nss/cmd/signtool/list.c
security/nss/cmd/signtool/manifest.mn
security/nss/cmd/signtool/sign.c
security/nss/cmd/signtool/signtool.c
security/nss/cmd/signtool/signtool.h
security/nss/cmd/signtool/util.c
security/nss/cmd/smimetools/cmsutil.c
security/nss/cmd/ssltap/ssltap.c
security/nss/cmd/strsclnt/strsclnt.c
security/nss/cmd/tests/manifest.mn
security/nss/cmd/tests/nonspr10.c
security/nss/cmd/tests/remtest.c
security/nss/cmd/vfychain/vfychain.c
security/nss/cmd/vfyserv/vfyserv.c
security/nss/lib/base/arena.c
security/nss/lib/base/base.h
security/nss/lib/base/error.c
security/nss/lib/certdb/alg1485.c
security/nss/lib/certdb/cert.h
security/nss/lib/certdb/certdb.c
security/nss/lib/certdb/certdb.h
security/nss/lib/certdb/certi.h
security/nss/lib/certdb/certt.h
security/nss/lib/certdb/secname.c
security/nss/lib/certdb/stanpcertdb.c
security/nss/lib/certdb/xconst.h
security/nss/lib/certhigh/certvfy.c
security/nss/lib/certhigh/certvfypkix.c
security/nss/lib/certhigh/ocsp.c
security/nss/lib/certhigh/ocsp.h
security/nss/lib/certhigh/ocspi.h
security/nss/lib/certhigh/xcrldist.c
security/nss/lib/ckfw/builtins/certdata.c
security/nss/lib/ckfw/builtins/certdata.txt
security/nss/lib/ckfw/builtins/nssckbi.h
security/nss/lib/ckfw/capi/ckcapi.h
security/nss/lib/ckfw/mutex.c
security/nss/lib/ckfw/nsprstub.c
security/nss/lib/cryptohi/cryptohi.h
security/nss/lib/cryptohi/keyhi.h
security/nss/lib/cryptohi/keythi.h
security/nss/lib/cryptohi/seckey.c
security/nss/lib/dev/ckhelper.c
security/nss/lib/dev/dev.h
security/nss/lib/dev/devslot.c
security/nss/lib/dev/devtoken.c
security/nss/lib/dev/devutil.c
security/nss/lib/freebl/blapit.h
security/nss/lib/freebl/ec.c
security/nss/lib/freebl/genload.c
security/nss/lib/freebl/ldvector.c
security/nss/lib/freebl/unix_rand.c
security/nss/lib/libpkix/include/pkix_errorstrings.h
security/nss/lib/libpkix/include/pkix_params.h
security/nss/lib/libpkix/include/pkix_pl_pki.h
security/nss/lib/libpkix/include/pkix_pl_system.h
security/nss/lib/libpkix/pkix/checker/pkix_ocspchecker.c
security/nss/lib/libpkix/pkix/params/pkix_procparams.c
security/nss/lib/libpkix/pkix/params/pkix_procparams.h
security/nss/lib/libpkix/pkix/results/pkix_verifynode.c
security/nss/lib/libpkix/pkix/results/pkix_verifynode.h
security/nss/lib/libpkix/pkix/top/pkix_build.c
security/nss/lib/libpkix/pkix/top/pkix_build.h
security/nss/lib/libpkix/pkix/top/pkix_policychecker.c
security/nss/lib/libpkix/pkix/top/pkix_validate.c
security/nss/lib/libpkix/pkix/util/pkix_list.c
security/nss/lib/libpkix/pkix/util/pkix_logger.c
security/nss/lib/libpkix/pkix/util/pkix_tools.c
security/nss/lib/libpkix/pkix/util/pkix_tools.h
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_httpdefaultclient.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_ldapcertstore.c
security/nss/lib/libpkix/pkix_pl_nss/module/pkix_pl_socket.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_cert.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_generalname.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_infoaccess.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspcertid.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspcertid.h
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocsprequest.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocsprequest.h
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_ocspresponse.c
security/nss/lib/libpkix/pkix_pl_nss/pki/pkix_pl_x500name.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_mem.c
security/nss/lib/libpkix/pkix_pl_nss/system/pkix_pl_monitorlock.c
security/nss/lib/nss/nss.def
security/nss/lib/nss/nss.h
security/nss/lib/nss/nssinit.c
security/nss/lib/pk11wrap/dev3hack.c
security/nss/lib/pk11wrap/pk11cert.c
security/nss/lib/pk11wrap/pk11pbe.c
security/nss/lib/pk11wrap/pk11priv.h
security/nss/lib/pk11wrap/pk11pub.h
security/nss/lib/pk11wrap/pk11sdr.c
security/nss/lib/pk11wrap/pk11slot.c
security/nss/lib/pk11wrap/secmod.h
security/nss/lib/pk11wrap/secmodt.h
security/nss/lib/pk11wrap/secpkcs5.h
security/nss/lib/pkcs12/p12.h
security/nss/lib/pkcs12/p12e.c
security/nss/lib/pkcs12/p12t.h
security/nss/lib/pkcs12/pkcs12t.h
security/nss/lib/pkcs7/certread.c
security/nss/lib/pkcs7/p7local.c
security/nss/lib/pkcs7/pkcs7t.h
security/nss/lib/pkcs7/secpkcs7.h
security/nss/lib/pki/certificate.c
security/nss/lib/pki/pki3hack.c
security/nss/lib/pki/pkistore.c
security/nss/lib/pki/pkistore.h
security/nss/lib/pki/trustdomain.c
security/nss/lib/smime/cms.h
security/nss/lib/smime/cmsrecinfo.c
security/nss/lib/softoken/legacydb/keydb.c
security/nss/lib/softoken/legacydb/lgattr.c
security/nss/lib/softoken/pkcs11.c
security/nss/lib/softoken/pkcs11c.c
security/nss/lib/softoken/sftkdb.c
security/nss/lib/softoken/softkver.h
security/nss/lib/ssl/derive.c
security/nss/lib/ssl/sslenum.c
security/nss/lib/util/dertime.c
security/nss/lib/util/nssb64.h
security/nss/lib/util/oidstring.c
security/nss/lib/util/secasn1.h
security/nss/lib/util/secder.h
security/nss/lib/util/secdig.h
security/nss/lib/util/secitem.h
security/nss/lib/util/secoid.h
security/nss/lib/util/secport.c
security/nss/tests/all.sh
security/nss/tests/cert/cert.sh
security/nss/tests/cert/certext.txt
security/nss/tests/common/init.sh
security/nss/tests/iopr/cert_iopr.sh
security/nss/tests/libpkix/cert_trust.map
security/nss/tests/libpkix/certs/PayPalEE.cert
security/nss/tests/libpkix/certs/PayPalICA.cert
security/nss/tests/libpkix/certs/PayPalRootCA.cert
security/nss/tests/libpkix/libpkix.sh
security/nss/tests/libpkix/vfychain_test.lst
security/nss/tests/memleak/ignored
security/nss/tests/sdr/sdr.sh
security/nss/tests/ssl/ssl.sh
--- a/dbm/tests/lots.c
+++ b/dbm/tests/lots.c
@@ -1,9 +1,9 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
+/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
 /* ***** BEGIN LICENSE BLOCK *****
  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  *
  * The contents of this file are subject to the Mozilla Public License Version
  * 1.1 (the "License"); you may not use this file except in compliance with
  * the License. You may obtain a copy of the License at
  * http://www.mozilla.org/MPL/
  *
@@ -200,20 +200,20 @@ DBT * GenKey(int32 num, key_type_enum ke
 int
 SeqDatabase()
 {
 	int status;
 	DBT key, data;
 
 	ReportStatus("SEQuencing through database...");
 
-	/* seq throught the whole database */
+	/* seq through the whole database */
     if(!(status = (*database->seq)(database, &key, &data, R_FIRST)))
 	  {
-        while(!(status = (database->seq) (database, &key, &data, R_NEXT)));
+        while(!(status = (database->seq) (database, &key, &data, R_NEXT)))
 			; /* null body */
 	  }
 
 	if(status < 0)
 		ReportError("Error seq'ing database");
 
 	return(status);
 }
--- a/security/coreconf/Linux.mk
+++ b/security/coreconf/Linux.mk
@@ -112,18 +112,23 @@ else
 ifeq ($(OS_TEST),s390x)
 	OS_REL_CFLAGS   = -DLINUX1_2 -D_XOPEN_SOURCE
 	CPU_ARCH        = s390x
 else
 ifeq ($(OS_TEST),mips)
 	OS_REL_CFLAGS   = -DLINUX1_2 -D_XOPEN_SOURCE
 	CPU_ARCH        = mips
 else
+ifeq (,$(filter-out i%86,$(OS_TEST)))
 	OS_REL_CFLAGS	= -DLINUX1_2 -Di386 -D_XOPEN_SOURCE
 	CPU_ARCH	= x86
+else
+	OS_REL_CFLAGS   = -DLINUX1_2 -D_XOPEN_SOURCE
+	CPU_ARCH	= $(OS_TEST)
+endif
 endif
 endif
 endif
 endif
 endif
 endif
 endif
 endif
new file mode 100644
--- /dev/null
+++ b/security/coreconf/RISCOS.mk
@@ -0,0 +1,48 @@
+#
+# ***** BEGIN LICENSE BLOCK *****
+# Version: MPL 1.1/GPL 2.0/LGPL 2.1
+#
+# The contents of this file are subject to the Mozilla Public License Version
+# 1.1 (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+# http://www.mozilla.org/MPL/
+#
+# Software distributed under the License is distributed on an "AS IS" basis,
+# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+# for the specific language governing rights and limitations under the
+# License.
+#
+# The Original Code is the Netscape security libraries.
+#
+# The Initial Developer of the Original Code is
+# Netscape Communications Corporation.
+# Portions created by the Initial Developer are Copyright (C) 1994-2000
+# the Initial Developer. All Rights Reserved.
+#
+# Contributor(s):
+#
+# Alternatively, the contents of this file may be used under the terms of
+# either the GNU General Public License Version 2 or later (the "GPL"), or
+# the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+# in which case the provisions of the GPL or the LGPL are applicable instead
+# of those above. If you wish to allow use of your version of this file only
+# under the terms of either the GPL or the LGPL, and not to allow others to
+# use your version of this file under the terms of the MPL, indicate your
+# decision by deleting the provisions above and replace them with the notice
+# and other provisions required by the GPL or the LGPL. If you do not delete
+# the provisions above, a recipient may use your version of this file under
+# the terms of any one of the MPL, the GPL or the LGPL.
+#
+# ***** END LICENSE BLOCK *****
+
+include $(CORE_DEPTH)/coreconf/UNIX.mk
+
+DLL_SUFFIX  = a
+MKSHLIB     = $(GCCSDK_INSTALL_CROSSBIN)/arm-unknown-riscos-ar cr
+
+OS_RELEASE =
+OS_TARGET  = RISCOS
+
+ifdef BUILD_OPT
+	OPTIMIZER = -O2 -mpoke-function-name
+endif
--- a/security/coreconf/config.mk
+++ b/security/coreconf/config.mk
@@ -58,17 +58,17 @@ endif
 #       (dependent upon <architecture> tags)                          #
 #                                                                     #
 #       We are moving towards just having a $(OS_TARGET).mk file      #
 #       as opposed to multiple $(OS_TARGET)$(OS_RELEASE).mk files,    #
 #       one for each OS release.                                      #
 #######################################################################
 
 TARGET_OSES = FreeBSD BSD_OS NetBSD OpenUNIX OS2 QNX Darwin BeOS OpenBSD \
-              OpenVMS AIX
+              OpenVMS AIX RISCOS
 
 ifeq (,$(filter-out $(TARGET_OSES),$(OS_TARGET)))
 include $(CORE_DEPTH)/coreconf/$(OS_TARGET).mk
 else
 include $(CORE_DEPTH)/coreconf/$(OS_TARGET)$(OS_RELEASE).mk
 endif
 
 #######################################################################
--- a/security/coreconf/nsinstall/nsinstall.c
+++ b/security/coreconf/nsinstall/nsinstall.c
@@ -53,17 +53,17 @@ typedef unsigned int mode_t;
 #include <utime.h>
 #endif
 #include <sys/types.h>
 #include <sys/stat.h>
 #include "pathsub.h"
 
 #define HAVE_LCHOWN
 
-#if defined(AIX) || defined(BSDI) || defined(HPUX) || defined(LINUX) || defined(SUNOS4) || defined(SCO) || defined(UNIXWARE) || defined(VMS) || defined(NTO) || defined(DARWIN) || defined(BEOS)
+#if defined(AIX) || defined(BSDI) || defined(HPUX) || defined(LINUX) || defined(SUNOS4) || defined(SCO) || defined(UNIXWARE) || defined(VMS) || defined(NTO) || defined(DARWIN) || defined(BEOS) || defined(__riscos__)
 #undef HAVE_LCHOWN
 #endif
 
 #define HAVE_FCHMOD
 
 #if defined(BEOS)
 #undef HAVE_FCHMOD
 #endif
--- a/security/coreconf/rules.mk
+++ b/security/coreconf/rules.mk
@@ -333,17 +333,21 @@ else
 ifdef MT
 	if test -f $@.manifest; then \
 		$(MT) -NOLOGO -MANIFEST $@.manifest -OUTPUTRESOURCE:$@\;2; \
 		rm -f $@.manifest; \
 	fi
 endif	# MSVC with manifest tool
 endif
 else
+ifeq ($(OS_TARGET),RISCOS)
+	$(MKSHLIB) $@ $(OBJS) $(SUB_SHLOBJS)
+else
 	$(MKSHLIB) -o $@ $(OBJS) $(SUB_SHLOBJS) $(LD_LIBS) $(EXTRA_LIBS) $(EXTRA_SHARED_LIBS) $(OS_LIBS)
+endif
 	chmod +x $@
 ifeq ($(OS_TARGET),Darwin)
 ifdef MAPFILE
 	nmedit -s $(MAPFILE) $@
 endif
 endif
 endif
 endif
--- a/security/nss/cmd/certutil/certutil.c
+++ b/security/nss/cmd/certutil/certutil.c
@@ -159,17 +159,17 @@ AddCert(PK11SlotInfo *slot, CERTCertDBHa
 
 	/* Read in an ASCII cert and return a CERTCertificate */
 	cert = CERT_DecodeCertFromPackage((char *)certDER.data, certDER.len);
 	if (!cert) {
 	    SECU_PrintError(progName, "could not obtain certificate from file"); 
 	    GEN_BREAK(SECFailure);
 	}
 
-	/* Create a cert trust to pass to SEC_AddPermCertificate */
+	/* Create a cert trust */
 	trust = (CERTCertTrust *)PORT_ZAlloc(sizeof(CERTCertTrust));
 	if (!trust) {
 	    SECU_PrintError(progName, "unable to allocate cert trust");
 	    GEN_BREAK(SECFailure);
 	}
 
 	rv = CERT_DecodeTrustString(trust, trusts);
 	if (rv) {
@@ -461,20 +461,30 @@ listCerts(CERTCertDBHandle *handle, char
 	the_cert = CERT_FindCertByNicknameOrEmailAddr(handle, name);
 	if (!the_cert) {
 	    the_cert = PK11_FindCertFromNickname(name, NULL);
 	    if (!the_cert) {
 		SECU_PrintError(progName, "Could not find: %s\n", name);
 		return SECFailure;
 	    }
 	}
+	/* Here, we have one cert with the desired nickname or email 
+	 * address.  Now, we will attempt to get a list of ALL certs 
+	 * with the same subject name as the cert we have.  That list 
+	 * should contain, at a minimum, the one cert we have already found.
+	 * If the list of certs is empty (NULL), the libraries have failed.
+	 */
 	certs = CERT_CreateSubjectCertList(NULL, handle, &the_cert->derSubject,
 		PR_Now(), PR_FALSE);
 	CERT_DestroyCertificate(the_cert);
-
+	if (!certs) {
+	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
+	    SECU_PrintError(progName, "problem printing certificates");
+	    return SECFailure;
+	}
 	for (node = CERT_LIST_HEAD(certs); !CERT_LIST_END(node,certs);
 						node = CERT_LIST_NEXT(node)) {
 	    the_cert = node->cert;
 	    /* now get the subjectList that matches this cert */
 	    data.data = the_cert->derCert.data;
 	    data.len = the_cert->derCert.len;
 	    if (ascii) {
 		PR_fprintf(outfile, "%s\n%s\n%s\n", NS_CERT_HEADER, 
@@ -827,29 +837,36 @@ ListKeysInSlot(PK11SlotInfo *slot, const
 }
 
 /* returns SECSuccess if ANY keys are found, SECFailure otherwise. */
 static SECStatus
 ListKeys(PK11SlotInfo *slot, const char *nickName, int index, 
          KeyType keyType, PRBool dopriv, secuPWData *pwdata)
 {
     SECStatus rv = SECFailure;
+    static const char fmt[] = \
+    	"%s: Checking token \"%.33s\" in slot \"%.65s\"\n";
 
     if (slot == NULL) {
 	PK11SlotList *list;
 	PK11SlotListElement *le;
 
 	list= PK11_GetAllTokens(CKM_INVALID_MECHANISM,PR_FALSE,PR_FALSE,pwdata);
 	if (list) {
 	    for (le = list->head; le; le = le->next) {
+		PR_fprintf(PR_STDOUT, fmt, progName, 
+			   PK11_GetTokenName(le->slot), 
+			   PK11_GetSlotName(le->slot));
 		rv &= ListKeysInSlot(le->slot,nickName,keyType,pwdata);
 	    }
 	    PK11_FreeSlotList(list);
 	}
     } else {
+	PR_fprintf(PR_STDOUT, fmt, progName, PK11_GetTokenName(slot), 
+	           PK11_GetSlotName(slot));
 	rv = ListKeysInSlot(slot,nickName,keyType,pwdata);
     }
     return rv;
 }
 
 static SECStatus
 DeleteKey(char *nickname, secuPWData *pwdata)
 {
@@ -911,17 +928,18 @@ ListModules(void)
 }
 
 static void 
 Usage(char *progName)
 {
 #define FPS fprintf(stderr, 
     FPS "Type %s -H for more detailed descriptions\n", progName);
     FPS "Usage:  %s -N [-d certdir] [-P dbprefix] [-f pwfile]\n", progName);
-    FPS "Usage:  %s -T [-d certdir] [-P dbprefix] [-h token-name] [-f pwfile]\n", progName);
+    FPS "Usage:  %s -T [-d certdir] [-P dbprefix] [-h token-name]\n"
+	"\t\t [-f pwfile] [-0 SSO-password]\n", progName);
     FPS "\t%s -A -n cert-name -t trustargs [-d certdir] [-P dbprefix] [-a] [-i input]\n", 
     	progName);
     FPS "\t%s -B -i batch-file\n", progName);
     FPS "\t%s -C [-c issuer-name | -x] -i cert-request-file -o cert-file\n"
 	"\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n"
         "\t\t [-f pwfile] [-d certdir] [-P dbprefix] [-1] [-2] [-3] [-4] [-5]\n"
 	"\t\t [-6] [-7 emailAddrs] [-8 dns-names] [-a]\n",
 	progName);
@@ -951,17 +969,17 @@ Usage(char *progName)
 	progName);
     FPS "\t\t [-P targetDBPrefix] [--source-prefix sourceDBPrefix]\n");
     FPS "\t\t [-f targetPWfile] [-@ sourcePWFile]\n");
     FPS "\t%s -L [-n cert-name] [-X] [-d certdir] [-P dbprefix] [-r] [-a]\n", progName);
     FPS "\t%s -M -n cert-name -t trustargs [-d certdir] [-P dbprefix]\n",
 	progName);
     FPS "\t%s -O -n cert-name [-X] [-d certdir] [-P dbprefix]\n", progName);
     FPS "\t%s -R -s subj -o cert-request-file [-d certdir] [-P dbprefix] [-p phone] [-a]\n"
-	"\t\t [-y emailAddrs] [-k key-type-or-id] [-h token-name] [-f pwfile] [-g key-size]\n",
+	"\t\t [-7 emailAddrs] [-k key-type-or-id] [-h token-name] [-f pwfile] [-g key-size]\n",
 	progName);
     FPS "\t%s -V -n cert-name -u usage [-b time] [-e] \n"
 	"\t\t[-X] [-d certdir] [-P dbprefix]\n",
 	progName);
     FPS "\t%s -S -n cert-name -s subj [-c issuer-name | -x]  -t trustargs\n"
 	"\t\t [-k key-type-or-id] [-q key-params] [-h token-name] [-g key-size]\n"
         "\t\t [-m serial-number] [-w warp-months] [-v months-valid]\n"
 	"\t\t [-f pwfile] [-d certdir] [-P dbprefix]\n"
@@ -1039,19 +1057,19 @@ static void LongUsage(char *progName)
 	"   -3 ");
     FPS "%-20s Create crl distribution point extension\n",
 	"   -4 ");
     FPS "%-20s Create netscape cert type extension\n",
 	"   -5 ");
     FPS "%-20s Create extended key usage extension\n",
 	"   -6 ");
     FPS "%-20s Create an email subject alt name extension\n",
-	"   -7 ");
+	"   -7 emailAddrs");
     FPS "%-20s Create an dns subject alt name extension\n",
-	"   -8 ");
+	"   -8 dnsNames");
     FPS "%-20s The input certificate request is encoded in ASCII (RFC1113)\n",
 	"   -a");
     FPS "\n");
 
     FPS "%-15s Generate a new key pair\n",
 	"-G");
     FPS "%-20s Name of token in which to generate key (default is internal)\n",
 	"   -h token-name");
@@ -1185,16 +1203,18 @@ static void LongUsage(char *progName)
     FPS "%-15s Reset the Key database or token\n",
 	"-T");
     FPS "%-20s Cert database directory (default is ~/.netscape)\n",
 	"   -d certdir");
     FPS "%-20s Cert & Key database prefix\n",
 	"   -P dbprefix");
     FPS "%-20s Token to reset (default is internal)\n",
 	"   -h token-name");
+    FPS "%-20s Set token's Site Security Officer password\n",
+	"   -0 SSO-password");
     FPS "\n");
 
     FPS "\n");
     FPS "%-15s Print the chain of a certificate\n",
 	"-O");
     FPS "%-20s The nickname of the cert to modify\n",
 	"   -n cert-name");
     FPS "%-20s Cert database directory (default is ~/.netscape)\n",
@@ -1356,19 +1376,19 @@ static void LongUsage(char *progName)
 	"   -3 ");
     FPS "%-20s Create crl distribution point extension\n",
 	"   -4 ");
     FPS "%-20s Create netscape cert type extension\n",
 	"   -5 ");
     FPS "%-20s Create extended key usage extension\n",
 	"   -6 ");
     FPS "%-20s Create an email subject alt name extension\n",
-	"   -7 ");
+	"   -7 emailAddrs ");
     FPS "%-20s Create a DNS subject alt name extension\n",
-	"   -8 ");
+	"   -8 DNS-names");
     FPS "%-20s Create an Authority Information Access extension\n",
 	"   --extAIA ");
     FPS "%-20s Create a Subject Information Access extension\n",
 	"   --extSIA ");
     FPS "%-20s Create a Certificate Policies extension\n",
 	"   --extCP ");
     FPS "%-20s Create a Policy Mappings extension\n",
 	"   --extPM ");
@@ -1512,47 +1532,42 @@ done:
 	SECKEY_DestroyPrivateKey(caPrivateKey);
     }
     return result;
 }
 
 static SECStatus
 CreateCert(
 	CERTCertDBHandle *handle, 
+	PK11SlotInfo *slot,
 	char *  issuerNickName, 
 	PRFileDesc *inFile,
 	PRFileDesc *outFile, 
-	SECKEYPrivateKey *selfsignprivkey,
+	SECKEYPrivateKey **selfsignprivkey,
 	void 	*pwarg,
 	SECOidTag hashAlgTag,
 	unsigned int serialNumber, 
 	int     warpmonths,
 	int     validityMonths,
 	const char *emailAddrs,
 	const char *dnsNames,
 	PRBool  ascii,
 	PRBool  selfsign,
 	certutilExtnList extnList)
 {
     void *	extHandle;
     SECItem *	certDER;
-    PRArenaPool *arena			= NULL;
     CERTCertificate *subjectCert 	= NULL;
     CERTCertificateRequest *certReq	= NULL;
     SECStatus 	rv 			= SECSuccess;
     SECItem 	reqDER;
     CERTCertExtension **CRexts;
 
     reqDER.data = NULL;
     do {
-	arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
-	if (!arena) {
-	    GEN_BREAK (SECFailure);
-	}
-	
 	/* Create a certrequest object from the input cert request der */
 	certReq = GetCertRequest(inFile, ascii);
 	if (certReq == NULL) {
 	    GEN_BREAK (SECFailure)
 	}
 
 	subjectCert = MakeV1Cert (handle, certReq, issuerNickName, selfsign,
 				  serialNumber, warpmonths, validityMonths);
@@ -1582,33 +1597,42 @@ CreateCert(
                 break;
             rv = CERT_MergeExtensions(extHandle, CRexts);
             if (rv != SECSuccess)
                 break;
         }
 
 	CERT_FinishExtensions(extHandle);
 
+	/* self-signing a cert request, find the private key */
+	if (selfsign && *selfsignprivkey == NULL) {
+	    *selfsignprivkey = PK11_FindKeyByDERCert(slot, subjectCert, pwarg);
+	    if (!*selfsignprivkey) {
+		fprintf(stderr, "Failed to locate private key.\n");
+		rv = SECFailure;
+		break;
+	    }
+	}
+
 	certDER = SignCert(handle, subjectCert, selfsign, hashAlgTag,
-	                   selfsignprivkey, issuerNickName,pwarg);
+	                   *selfsignprivkey, issuerNickName,pwarg);
 
 	if (certDER) {
 	   if (ascii) {
 		PR_fprintf(outFile, "%s\n%s\n%s\n", NS_CERT_HEADER, 
 		           BTOA_DataToAscii(certDER->data, certDER->len), 
 			   NS_CERT_TRAILER);
 	   } else {
 		PR_Write(outFile, certDER->data, certDER->len);
 	   }
 	}
 
     } while (0);
     CERT_DestroyCertificateRequest (certReq);
     CERT_DestroyCertificate (subjectCert);
-    PORT_FreeArena (arena, PR_FALSE);
     if (rv != SECSuccess) {
 	PRErrorCode  perr = PR_GetError();
         fprintf(stderr, "%s: unable to create cert (%s)\n", progName,
                SECU_Strerror(perr));
     }
     return (rv);
 }
 
@@ -1723,17 +1747,17 @@ enum {
     cmd_CreateAndAddCert,
     cmd_TokenReset,
     cmd_ListModules,
     cmd_CheckCertValidity,
     cmd_ChangePassword,
     cmd_Version,
     cmd_Batch,
     cmd_Merge,
-    cmd_UpgradeMerge, /* test only */
+    cmd_UpgradeMerge /* test only */
 };
 
 /*  Certutil options */
 enum certutilOpts {
     opt_SSOPass = 0,
     opt_AddKeyUsageExt,
     opt_AddBasicConstraintExt,
     opt_AddAuthorityKeyIDExt,
@@ -2175,25 +2199,16 @@ certutil_main(int argc, char **argv, PRB
         certutil.options[opt_ASCIIForIO].activated &&
         certutil.options[opt_BinaryDER].activated) {
 	PR_fprintf(PR_STDERR, 
 	           "%s: cannot specify both -r and -a when dumping cert.\n",
 	           progName);
 	return 255;
     }
 
-    /*  For now, deny -C -x combination */
-    if (certutil.commands[cmd_CreateNewCert].activated &&
-        certutil.options[opt_SelfSign].activated) {
-	PR_fprintf(PR_STDERR,
-	           "%s: self-signing a cert request is not supported.\n",
-	           progName);
-	return 255;
-    }
-
     /*  If making a cert request, need a subject.  */
     if ((certutil.commands[cmd_CertReq].activated ||
          certutil.commands[cmd_CreateAndAddCert].activated) &&
         !certutil.options[opt_Subject].activated) {
 	PR_fprintf(PR_STDERR, 
 	           "%s -%c: subject is required to create a cert request.\n",
 	           progName, commandToRun);
 	return 255;
@@ -2728,19 +2743,19 @@ merge_fail:
 	    rv = SECFailure;
 	    goto shutdown;
 	}
     }
 
     /*  Create a certificate (-C or -S).  */
     if (certutil.commands[cmd_CreateAndAddCert].activated ||
          certutil.commands[cmd_CreateNewCert].activated) {
-	rv = CreateCert(certHandle, 
+	rv = CreateCert(certHandle, slot,
 	                certutil.options[opt_IssuerName].arg,
-	                inFile, outFile, privkey, &pwdata, hashAlgTag,
+	                inFile, outFile, &privkey, &pwdata, hashAlgTag,
 	                serialNumber, warpmonths, validityMonths,
 		        certutil.options[opt_ExtendedEmailAddrs].arg,
 		        certutil.options[opt_ExtendedDNSNames].arg,
 	                certutil.options[opt_ASCIIForIO].activated,
 	                certutil.options[opt_SelfSign].activated,
 	                certutil_extns);
 	if (rv) 
 	    goto shutdown;
@@ -2887,22 +2902,23 @@ shutdown:
             PORT_Free(commandline);
         }
         fclose(batchFile);
     }
 
     if ((initialized == PR_TRUE) && NSS_Shutdown() != SECSuccess) {
         exit(1);
     }
-    PR_Cleanup();
-
     if (rv == SECSuccess) {
 	return 0;
     } else {
 	return 255;
     }
 }
 
 int
 main(int argc, char **argv)
 {
-    return certutil_main(argc, argv, PR_TRUE);
+    int rv = certutil_main(argc, argv, PR_TRUE);
+    PR_Cleanup();
+    return rv;
 }
+
--- a/security/nss/cmd/crmftest/testcrmf.c
+++ b/security/nss/cmd/crmftest/testcrmf.c
@@ -1492,16 +1492,17 @@ loser:
 
 void
 Usage (void)
 {
     printf ("Usage:\n"
 	    "\tcrmftest -d [Database Directory] -p [Personal Cert]\n"
 	    "\t         -e [Encrypter] -s [CA Certificate] [-P password]\n\n"
 	    "\t         [crmf] [dsa] [decode] [cmmf] [recover] [challenge]\n"
+	    "\t         [-f password_file]\n"
 	    "Database Directory\n"
 	    "\tThis is the directory where the key3.db, cert7.db, and\n"
 	    "\tsecmod.db files are located.  This is also the directory\n"
 	    "\twhere the program will place CRMF/CMMF der files\n"
 	    "Personal Cert\n"
 	    "\tThis is the certificate that already exists in the cert\n"
 	    "\tdatabase to use while encoding the response.  The private\n"
 	    "\tkey associated with the certificate must also exist in the\n"
@@ -1553,29 +1554,30 @@ parsePositionalParam(const char * arg, P
 
 int
 main(int argc, char **argv) 
 {
     TESTKeyPair       signPair, cryptPair;
     PLOptState       *optstate;
     PLOptStatus       status;
     char             *password = NULL;
+    char             *pwfile = NULL;
     int               irv     = 0;
     PRUint32          flags   = 0;
     SECStatus         rv;
     PRBool            nssInit = PR_FALSE;
     PRBool            pArg    = PR_FALSE;
     PRBool            eArg    = PR_FALSE;
     PRBool            sArg    = PR_FALSE;
     PRBool            PArg    = PR_FALSE;
 
     memset( &signPair,  0, sizeof signPair);
     memset( &cryptPair, 0, sizeof cryptPair);
     printf ("\ncrmftest v1.0\n");
-    optstate = PL_CreateOptState(argc, argv, "d:p:e:s:P:");
+    optstate = PL_CreateOptState(argc, argv, "d:p:e:s:P:f:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	case 'd':
 	    configdir = PORT_Strdup(optstate->value);
 	    rv = NSS_Init(configdir);
 	    if (rv != SECSuccess) {
 	        printf ("NSS_Init (-d) failed\n");
 		return 101;
@@ -1607,18 +1609,29 @@ main(int argc, char **argv)
 	    sArg = PR_TRUE;
 	    break;
 	case 'P':
 	    password = PORT_Strdup(optstate->value);
 	    if (password == NULL) {
 	        printf ("-P  failed\n");
 	        return 606;
 	    }
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = password;
 	    PArg = PR_TRUE;
 	    break;
+        case 'f':
+	    pwfile = PORT_Strdup(optstate->value);
+	    if (pwfile == NULL) {
+	        printf ("-f  failed\n");
+	        return 607;
+	    }
+            pwdata.source = PW_FROMFILE;
+            pwdata.data = pwfile;
+            break;
 	case 0:  /* positional parameter */
 	    rv = parsePositionalParam(optstate->value, &flags);
 	    if (rv) {
 	        printf ("bad positional parameter.\n");
 	        return 605;
 	    }
 	    break;
 	default:
@@ -1630,20 +1643,16 @@ main(int argc, char **argv)
     if (status == PL_OPT_BAD || !nssInit) {
         Usage();
 	return 600;
     }
     if (!flags) 
     	flags = ~ TEST_USE_DSA;
     db = CERT_GetDefaultCertDB();
     InitPKCS11();
-    if (password) {
-	pwdata.source = PW_PLAINTEXT;
-	pwdata.data = password;
-    }
 
     if (flags & TEST_MAKE_CRMF_REQ) {
 	printf("Generating CRMF request\n");
     	irv = DoCRMFRequest(&signPair, &cryptPair);
 	if (irv)
 	    goto loser;
     }
 
--- a/security/nss/cmd/lib/secutil.c
+++ b/security/nss/cmd/lib/secutil.c
@@ -208,47 +208,91 @@ SECU_GetPasswordString(void *arg, char *
  *  A function to use the password passed in the -f(pwfile) argument
  *  of the command line.  
  *  After use once, null it out otherwise PKCS11 calls us forever.?
  *
  */
 char *
 SECU_FilePasswd(PK11SlotInfo *slot, PRBool retry, void *arg)
 {
-    unsigned char phrase[200];
+    char* phrases, *phrase;
     PRFileDesc *fd;
     PRInt32 nb;
     char *pwFile = arg;
     int i;
+    const long maxPwdFileSize = 4096;
+    char* tokenName = NULL;
+    int tokenLen = 0;
 
     if (!pwFile)
 	return 0;
 
     if (retry) {
 	return 0;  /* no good retrying - the files contents will be the same */
-    } 
+    }
+
+    phrases = PORT_ZAlloc(maxPwdFileSize);
+
+    if (!phrases) {
+        return 0; /* out of memory */
+    }
  
     fd = PR_Open(pwFile, PR_RDONLY, 0);
     if (!fd) {
 	fprintf(stderr, "No password file \"%s\" exists.\n", pwFile);
+        PORT_Free(phrases);
 	return NULL;
     }
 
-    nb = PR_Read(fd, phrase, sizeof(phrase));
+    nb = PR_Read(fd, phrases, maxPwdFileSize);
   
     PR_Close(fd);
-    /* handle the Windows EOL case */
-    i = 0;
-    while (phrase[i] != '\r' && phrase[i] != '\n' && i < nb) i++;
-    phrase[i] = '\0';
+
     if (nb == 0) {
-	fprintf(stderr,"password file contains no data\n");
-	return NULL;
+        fprintf(stderr,"password file contains no data\n");
+        PORT_Free(phrases);
+        return NULL;
+    }
+
+    if (slot) {
+        tokenName = PK11_GetTokenName(slot);
+        if (tokenName) {
+            tokenLen = PORT_Strlen(tokenName);
+        }
     }
-    return (char*) PORT_Strdup((char*)phrase);
+    i = 0;
+    do
+    {
+        int startphrase = i;
+        int phraseLen;
+
+        /* handle the Windows EOL case */
+        while (phrases[i] != '\r' && phrases[i] != '\n' && i < nb) i++;
+        /* terminate passphrase */
+        phrases[i++] = '\0';
+        /* clean up any EOL before the start of the next passphrase */
+        while ( (i<nb) && (phrases[i] == '\r' || phrases[i] == '\n')) {
+            phrases[i++] = '\0';
+        }
+        /* now analyze the current passphrase */
+        phrase = &phrases[startphrase];
+        if (!tokenName)
+            break;
+        if (PORT_Strncmp(phrase, tokenName, tokenLen)) continue;
+        phraseLen = PORT_Strlen(phrase);
+        if (phraseLen < (tokenLen+1)) continue;
+        if (phrase[tokenLen] != ':') continue;
+        phrase = &phrase[tokenLen+1];
+        break;
+
+    } while (i<nb);
+
+    phrase = PORT_Strdup((char*)phrase);
+    PORT_Free(phrases);
+    return phrase;
 }
 
 char *
 SECU_GetModulePassword(PK11SlotInfo *slot, PRBool retry, void *arg) 
 {
     char prompt[255];
     secuPWData *pwdata = (secuPWData *)arg;
     secuPWData pwnull = { PW_NONE, 0 };
@@ -1993,24 +2037,16 @@ secu_PrintAuthKeyIDExtension(FILE *out, 
 	SECU_PrintErrMsg(out, level, "Error", "Parsing extension");
 	SECU_PrintAny(out, value, "Data", level);
     } else {
 	int keyIDPresent  = (kid->keyID.data && kid->keyID.len);
 	int issuerPresent = kid->authCertIssuer != NULL;
 	int snPresent = (kid->authCertSerialNumber.data &&
 	                 kid->authCertSerialNumber.len);
 
-        if ((keyIDPresent && !issuerPresent && !snPresent) ||
-	    (!keyIDPresent && issuerPresent && snPresent)) {
-	    /* all is well */
-	} else {
-	    SECU_Indent(out, level);
-	    fprintf(out, 
-	    "Error: KeyID OR (Issuer AND Serial) must be present, not both.\n");
-	}
 	if (keyIDPresent)
 	    SECU_PrintAsHex(out, &kid->keyID, "Key ID", level);
 	if (issuerPresent)
 	    secu_PrintGeneralName(out, kid->authCertIssuer, "Issuer", level);
 	if (snPresent)
 	    SECU_PrintInteger(out, &kid->authCertSerialNumber, 
 	                    "Serial Number", level);
     }
@@ -2060,20 +2096,20 @@ secu_PrintCRLDistPtsExtension(FILE *out,
     if (dPoints && dPoints->distPoints && dPoints->distPoints[0]) {
 	CRLDistributionPoint ** pPoints = dPoints->distPoints;
 	CRLDistributionPoint *  pPoint;
 	while (NULL != (pPoint = *pPoints++)) {
 	    if (pPoint->distPointType == generalName && 
 	        pPoint->distPoint.fullName != NULL) {
 		secu_PrintGeneralNames(out, pPoint->distPoint.fullName, NULL,
 		                       level);
-#if defined(LATER)
-	    } else if (pPoint->distPointType == relativeDistinguishedName) {
-	    	/* print the relative name */
-#endif
+	    } else if (pPoint->distPointType == relativeDistinguishedName &&
+	               pPoint->distPoint.relativeName.avas) {
+		SECU_PrintRDN(out, &pPoint->distPoint.relativeName, "RDN", 
+		              level);
 	    } else if (pPoint->derDistPoint.data) {
 		SECU_PrintAny(out, &pPoint->derDistPoint, "Point", level);
 	    }
 	    if (pPoint->reasons.data) {
 		secu_PrintDecodedBitString(out, &pPoint->reasons, "Reasons", 
 		                           level);
 	    }
 	    if (pPoint->crlIssuer) {
@@ -2290,16 +2326,31 @@ SECU_PrintExtensions(FILE *out, CERTCert
 	    }
 
 	    secu_Newline(out);
 	    extensions++;
 	}
     }
 }
 
+/* An RDN is a subset of a DirectoryName, and we already know how to
+ * print those, so make a directory name out of the RDN, and print it.
+ */
+void
+SECU_PrintRDN(FILE *out, CERTRDN *rdn, char *msg, int level)
+{
+    CERTName name;
+    CERTRDN *rdns[2];
+
+    name.arena = NULL;
+    name.rdns  = rdns;
+    rdns[0] = rdn;
+    rdns[1] = NULL;
+    SECU_PrintName(out, &name, msg, level);
+}
 
 void
 SECU_PrintName(FILE *out, CERTName *name, char *msg, int level)
 {
     char *nameStr;
     char *str;
     SECItem my;
 
@@ -3271,17 +3322,17 @@ SECU_ParseCommandLine(int argc, char **a
     PRBool found;
     PLOptState *optstate;
     PLOptStatus status;
     char *optstring;
     PLLongOpt *longopts = NULL;
     int i, j;
     int lcmd = 0, lopt = 0;
 
-    optstring = (char *)PORT_Alloc(cmd->numCommands + 2*cmd->numOptions);
+    optstring = (char *)PORT_Alloc(cmd->numCommands + 2*cmd->numOptions+1);
     if (optstring == NULL)
         return SECFailure;
     
     j = 0;
     for (i=0; i<cmd->numCommands; i++) {
 	if (cmd->commands[i].flag) /* single character option ? */
 	    optstring[j++] = cmd->commands[i].flag;
 	if (cmd->commands[i].longform)
--- a/security/nss/cmd/lib/secutil.h
+++ b/security/nss/cmd/lib/secutil.h
@@ -57,21 +57,16 @@
 #define NS_CERTREQ_TRAILER "-----END NEW CERTIFICATE REQUEST-----"
 
 #define NS_CERT_HEADER "-----BEGIN CERTIFICATE-----"
 #define NS_CERT_TRAILER "-----END CERTIFICATE-----"
 
 #define NS_CRL_HEADER  "-----BEGIN CRL-----"
 #define NS_CRL_TRAILER "-----END CRL-----"
 
-/* From libsec/pcertdb.c --- it's not declared in sec.h */
-extern SECStatus SEC_AddPermCertificate(CERTCertDBHandle *handle,
-		SECItem *derCert, char *nickname, CERTCertTrust *trust);
-
-
 #ifdef SECUTIL_NEW
 typedef int (*SECU_PPFunc)(PRFileDesc *out, SECItem *item, 
                            char *msg, int level);
 #else
 typedef int (*SECU_PPFunc)(FILE *out, SECItem *item, char *msg, int level);
 #endif
 
 typedef struct {
@@ -310,16 +305,17 @@ extern void SECU_PrintAny(FILE *out, SEC
 extern void SECU_PrintPolicy(FILE *out, SECItem *value, char *msg, int level);
 extern void SECU_PrintPrivKeyUsagePeriodExtension(FILE *out, SECItem *value,
                                  char *msg, int level);
 
 extern void SECU_PrintExtensions(FILE *out, CERTCertExtension **extensions,
 				 char *msg, int level);
 
 extern void SECU_PrintName(FILE *out, CERTName *name, char *msg, int level);
+extern void SECU_PrintRDN(FILE *out, CERTRDN *rdn, char *msg, int level);
 
 #ifdef SECU_GetPassword
 /* Convert a High public Key to a Low public Key */
 extern SECKEYLowPublicKey *SECU_ConvHighToLow(SECKEYPublicKey *pubHighKey);
 #endif
 
 extern char *SECU_GetModulePassword(PK11SlotInfo *slot, PRBool retry, void *arg);
 
--- a/security/nss/cmd/manifest.mn
+++ b/security/nss/cmd/manifest.mn
@@ -71,16 +71,17 @@ DIRS = lib  \
  signtool \
  signver \
  shlibsign \
  smimetools  \
  SSLsample \
  ssltap  \
  strsclnt \
  symkeyutil \
+ tests \
  tstclnt  \
  vfychain \
  vfyserv \
  modutil \
  $(NULL)
 
 TEMPORARILY_DONT_BUILD = \
  $(NULL)
--- a/security/nss/cmd/modutil/pk11.c
+++ b/security/nss/cmd/modutil/pk11.c
@@ -678,18 +678,16 @@ ChangePW(char *tokenName, char *pwFile, 
     PRBool matching;
 
     slot = PK11_FindSlotByName(tokenName);
     if(!slot) {
 	PR_fprintf(PR_STDERR, errStrings[NO_SUCH_TOKEN_ERR], tokenName);
 	return NO_SUCH_TOKEN_ERR;
     }
 
-    PK11_SetPasswordFunc(SECU_GetModulePassword);
-
     /* Get old password */
     if(! PK11_NeedUserInit(slot)) {
 	if(pwFile) {
 	    oldpw = SECU_FilePasswd(NULL, PR_FALSE, pwFile);
 	    if(PK11_CheckUserPassword(slot, oldpw) != SECSuccess) {
 		PR_fprintf(PR_STDERR, errStrings[BAD_PW_ERR]);
 		ret=BAD_PW_ERR;
 		goto loser;
--- a/security/nss/cmd/p7content/p7content.c
+++ b/security/nss/cmd/p7content/p7content.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * p7content -- A command to display pkcs7 content.
  *
- * $Id: p7content.c,v 1.11 2007/01/25 00:52:25 alexei.volkov.bugs%sun.com Exp $
+ * $Id: p7content.c,v 1.12 2008/08/04 22:58:31 julien.pierre.boogz%sun.com Exp $
  */
 
 #include "nspr.h"
 #include "secutil.h"
 #include "plgetopt.h"
 #include "secpkcs7.h"
 #include "cert.h"
 #include "certdb.h"
@@ -75,16 +75,17 @@ Usage(char *progName)
     fprintf(stderr, "%-20s Define an input file to use (default is stdin)\n",
 	    "-i input");
     fprintf(stderr, "%-20s Define an output file to use (default is stdout)\n",
 	    "-o output");
     exit(-1);
 }
 
 static PRBool saw_content;
+static secuPWData  pwdata          = { PW_NONE, 0 };
 
 static void
 PrintBytes(void *arg, const char *buf, unsigned long len)
 {
     FILE *out;
 
     out = arg; 
     fwrite (buf, len, 1, out);
@@ -99,29 +100,16 @@ PrintBytes(void *arg, const char *buf, u
  * need to do it.
  */
 static PRBool
 decryption_allowed(SECAlgorithmID *algid, PK11SymKey *key)
 {
     return PR_TRUE;
 }
 
-char* KeyDbPassword = 0;
-
-
-char* MyPK11PasswordFunc (PK11SlotInfo *slot, PRBool retry, void* arg)
-{
-    char *ret=0;
-
-    if (retry == PR_TRUE)
-        return NULL;
-    ret = PL_strdup (KeyDbPassword);
-    return ret;
-}
-
 int
 DecodeAndPrintFile(FILE *out, PRFileDesc *in, char *progName)
 {
     SECItem derdata;
     SEC_PKCS7ContentInfo *cinfo = NULL;
     SEC_PKCS7DecoderContext *dcx;
 
     if (SECU_ReadDERFromFile(&derdata, in, PR_FALSE)) {
@@ -129,17 +117,17 @@ DecodeAndPrintFile(FILE *out, PRFileDesc
 	return -1;
     }
 
     fprintf(out,
 	    "Content printed between bars (newline added before second bar):");
     fprintf(out, "\n---------------------------------------------\n");
 
     saw_content = PR_FALSE;
-    dcx = SEC_PKCS7DecoderStart(PrintBytes, out, NULL, NULL,
+    dcx = SEC_PKCS7DecoderStart(PrintBytes, out, NULL, &pwdata,
 				NULL, NULL, decryption_allowed);
     if (dcx != NULL) {
 #if 0	/* Test that decoder works when data is really streaming in. */
 	{
 	    unsigned long i;
 	    for (i = 0; i < derdata.len; i++)
 		SEC_PKCS7DecoderUpdate(dcx, derdata.data + i, 1);
 	}
@@ -202,17 +190,16 @@ DecodeAndPrintFile(FILE *out, PRFileDesc
 
     fprintf(out, "There were%s certs or crls included.\n",
 	    SEC_PKCS7ContainsCertsOrCrls(cinfo) ? "" : " no");
 
     SEC_PKCS7DestroyContentInfo(cinfo);
     return 0;
 }
 
-
 /*
  * Print the contents of a PKCS7 message, indicating signatures, etc.
  */
 
 int
 main(int argc, char **argv)
 {
     char *progName;
@@ -226,17 +213,17 @@ main(int argc, char **argv)
     progName = progName ? progName+1 : argv[0];
 
     inFile = NULL;
     outFile = NULL;
 
     /*
      * Parse command line arguments
      */
-    optstate = PL_CreateOptState(argc, argv, "d:i:o:p:");
+    optstate = PL_CreateOptState(argc, argv, "d:i:o:p:f:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	  case 'd':
 	    SECU_ConfigDirectory(optstate->value);
 	    break;
 
 	  case 'i':
 	    inFile = PR_Open(optstate->value, PR_RDONLY, 0);
@@ -252,17 +239,23 @@ main(int argc, char **argv)
 	    if (!outFile) {
 		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
 			progName, optstate->value);
 		return -1;
 	    }
 	    break;
 
 	  case 'p':
-            KeyDbPassword = strdup (optstate->value);
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = PORT_Strdup (optstate->value);
+            break;
+
+          case 'f':
+            pwdata.source = PW_FROMFILE;
+            pwdata.data = PORT_Strdup (optstate->value);
             break;
 
 	  default:
 	    Usage(progName);
 	    break;
 	}
     }
     if (status == PL_OPT_BAD)
@@ -274,17 +267,17 @@ main(int argc, char **argv)
     /* Call the initialization routines */
     PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
     rv = NSS_Init(SECU_ConfigDirectory(NULL));
     if (rv != SECSuccess) {
 	SECU_PrintPRandOSError(progName);
 	return -1;
     }
 
-    PK11_SetPasswordFunc (MyPK11PasswordFunc);
+    PK11_SetPasswordFunc(SECU_GetModulePassword);
 
     if (DecodeAndPrintFile(outFile, inFile, progName)) {
 	SECU_PrintError(progName, "problem decoding data");
 	return -1;
     }
     
     if (NSS_Shutdown() != SECSuccess) {
         exit(1);
--- a/security/nss/cmd/p7env/p7env.c
+++ b/security/nss/cmd/p7env/p7env.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * p7env -- A command to create a pkcs7 enveloped data.
  *
- * $Id: p7env.c,v 1.8 2007/01/26 01:15:43 nelson%bolyard.com Exp $
+ * $Id: p7env.c,v 1.9 2008/08/08 23:47:56 julien.pierre.boogz%sun.com Exp $
  */
 
 #include "nspr.h"
 #include "secutil.h"
 #include "plgetopt.h"
 #include "secpkcs7.h"
 #include "cert.h"
 #include "certdb.h"
@@ -236,17 +236,17 @@ main(int argc, char **argv)
 	}
     }
 
     if (!recipients) Usage(progName);
 
     if (!inFile) inFile = stdin;
     if (!outFile) outFile = stdout;
 
-    /* Call the libsec initialization routines */
+    /* Call the NSS initialization routines */
     PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
     rv = NSS_Init(SECU_ConfigDirectory(NULL));
     if (rv != SECSuccess) {
     	SECU_PrintPRandOSError(progName);
 	return -1;
     }
 
     /* open cert database */
--- a/security/nss/cmd/p7sign/p7sign.c
+++ b/security/nss/cmd/p7sign/p7sign.c
@@ -33,17 +33,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * p7sign -- A command to create a *detached* pkcs7 signature (over a given
  * input file).
  *
- * $Id: p7sign.c,v 1.13 2007/01/26 01:15:43 nelson%bolyard.com Exp $
+ * $Id: p7sign.c,v 1.14 2008/08/04 22:58:28 julien.pierre.boogz%sun.com Exp $
  */
 
 #include "nspr.h"
 #include "plgetopt.h"
 #include "secutil.h"
 #include "secpkcs7.h"
 #include "cert.h"
 #include "certdb.h"
@@ -59,29 +59,17 @@
 #include <string.h>
 
 #if (defined(XP_WIN) && !defined(WIN32)) || (defined(__sun) && !defined(SVR4))
 extern int fread(char *, size_t, size_t, FILE*);
 extern int fwrite(char *, size_t, size_t, FILE*);
 extern int fprintf(FILE *, char *, ...);
 #endif
 
-char* KeyDbPassword = 0;
-
-
-char* MyPK11PasswordFunc (PK11SlotInfo *slot, PRBool retry, void* arg)
-{
-    char *ret=0;
-
-    if (retry == PR_TRUE)
-        return NULL;
-    ret = PL_strdup (KeyDbPassword);
-    return ret;
-}
-
+static secuPWData  pwdata          = { PW_NONE, 0 };
 
 static void
 Usage(char *progName)
 {
     fprintf(stderr,
 	    "Usage:  %s -k keyname [-d keydir] [-i input] [-o output]\n",
 	    progName);
     fprintf(stderr, "%-20s Nickname of key to use for signature\n",
@@ -90,16 +78,17 @@ Usage(char *progName)
 	    "-d keydir");
     fprintf(stderr, "%-20s Define an input file to use (default is stdin)\n",
 	    "-i input");
     fprintf(stderr, "%-20s Define an output file to use (default is stdout)\n",
 	    "-o output");
     fprintf(stderr, "%-20s Encapsulate content in signature message\n",
 	    "-e");
     fprintf(stderr, "%-20s Password to the key databse\n", "-p");
+    fprintf(stderr, "%-20s password file\n", "-f");
     exit(-1);
 }
 
 static void
 SignOut(void *arg, const char *buf, unsigned long len)
 {
    FILE *out;
 
@@ -169,17 +158,17 @@ SignFile(FILE *outFile, PRFileDesc *inFi
 
     rv = SEC_PKCS7IncludeCertChain (cinfo, NULL);
     if (rv != SECSuccess) {
 	SEC_PKCS7DestroyContentInfo (cinfo);
 	return -1;
     }
 
     rv = SEC_PKCS7Encode (cinfo, SignOut, outFile, NULL,
-			  NULL, NULL);
+			  NULL, &pwdata);
 
     SEC_PKCS7DestroyContentInfo (cinfo);
 
     if (rv != SECSuccess)
 	return -1;
 
     return 0;
 }
@@ -203,17 +192,17 @@ main(int argc, char **argv)
 
     inFile = NULL;
     outFile = NULL;
     keyName = NULL;
 
     /*
      * Parse command line arguments
      */
-    optstate = PL_CreateOptState(argc, argv, "ed:k:i:o:p:");
+    optstate = PL_CreateOptState(argc, argv, "ed:k:i:o:p:f:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	  case '?':
 	    Usage(progName);
 	    break;
 
 	  case 'e':
 	    /* create a message with the signed content encapsulated */
@@ -241,35 +230,41 @@ main(int argc, char **argv)
 	    outFile = fopen(optstate->value, "wb");
 	    if (!outFile) {
 		fprintf(stderr, "%s: unable to open \"%s\" for writing\n",
 			progName, optstate->value);
 		return -1;
 	    }
 	    break;
 	  case 'p':
-            KeyDbPassword = strdup (optstate->value);
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = strdup (optstate->value);
             break;
+
+	  case 'f':
+              pwdata.source = PW_FROMFILE;
+              pwdata.data = PORT_Strdup (optstate->value);
+              break;
 	}
     }
 
     if (!keyName) Usage(progName);
 
     if (!inFile) inFile = PR_STDIN;
     if (!outFile) outFile = stdout;
 
     /* Call the initialization routines */
     PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
     rv = NSS_Init(SECU_ConfigDirectory(NULL));
     if (rv != SECSuccess) {
 	SECU_PrintPRandOSError(progName);
 	goto loser;
     }
 
-    PK11_SetPasswordFunc (MyPK11PasswordFunc);
+    PK11_SetPasswordFunc(SECU_GetModulePassword);
 
     /* open cert database */
     certHandle = CERT_GetDefaultCertDB();
     if (certHandle == NULL) {
 	rv = SECFailure;
 	goto loser;
     }
 
@@ -285,18 +280,18 @@ main(int argc, char **argv)
 
     if (SignFile(outFile, inFile, cert, encapsulated)) {
 	SECU_PrintError(progName, "problem signing data");
 	rv = SECFailure;
 	goto loser;
     }
 
 loser:
-    if (KeyDbPassword) {
-        PORT_Free(KeyDbPassword);
+    if (pwdata.data) {
+        PORT_Free(pwdata.data);
     }
     if (keyName) {
         PORT_Free(keyName);
     }
     if (cert) {
         CERT_DestroyCertificate(cert);
     }
     if (inFile && inFile != PR_STDIN) {
--- a/security/nss/cmd/p7verify/p7verify.c
+++ b/security/nss/cmd/p7verify/p7verify.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * p7verify -- A command to do a verification of a *detached* pkcs7 signature.
  *
- * $Id: p7verify.c,v 1.9 2004/04/25 15:02:49 gerv%gerv.net Exp $
+ * $Id: p7verify.c,v 1.10 2008/08/08 23:47:57 julien.pierre.boogz%sun.com Exp $
  */
 
 #include "nspr.h"
 #include "secutil.h"
 #include "plgetopt.h"
 #include "secpkcs7.h"
 #include "cert.h"
 #include "certdb.h"
@@ -281,17 +281,17 @@ main(int argc, char **argv)
 	      
 	}
     }
 
     if (!contentFile) Usage (progName);
     if (!signatureFile) Usage (progName);
     if (!outFile) outFile = stdout;
 
-    /* Call the libsec initialization routines */
+    /* Call the NSS initialization routines */
     PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
     rv = NSS_Init(SECU_ConfigDirectory(NULL));
     if (rv != SECSuccess) {
     	SECU_PrintPRandOSError(progName);
 	return -1;
     }
 
     if (HashDecodeAndVerify(outFile, contentFile, signatureFile,
--- a/security/nss/cmd/pk11mode/pk11mode.c
+++ b/security/nss/cmd/pk11mode/pk11mode.c
@@ -1,14 +1,15 @@
 /*
  * pk11mode.c - Test FIPS or NONFIPS Modes for the NSS PKCS11 api.
  *              The goal of this program is to test every function
  *              entry point of the PKCS11 api at least once.
  *              To test in FIPS mode: pk11mode
- *              To test in NONFIPS mode: pk11mode nonFIPS
+ *              To test in NONFIPS mode: pk11mode -n
+ *              usage: pk11mode -h
  *
  * ***** BEGIN LICENSE BLOCK *****
  * Version: MPL 1.1/GPL 2.0/LGPL 2.1
  *
  * The contents of this file are subject to the Mozilla Public License Version
  * 1.1 (the "License"); you may not use this file except in compliance with
  * the License. You may obtain a copy of the License at
  * http://www.mozilla.org/MPL/
@@ -5010,41 +5011,39 @@ PKM_TLSKeyAndMacDerive( CK_FUNCTION_LIST
     }
 
     if (mk_obj != CK_INVALID_HANDLE)
         (void) pFunctionList->C_DestroyObject(hSession, mk_obj);
     if (kmo.hClientMacSecret != CK_INVALID_HANDLE)
         (void) pFunctionList->C_DestroyObject(hSession, kmo.hClientMacSecret);
     if (kmo.hServerMacSecret != CK_INVALID_HANDLE)
         (void) pFunctionList->C_DestroyObject(hSession, kmo.hServerMacSecret);
-    if (kmo.hClientKey != CK_INVALID_HANDLE);
+    if (kmo.hClientKey != CK_INVALID_HANDLE)
         (void) pFunctionList->C_DestroyObject(hSession, kmo.hClientKey);
     if (kmo.hServerKey != CK_INVALID_HANDLE)
         (void) pFunctionList->C_DestroyObject(hSession, kmo.hServerKey);
+
     crv = pFunctionList->C_Logout(hSession);
     if (crv == CKR_OK) {
         PKM_LogIt("C_Logout succeeded\n");
     } else {
         PKM_Error( "C_Logout failed with 0x%08X, %-26s\n", crv, 
                    PKM_CK_RVtoStr(crv));
         return crv;
     }
     crv = pFunctionList->C_CloseSession(hSession);
     if (crv != CKR_OK) {
         PKM_Error( "C_CloseSession failed with 0x%08X, %-26s\n", crv, 
                    PKM_CK_RVtoStr(crv));
         return crv;
     }
 
-
     return (crv);
 }
 
-
-
 CK_RV PKM_DualFuncSign(CK_FUNCTION_LIST_PTR pFunctionList,
                        CK_SESSION_HANDLE hRwSession,
                        CK_OBJECT_HANDLE publicKey, CK_OBJECT_HANDLE privateKey,
                        CK_MECHANISM *sigMech,
                        CK_OBJECT_HANDLE secretKey, CK_MECHANISM *cryptMech,
                        const CK_BYTE *  pData, CK_ULONG pDataLen) {
 
     CK_RV crv = CKR_OK;
@@ -5312,18 +5311,18 @@ char * PKM_FilePasswd(char *pwFile)
 }
 
 void PKM_Help() 
 {
     PRFileDesc *debug_out = PR_GetSpecialFD(PR_StandardError);
     PR_fprintf(debug_out, "pk11mode test program usage:\n");
     PR_fprintf(debug_out, "\t-f <file>   Password File : echo pw > file \n");
     PR_fprintf(debug_out, "\t-n          Non Fips Mode \n");
-    PR_fprintf(debug_out, "\t-d <path>   Database path location)\n");
-    PR_fprintf(debug_out, "\t-p <prefix> DataBase prefix)\n");
+    PR_fprintf(debug_out, "\t-d <path>   Database path location\n");
+    PR_fprintf(debug_out, "\t-p <prefix> DataBase prefix\n");
     PR_fprintf(debug_out, "\t-h          this help message\n");
     exit(1);
 }
 
 void PKM_CheckPath(char *string)
 {
    char *src;
    char *dest;
--- a/security/nss/cmd/pwdecrypt/pwdecrypt.c
+++ b/security/nss/cmd/pwdecrypt/pwdecrypt.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Test program for SDR (Secret Decoder Ring) functions.
  *
- * $Id: pwdecrypt.c,v 1.4 2005/11/15 23:40:18 nelsonb%netscape.com Exp $
+ * $Id: pwdecrypt.c,v 1.5 2008/08/08 23:47:58 julien.pierre.boogz%sun.com Exp $
  */
 
 #include "nspr.h"
 #include "string.h"
 #include "nss.h"
 #include "secutil.h"
 #include "cert.h"
 #include "pk11func.h"
@@ -54,20 +54,19 @@
 #define DEFAULT_VALUE "Test"
 
 static void
 synopsis (char *program_name)
 {
     PRFileDesc *pr_stderr;
 
     pr_stderr = PR_STDERR;
-    PR_fprintf (pr_stderr, "Usage:");
     PR_fprintf (pr_stderr,
-	"\t%s [-i <input-file>] [-o <output-file>] [-d <dir>] [-l logfile]\n",
-		program_name);
+	"Usage:\t%s [-i <input-file>] [-o <output-file>] [-d <dir>]\n"
+        "      \t[-l logfile] [-p pwd] [-f pwfile]\n", program_name);
 }
 
 
 static void
 short_usage (char *program_name)
 {
     PR_fprintf (PR_STDERR,
 		"Type %s -H for more detailed descriptions\n",
@@ -100,16 +99,22 @@ long_usage (char *program_name)
 		"  %-13s Write results to \"write_file\"\n",
 		"-o write_file");
     PR_fprintf (pr_stderr,
 		"  %-13s Find security databases in \"dbdir\"\n",
 		"-d dbdir");
     PR_fprintf (pr_stderr,
 		"  %-13s Log failed decrypt/decode attempts to \"log_file\"\n",
 		"-l log_file");
+    PR_fprintf (pr_stderr,
+		"  %-13s Token password\n",
+		"-p pwd");
+    PR_fprintf (pr_stderr,
+		"  %-13s Password file\n",
+		"-f pwfile");
 }
 
 /*
  * base64 table only used to identify the end of a base64 string 
  */
 static unsigned char b64[256] = {
 /*   0: */        0,      0,      0,      0,      0,      0,      0,      0,
 /*   8: */        0,      0,      0,      0,      0,      0,      0,      0,
@@ -202,23 +207,24 @@ main (int argc, char **argv)
     char  *output_file = NULL;	/* write new encrypted data here */
     char  *log_file = NULL;	/* write new encrypted data here */
     FILE	*inFile = stdin;
     FILE	*outFile = stdout;
     FILE	*logFile = NULL;
     PLOptStatus optstatus;
     SECItem	result;
     int		c;
+    secuPWData  pwdata = { PW_NONE, NULL };
 
     result.data = 0;
 
     program_name = PL_strrchr(argv[0], '/');
     program_name = program_name ? (program_name + 1) : argv[0];
 
-    optstate = PL_CreateOptState (argc, argv, "Hd:i:o:l:?");
+    optstate = PL_CreateOptState (argc, argv, "Hd:f:i:o:l:p:?");
     if (optstate == NULL) {
 	SECU_PrintError (program_name, "PL_CreateOptState failed");
 	return 1;
     }
 
     while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	  case '?':
@@ -240,16 +246,26 @@ main (int argc, char **argv)
           case 'o':
             output_file = PL_strdup(optstate->value);
             break;
 
           case 'l':
             log_file = PL_strdup(optstate->value);
             break;
 
+          case 'f':
+            pwdata.source = PW_FROMFILE;
+            pwdata.data = PL_strdup(optstate->value);
+            break;
+
+          case 'p':
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = PL_strdup(optstate->value);
+            break;
+
 	}
     }
     PL_DestroyOptState(optstate);
     if (optstatus == PL_OPT_BAD) {
 	short_usage (program_name);
 	return 1;
     }
 
@@ -314,17 +330,17 @@ main (int argc, char **argv)
 			SECU_Strerror(PORT_GetError()));
 		}
 		fputs(dataString,outFile);
 		free(dataString);
 		continue;
 	   }
 	   result.data = NULL;
 	   result.len  = 0;
-	   rv = PK11SDR_Decrypt(inText, &result, NULL);
+	   rv = PK11SDR_Decrypt(inText, &result, &pwdata);
 	   SECITEM_FreeItem(inText, PR_TRUE);
 	   if (rv != SECSuccess) {
 		if (logFile) {
 		    fprintf(logFile,"SDR decrypt failed on <%s>\n",
 								dataString);
 		    fprintf(logFile," Error %x: %s\n",PORT_GetError(),
 			SECU_Strerror(PORT_GetError()));
 		}
--- a/security/nss/cmd/rsaperf/rsaperf.c
+++ b/security/nss/cmd/rsaperf/rsaperf.c
@@ -158,17 +158,17 @@ char *TimingGenerateString(TimingContext
 
 void
 Usage(char *progName)
 {
     fprintf(stderr, "Usage: %s [-s | -e] [-i iterations | -p period] "
             "[-t threads]\n[-n none [-k keylength] [ [-g] -x exponent] |\n"
             " -n token:nickname [-d certdir] [-w password] |\n"
             " -h token [-d certdir] [-w password] [-g] [-k keylength] "
-            "[-x exponent] ]\n",
+            "[-x exponent] [-f pwfile]\n",
 	    progName);
     fprintf(stderr, "%-20s Cert database directory (default is ~/.netscape)\n",
 	    "-d certdir");
     fprintf(stderr, "%-20s How many operations to perform\n", "-i iterations");
     fprintf(stderr, "%-20s How many seconds to run\n", "-p period");
     fprintf(stderr, "%-20s Perform signing (private key) operations\n", "-s");
     fprintf(stderr, "%-20s Perform encryption (public key) operations\n","-e");
     fprintf(stderr, "%-20s Nickname of certificate or key, prefixed "
@@ -320,17 +320,16 @@ main(int argc, char **argv)
     SECKEYPrivateKey *    privHighKey   = NULL;
     NSSLOWKEYPrivateKey * privKey       = NULL;
     NSSLOWKEYPublicKey *  pubKey        = NULL;
     CERTCertificate *	  cert          = NULL;
     char *		  progName      = NULL;
     char *		  secDir 	= NULL;
     char *		  nickname 	= NULL;
     char *                slotname      = NULL;
-    char *                password      = NULL;
     long                  keybits     = 0;
     RSAOp                 fn;
     void *                rsaKey        = NULL;
     PLOptState *          optstate;
     PLOptStatus           optstatus;
     long 		  iters 	= DEFAULT_ITERS;
     int		 	  i;
     PRBool 		  doPriv 	= PR_FALSE;
@@ -360,17 +359,17 @@ main(int argc, char **argv)
     PRThread           ** threadsArr = NULL;
     int                   calcThreads = 0;
 
     progName = strrchr(argv[0], '/');
     if (!progName)
 	progName = strrchr(argv[0], '\\');
     progName = progName ? progName+1 : argv[0];
 
-    optstate = PL_CreateOptState(argc, argv, "d:i:sen:p:t:h:k:w:gx:");
+    optstate = PL_CreateOptState(argc, argv, "d:ef:gh:i:k:n:p:st:w:x:");
     while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	case '?':
 	    Usage(progName);
 	    break;
 	case 'd':
 	    secDir = PORT_Strdup(optstate->value);
 	    break;
@@ -403,20 +402,23 @@ main(int argc, char **argv)
 	case 'h':
 	    slotname = PORT_Strdup(optstate->value);
 	    useSessionKey = PR_TRUE;
 	    break;
 	case 'k':
 	    keybits = INT_ARG(optstate->value, DEFAULT_KEY_BITS);
 	    break;
 	case 'w':
-	    password = PORT_Strdup(optstate->value);
-	    pwData.data = password;
+	    pwData.data = PORT_Strdup(optstate->value);;
 	    pwData.source = PW_PLAINTEXT;
 	    break;
+        case 'f':
+            pwData.data = PORT_Strdup(optstate->value);
+            pwData.source = PW_FROMFILE;
+            break;
 	case 'x':
 	    /*  -x public exponent (for RSA keygen)  */
 	    publicExponent = INT_ARG(optstate->value, DEFAULT_EXPONENT);
 	    break;
 	case 't':
 	    threadNum = INT_ARG(optstate->value, DEFAULT_THREADS);
 	    break;
 	}
--- a/security/nss/cmd/selfserv/selfserv.c
+++ b/security/nss/cmd/selfserv/selfserv.c
@@ -158,45 +158,29 @@ static PRBool  noDelay;
 static int     requestCert;
 static int	verbose;
 static SECItem	bigBuf;
 
 static PRThread * acceptorThread;
 
 static PRLogModuleInfo *lm;
 
-/* Add custom password handler because SECU_GetModulePassword 
- * makes automation of this program next to impossible.
- */
-
-char *
-ownPasswd(PK11SlotInfo *info, PRBool retry, void *arg)
-{
-	char * passwd = NULL;
-
-	if ( (!retry) && arg ) {
-		passwd = PL_strdup((char *)arg);
-	}
-
-	return passwd;
-}
-
 #define PRINTF  if (verbose)  printf
 #define FPRINTF if (verbose) fprintf
 #define FLUSH	if (verbose) { fflush(stdout); fflush(stderr); }
 #define VLOG(arg) PR_LOG(lm,PR_LOG_DEBUG,arg)
 
 static void
 Usage(const char *progName)
 {
     fprintf(stderr, 
 
 "Usage: %s -n rsa_nickname -p port [-3BDENRSTbjlmrsuvx] [-w password]\n"
 "         [-t threads] [-i pid_file] [-c ciphers] [-d dbdir] [-g numblocks]\n"
-"         [-f fortezza_nickname] [-L [seconds]] [-M maxProcs] [-P dbprefix]\n"
+"         [-f password_file] [-L [seconds]] [-M maxProcs] [-P dbprefix]\n"
 #ifdef NSS_ENABLE_ECC
 "         [-C SSLCacheEntries] [-e ec_nickname]\n"
 #else
 "         [-C SSLCacheEntries]\n"
 #endif /* NSS_ENABLE_ECC */
 "-S means disable SSL v2\n"
 "-3 means disable SSL v3\n"
 "-T means disable TLS\n"
@@ -1829,21 +1813,21 @@ WaitForDebugger(void)
 int
 main(int argc, char **argv)
 {
     char *               progName    = NULL;
     char *               nickName    = NULL;
 #ifdef NSS_ENABLE_ECC
     char *               ecNickName   = NULL;
 #endif
-    char *               fNickName   = NULL;
     const char *         fileName    = NULL;
     char *               cipherString= NULL;
     const char *         dir         = ".";
     char *               passwd      = NULL;
+    char *               pwfile      = NULL;
     const char *         pidFile     = NULL;
     char *               tmp;
     char *               envString;
     PRFileDesc *         listen_sock;
     CERTCertificate *    cert   [kt_kea_size] = { NULL };
     SECKEYPrivateKey *   privKey[kt_kea_size] = { NULL };
     int                  optionsFound = 0;
     int                  maxProcs     = 1;
@@ -1857,16 +1841,17 @@ main(int argc, char **argv)
     PLOptStatus          status;
     PRThread             *loggerThread = NULL;
     PRBool               debugCache = PR_FALSE; /* bug 90518 */
     char                 emptyString[] = { "" };
     char*                certPrefix = emptyString;
     PRUint32             protos = 0;
     SSL3Statistics      *ssl3stats;
     PRUint32             i;
+    secuPWData  pwdata = { PW_NONE, 0 };
  
     tmp = strrchr(argv[0], '/');
     tmp = tmp ? tmp + 1 : argv[0];
     progName = strrchr(tmp, '\\');
     progName = progName ? progName + 1 : tmp;
 
     PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
 
@@ -1918,17 +1903,20 @@ main(int argc, char **argv)
 	case 'c': cipherString = PORT_Strdup(optstate->value); break;
 
 	case 'd': dir = optstate->value; break;
 
 #ifdef NSS_ENABLE_ECC
 	case 'e': ecNickName = PORT_Strdup(optstate->value); break;
 #endif /* NSS_ENABLE_ECC */
 
-	case 'f': fNickName = PORT_Strdup(optstate->value); break;
+	case 'f':
+            pwdata.source = PW_FROMFILE;
+            pwdata.data = pwfile = PORT_Strdup(optstate->value);
+            break;
 
         case 'g': 
             testBulk = PR_TRUE;
             testBulkTotal = PORT_Atoi(optstate->value);
             break;
 
 	case 'h': Usage(progName); exit(0); break;
 
@@ -1962,17 +1950,20 @@ main(int argc, char **argv)
 	    if ( maxThreads > MAX_THREADS ) maxThreads = MAX_THREADS;
 	    if ( maxThreads < MIN_THREADS ) maxThreads = MIN_THREADS;
 	    break;
 
 	case 'u': enableSessionTickets = PR_TRUE; break;
 
 	case 'v': verbose++; break;
 
-	case 'w': passwd = PORT_Strdup(optstate->value); break;
+	case 'w':
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = passwd = PORT_Strdup(optstate->value);
+            break;
 
 	case 'x': useExportPolicy = PR_TRUE; break;
 
 	case 'y': debugCache = PR_TRUE; break;
 
 	default:
 	case '?':
 	    fprintf(stderr, "Unrecognized or bad option specified.\n");
@@ -2002,17 +1993,17 @@ main(int argc, char **argv)
 	    exit(1);
 	}
         if (listen_sock) {
             PR_Close(listen_sock);
         }
 	exit(0);
     }
 
-    if ((nickName == NULL) && (fNickName == NULL) 
+    if ((nickName == NULL)
  #ifdef NSS_ENABLE_ECC
 						&& (ecNickName == NULL)
  #endif
     ) {
 
 	fprintf(stderr, "Required arg '-n' (rsa nickname) not supplied.\n");
 	fprintf(stderr, "Run '%s -h' for usage information.\n", progName);
         exit(6);
@@ -2102,19 +2093,19 @@ main(int argc, char **argv)
     }
 
     lm = PR_NewLogModule("TestCase");
 
     if (fileName)
     	readBigFile(fileName);
 
     /* set our password function */
-    PK11_SetPasswordFunc( passwd ? ownPasswd : SECU_GetModulePassword);
+    PK11_SetPasswordFunc(SECU_GetModulePassword);
 
-    /* Call the libsec initialization routines */
+    /* Call the NSS initialization routines */
     rv = NSS_Initialize(dir, certPrefix, certPrefix, SECMOD_DB, NSS_INIT_READONLY);
     if (rv != SECSuccess) {
     	fputs("NSS_Init failed.\n", stderr);
 		exit(8);
     }
 
     /* set the policy bits true for all the cipher suites. */
     if (useExportPolicy) {
@@ -2197,64 +2188,56 @@ main(int argc, char **argv)
 				    && enabled)
 		savecipher(*cipherSuites);		    
 	}
 	protos = (disableTLS ? 0 : SSL_CBP_TLS1_0) +
 		 (disableSSL3 ? 0 : SSL_CBP_SSL3);
     }
 
     if (nickName) {
-	cert[kt_rsa] = PK11_FindCertFromNickname(nickName, passwd);
+	cert[kt_rsa] = PK11_FindCertFromNickname(nickName, &pwdata);
 	if (cert[kt_rsa] == NULL) {
 	    fprintf(stderr, "selfserv: Can't find certificate %s\n", nickName);
 	    exit(10);
 	}
-	privKey[kt_rsa] = PK11_FindKeyByAnyCert(cert[kt_rsa], passwd);
+	privKey[kt_rsa] = PK11_FindKeyByAnyCert(cert[kt_rsa], &pwdata);
 	if (privKey[kt_rsa] == NULL) {
 	    fprintf(stderr, "selfserv: Can't find Private Key for cert %s\n", 
 	            nickName);
 	    exit(11);
 	}
 	if (testbypass) {
 	    PRBool bypassOK;
 	    if (SSL_CanBypass(cert[kt_rsa], privKey[kt_rsa], protos, cipherlist, 
-	                      nciphers, &bypassOK, passwd) != SECSuccess) {
+	                      nciphers, &bypassOK, &pwdata) != SECSuccess) {
 		SECU_PrintError(progName, "Bypass test failed %s\n", nickName);
 		exit(14);
 	    }
 	    fprintf(stderr, "selfserv: %s can%s bypass\n", nickName,
 		    bypassOK ? "" : "not");
 	}
     }
-    if (fNickName) {
-	cert[kt_fortezza] = PK11_FindCertFromNickname(fNickName, NULL);
-	if (cert[kt_fortezza] == NULL) {
-	    fprintf(stderr, "selfserv: Can't find certificate %s\n", fNickName);
-	    exit(12);
-	}
-	privKey[kt_fortezza] = PK11_FindKeyByAnyCert(cert[kt_fortezza], NULL);
-    }
 #ifdef NSS_ENABLE_ECC
     if (ecNickName) {
-	cert[kt_ecdh] = PK11_FindCertFromNickname(ecNickName, passwd);
+	cert[kt_ecdh] = PK11_FindCertFromNickname(ecNickName, &pwdata);
 	if (cert[kt_ecdh] == NULL) {
 	    fprintf(stderr, "selfserv: Can't find certificate %s\n",
 		    ecNickName);
 	    exit(13);
 	}
-	privKey[kt_ecdh] = PK11_FindKeyByAnyCert(cert[kt_ecdh], passwd);
+	privKey[kt_ecdh] = PK11_FindKeyByAnyCert(cert[kt_ecdh], &pwdata);
 	if (privKey[kt_ecdh] == NULL) {
 	    fprintf(stderr, "selfserv: Can't find Private Key for cert %s\n", 
 	            ecNickName);
 	    exit(11);
 	}	    
 	if (testbypass) {
 	    PRBool bypassOK;
 	    if (SSL_CanBypass(cert[kt_ecdh], privKey[kt_ecdh], protos, cipherlist,
-			      nciphers, &bypassOK, passwd) != SECSuccess) {
+			      nciphers, &bypassOK, &pwdata) != SECSuccess) {
 		SECU_PrintError(progName, "Bypass test failed %s\n", ecNickName);
 		exit(15);
 	    }
 	    fprintf(stderr, "selfserv: %s can%s bypass\n", ecNickName,
 		    bypassOK ? "" : "not");
        }
     }
 #endif /* NSS_ENABLE_ECC */
@@ -2307,22 +2290,22 @@ cleanup:
     }
 
     if (nickName) {
         PORT_Free(nickName);
     }
     if (passwd) {
         PORT_Free(passwd);
     }
+    if (pwfile) {
+        PORT_Free(pwfile);
+    }
     if (certPrefix && certPrefix != emptyString) {                            
         PORT_Free(certPrefix);
     }
-    if (fNickName) {
-        PORT_Free(fNickName);
-    }
  #ifdef NSS_ENABLE_ECC
     if (ecNickName) {
         PORT_Free(ecNickName);
     }
  #endif
 
     if (hasSidCache) {
 	SSL_ShutdownServerSessionIDCache();
--- a/security/nss/cmd/shlibsign/shlibsign.c
+++ b/security/nss/cmd/shlibsign/shlibsign.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Test program for SDR (Secret Decoder Ring) functions.
  *
- * $Id: shlibsign.c,v 1.15 2007/11/05 17:13:27 wtc%google.com Exp $
+ * $Id: shlibsign.c,v 1.16 2008/08/08 23:48:04 julien.pierre.boogz%sun.com Exp $
  */
 
 #ifdef XP_UNIX
 #define USES_LINKS 1
 #endif
 
 #include "nspr.h"
 #include <stdio.h>
@@ -64,18 +64,19 @@
 #endif
 
 static void
 usage (char *program_name)
 {
     PRFileDesc *pr_stderr;
 
     pr_stderr = PR_STDERR;
-    PR_fprintf (pr_stderr, "Usage:");
-    PR_fprintf (pr_stderr, "%s [-v] -i shared_library_name\n", program_name);
+    PR_fprintf (pr_stderr,
+      "Usage:%s [-v] [-o outfile] [-d dbdir] [-f pwfile] [-p pwd]\n"
+      "      -i shared_library_name\n", program_name);
 }
 
 static char *
 mkoutput(const char *input)
 {
     int in_len = PORT_Strlen(input);
     char *output = PORT_Alloc(in_len+sizeof(SGN_SUFFIX));
     int index = in_len + 1 - sizeof("."SHLIB_SUFFIX);
@@ -151,30 +152,31 @@ main (int argc, char **argv)
     unsigned char sign_buf[40]; /* DSA_LENGTH */
     SECItem hash,sign;
     PK11Context *hashcx = NULL;
     int ks, count=0;
     int keySize = 1024;
     PQGParams *pqgParams = NULL;
     PQGVerify *pqgVerify = NULL;
     const char *nssDir = NULL;
+    secuPWData  pwdata = { PW_NONE, 0 };
 #ifdef USES_LINKS
     int ret;
     struct stat stat_buf;
     char link_buf[MAXPATHLEN+1];
     char *link_file = NULL;
 #endif
 
     hash.len = sizeof(hash_buf); hash.data = hash_buf;
     sign.len = sizeof(sign_buf); sign.data = sign_buf;
 
     program_name = PL_strrchr(argv[0], '/');
     program_name = program_name ? (program_name + 1) : argv[0];
 
-    optstate = PL_CreateOptState (argc, argv, "d:i:o:v");
+    optstate = PL_CreateOptState (argc, argv, "d:f:i:o:p:v");
     if (optstate == NULL) {
 	SECU_PrintError (program_name, "PL_CreateOptState failed");
 	return 1;
     }
 
     while (PL_GetNextOpt (optstate) == PL_OPT_OK) {
 	switch (optstate->option) {
 #ifdef notdef
@@ -194,16 +196,26 @@ main (int argc, char **argv)
           case 'i':
             input_file = optstate->value;
             break;
 
           case 'o':
             output_file = PORT_Strdup(optstate->value);
             break;
 
+          case 'f':
+            pwdata.source = PW_FROMFILE;
+            pwdata.data = PORT_Strdup(optstate->value);
+            break;
+
+          case 'p':
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = PORT_Strdup(optstate->value);
+            break;
+
           case 'v':
             verbose = PR_TRUE;
             break;
 	}
     }
 
     if (input_file == NULL) {
 	usage(program_name);
@@ -225,31 +237,31 @@ main (int argc, char **argv)
     }
     
     if (rv != SECSuccess) {
 	lperror("NSS_Init failed");
 	goto prdone;
     }
     
     /* Generate a DSA Key pair */
-    slot = PK11_GetBestSlot(CKM_DSA,NULL);
+    slot = PK11_GetBestSlot(CKM_DSA,&pwdata);
     if (slot == NULL) {
 	lperror("CKM_DSA");
 	goto loser;
 	
     }
     printf("Generating DSA Key Pair...."); fflush(stdout);
     ks = PQG_PBITS_TO_INDEX(keySize);
     rv = PK11_PQG_ParamGen(ks,&pqgParams, &pqgVerify);
     if (rv != SECSuccess) {
 	lperror("Generating PQG Params");
 	goto loser;
     }
     privk = PK11_GenerateKeyPair(slot, CKM_DSA_KEY_PAIR_GEN, pqgParams, &pubk, 
-						PR_FALSE, PR_TRUE, NULL);
+						PR_FALSE, PR_TRUE, &pwdata);
     if (privk == NULL) {
 	lperror("Generating DSA Key");
 	goto loser;
     }
 
     printf("done\n");
 
     /* open the shared library */
@@ -420,16 +432,19 @@ loser:
         SECKEY_DestroyPrivateKey(privk);
     }
     if (pubk) {
         SECKEY_DestroyPublicKey(pubk);
     }
     if (slot) {
         PK11_FreeSlot(slot);
     }
+    if (pwdata.data) {
+        PORT_Free(pwdata.data);
+    }
     if (NSS_Shutdown() != SECSuccess) {
 	exit(1);
     }
 
 prdone:
     PR_Cleanup ();
     return retval;
 }
--- a/security/nss/cmd/signtool/certgen.c
+++ b/security/nss/cmd/signtool/certgen.c
@@ -89,17 +89,17 @@ GenerateCert(char *nickname, int keysize
 	return - 1;
     }
 
     db = CERT_GetDefaultCertDB();
     if (!db) {
 	FatalError("Unable to open certificate database");
     }
 
-    if (PK11_FindCertFromNickname(nickname, NULL)) {
+    if (PK11_FindCertFromNickname(nickname, &pwdata)) {
 	PR_fprintf(errorFD,
 	    "ERROR: Certificate with nickname \"%s\" already exists in database. You\n"
 	    "must choose a different nickname.\n", nickname);
 	errorCount++;
 	exit(ERRX);
     }
 
     LL_L2UI(serial, PR_Now());
@@ -468,17 +468,17 @@ sign_cert(CERTCertificate *cert, SECKEYP
 	errorCount++;
 	exit (ERRX);
     }
 
     der2.len = 0;
     der2.data = NULL;
 
     dummy = SEC_ASN1EncodeItem
-        (cert->arena, &der2, cert, CERT_CertificateTemplate);
+        (cert->arena, &der2, cert, SEC_ASN1_GET(CERT_CertificateTemplate));
 
     if (rv != SECSuccess) {
 	PR_fprintf(errorFD, "%s: error encoding cert\n", PROGRAM_NAME);
 	errorCount++;
 	exit (ERRX);
     }
 
     result2 = (SECItem * ) PORT_ArenaZAlloc (cert->arena, sizeof (SECItem));
@@ -509,32 +509,32 @@ sign_cert(CERTCertificate *cert, SECKEYP
  * Installs the cert in the permanent database.
  */
 static CERTCertificate*
 install_cert(CERTCertDBHandle *db, SECItem *derCert, char *nickname)
 {
     CERTCertificate * newcert;
     PK11SlotInfo * newSlot;
 
-    newcert = CERT_DecodeDERCertificate(derCert, PR_TRUE, NULL);
 
-    if (newcert == NULL) {
-	PR_fprintf(errorFD, "%s: can't create new certificate\n",
-	     PROGRAM_NAME);
-	errorCount++;
-	exit (ERRX);
-    }
-
-    newSlot = PK11_ImportCertForKey(newcert, nickname, NULL /*wincx*/);
+    newSlot = PK11_ImportDERCertForKey(derCert, nickname, &pwdata);
     if ( newSlot == NULL ) {
 	PR_fprintf(errorFD, "Unable to install certificate\n");
 	errorCount++;
 	exit(ERRX);
     }
+
+    newcert = PK11_FindCertFromDERCertItem(newSlot, derCert, &pwdata);
     PK11_FreeSlot(newSlot);
+    if (newcert == NULL) {
+	PR_fprintf(errorFD, "%s: can't find new certificate\n",
+	     PROGRAM_NAME);
+	errorCount++;
+	exit (ERRX);
+    }
 
     if (verbosity >= 0) {
 	PR_fprintf(outputFD, "certificate \"%s\" added to database\n",
 	     nickname);
     }
 
     return newcert;
 }
@@ -553,25 +553,25 @@ SECKEYPrivateKey **privk, int keysize)
 
     if ( keysize == -1 ) {
 	rsaParams.keySizeInBits = DEFAULT_RSA_KEY_SIZE;
     } else {
 	rsaParams.keySizeInBits = keysize;
     }
     rsaParams.pe = 0x10001;
 
-    if (PK11_Authenticate( slot, PR_FALSE /*loadCerts*/, NULL /*wincx*/)
+    if (PK11_Authenticate( slot, PR_FALSE /*loadCerts*/, &pwdata)
          != SECSuccess) {
 	SECU_PrintError(progName, "failure authenticating to key database.\n");
 	exit(ERRX);
     }
 
     *privk = PK11_GenerateKeyPair (slot, CKM_RSA_PKCS_KEY_PAIR_GEN, &rsaParams,
          
-        pubk, PR_TRUE /*isPerm*/, PR_TRUE /*isSensitive*/, NULL /*wincx*/ );
+        pubk, PR_TRUE /*isPerm*/, PR_TRUE /*isSensitive*/, &pwdata);
 
     if (*privk != NULL && *pubk != NULL) {
 	if (verbosity >= 0) {
 	    PR_fprintf(outputFD, "generated public/private key pair\n");
 	}
     } else {
 	SECU_PrintError(progName, "failure generating key pair\n");
 	exit (ERRX);
--- a/security/nss/cmd/signtool/list.c
+++ b/security/nss/cmd/signtool/list.c
@@ -82,17 +82,17 @@ ListCerts(char *key, int list_certs)
 	PR_fprintf(outputFD, "\nObject signing certificates\n");
 	PR_fprintf(outputFD, "---------------------------------------\n");
     }
 
     num_trav_certs = 0;
 
     /* Traverse non-internal DBs */
     rv = PK11_TraverseSlotCerts(cert_trav_callback, (void * )&list_certs,
-         		NULL /*wincx*/);
+         		&pwdata);
 
     if (rv) {
 	PR_fprintf(outputFD, "**Traverse of non-internal DBs failed**\n");
 	return - 1;
     }
 
     if (num_trav_certs == 0) {
 	PR_fprintf(outputFD,
@@ -114,17 +114,17 @@ ListCerts(char *key, int list_certs)
 	PR_fprintf(outputFD,
 	    "Certificates that can be used to sign objects have *'s to "
 	    "their left.\n");
     }
 
     if (key) {
 	/* Do an analysis of the given cert */
 
-	cert = PK11_FindCertFromNickname(key, NULL /*wincx*/);
+	cert = PK11_FindCertFromNickname(key, &pwdata);
 
 	if (cert) {
 	    PR_fprintf(outputFD,
 	        "\nThe certificate with nickname \"%s\" was found:\n",
 	         			 cert->nickname);
 	    PR_fprintf(outputFD, "\tsubject name: %s\n", cert->subjectName);
 	    PR_fprintf(outputFD, "\tissuer name: %s\n", cert->issuerName);
 
@@ -133,17 +133,17 @@ ListCerts(char *key, int list_certs)
 	    rv = CERT_CertTimesValid (cert);
 	    if (rv != SECSuccess) {
 		PR_fprintf(outputFD, "**This certificate is expired**\n");
 	    } else {
 		PR_fprintf(outputFD, "This certificate is not expired.\n");
 	    }
 
 	    rv = CERT_VerifyCert (db, cert, PR_TRUE,
-	        certUsageObjectSigner, PR_Now(), NULL, &errlog);
+	        certUsageObjectSigner, PR_Now(), &pwdata, &errlog);
 
 	    if (rv != SECSuccess) {
 		failed = 1;
 		if (errlog.count > 0) {
 		    PR_fprintf(outputFD,
 		        "**Certificate validation failed for the "
 		        "following reason(s):**\n");
 		} else {
@@ -234,17 +234,17 @@ cert_trav_callback(CERTCertificate *cert
 		rv = CERT_CertTimesValid (cert);
 
 		if (rv != SECSuccess)
 		    PR_fprintf(outputFD, 
 			"    ++ Error ++ THIS CERTIFICATE IS EXPIRED\n");
 
 		if (rv == SECSuccess) {
 		    rv = CERT_VerifyCertNow (cert->dbhandle, cert,
-		        PR_TRUE, certUsageObjectSigner, NULL);
+		        PR_TRUE, certUsageObjectSigner, &pwdata);
 
 		    if (rv != SECSuccess) {
 			rv = PORT_GetError();
 			PR_fprintf(outputFD,
 			"    ++ Error ++ THIS CERTIFICATE IS NOT VALID (%s)\n",
 			     				secErrorString(rv));            
 		    }
 		}
@@ -257,17 +257,17 @@ cert_trav_callback(CERTCertificate *cert
 
 		if (rv != SECSuccess)
 		    PR_fprintf(outputFD,
 		        "    ++ Error ++ ISSUER CERT \"%s\" EXPIRED ON %s\n",
 			issuerCert->nickname, expires);
 
 		if (rv == SECSuccess) {
 		    rv = CERT_VerifyCertNow (issuerCert->dbhandle, issuerCert, 
-		        PR_TRUE, certUsageVerifyCA, NULL);
+		        PR_TRUE, certUsageVerifyCA, &pwdata);
 		    if (rv != SECSuccess) {
 			rv = PORT_GetError();
 			PR_fprintf(outputFD,
 			"    ++ Error ++ ISSUER CERT \"%s\" IS NOT VALID (%s)\n",
 			     issuerCert->nickname, secErrorString(rv));
 		    }
 		}
 	    }
--- a/security/nss/cmd/signtool/manifest.mn
+++ b/security/nss/cmd/signtool/manifest.mn
@@ -47,15 +47,11 @@ CSRCS = signtool.c		\
 		sign.c		\
 		util.c		\
 		verify.c	\
 		zip.c		\
 	$(NULL)
 
 PROGRAM =  signtool
 
-REQUIRES = dbm seccmd
-
-DEFINES += -DNSPR20
-
-USE_STATIC_LIBS = 1
+REQUIRES = seccmd
 
 EXTRA_LIBS = $(JAR_LIBS)
--- a/security/nss/cmd/signtool/sign.c
+++ b/security/nss/cmd/signtool/sign.c
@@ -262,17 +262,17 @@ create_pk7 (char *dir, char *keyName, in
     /* open cert database */
     db = CERT_GetDefaultCertDB();
 
     if (db == NULL)
 	return - 1;
 
     /* find cert */
     /*cert = CERT_FindCertByNicknameOrEmailAddr(db, keyName);*/
-    cert = PK11_FindCertFromNickname(keyName, NULL /*wincx*/);
+    cert = PK11_FindCertFromNickname(keyName, &pwdata);
 
     if (cert == NULL) {
 	SECU_PrintError ( PROGRAM_NAME,
 	    "Cannot find the cert \"%s\"", keyName);
 	return -1;
     }
 
 
@@ -320,32 +320,21 @@ create_pk7 (char *dir, char *keyName, in
  * 
  *  Determine the key type for a given cert, which 
  * should be rsaKey or dsaKey. Any error return 0.
  *
  */
 static int	
 jar_find_key_type (CERTCertificate *cert)
 {
-    PK11SlotInfo * slot = NULL;
     SECKEYPrivateKey * privk = NULL;
     KeyType keyType;
 
     /* determine its type */
-    PK11_FindObjectForCert (cert, /*wincx*/ NULL, &slot);
-
-    if (slot == NULL) {
-	PR_fprintf(errorFD, "warning - can't find slot for this cert\n");
-	warningCount++;
-	return 0;
-    }
-
-    privk = PK11_FindPrivateKeyFromCert (slot, cert, /*wincx*/ NULL);
-    PK11_FreeSlot (slot);
-
+    privk = PK11_FindKeyByAnyCert (cert, &pwdata);
     if (privk == NULL) {
 	PR_fprintf(errorFD, "warning - can't find private key for this cert\n");
 	warningCount++;
 	return 0;
     }
 
     keyType = privk->keyType;
     SECKEY_DestroyPrivateKey (privk);
@@ -690,24 +679,17 @@ SignFile (FILE *outFile, FILE *inFile, C
 
     if (no_time == 0) {
 	rv = SEC_PKCS7AddSigningTime (cinfo);
 	if (rv != SECSuccess) {
 	    /* don't check error */
 	}
     }
 
-    if (password) {
-	rv = SEC_PKCS7Encode(cinfo, SignOut, outFile, NULL, 
-	    (SECKEYGetPasswordKey) password_hardcode, NULL);
-    } else {
-	rv = SEC_PKCS7Encode(cinfo, SignOut, outFile, NULL, NULL,
-	     			NULL);
-    }
-
+    rv = SEC_PKCS7Encode(cinfo, SignOut, outFile, NULL, NULL, &pwdata);
 
     SEC_PKCS7DestroyContentInfo (cinfo);
 
     if (rv != SECSuccess)
 	return - 1;
 
     return 0;
 }
@@ -839,21 +821,17 @@ static int	generate_SF_file (char *manif
  *
  */
 static int	
 calculate_MD5_range (FILE *fp, long r1, long r2, JAR_Digest *dig)
 {
     int	num;
     int	range;
     unsigned char	*buf;
-
-    MD5Context * md5 = 0;
-    SHA1Context * sha1 = 0;
-
-    unsigned int	sha1_length, md5_length;
+    SECStatus rv;
 
     range = r2 - r1;
 
     /* position to the beginning of range */
     fseek (fp, r1, SEEK_SET);
 
     buf = (unsigned char *) PORT_ZAlloc (range);
     if (buf == NULL)
@@ -861,38 +839,27 @@ calculate_MD5_range (FILE *fp, long r1, 
 
     if ((num = fread (buf, 1, range, fp)) != range) {
 	PR_fprintf(errorFD, "%s: expected %d bytes, got %d\n", PROGRAM_NAME,
 	     		range, num);
 	errorCount++;
 	exit (ERRX);
     }
 
-    md5 = MD5_NewContext();
-    sha1 = SHA1_NewContext();
-
-    if (md5 == NULL || sha1 == NULL) {
+    rv = PK11_HashBuf(SEC_OID_MD5, dig->md5, buf, range);
+    if (rv == SECSuccess) {
+	rv =PK11_HashBuf(SEC_OID_SHA1, dig->sha1, buf, range);
+    }
+    if (rv != SECSuccess) {
 	PR_fprintf(errorFD, "%s: can't generate digest context\n",
 	     PROGRAM_NAME);
 	errorCount++;
 	exit (ERRX);
     }
 
-    MD5_Begin (md5);
-    SHA1_Begin (sha1);
-
-    MD5_Update (md5, buf, range);
-    SHA1_Update (sha1, buf, range);
-
-    MD5_End (md5, dig->md5, &md5_length, MD5_LENGTH);
-    SHA1_End (sha1, dig->sha1, &sha1_length, SHA1_LENGTH);
-
-    MD5_DestroyContext (md5, PR_TRUE);
-    SHA1_DestroyContext (sha1, PR_TRUE);
-
     PORT_Free (buf);
 
     return 0;
 }
 
 
 static void	SignOut (void *arg, const char *buf, unsigned long len)
 {
--- a/security/nss/cmd/signtool/signtool.c
+++ b/security/nss/cmd/signtool/signtool.c
@@ -50,18 +50,18 @@
 #include "prmem.h"
 #include "prio.h"
 
 /***********************************************************************
  * Global Variable Definitions
  */
 char	*progName; /* argv[0] */
 
-/* password on command line. Use for build testing only */
-char	*password = NULL;
+/* password data */
+secuPWData  pwdata = { PW_NONE, 0 };
 
 /* directories or files to exclude in descent */
 PLHashTable *excludeDirs = NULL;
 static PRBool exclusionsGiven = PR_FALSE;
 
 /* zatharus is the man who knows no time, dies tragic death */
 int	no_time = 0;
 
@@ -638,30 +638,31 @@ ProcessOneOpt(OPT_TYPE type, char *arg)
 	break;
     case OPTIMIZE_OPT:
 	optimize = 1;
 	break;
     case ENABLE_OCSP_OPT:
 	enableOCSP = 1;
 	break;
     case PASSWORD_OPT:
-	if (password) {
+	if (pwdata.data) {
 	    PR_fprintf(errorFD, errStrings[DUPLICATE_OPTION_ERR],
 	         				"password (-p)");
 	    warningCount++;
-	    PR_Free(password); 
-	    password = NULL;
+	    PR_Free(pwdata.data); 
+	    pwdata.data = NULL;
 	}
 	if (!arg) {
 	    PR_fprintf(errorFD, errStrings[OPTION_NEEDS_ARG_ERR],
 	         				"password (-p)");
 	    errorCount++;
 	    goto loser;
 	}
-	password = PL_strdup(arg);
+        pwdata.source = PW_PLAINTEXT;
+	pwdata.data = PL_strdup(arg);
 	ate = 1;
 	break;
     case VERIFY_OPT:
 	if (verify) {
 	    PR_fprintf(errorFD, errStrings[DUPLICATE_OPTION_ERR],
 	         				"verify (-v)");
 	    warningCount++;
 	    PR_Free(verify); 
--- a/security/nss/cmd/signtool/signtool.h
+++ b/security/nss/cmd/signtool/signtool.h
@@ -47,17 +47,16 @@
 #include "prio.h"
 #include "secutil.h"
 #include "ocsp.h"
 #include "jar.h"
 #include "jarfile.h"
 #include "secpkcs7.h"
 #include "pk11func.h"
 #include "secmod.h"
-#include "secmodi.h"
 #include "plhash.h"
 #include "nss.h"
 
 #ifdef _UNIX
 #include <unistd.h> 
 #endif
 
 /**********************************************************************
@@ -137,10 +136,11 @@ extern char *progName; /* argv[0] */
 extern PLHashTable *extensions;/* only sign files with this extension */
 extern PRBool extensionsGiven;
 extern char *scriptdir;
 extern int compression_level;
 extern PRFileDesc *outputFD, *errorFD;
 extern int verbosity;
 extern int errorCount;
 extern int warningCount;
+extern secuPWData pwdata;
 
 #endif /* SIGNTOOL_H */
--- a/security/nss/cmd/signtool/util.c
+++ b/security/nss/cmd/signtool/util.c
@@ -624,52 +624,16 @@ static int	is_dir (char *filename)
 	printf("Unable to get information about %s\n", filename);
 	return 0;
     }
 
     return ( finfo.type == PR_FILE_DIRECTORY );
 }
 
 
-/*
- *  p a s s w o r d _ h a r d c o d e 
- *
- *  A function to use the password passed in the -p(password) argument
- *  of the command line. This is only to be used for build & testing purposes,
- *  as it's extraordinarily insecure. 
- *
- *  After use once, null it out otherwise PKCS11 calls us forever.
- *
- */
-SECItem *
-password_hardcode(void *arg, void *handle)
-{
-    SECItem * pw = NULL;
-    if (password) {
-	pw = SECITEM_AllocItem(NULL, NULL, PL_strlen(password));
-	pw->data = (unsigned char *)PL_strdup(password);
-	password = NULL;
-    }
-    return pw;
-}
-
-char	*
-pk11_password_hardcode(PK11SlotInfo *slot, PRBool retry, void *arg)
-{
-    char	*pw;
-    if (retry) {
-	return NULL; /* the password is incorrect, fail */
-    }
-    pw = password ? PORT_Strdup (password) : NULL;
-    /* XXX don't do this, or FIPS won't work */
-    /*password = NULL;*/
-    return pw;
-}
-
-
 /***************************************************************
  *
  * s e c E r r o r S t r i n g
  *
  * Returns an error string corresponding to the given error code.
  * Doesn't cover all errors; returns a default for many.
  * Returned string is only valid until the next call of this function.
  */
@@ -826,34 +790,35 @@ JarListModules(void)
     int	i;
     int	count = 0;
 
     SECMODModuleList * modules = NULL;
     static SECMODListLock *moduleLock = NULL;
 
     SECMODModuleList * mlp;
 
-    modules = SECMOD_GetDefaultModuleList();
-
-    if (modules == NULL) {
-	PR_fprintf(errorFD, "%s: Can't get module list\n", PROGRAM_NAME);
-	errorCount++;
-	exit (ERRX);
-    }
-
-    if ((moduleLock = SECMOD_NewListLock()) == NULL) {
+    if ((moduleLock = SECMOD_GetDefaultModuleListLock()) == NULL) {
 	/* this is the wrong text */
 	PR_fprintf(errorFD, "%s: unable to acquire lock on module list\n",
 	     		PROGRAM_NAME);
 	errorCount++;
 	exit (ERRX);
     }
 
     SECMOD_GetReadLock (moduleLock);
 
+    modules = SECMOD_GetDefaultModuleList();
+
+    if (modules == NULL) {
+	SECMOD_ReleaseReadLock (moduleLock);
+	PR_fprintf(errorFD, "%s: Can't get module list\n", PROGRAM_NAME);
+	errorCount++;
+	exit (ERRX);
+    }
+
     PR_fprintf(outputFD, "\nListing of PKCS11 modules\n");
     PR_fprintf(outputFD, "-----------------------------------------------\n");
 
     for (mlp = modules; mlp != NULL; mlp = mlp->next) {
 	count++;
 	PR_fprintf(outputFD, "%3d. %s\n", count, mlp->module->commonName);
 
 	if (mlp->module->internal)
@@ -972,33 +937,28 @@ InitCrypto(char *cert_dir, PRBool readOn
 	    exit(-1);
 	}
 
 	SECU_ConfigDirectory (cert_dir);
 
 	/* Been there done that */
 	prior++;
 
-	if (password) {
-	    PK11_SetPasswordFunc(pk11_password_hardcode);
-	} else {
-	    PK11_SetPasswordFunc(SECU_GetModulePassword);
-	}
-	
+        PK11_SetPasswordFunc(SECU_GetModulePassword);
 
 	/* Must login to FIPS before you do anything else */
 	if (PK11_IsFIPS()) {
 	    slotinfo = PK11_GetInternalSlot();
 	    if (!slotinfo) {
 		fprintf(stderr, "%s: Unable to get PKCS #11 Internal Slot."
 				    "\n", PROGRAM_NAME);
 		return - 1;
 	    }
 	    if (PK11_Authenticate(slotinfo, PR_FALSE /*loadCerts*/,
-	         			  NULL /*wincx*/) != SECSuccess) {
+	         			  &pwdata) != SECSuccess) {
 		fprintf(stderr, "%s: Unable to authenticate to %s.\n",
 				    PROGRAM_NAME, PK11_GetSlotName(slotinfo));
 		PK11_FreeSlot(slotinfo);
 		return - 1;
 	    }
 	    PK11_FreeSlot(slotinfo);
 	}
 
@@ -1014,17 +974,17 @@ InitCrypto(char *cert_dir, PRBool readOn
 	        "\nWARNING: No password set on internal key database.  Most operations will fail."
 	        "\nYou must create a password.\n");
 	    warningCount++;
 	}
 
 	/* Make sure we can authenticate to the key slot in FIPS mode */
 	if (PK11_IsFIPS()) {
 	    if (PK11_Authenticate(slotinfo, PR_FALSE /*loadCerts*/,
-	         			  NULL /*wincx*/) != SECSuccess) {
+	         			  &pwdata) != SECSuccess) {
 		fprintf(stderr, "%s: Unable to authenticate to %s.\n",
 				PROGRAM_NAME, PK11_GetSlotName(slotinfo));
 		PK11_FreeSlot(slotinfo);
 		return - 1;
 	    }
 	}
 	PK11_FreeSlot(slotinfo);
     }
--- a/security/nss/cmd/smimetools/cmsutil.c
+++ b/security/nss/cmd/smimetools/cmsutil.c
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * cmsutil -- A command to work with CMS data
  *
- * $Id: cmsutil.c,v 1.53 2006/08/05 01:19:23 julien.pierre.bugs%sun.com Exp $
+ * $Id: cmsutil.c,v 1.54 2008/08/08 23:48:06 julien.pierre.boogz%sun.com Exp $
  */
 
 #include "nspr.h"
 #include "secutil.h"
 #include "plgetopt.h"
 #include "secpkcs7.h"
 #include "cert.h"
 #include "certdb.h"
@@ -128,16 +128,17 @@ Usage(char *progName)
 "                 (use \"NONE\" to omit)\n"
 " -O            create a CMS signed message containing only certificates\n"
 " General Options:\n"
 " -d dbdir      key/cert database directory (default: ~/.netscape)\n"
 " -e envelope   enveloped data message in this file is used for bulk key\n"
 " -i infile     use infile as source of data (default: stdin)\n"
 " -o outfile    use outfile as destination of data (default: stdout)\n"
 " -p password   use password as key db password (default: prompt)\n"
+" -f pwfile     use password file to set password on all PKCS#11 tokens)\n"
 " -u certusage  set type of certificate usage (default: certUsageEmailSigner)\n"
 " -v            print debugging information\n"
 "\n"
 "Cert usage codes:\n",
 	    progName);
     fprintf(stderr, "%-25s  0 - certUsageSSLClient\n", " ");
     fprintf(stderr, "%-25s  1 - certUsageSSLServer\n", " ");
     fprintf(stderr, "%-25s  2 - certUsageSSLServerWithStepUp\n", " ");
@@ -150,16 +151,17 @@ Usage(char *progName)
     fprintf(stderr, "%-25s  9 - certUsageProtectedObjectSigner\n", " ");
     fprintf(stderr, "%-25s 10 - certUsageStatusResponder\n", " ");
     fprintf(stderr, "%-25s 11 - certUsageAnyCA\n", " ");
 
     exit(-1);
 }
 
 struct optionsStr {
+    char *pwfile;
     char *password;
     SECCertUsage certUsage;
     CERTCertDBHandle *certHandle;
 };
 
 struct decodeOptionsStr {
     struct optionsStr *options;
     SECItem            content;
@@ -435,16 +437,18 @@ signed_data(struct signOptionsStr *signO
     NSSCMSSignedData *sigd;
     NSSCMSSignerInfo *signerinfo;
     CERTCertificate *cert= NULL, *ekpcert = NULL;
 
     if (cms_verbose) {
 	fprintf(stderr, "Input to signed_data:\n");
 	if (signOptions->options->password)
 	    fprintf(stderr, "password [%s]\n", signOptions->options->password);
+        else if (signOptions->options->pwfile)
+	    fprintf(stderr, "password file [%s]\n", signOptions->options->pwfile);
 	else
 	    fprintf(stderr, "password [NULL]\n");
 	fprintf(stderr, "certUsage [%d]\n", signOptions->options->certUsage);
 	if (signOptions->options->certHandle)
 	    fprintf(stderr, "certdb [%p]\n", signOptions->options->certHandle);
 	else
 	    fprintf(stderr, "certdb [NULL]\n");
 	if (signOptions->nickname)
@@ -1116,16 +1120,17 @@ main(int argc, char **argv)
     mode = UNKNOWN;
     decodeOptions.content.data = NULL;
     decodeOptions.content.len  = 0;
     decodeOptions.suppressContent = PR_FALSE;
     decodeOptions.headerLevel = -1;
     decodeOptions.keepCerts = PR_FALSE;
     options.certUsage = certUsageEmailSigner;
     options.password = NULL;
+    options.pwfile = NULL;
     signOptions.nickname = NULL;
     signOptions.detached = PR_FALSE;
     signOptions.signingTime = PR_FALSE;
     signOptions.smimeProfile = PR_FALSE;
     signOptions.encryptionKeyPreferenceNick = NULL;
     signOptions.hashAlgTag = SEC_OID_SHA1;
     envelopeOptions.recipients = NULL;
     encryptOptions.recipients = NULL;
@@ -1134,17 +1139,17 @@ main(int argc, char **argv)
     encryptOptions.bulkalgtag = SEC_OID_UNKNOWN;
     encryptOptions.bulkkey = NULL;
     encryptOptions.keysize = -1;
 
     /*
      * Parse command line arguments
      */
     optstate = PL_CreateOptState(argc, argv, 
-				 "CDEGH:N:OPSTY:bc:d:e:h:i:kno:p:r:s:u:v");
+				 "CDEGH:N:OPSTY:bc:d:e:f:h:i:kno:p:r:s:u:v");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch (optstate->option) {
 	case 'C':
 	    mode = ENCRYPT;
 	    break;
 	case 'D':
 	    mode = DECODE;
 	    break;
@@ -1346,16 +1351,26 @@ main(int argc, char **argv)
 		fprintf(stderr, "%s: option -p must have a value.\n", progName);
 		Usage(progName);
 		exit(1);
 	    }
 		
 	    options.password = strdup(optstate->value);
 	    break;
 
+        case 'f':
+            if (!optstate->value) {
+                fprintf(stderr, "%s: option -f must have a value.\n", progName);
+                Usage(progName);
+                exit(1);
+            }
+
+            options.pwfile = strdup(optstate->value);
+            break;
+
 	case 'r':
 	    if (!optstate->value) {
 		fprintf(stderr, "%s: option -r must have a value.\n", progName);
 		Usage(progName);
 		exit(1);
 	    }
 	    envelopeOptions.recipients = ptrarray;
 	    str = (char *)optstate->value;
@@ -1401,17 +1416,17 @@ main(int argc, char **argv)
 	if (inFile != PR_STDIN) {
 	    PR_Close(inFile);
     	}
     }
     if (cms_verbose) {
 	fprintf(stderr, "received commands\n");
     }
 
-    /* Call the libsec initialization routines */
+    /* Call the NSS initialization routines */
     PR_Init(PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
     rv = NSS_InitReadWrite(SECU_ConfigDirectory(NULL));
     if (SECSuccess != rv) {
 	SECU_PrintError(progName, "NSS_Init failed");
 	exit(1);
     }
     if (cms_verbose) {
 	fprintf(stderr, "NSS has been initialized.\n");
@@ -1424,16 +1439,21 @@ main(int argc, char **argv)
     if (cms_verbose) {
 	fprintf(stderr, "Got default certdb\n");
     }
     if (options.password)
     {
     	pwdata.source = PW_PLAINTEXT;
     	pwdata.data = options.password;
     }
+    if (options.pwfile)
+    {
+    	pwdata.source = PW_FROMFILE;
+    	pwdata.data = options.pwfile;
+    }
     pwcb = SECU_GetModulePassword;
     pwcb_arg = (void *)&pwdata;
 
     PK11_SetPasswordFunc(&SECU_GetModulePassword);
 
 
 #if defined(_WIN32)
     if (outFile == stdout) {
@@ -1563,18 +1583,19 @@ main(int argc, char **argv)
 	if (!arena) {
 	    fprintf(stderr, "%s: out of memory.\n", progName);
 	    exit(1);
 	}
 
 	if (cms_verbose) {
 	    fprintf(stderr, "cmsg [%p]\n", cmsg);
 	    fprintf(stderr, "arena [%p]\n", arena);
-	    if (pwcb_arg)
-		fprintf(stderr, "password [%s]\n", (char *)pwcb_arg);
+	    if (pwcb_arg && (PW_PLAINTEXT == ((secuPWData*)pwcb_arg)->source))
+		fprintf(stderr, "password [%s]\n",
+                        ((secuPWData*)pwcb_arg)->data);
 	    else
 		fprintf(stderr, "password [NULL]\n");
 	}
 	ecx = NSS_CMSEncoder_Start(cmsg, 
                                    NULL, NULL,     /* DER output callback  */
                                    &output, arena, /* destination storage  */
                                    pwcb, pwcb_arg, /* password callback    */
                                    NULL, NULL,     /* decrypt key callback */
--- a/security/nss/cmd/ssltap/ssltap.c
+++ b/security/nss/cmd/ssltap/ssltap.c
@@ -61,17 +61,17 @@
 #include <string.h>
 #include <time.h>
 
 #include "plgetopt.h"
 #include "nss.h"
 #include "cert.h"
 #include "sslproto.h"
 
-#define VERSIONSTRING "$Revision: 1.10 $ ($Date: 2006/09/20 22:37:35 $) $Author: alexei.volkov.bugs%sun.com $"
+#define VERSIONSTRING "$Revision: 1.12 $ ($Date: 2008/05/07 15:42:59 $) $Author: wtc%google.com $"
 
 
 struct _DataBufferList;
 struct _DataBuffer;
 
 typedef struct _DataBufferList {
   struct _DataBuffer *first,*last;
   int size;
@@ -154,16 +154,25 @@ int hMACsize=0;
 #define GET_SHORT(x) ((PRUint16)(((PRUint16)((PRUint8*)x)[0]) << 8) + ((PRUint16)((PRUint8*)x)[1]))
 #define GET_24(x) ((PRUint32)   (  \
 				 (((PRUint32)((PRUint8*)x)[0]) << 16) \
 				 +                          \
 				 (((PRUint32)((PRUint8*)x)[1]) << 8)  \
 				 +                          \
 				 (((PRUint32)((PRUint8*)x)[2]) << 0)  \
 				 ) )
+#define GET_32(x) ((PRUint32)   (  \
+				 (((PRUint32)((PRUint8*)x)[0]) << 24) \
+				 +                          \
+				 (((PRUint32)((PRUint8*)x)[1]) << 16) \
+				 +                          \
+				 (((PRUint32)((PRUint8*)x)[2]) << 8)  \
+				 +                          \
+				 (((PRUint32)((PRUint8*)x)[3]) << 0)  \
+				 ) )
 
 void print_hex(int amt, unsigned char *buf);
 void read_stream_bytes(unsigned char *d, DataBufferList *db, int length);
 
 void myhalt(int dblsize,int collectedsize) {
 
   while(1) ;
 
@@ -441,16 +450,17 @@ const char * helloExtensionNameString(in
   case  0: ex_name = "server_name";                    break;
   case  1: ex_name = "max_fragment_length";            break;
   case  2: ex_name = "client_certificate_url";         break;
   case  3: ex_name = "trusted_ca_keys";                break;
   case  4: ex_name = "truncated_hmac";                 break;
   case  5: ex_name = "status_request";                 break;
   case 10: ex_name = "elliptic_curves";                break;
   case 11: ex_name = "ec_point_formats";               break;
+  case 35: ex_name = "session_ticket";                 break;
   default: sprintf(buf, "%d", ex_num);  ex_name = (const char *)buf; break;
   }
 
   return ex_name;
 }
 
 static int isNULLmac(int cs_int)
 {
@@ -718,16 +728,17 @@ void print_ssl3_handshake(unsigned char 
 
     if (sslhexparse) print_hex(4,tbuf+offset);
 
     PR_fprintf(PR_STDOUT,"      type = %d (",sslh.type);
     switch(sslh.type) {
     case 0:  PR_FPUTS("hello_request)\n"               ); break;
     case 1:  PR_FPUTS("client_hello)\n"                ); break;
     case 2:  PR_FPUTS("server_hello)\n"                ); break;
+    case 4:  PR_FPUTS("new_session_ticket)\n"          ); break;
     case 11: PR_FPUTS("certificate)\n"                 ); break;
     case 12: PR_FPUTS("server_key_exchange)\n"         ); break;
     case 13: PR_FPUTS("certificate_request)\n"         ); break;
     case 14: PR_FPUTS("server_hello_done)\n"           ); break;
     case 15: PR_FPUTS("certificate_verify)\n"          ); break;
     case 16: PR_FPUTS("client_key_exchange)\n"         ); break;
     case 20: PR_FPUTS("finished)\n"                    ); break;
     default: PR_FPUTS("unknown)\n"                     ); break;
@@ -751,17 +762,17 @@ void print_ssl3_handshake(unsigned char 
 	  PR_fprintf(PR_STDOUT,"            random = {...}\n");
 	  if (sslhexparse) print_hex(32,&hsdata[2]);
 
 	  /* pretty print Session ID */
 	  {
 	    int sidlength = (int)hsdata[2+32];
 	    PR_fprintf(PR_STDOUT,"            session ID = {\n");
 	    PR_fprintf(PR_STDOUT,"                length = %d\n",sidlength);
-	    PR_fprintf(PR_STDOUT,"                contents = {..}\n");
+	    PR_fprintf(PR_STDOUT,"                contents = {...}\n");
 	    if (sslhexparse) print_hex(sidlength,&hsdata[2+32+1]);
 	    PR_fprintf(PR_STDOUT,"            }\n");
 	    pos = 2+32+1+sidlength;
 	  }
 
 	  /* pretty print cipher suites */
 	  {
 	    int csuitelength = GET_SHORT((hsdata+pos));
@@ -817,17 +828,17 @@ void print_ssl3_handshake(unsigned char 
 
 	PR_fprintf(PR_STDOUT,"            server_version = {%d, %d}\n",
 		   (PRUint8)hsdata[0],(PRUint8)hsdata[1]);
 	PR_fprintf(PR_STDOUT,"            random = {...}\n");
 	if (sslhexparse) print_hex(32,&hsdata[2]);
 	PR_fprintf(PR_STDOUT,"            session ID = {\n");
 	sidlength = (int)hsdata[2+32];
 	PR_fprintf(PR_STDOUT,"                length = %d\n",sidlength);
-	PR_fprintf(PR_STDOUT,"                contents = {..}\n");
+	PR_fprintf(PR_STDOUT,"                contents = {...}\n");
 	if (sslhexparse) print_hex(sidlength,&hsdata[2+32+1]);
 	PR_fprintf(PR_STDOUT,"            }\n");
 	pos = 2+32+1+sidlength;
 
 	/* pretty print chosen cipher suite */
 	{
 	  PRUint32 cs_int    = GET_SHORT((hsdata+pos));
 	  const char *cs_str = V2CipherString(cs_int);
@@ -841,16 +852,47 @@ void print_ssl3_handshake(unsigned char 
 
 	/* pretty print extensions, if any */
 	pos = print_hello_extension(hsdata, sslh.length, pos);
 
 	PR_fprintf(PR_STDOUT,"         }\n");
       }
       break;
 
+    case 4: /* new session ticket */
+      {
+	PRUint32 lifetimehint;
+	PRUint16 ticketlength;
+	char lifetime[32];
+	lifetimehint = GET_32(hsdata);
+	if (lifetimehint) {
+	  PRExplodedTime et;
+	  PRTime t = lifetimehint;
+	  t *= PR_USEC_PER_SEC;
+	  PR_ExplodeTime(t, PR_GMTParameters, &et);
+	  /* use HTTP Cookie header's date format */
+	  PR_FormatTimeUSEnglish(lifetime, sizeof lifetime,
+				 "%a, %d-%b-%Y %H:%M:%S GMT", &et);
+	} else {
+	  /* 0 means the lifetime of the ticket is unspecified */
+	  strcpy(lifetime, "unspecified");
+	}
+	ticketlength = GET_SHORT((hsdata+4));
+	PR_fprintf(PR_STDOUT,"         NewSessionTicket {\n");
+	PR_fprintf(PR_STDOUT,"            ticket_lifetime_hint = %s\n",
+		   lifetime);
+	PR_fprintf(PR_STDOUT,"            ticket = {\n");
+	PR_fprintf(PR_STDOUT,"                length = %d\n",ticketlength);
+	PR_fprintf(PR_STDOUT,"                contents = {...}\n");
+	if (sslhexparse) print_hex(ticketlength,&hsdata[4+2]);
+	PR_fprintf(PR_STDOUT,"            }\n");
+	PR_fprintf(PR_STDOUT,"         }\n");
+      }
+      break;
+
     case 11: /* certificate */
       {
 	PRFileDesc *cfd;
 	int         pos;
 	int         certslength;
 	int         certlength;
 	int         certbytesread	= 0;
 	static int  certFileNumber;
--- a/security/nss/cmd/strsclnt/strsclnt.c
+++ b/security/nss/cmd/strsclnt/strsclnt.c
@@ -161,41 +161,31 @@ static PRBool bypassPKCS11    = PR_FALSE
 static PRBool disableLocking  = PR_FALSE;
 static PRBool ignoreErrors    = PR_FALSE;
 static PRBool enableSessionTickets = PR_FALSE;
 
 PRIntervalTime maxInterval    = PR_INTERVAL_NO_TIMEOUT;
 
 char * progName;
 
-char * ownPasswd( PK11SlotInfo *slot, PRBool retry, void *arg)
-{
-        char *passwd = NULL;
-
-        if ( (!retry) && arg ) {
-                passwd = PL_strdup((char *)arg);
-        }
-
-        return passwd;
-}
-
 int	stopping;
 int	verbose;
 SECItem	bigBuf;
 
 #define PRINTF  if (verbose)  printf
 #define FPRINTF if (verbose) fprintf
 
 static void
 Usage(const char *progName)
 {
     fprintf(stderr, 
     	"Usage: %s [-n nickname] [-p port] [-d dbdir] [-c connections]\n"
  	"          [-23BDNTovqs] [-f filename] [-N | -P percentage]\n"
 	"          [-w dbpasswd] [-C cipher(s)] [-t threads] hostname\n"
+        "          [-W pwfile]\n"
 	" where -v means verbose\n"
         "       -o flag is interpreted as follows:\n"
         "          1 -o   means override the result of server certificate validation.\n"
         "          2 -o's mean skip server certificate validation altogether.\n"
 	"       -D means no TCP delays\n"
 	"       -q means quit when server gone (timeout rather than retry forever)\n"
 	"       -s means disable SSL socket locking\n"
 	"       -N means no session reuse\n"
@@ -895,29 +885,29 @@ done:
 }
 
 
 typedef struct {
     PRLock* lock;
     char* nickname;
     CERTCertificate* cert;
     SECKEYPrivateKey* key;
-    char* password;
+    void* wincx;
 } cert_and_key;
 
 PRBool FindCertAndKey(cert_and_key* Cert_And_Key)
 {
     if ( (NULL == Cert_And_Key->nickname) || (0 == strcmp(Cert_And_Key->nickname,"none"))) {
         return PR_TRUE;
     }
     Cert_And_Key->cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(),
                             Cert_And_Key->nickname, certUsageSSLClient,
-                            PR_FALSE, Cert_And_Key->password);
+                            PR_FALSE, Cert_And_Key->wincx);
     if (Cert_And_Key->cert) {
-        Cert_And_Key->key = PK11_FindKeyByAnyCert(Cert_And_Key->cert, Cert_And_Key->password);
+        Cert_And_Key->key = PK11_FindKeyByAnyCert(Cert_And_Key->cert, Cert_And_Key->wincx);
     }
     if (Cert_And_Key->cert && Cert_And_Key->key) {
         return PR_TRUE;
     } else {
         return PR_FALSE;
     }
 }
 
@@ -1024,17 +1014,17 @@ StressClient_GetClientAuthData(void * ar
         CERTCertificate *  cert = NULL;
         SECKEYPrivateKey * privkey = NULL;
         CERTCertNicknames * names;
         int                 i;
         void *             proto_win = NULL;
         SECStatus          rv         = SECFailure;
 
         if (Cert_And_Key) {
-            proto_win = Cert_And_Key->password;
+            proto_win = Cert_And_Key->wincx;
         }
 
         names = CERT_GetCertNicknames(CERT_GetDefaultCertDB(),
                                       SEC_CERT_NICKNAMES_USER, proto_win);
         if (names != NULL) {
             for (i = 0; i < names->numnicknames; i++) {
                 cert = CERT_FindUserCertByUsage(CERT_GetDefaultCertDB(),
                             names->nicknames[i], certUsageSSLClient,
@@ -1324,36 +1314,36 @@ done:
 int
 main(int argc, char **argv)
 {
     const char *         dir         = ".";
     const char *         fileName    = NULL;
     char *               hostName    = NULL;
     char *               nickName    = NULL;
     char *               tmp         = NULL;
-    char *		 passwd      = NULL;
     int                  connections = 1;
     int                  exitVal;
     int                  tmpInt;
     unsigned short       port        = 443;
     SECStatus            rv;
     PLOptState *         optstate;
     PLOptStatus          status;
     cert_and_key Cert_And_Key;
+    secuPWData  pwdata          = { PW_NONE, 0 };
 
     /* Call the NSPR initialization routines */
     PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
 
     tmp      = strrchr(argv[0], '/');
     tmp      = tmp ? tmp + 1 : argv[0];
     progName = strrchr(tmp, '\\');
     progName = progName ? progName + 1 : tmp;
  
 
-    optstate = PL_CreateOptState(argc, argv, "23BC:DNP:TUc:d:f:in:op:qst:uvw:");
+    optstate = PL_CreateOptState(argc, argv, "23BC:DNP:TUW:c:d:f:in:op:qst:uvw:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch(optstate->option) {
 
 	case '2': disableSSL2 = PR_TRUE; break;
 
 	case '3': disableSSL3 = PR_TRUE; break;
 
 	case 'B': bypassPKCS11 = PR_TRUE; break;
@@ -1393,17 +1383,25 @@ main(int argc, char **argv)
 	    if (tmpInt > 0 && tmpInt < MAX_THREADS) 
 	        max_threads = active_threads = tmpInt;
 	    break;
 
 	case 'u': enableSessionTickets = PR_TRUE; break;
 
 	case 'v': verbose++; break;
 
-	case 'w': passwd = PL_strdup(optstate->value); break;
+        case 'w':
+            pwdata.source = PW_PLAINTEXT;
+            pwdata.data = PL_strdup(optstate->value);
+            break;
+
+        case 'W':
+            pwdata.source = PW_FROMFILE;
+            pwdata.data = PL_strdup(optstate->value);
+            break;
 
 	case 0:   /* positional parameter */
 	    if (hostName) {
 		Usage(progName);
 	    }
 	    hostName = PL_strdup(optstate->value);
 	    break;
 
@@ -1423,41 +1421,36 @@ main(int argc, char **argv)
         Usage(progName);
 
     if (port == 0)
 	Usage(progName);
 
     if (fileName)
     	readBigFile(fileName);
 
-    /* set our password function */
-    if ( passwd ) {
-	PK11_SetPasswordFunc(ownPasswd);
-    } else {
-	PK11_SetPasswordFunc(SECU_GetModulePassword);
-    }
+    PK11_SetPasswordFunc(SECU_GetModulePassword);
 
     tmp = PR_GetEnv("NSS_DEBUG_TIMEOUT");
     if (tmp && tmp[0]) {
         int sec = PORT_Atoi(tmp);
 	if (sec > 0) {
 	    maxInterval = PR_SecondsToInterval(sec);
     	}
     }
 
-    /* Call the libsec initialization routines */
+    /* Call the NSS initialization routines */
     rv = NSS_Initialize(dir, "", "", SECMOD_DB, NSS_INIT_READONLY);
     if (rv != SECSuccess) {
     	fputs("NSS_Init failed.\n", stderr);
 	exit(1);
     }
     ssl3stats = SSL_GetStatistics();
     Cert_And_Key.lock = PR_NewLock();
     Cert_And_Key.nickname = nickName;
-    Cert_And_Key.password = passwd;
+    Cert_And_Key.wincx = &pwdata;
     Cert_And_Key.cert = NULL;
     Cert_And_Key.key = NULL;
 
     if (PR_FALSE == FindCertAndKey(&Cert_And_Key)) {
 
 	if (Cert_And_Key.cert == NULL) {
 	    fprintf(stderr, "strsclnt: Can't find certificate %s\n", Cert_And_Key.nickname);
 	    exit(1);
@@ -1478,18 +1471,18 @@ main(int argc, char **argv)
 	CERT_DestroyCertificate(Cert_And_Key.cert);
     }
     if (Cert_And_Key.key) {
 	SECKEY_DestroyPrivateKey(Cert_And_Key.key);
     }
 
     PR_DestroyLock(Cert_And_Key.lock);
 
-    if (Cert_And_Key.password) {
-        PL_strfree(Cert_And_Key.password);
+    if (pwdata.data) {
+        PL_strfree(pwdata.data);
     }
     if (Cert_And_Key.nickname) {
         PL_strfree(Cert_And_Key.nickname);
     }
 
     PL_strfree(hostName);
 
     /* some final stats. */
--- a/security/nss/cmd/tests/manifest.mn
+++ b/security/nss/cmd/tests/manifest.mn
@@ -35,19 +35,22 @@
 #
 # ***** END LICENSE BLOCK *****
 
 CORE_DEPTH = ../../..
 
 # MODULE public and private header  directories are implicitly REQUIRED.
 MODULE = nss
 
-CSRCS = remtest.c
+CSRCS = \
+	nonspr10.c \
+	remtest.c \
+	$(NULL)
 
 # The MODULE is always implicitly required.
 # Listing it here in REQUIRES makes it appear twice in the cc command line.
 REQUIRES = seccmd dbm
 
 PROGRAMS = $(CSRCS:.c=)
 
 TARGETS = $(PROGRAMS)
 
-#NO_MD_RELEASE = 1
+NO_MD_RELEASE = 1
new file mode 100644
--- /dev/null
+++ b/security/nss/cmd/tests/nonspr10.c
@@ -0,0 +1,122 @@
+/* ***** BEGIN LICENSE BLOCK *****
+ * Version: MPL 1.1/GPL 2.0/LGPL 2.1
+ *
+ * The contents of this file are subject to the Mozilla Public License Version
+ * 1.1 (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ * http://www.mozilla.org/MPL/
+ *
+ * Software distributed under the License is distributed on an "AS IS" basis,
+ * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
+ * for the specific language governing rights and limitations under the
+ * License.
+ *
+ * The Original Code is the Netscape security libraries.
+ *
+ * The Initial Developer of the Original Code is
+ * Netscape Communications Corporation.
+ * Portions created by the Initial Developer are Copyright (C) 2008
+ * the Initial Developer. All Rights Reserved.
+ *
+ * Contributor(s):
+ *
+ * Alternatively, the contents of this file may be used under the terms of
+ * either the GNU General Public License Version 2 or later (the "GPL"), or
+ * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
+ * in which case the provisions of the GPL or the LGPL are applicable instead
+ * of those above. If you wish to allow use of your version of this file only
+ * under the terms of either the GPL or the LGPL, and not to allow others to
+ * use your version of this file under the terms of the MPL, indicate your
+ * decision by deleting the provisions above and replace them with the notice
+ * and other provisions required by the GPL or the LGPL. If you do not delete
+ * the provisions above, a recipient may use your version of this file under
+ * the terms of any one of the MPL, the GPL or the LGPL.
+ *
+ * ***** END LICENSE BLOCK ***** */
+
+/*
+ * This test verifies that NSS public headers can be compiled with no
+ * NSPR 1.0 support.
+ */
+
+#define NO_NSPR_10_SUPPORT 1
+
+#include "base64.h"
+#include "blapit.h"
+#include "cert.h"
+#include "certdb.h"
+#include "certt.h"
+#include "ciferfam.h"
+#include "cmmf.h"
+#include "cmmft.h"
+#include "cms.h"
+#include "cmsreclist.h"
+#include "cmst.h"
+#include "crmf.h"
+#include "crmft.h"
+#include "cryptohi.h"
+#include "cryptoht.h"
+#include "ecl-exp.h"
+#include "hasht.h"
+#include "key.h"
+#include "keyhi.h"
+#include "keyt.h"
+#include "keythi.h"
+#include "nss.h"
+#include "nssb64.h"
+#include "nssb64t.h"
+#include "nssbase.h"
+#include "nssbaset.h"
+#include "nssckbi.h"
+#include "nssilckt.h"
+#include "nssilock.h"
+#include "nsslocks.h"
+#include "nssrwlk.h"
+#include "nssrwlkt.h"
+#include "ocsp.h"
+#include "ocspt.h"
+#include "p12.h"
+#include "p12plcy.h"
+#include "p12t.h"
+#include "pk11func.h"
+#include "pk11pqg.h"
+#include "pk11priv.h"
+#include "pk11pub.h"
+#include "pk11sdr.h"
+#include "pkcs11.h"
+#include "pkcs11t.h"
+#include "pkcs12.h"
+#include "pkcs12t.h"
+#include "pkcs7t.h"
+#include "portreg.h"
+#include "preenc.h"
+#include "secasn1.h"
+#include "secasn1t.h"
+#include "seccomon.h"
+#include "secder.h"
+#include "secdert.h"
+#include "secdig.h"
+#include "secdigt.h"
+#include "secerr.h"
+#include "sechash.h"
+#include "secitem.h"
+#include "secmime.h"
+#include "secmod.h"
+#include "secmodt.h"
+#include "secoid.h"
+#include "secoidt.h"
+#include "secpkcs5.h"
+#include "secpkcs7.h"
+#include "secport.h"
+#include "shsign.h"
+#include "smime.h"
+#include "ssl.h"
+#include "sslerr.h"
+#include "sslproto.h"
+#include "sslt.h"
+#include "watcomfx.h"
+
+int main()
+{
+    return 0;
+}
--- a/security/nss/cmd/tests/remtest.c
+++ b/security/nss/cmd/tests/remtest.c
@@ -31,17 +31,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
 **
-** Sample client side test program that uses SSL and libsec
+** Sample client side test program that uses SSL and NSS
 **
 */
 
 #include "secutil.h"
 
 #if defined(XP_UNIX)
 #include <unistd.h>
 #else
--- a/security/nss/cmd/vfychain/vfychain.c
+++ b/security/nss/cmd/vfychain/vfychain.c
@@ -70,60 +70,45 @@
 #include "nss.h"
 
 /* #include "vfyutil.h" */
 
 #define RD_BUF_SIZE (60 * 1024)
 
 int verbose;
 
-char *password = NULL;
-
-/* Function: char * myPasswd()
- * 
- * Purpose: This function is our custom password handler that is called by
- * SSL when retreiving private certs and keys from the database. Returns a
- * pointer to a string that with a password for the database. Password pointer
- * should point to dynamically allocated memory that will be freed later.
- */
-char *
-myPasswd(PK11SlotInfo *info, PRBool retry, void *arg)
-{
-    char * passwd = NULL;
-
-    if ( (!retry) && arg ) {
-	passwd = PORT_Strdup((char *)arg);
-    }
-    return passwd;
-}
+secuPWData  pwdata          = { PW_NONE, 0 };
 
 static void
 Usage(const char *progName)
 {
     fprintf(stderr, 
 	"Usage: %s [options] certfile [[options] certfile] ...\n"
-	"\twhere options are:\n"
+	"\tWhere options are:\n"
 	"\t-a\t\t Following certfile is base64 encoded\n"
 	"\t-b YYMMDDHHMMZ\t Validate date (default: now)\n"
 	"\t-d directory\t Database directory\n"
+	"\t-f \t\t Enable cert fetching from AIA URL\n"
 	"\t-o oid\t\t Set policy OID for cert validation(Format OID.1.2.3)\n"
 	"\t-p \t\t Use PKIX Library to validate certificate by calling:\n"
 	"\t\t\t   * CERT_VerifyCertificate if specified once,\n"
 	"\t\t\t   * CERT_PKIXVerifyCert if specified twice and more.\n"
 	"\t-r\t\t Following certfile is raw binary DER (default)\n"
         "\t-s\t\t Status checking, following a configuration description.\n"
         "\t\t\t Implemented as of today are:\n"
         "\t\t\t   * allow-crl (default)\n"
         "\t\t\t   * allow-crl-and-ocsp\n"
+        "\t-t\t\t Following cert is explicitly trusted (overrides db trust).\n"
 	"\t-u usage \t 0=SSL client, 1=SSL server, 2=SSL StepUp, 3=SSL CA,\n"
 	"\t\t\t 4=Email signer, 5=Email recipient, 6=Object signer,\n"
 	"\t\t\t 9=ProtectedObjectSigner, 10=OCSP responder, 11=Any CA\n"
 	"\t-v\t\t Verbose mode. Prints root cert subject(double the\n"
-         "\t\t\t argument for whole root cert info)\n"
-	"\t-w password\t Database password\n",
+	"\t\t\t argument for whole root cert info)\n"
+	"\t-w password\t Database password.\n",
+	"\t-W pwfile\t Password file.\n",
 	progName);
     exit(1);
 }
 
 /**************************************************************************
 ** 
 ** Error and information routines.
 **
@@ -188,27 +173,23 @@ forgetCerts(void)
     }
     if (trustedCertList) {
         CERT_DestroyCertList(trustedCertList);
     }
 }
 
 
 CERTCertificate *
-getCert(const char *name, PRBool isAscii)
+getCert(const char *name, PRBool isAscii, const char * progName)
 {
-    unsigned char * pb;
-    CERTCertificate * cert  = NULL;
-    CERTCertDBHandle *defaultDB = NULL;
+    CERTCertificate * cert;
+    CERTCertDBHandle *defaultDB;
     PRFileDesc*     fd;
-    PRInt32         cc      = -1;
-    PRInt32         total;
-    PRInt32         remaining;
-    SECItem         item;
-    static unsigned char certBuf[RD_BUF_SIZE];
+    SECStatus       rv;
+    SECItem         item        = {0, NULL, 0};
 
     defaultDB = CERT_GetDefaultCertDB();
 
     /* First, let's try to find the cert in existing DB. */
     cert = CERT_FindCertByNicknameOrEmailAddr(defaultDB, name);
     if (cert) {
         return cert;
     }
@@ -217,58 +198,39 @@ getCert(const char *name, PRBool isAscii
      * open a file with such name and get the cert from there.*/
     fd = PR_Open(name, PR_RDONLY, 0777); 
     if (!fd) {
 	PRIntn err = PR_GetError();
     	fprintf(stderr, "open of %s failed, %d = %s\n", 
 	        name, err, SECU_Strerror(err));
 	return cert;
     }
-    /* read until EOF or buffer is full */
-    pb = certBuf;
-    while (0 < (remaining = (sizeof certBuf) - (pb - certBuf))) {
-	cc = PR_Read(fd, pb, remaining);
-	if (cc == 0) 
-	    break;
-	if (cc < 0) {
-	    PRIntn err = PR_GetError();
-	    fprintf(stderr, "read of %s failed, %d = %s\n", 
-	        name, err, SECU_Strerror(err));
-	    break;
-	}
-	/* cc > 0 */
-	pb += cc;
-    }
+
+    rv = SECU_ReadDERFromFile(&item, fd, isAscii);
     PR_Close(fd);
-    if (cc < 0)
-    	return cert;
-    if (!remaining || cc > 0) { /* file was too big. */
-	fprintf(stderr, "cert file %s was too big.\n", name);
+    if (rv != SECSuccess) {
+	fprintf(stderr, "%s: SECU_ReadDERFromFile failed\n", progName);
 	return cert;
     }
-    total = pb - certBuf;
-    if (!total) { /* file was empty */
+
+    if (!item.len) { /* file was empty */
 	fprintf(stderr, "cert file %s was empty.\n", name);
 	return cert;
     }
-    if (isAscii) {
-    	/* convert from Base64 to binary here ... someday */
-    }
-    item.type = siBuffer;
-    item.data = certBuf;
-    item.len  = total;
+
     cert = CERT_NewTempCertificate(defaultDB, &item, 
                                    NULL     /* nickname */, 
                                    PR_FALSE /* isPerm */, 
 				   PR_TRUE  /* copyDER */);
     if (!cert) {
 	PRIntn err = PR_GetError();
 	fprintf(stderr, "couldn't import %s, %d = %s\n",
 	        name, err, SECU_Strerror(err));
     }
+    PORT_Free(item.data);
     return cert;
 }
 
 #define REVCONFIG_ALLOW_CRL "allow-crl"
 #define REVCONFIG_ALLOW_CRL_OCSP "allow-crl-and-ocsp"
 
 PRBool
 isAllowedRevConfig(const char *name)
@@ -300,54 +262,78 @@ main(int argc, char *argv[], char *envp[
     PRTime               time         = 0;
     PLOptStatus          status;
     int                  usePkix      = 0;
     int                  rv           = 1;
     int                  usage;
     CERTVerifyLog        log;
     CERTCertList        *builtChain = NULL;
     char *               revConfig    = NULL;
+    PRBool               certFetching = PR_FALSE;
 
     PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
 
     progName = PL_strdup(argv[0]);
 
-    optstate = PL_CreateOptState(argc, argv, "ab:d:o:prs:tu:w:v");
+    optstate = PL_CreateOptState(argc, argv, "ab:d:fo:prs:tu:vw:W:");
     while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 	switch(optstate->option) {
 	case  0  : /* positional parameter */  goto breakout;
 	case 'a' : isAscii  = PR_TRUE;                        break;
 	case 'b' : secStatus = DER_AsciiToTime(&time, optstate->value);
 	           if (secStatus != SECSuccess) Usage(progName); break;
 	case 'd' : certDir  = PL_strdup(optstate->value);     break;
+	case 'f' : certFetching = PR_TRUE;                    break;
 	case 'o' : oidStr = PL_strdup(optstate->value);       break;
 	case 'p' : usePkix += 1;                              break;
 	case 'r' : isAscii  = PR_FALSE;                       break;
-        case 's' : revConfig  = PL_strdup(optstate->value);   break;
+	case 's' : revConfig  = PL_strdup(optstate->value);   break;
+	case 't' : trusted  = PR_TRUE;                        break;
 	case 'u' : usage    = PORT_Atoi(optstate->value);
 	           if (usage < 0 || usage > 62) Usage(progName);
 		   certUsage = ((SECCertificateUsage)1) << usage; 
 		   if (certUsage > certificateUsageHighest) Usage(progName);
 		   break;
-	case 'w' : password = PL_strdup(optstate->value);     break;
+        case 'w':
+                  pwdata.source = PW_PLAINTEXT;
+                  pwdata.data = PORT_Strdup(optstate->value);
+                  break;
+
+        case 'W':
+                  pwdata.source = PW_FROMFILE;
+                  pwdata.data = PORT_Strdup(optstate->value);
+                  break;
 	case 'v' : verbose++;                                 break;
 	default  : Usage(progName);                           break;
 	}
     }
 breakout:
     if (status != PL_OPT_OK)
 	Usage(progName);
 
+    if (usePkix < 2) {
+        if (oidStr) {
+            fprintf(stderr, "Policy oid(-o) can be used only with"
+                    " CERT_PKIXVerifyChain(-pp) function.\n");
+            Usage(progName);
+        }
+        if (trusted) {
+            fprintf(stderr, "Cert trust flag can be used only with"
+                    " CERT_PKIXVerifyChain(-pp) function.\n");
+            Usage(progName);
+        }
+    }
+
     if (revConfig && !isAllowedRevConfig(revConfig)) {
         fprintf(stderr, "Invalid revocation configuration specified.\n");
         goto punt;
     }
 
     /* Set our password function callback. */
-    PK11_SetPasswordFunc(myPasswd);
+    PK11_SetPasswordFunc(SECU_GetModulePassword);
 
     /* Initialize the NSS libraries. */
     if (certDir) {
 	secStatus = NSS_Init(certDir);
     } else {
 	secStatus = NSS_NoDB_Init(NULL);
 
 	/* load the builtins */
@@ -364,17 +350,22 @@ breakout:
 
     while (status == PL_OPT_OK) {
 	switch(optstate->option) {
 	default  : Usage(progName);                           break;
 	case 'a' : isAscii  = PR_TRUE;                        break;
 	case 'r' : isAscii  = PR_FALSE;                       break;
 	case 't' : trusted  = PR_TRUE;                       break;
 	case  0  : /* positional parameter */
-	    cert = getCert(optstate->value, isAscii);
+            if (usePkix < 2 && trusted) {
+                fprintf(stderr, "Cert trust flag can be used only with"
+                        " CERT_PKIXVerifyChain(-pp) function.\n");
+                Usage(progName);
+            }
+	    cert = getCert(optstate->value, isAscii, progName);
 	    if (!cert) 
 	        goto punt;
 	    rememberCert(cert, trusted);
 	    if (!firstCert)
 	        firstCert = cert;
             trusted = PR_FALSE;
 	}
         status = PL_GetNextOpt(optstate);
@@ -397,26 +388,26 @@ breakout:
             /* Use old API with libpkix validation lib */
             CERT_SetUsePKIXForValidation(PR_TRUE);
         }
         defaultDB = CERT_GetDefaultCertDB();
         secStatus = CERT_VerifyCertificate(defaultDB, firstCert, 
                                            PR_TRUE /* check sig */,
                                            certUsage, 
                                            time, 
-                                           NULL, /* wincx  */
+                                           &pwdata, /* wincx  */
                                            &log, /* error log */
                                            NULL);/* returned usages */
     } else do {
-        CERTValOutParam cvout[4];
-        CERTValInParam cvin[5];
+        static CERTValOutParam cvout[4];
+        static CERTValInParam cvin[6];
         SECOidTag oidTag;
         int inParamIndex = 0;
-        CERTRevocationFlags rev;
-        PRUint64 revFlags[2];
+        static CERTRevocationFlags rev;
+        static PRUint64 revFlags[2];
 
         if (oidStr) {
             PRArenaPool *arena;
             SECOidData od;
             memset(&od, 0, sizeof od);
             od.offset = SEC_OID_UNKNOWN;
             od.desc = "User Defined Policy OID";
             od.mechanism = CKM_INVALID_MECHANISM;
@@ -454,19 +445,23 @@ breakout:
 
         if (trustedCertList) {
             cvin[inParamIndex].type = cert_pi_trustAnchors;
             cvin[inParamIndex].value.pointer.chain = trustedCertList;
             
             inParamIndex++;
         }
 
-	cvin[inParamIndex].type = cert_pi_date;
-	cvin[inParamIndex].value.scalar.time = time;
-	inParamIndex++;
+        cvin[inParamIndex].type = cert_pi_useAIACertFetch;
+        cvin[inParamIndex].value.scalar.b = certFetching;
+        inParamIndex++;
+
+        cvin[inParamIndex].type = cert_pi_date;
+        cvin[inParamIndex].value.scalar.time = time;
+        inParamIndex++;
 
         revFlags[cert_revocation_method_crl] = 
             CERT_REV_M_TEST_USING_THIS_METHOD;
         rev.leafTests.number_of_defined_methods = 
             cert_revocation_method_crl +1;
         rev.chainTests.number_of_defined_methods = 
             cert_revocation_method_crl +1;
 
@@ -491,27 +486,29 @@ breakout:
 
         cvin[inParamIndex].type = cert_pi_revocationFlags;
         cvin[inParamIndex].value.pointer.revocation = &rev;
 	inParamIndex++;
 
         cvin[inParamIndex].type = cert_pi_end;
         
         cvout[0].type = cert_po_trustAnchor;
+        cvout[0].value.pointer.cert = NULL;
         cvout[1].type = cert_po_certList;
+        cvout[1].value.pointer.chain = NULL;
 
         /* setting pointer to CERTVerifyLog. Initialized structure
          * will be used CERT_PKIXVerifyCert */
         cvout[2].type = cert_po_errorLog;
         cvout[2].value.pointer.log = &log;
 
         cvout[3].type = cert_po_end;
         
         secStatus = CERT_PKIXVerifyCert(firstCert, certUsage,
-                                        cvin, cvout, NULL);
+                                        cvin, cvout, &pwdata);
         if (secStatus != SECSuccess) {
             break;
         }
         issuerCert = cvout[0].value.pointer.cert;
         builtChain = cvout[1].value.pointer.chain;
     } while (0);
 
     /* Display validation results */
@@ -564,11 +561,18 @@ breakout:
     PORT_FreeArena(log.arena, PR_FALSE);
 
 punt:
     forgetCerts();
     if (NSS_Shutdown() != SECSuccess) {
 	SECU_PrintError(progName, "NSS_Shutdown");
 	rv = 1;
     }
+    PORT_Free(progName);
+    PORT_Free(certDir);
+    PORT_Free(oidStr);
+    PORT_Free(revConfig);
+    if (pwdata.data) {
+        PORT_Free(pwdata.data);
+    }
     PR_Cleanup();
     return rv;
 }
--- a/security/nss/cmd/vfyserv/vfyserv.c
+++ b/security/nss/cmd/vfyserv/vfyserv.c
@@ -75,29 +75,29 @@
 #define RD_BUF_SIZE (60 * 1024)
 
 extern int ssl2CipherSuites[];
 extern int ssl3CipherSuites[];
 
 GlobalThreadMgr threadMGR;
 char *certNickname = NULL;
 char *hostName = NULL;
-char *password = NULL;
+secuPWData  pwdata          = { PW_NONE, 0 };
 unsigned short port = 0;
 PRBool dumpChain;
 
 static void
 Usage(const char *progName)
 {
     PRFileDesc *pr_stderr;
 
     pr_stderr = PR_STDERR;
 
     PR_fprintf(pr_stderr, "Usage:\n"
-               "   %s  [-c ] [-o] [-p port] [-d dbdir] [-w password]\n"
+               "   %s  [-c ] [-o] [-p port] [-d dbdir] [-w password] [-f pwfile]\n"
                "   \t\t[-C cipher(s)]  [-l <url> -t <nickname> ] hostname",
                progName);
     PR_fprintf (pr_stderr, "\nWhere:\n");
     PR_fprintf (pr_stderr,
                 "  %-13s dump server cert chain into files\n",
                 "-c");
     PR_fprintf (pr_stderr,
                 "  %-13s perform server cert OCSP check\n",
@@ -107,16 +107,19 @@ Usage(const char *progName)
                 "-p");
     PR_fprintf (pr_stderr,
                 "  %-13s use security databases in \"dbdir\"\n",
                 "-d dbdir");
     PR_fprintf (pr_stderr,
                 "  %-13s key database password\n",
                 "-w password");
     PR_fprintf (pr_stderr,
+                "  %-13s token password file\n",
+                "-f pwfile");
+    PR_fprintf (pr_stderr,
                 "  %-13s communication cipher list\n",
                 "-C cipher(s)");
     PR_fprintf (pr_stderr,
                 "  %-13s OCSP responder location. This location is used to\n"
                 "  %-13s check  status  of a server  certificate.  If  not \n"
                 "  %-13s specified, location  will  be taken  from the AIA\n"
                 "  %-13s server certificate extension.\n",
                 "-l url", "", "", "");
@@ -284,17 +287,17 @@ do_connects(void *a, int connection)
 
 	/* Set up SSL secure socket. */
 	sslSocket = setupSSLSocket(addr);
 	if (sslSocket == NULL) {
 		errWarn("setupSSLSocket");
 		return SECFailure;
 	}
 
-	secStatus = SSL_SetPKCS11PinArg(sslSocket, password);
+	secStatus = SSL_SetPKCS11PinArg(sslSocket, &pwdata);
 	if (secStatus != SECSuccess) {
 		errWarn("SSL_SetPKCS11PinArg");
 		return secStatus;
 	}
 
 	secStatus = SSL_SetURL(sslSocket, hostName);
 	if (secStatus != SECSuccess) {
 		errWarn("SSL_SetURL");
@@ -431,27 +434,35 @@ main(int argc, char **argv)
 	PRBool               doOcspCheck = PR_FALSE;
 
 	/* Call the NSPR initialization routines */
 	PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
 
 	progName = PORT_Strdup(argv[0]);
 
 	hostName = NULL;
-	optstate = PL_CreateOptState(argc, argv, "C:cd:l:n:p:ot:w:");
+	optstate = PL_CreateOptState(argc, argv, "C:cd:f:l:n:p:ot:w:");
 	while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
 		switch(optstate->option) {
 		case 'C' : cipherString = PL_strdup(optstate->value); break;
  		case 'c' : dumpChain = PR_TRUE;                       break;
 		case 'd' : certDir = PL_strdup(optstate->value);      break;
 		case 'l' : respUrl = PL_strdup(optstate->value);      break;
 		case 'p' : port = PORT_Atoi(optstate->value);         break;
 		case 'o' : doOcspCheck = PR_TRUE;                     break;
 		case 't' : respCertName = PL_strdup(optstate->value); break;
-		case 'w' : password = PL_strdup(optstate->value);     break;
+                case 'w':
+                           pwdata.source = PW_PLAINTEXT;
+                           pwdata.data = PORT_Strdup(optstate->value);
+                           break;
+
+                case 'f':
+                           pwdata.source = PW_FROMFILE;
+                           pwdata.data = PORT_Strdup(optstate->value);
+                           break;
 		case '\0': hostName = PL_strdup(optstate->value);     break;
 		default  : Usage(progName);
 		}
 	}
 
 	if (port == 0) {
 		port = 443;
 	}
@@ -462,18 +473,17 @@ main(int argc, char **argv)
         if (doOcspCheck &&
             ((respCertName != NULL && respUrl == NULL) ||
              (respUrl != NULL && respCertName == NULL))) {
 	    SECU_PrintError (progName, "options -l <url> and -t "
 	                     "<responder> must be used together");
 	    Usage(progName);
         }
     
-	/* Set our password function callback. */
-	PK11_SetPasswordFunc(myPasswd);
+	PK11_SetPasswordFunc(SECU_GetModulePassword);
 
 	/* Initialize the NSS libraries. */
 	if (certDir) {
 	    secStatus = NSS_Init(certDir);
 	} else {
 	    secStatus = NSS_NoDB_Init(NULL);
 
 	    /* load the builtins */
--- a/security/nss/lib/base/arena.c
+++ b/security/nss/lib/base/arena.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: arena.c,v $ $Revision: 1.11 $ $Date: 2008/02/23 06:18:27 $";
+static const char CVS_ID[] = "@(#) $RCSfile: arena.c,v $ $Revision: 1.12 $ $Date: 2008/05/13 01:22:35 $";
 #endif /* DEBUG */
 
 /*
  * arena.c
  *
  * This contains the implementation of NSS's thread-safe arenas.
  */
 
@@ -524,16 +524,17 @@ nssArena_Destroy
     /* Just got destroyed */
     nss_SetError(NSS_ERROR_INVALID_ARENA);
     return PR_FAILURE;
   }
   PR_Lock(arena->lock);
   
 #ifdef DEBUG
   if( PR_SUCCESS != arena_remove_pointer(arena) ) {
+    PR_Unlock(arena->lock);
     return PR_FAILURE;
   }
 #endif /* DEBUG */
 
 #ifdef ARENA_DESTRUCTOR_LIST
   /* Note that the arena is locked at this time */
   nss_arena_call_destructor_chain(arena->first_destructor);
 #endif /* ARENA_DESTRUCTOR_LIST */
@@ -976,22 +977,22 @@ nss_ZFreeIf
   } else {
     /* Arena */
 #ifdef NSSDEBUG
     if( PR_SUCCESS != nssArena_verifyPointer(h->arena) ) {
       return PR_FAILURE;
     }
 #endif /* NSSDEBUG */
 
-    PR_Lock(h->arena->lock);
     if( (PRLock *)NULL == h->arena->lock ) {
       /* Just got destroyed.. so this pointer is invalid */
       nss_SetError(NSS_ERROR_INVALID_POINTER);
       return PR_FAILURE;
     }
+    PR_Lock(h->arena->lock);
 
     (void)nsslibc_memset(pointer, 0, h->size);
 
     /* No way to "free" it within an NSPR arena. */
 
     PR_Unlock(h->arena->lock);
     return PR_SUCCESS;
   }
@@ -1079,22 +1080,22 @@ nss_ZRealloc
     void *p;
     /* Arena */
 #ifdef NSSDEBUG
     if( PR_SUCCESS != nssArena_verifyPointer(h->arena) ) {
       return (void *)NULL;
     }
 #endif /* NSSDEBUG */
 
-    PR_Lock(h->arena->lock);
     if( (PRLock *)NULL == h->arena->lock ) {
       /* Just got destroyed.. so this pointer is invalid */
       nss_SetError(NSS_ERROR_INVALID_POINTER);
       return (void *)NULL;
     }
+    PR_Lock(h->arena->lock);
 
 #ifdef ARENA_THREADMARK
     if( (PRThread *)NULL != h->arena->marking_thread ) {
       if( PR_GetCurrentThread() != h->arena->marking_thread ) {
         PR_Unlock(h->arena->lock);
         nss_SetError(NSS_ERROR_ARENA_MARKED_BY_ANOTHER_THREAD);
         return (void *)NULL;
       }
--- a/security/nss/lib/base/base.h
+++ b/security/nss/lib/base/base.h
@@ -33,17 +33,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef BASE_H
 #define BASE_H
 
 #ifdef DEBUG
-static const char BASE_CVS_ID[] = "@(#) $RCSfile: base.h,v $ $Revision: 1.19 $ $Date: 2008/02/23 05:29:23 $";
+static const char BASE_CVS_ID[] = "@(#) $RCSfile: base.h,v $ $Revision: 1.20 $ $Date: 2008/05/10 01:03:14 $";
 #endif /* DEBUG */
 
 /*
  * base.h
  *
  * This header file contains basic prototypes and preprocessor 
  * definitions used throughout nss but not available publicly.
  */
@@ -570,16 +570,28 @@ nss_SetError
 
 NSS_EXTERN void
 nss_ClearErrorStack
 (
   void
 );
 
 /*
+ * nss_DestroyErrorStack
+ *
+ * This routine frees the calling thread's error stack.
+ */
+
+NSS_EXTERN void
+nss_DestroyErrorStack
+(
+  void
+);
+
+/*
  * NSSItem
  *
  * nssItem_Create
  * nssItem_Duplicate
  * nssItem_Equal
  */
 
 NSS_EXTERN NSSItem *
--- a/security/nss/lib/base/error.c
+++ b/security/nss/lib/base/error.c
@@ -30,29 +30,30 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: error.c,v $ $Revision: 1.7 $ $Date: 2005/12/19 17:53:28 $";
+static const char CVS_ID[] = "@(#) $RCSfile: error.c,v $ $Revision: 1.9 $ $Date: 2008/05/17 03:44:39 $";
 #endif /* DEBUG */
 
 /*
  * error.c
  *
  * This file contains the code implementing the per-thread error 
  * stacks upon which most NSS routines report their errors.
  */
 
 #ifndef BASE_H
 #include "base.h"
 #endif /* BASE_H */
+#include <limits.h> /* for UINT_MAX */
 #include <string.h> /* for memmove */
 
 #define NSS_MAX_ERROR_STACK_COUNT 16 /* error codes */
 
 /*
  * The stack itself has a header, and a sequence of integers.
  * The header records the amount of space (as measured in stack
  * slots) already allocated for the stack, and the count of the
@@ -70,19 +71,22 @@ struct error_stack_str {
 };
 typedef struct error_stack_str error_stack;
 
 /*
  * error_stack_index
  *
  * Thread-private data must be indexed.  This is that index.
  * See PR_NewThreadPrivateIndex for more information.
+ *
+ * Thread-private data indexes are in the range [0, 127].
  */
 
-static PRUintn error_stack_index;
+#define INVALID_TPD_INDEX UINT_MAX
+static PRUintn error_stack_index = INVALID_TPD_INDEX;
 
 /*
  * call_once
  *
  * The thread-private index must be obtained (once!) at runtime.
  * This block is used for that one-time call.
  */
 
@@ -111,17 +115,17 @@ static error_stack *
 error_get_my_stack ( void)
 {
   PRStatus st;
   error_stack *rv;
   PRUintn new_size;
   PRUint32 new_bytes;
   error_stack *new_stack;
 
-  if( 0 == error_stack_index ) {
+  if( INVALID_TPD_INDEX == error_stack_index ) {
     st = PR_CallOnce(&error_call_once, error_once_function);
     if( PR_SUCCESS != st ) {
       return (error_stack *)NULL;
     }
   }
 
   rv = (error_stack *)PR_GetThreadPrivate(error_stack_index);
   if( (error_stack *)NULL == rv ) {
@@ -279,8 +283,23 @@ nss_ClearErrorStack ( void)
     /* Oh, well. */
     return;
   }
 
   es->header.count = 0;
   es->stack[0] = 0;
   return;
 }
+
+/*
+ * nss_DestroyErrorStack
+ *
+ * This routine frees the calling thread's error stack.
+ */
+
+NSS_IMPLEMENT void
+nss_DestroyErrorStack ( void)
+{
+  if( INVALID_TPD_INDEX != error_stack_index ) {
+    PR_SetThreadPrivate(error_stack_index, NULL);
+  }
+  return;
+}
--- a/security/nss/lib/certdb/alg1485.c
+++ b/security/nss/lib/certdb/alg1485.c
@@ -39,68 +39,80 @@
 #include "prprf.h"
 #include "cert.h"
 #include "certi.h"
 #include "xconst.h"
 #include "genname.h"
 #include "secitem.h"
 #include "secerr.h"
 
-struct NameToKind {
+typedef struct NameToKindStr {
     const char * name;
     unsigned int maxLen; /* max bytes in UTF8 encoded string value */
     SECOidTag    kind;
     int		 valueType;
-};
+} NameToKind;
 
 /* local type for directory string--could be printable_string or utf8 */
 #define SEC_ASN1_DS SEC_ASN1_HIGH_TAG_NUMBER
 
 /* Add new entries to this table, and maybe to function CERT_ParseRFC1485AVA */
-static const struct NameToKind name2kinds[] = {
+static const NameToKind name2kinds[] = {
 /* IANA registered type names
-   (See: http://www.iana.org/assignments/ldap-parameters) */
-    /* RFC 3280,4630 MUST SUPPORT */
+ * (See: http://www.iana.org/assignments/ldap-parameters) 
+ */
+/* RFC 3280, 4630 MUST SUPPORT */
     { "CN",             64, SEC_OID_AVA_COMMON_NAME,    SEC_ASN1_DS},
     { "ST",            128, SEC_OID_AVA_STATE_OR_PROVINCE,
 							SEC_ASN1_DS},
     { "O",              64, SEC_OID_AVA_ORGANIZATION_NAME,
 							SEC_ASN1_DS},
     { "OU",             64, SEC_OID_AVA_ORGANIZATIONAL_UNIT_NAME,
                                                         SEC_ASN1_DS},
     { "dnQualifier", 32767, SEC_OID_AVA_DN_QUALIFIER, SEC_ASN1_PRINTABLE_STRING},
     { "C",               2, SEC_OID_AVA_COUNTRY_NAME, SEC_ASN1_PRINTABLE_STRING},
     { "serialNumber",   64, SEC_OID_AVA_SERIAL_NUMBER,SEC_ASN1_PRINTABLE_STRING},
-    /* RFC 3280,4630 SHOULD SUPPORT */
+
+/* RFC 3280, 4630 SHOULD SUPPORT */
     { "L",             128, SEC_OID_AVA_LOCALITY,       SEC_ASN1_DS},
     { "title",          64, SEC_OID_AVA_TITLE,          SEC_ASN1_DS},
     { "SN",             64, SEC_OID_AVA_SURNAME,        SEC_ASN1_DS},
     { "givenName",      64, SEC_OID_AVA_GIVEN_NAME,     SEC_ASN1_DS},
     { "initials",       64, SEC_OID_AVA_INITIALS,       SEC_ASN1_DS},
     { "generationQualifier",
                         64, SEC_OID_AVA_GENERATION_QUALIFIER,
                                                         SEC_ASN1_DS},
-    /* RFC 3280,4630 MAY SUPPORT */
+/* RFC 3280, 4630 MAY SUPPORT */
     { "DC",            128, SEC_OID_AVA_DC,             SEC_ASN1_IA5_STRING},
-    /* values from draft-ietf-ldapbis-user-schema-05 (not in RFC 3280) */
+    { "MAIL",          256, SEC_OID_RFC1274_MAIL,       SEC_ASN1_IA5_STRING},
+    { "UID",           256, SEC_OID_RFC1274_UID,        SEC_ASN1_DS},
+
+/* ------------------ "strict" boundary ---------------------------------
+ * In strict mode, cert_NameToAscii does not encode any of the attributes
+ * below this line. The first SECOidTag below this line must be used to
+ * conditionally define the "endKind" in function AppendAVA() below.
+ * Most new attribute names should be added below this line.
+ * Maybe this line should be up higher?  Say, after the 3280 MUSTs and 
+ * before the 3280 SHOULDs?
+ */
+
+/* values from draft-ietf-ldapbis-user-schema-05 (not in RFC 3280) */
     { "postalAddress", 128, SEC_OID_AVA_POSTAL_ADDRESS, SEC_ASN1_DS},
     { "postalCode",     40, SEC_OID_AVA_POSTAL_CODE,    SEC_ASN1_DS},
     { "postOfficeBox",  40, SEC_OID_AVA_POST_OFFICE_BOX,SEC_ASN1_DS},
     { "houseIdentifier",64, SEC_OID_AVA_HOUSE_IDENTIFIER,SEC_ASN1_DS},
-    /* legacy keywords */
-    { "MAIL",          256, SEC_OID_RFC1274_MAIL,       SEC_ASN1_IA5_STRING},
-    { "UID",           256, SEC_OID_RFC1274_UID,        SEC_ASN1_DS},
-    
 /* end of IANA registered type names */
+
+/* legacy keywords */
     { "E",             128, SEC_OID_PKCS9_EMAIL_ADDRESS,SEC_ASN1_DS},
 
-
 #if 0 /* removed.  Not yet in any IETF draft or RFC. */
     { "pseudonym",      64, SEC_OID_AVA_PSEUDONYM,      SEC_ASN1_DS},
 #endif
+
     { 0,           256, SEC_OID_UNKNOWN                      , 0},
 };
 
 #define C_DOUBLE_QUOTE '\042'
 
 #define C_BACKSLASH '\134'
 
 #define C_EQUAL '='
@@ -126,17 +138,17 @@ static const struct NameToKind name2kind
      (((c) >= '+') && ((c) <= '/')) ||		/* + , - . / */	\
      ((c) == ':') ||						\
      ((c) == '=') ||						\
      ((c) == '?'))
 
 int
 cert_AVAOidTagToMaxLen(SECOidTag tag)
 {
-    const struct NameToKind *n2k = name2kinds;
+    const NameToKind *n2k = name2kinds;
 
     while (n2k->kind != tag && n2k->kind != SEC_OID_UNKNOWN) {
 	++n2k;
     }
     return (n2k->kind != SEC_OID_UNKNOWN) ? n2k->maxLen : -1;
 }
 
 static PRBool
@@ -350,17 +362,17 @@ loser:
 }
 
 
 CERTAVA *
 CERT_ParseRFC1485AVA(PRArenaPool *arena, char **pbp, char *endptr,
 		    PRBool singleAVA) 
 {
     CERTAVA *a;
-    const struct NameToKind *n2k;
+    const NameToKind *n2k;
     char *bp;
     int       vt = -1;
     int       valLen;
     SECOidTag kind  = SEC_OID_UNKNOWN;
     SECStatus rv    = SECFailure;
     SECItem   derOid = { 0, NULL, 0 };
 
     char tagBuf[32];
@@ -550,24 +562,23 @@ AppendStr(stringBuf *bufp, char *str)
 
     /* Concatenate str onto buf */
     buf = buf + bufLen;
     if (bufLen) buf--;			/* stomp on old '\0' */
     PORT_Memcpy(buf, str, len+1);		/* put in new null */
     return SECSuccess;
 }
 
-SECStatus
-CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen)
+static int
+cert_RFC1485_GetRequiredLen(const char *src, int srclen, PRBool *pNeedsQuoting)
 {
     int i, reqLen=0;
-    char *d = dst;
     PRBool needsQuoting = PR_FALSE;
     char lastC = 0;
-    
+
     /* need to make an initial pass to determine if quoting is needed */
     for (i = 0; i < srclen; i++) {
 	char c = src[i];
 	reqLen++;
 	if (!needsQuoting && (SPECIAL_CHAR(c) ||
 	    (OPTIONAL_SPACE(c) && OPTIONAL_SPACE(lastC)))) {
 	    /* entirety will need quoting */
 	    needsQuoting = PR_TRUE;
@@ -578,27 +589,39 @@ CERT_RFC1485_EscapeAndQuote(char *dst, i
 	}
 	lastC = c;
     }
     /* if it begins or ends in optional space it needs quoting */
     if (!needsQuoting && srclen > 0 && 
 	(OPTIONAL_SPACE(src[srclen-1]) || OPTIONAL_SPACE(src[0]))) {
 	needsQuoting = PR_TRUE;
     }
-    
-    if (needsQuoting) reqLen += 2;
+
+    if (needsQuoting) 
+    	reqLen += 2;
+    if (pNeedsQuoting)
+    	*pNeedsQuoting = needsQuoting;
+
+    return reqLen;
+}
+
+SECStatus
+CERT_RFC1485_EscapeAndQuote(char *dst, int dstlen, char *src, int srclen)
+{
+    int i, reqLen=0;
+    char *d = dst;
+    PRBool needsQuoting = PR_FALSE;
 
     /* space for terminal null */
-    reqLen++;
-    
+    reqLen = cert_RFC1485_GetRequiredLen(src, srclen, &needsQuoting) + 1;
     if (reqLen > dstlen) {
 	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
 	return SECFailure;
     }
-    
+
     d = dst;
     if (needsQuoting) *d++ = C_DOUBLE_QUOTE;
     for (i = 0; i < srclen; i++) {
 	char c = src[i];
 	if (c == C_DOUBLE_QUOTE || c == C_BACKSLASH) {
 	    /* escape it */
 	    *d++ = C_BACKSLASH;
 	}
@@ -717,108 +740,209 @@ get_hex_string(SECItem *data)
 	j = data->data[i];
 	rv->data[2*i+1] = hex[j >> 4];
 	rv->data[2*i+2] = hex[j & 15];
     }
     rv->data[rv->len] = 0;
     return rv;
 }
 
+/* For compliance with RFC 2253, RFC 3280 and RFC 4630, we choose to 
+ * use the NAME=STRING form, rather than the OID.N.N=#hexXXXX form, 
+ * when both of these conditions are met:
+ *  1) The attribute name OID (kind) has a known name string that is 
+ *     defined in one of those RFCs, or in RFCs that they cite, AND
+ *  2) The attribute's value encoding is RFC compliant for the kind
+ *     (e.g., the value's encoding tag is correct for the kind, and
+ *     the value's length is in the range allowed for the kind, and
+ *     the value's contents are appropriate for the encoding tag).
+ *  Otherwise, we use the OID.N.N=#hexXXXX form.
+ *
+ *  If the caller prefers maximum human readability to RFC compliance,
+ *  then 
+ *  - We print the kind in NAME= string form if we know the name
+ *    string for the attribute type OID, regardless of whether the 
+ *    value is correctly encoded or not. else we use the OID.N.N= form.
+ *  - We use the non-hex STRING form for the attribute value if the
+ *    value can be represented in such a form.  Otherwise, we use 
+ *    the hex string form.
+ *  This implies that, for maximum human readability, in addition to 
+ *  the two forms allowed by the RFC, we allow two other forms of output:
+ *  - the OID.N.N=STRING form, and 
+ *  - the NAME=#hexXXXX form
+ *  When the caller prefers maximum human readability, we do not allow
+ *  the value of any attribute to exceed the length allowed by the RFC.
+ *  If the attribute value exceeds the allowed length, we truncate it to 
+ *  the allowed length and append "...".
+ *  Also in this case, we arbitrarily impose a limit on the length of the 
+ *  entire AVA encoding, regardless of the form, of 384 bytes per AVA.
+ *  This limit includes the trailing NULL character.  If the encoded 
+ *  AVA length exceeds that limit, this function reports failure to encode
+ *  the AVA.
+ *
+ *  An ASCII representation of an AVA is said to be "invertible" if 
+ *  conversion back to DER reproduces the original DER encoding exactly.
+ *  The RFC 2253 rules do not ensure that all ASCII AVAs derived according
+ *  to its rules are invertible. That is because the RFCs allow some 
+ *  attribute values to be encoded in any of a number of encodings,
+ *  and the encoding type information is lost in the non-hex STRING form.
+ *  This is particularly true of attributes of type DirectoryString.
+ *  The encoding type information is always preserved in the hex string 
+ *  form, because the hex includes the entire DER encoding of the value.
+ *
+ *  So, when the caller perfers maximum invertibility, we apply the 
+ *  RFC compliance rules stated above, and add a third required 
+ *  condition on the use of the NAME=STRING form.  
+ *   3) The attribute's kind is not is allowed to be encoded in any of 
+ *      several different encodings, such as DirectoryStrings.
+ *
+ * The chief difference between CERT_N2A_STRICT and CERT_N2A_INVERTIBLE
+ * is that the latter forces DirectoryStrings to be hex encoded.
+ *
+ * As a simplification, we assume the value is correctly encoded for 
+ * its encoding type.  That is, we do not test that all the characters
+ * in a string encoded type are allowed by that type.  We assume it.
+ */
 static SECStatus
-AppendAVA(stringBuf *bufp, CERTAVA *ava)
+AppendAVA(stringBuf *bufp, CERTAVA *ava, CertStrictnessLevel strict)
 {
-    const struct NameToKind *n2k = name2kinds;
-    const char *tagName;
-    unsigned len, maxLen;
-    int tag;
-    SECStatus rv;
-    SECItem *avaValue = NULL;
-    char *unknownTag = NULL;
-    PRBool hexValue = PR_FALSE;
-    char tmpBuf[384];
+    const NameToKind *pn2k   = name2kinds;
+    SECItem     *avaValue    = NULL;
+    char        *unknownTag  = NULL;
+    char        *encodedAVA  = NULL;
+    PRBool       useHex      = PR_FALSE;  /* use =#hexXXXX form */
+    SECOidTag    endKind;
+    SECStatus    rv;
+    unsigned int len;
+    int          nameLen, valueLen;
+    NameToKind   n2k         = { NULL, 32767, SEC_OID_UNKNOWN, SEC_ASN1_DS };
+    char         tmpBuf[384];
 
+#define tagName  n2k.name    /* non-NULL means use NAME= form */
+#define maxBytes n2k.maxLen
+#define tag      n2k.kind
+#define vt       n2k.valueType
+
+    /* READABLE mode recognizes more names from the name2kinds table
+     * than do STRICT or INVERTIBLE modes.  This assignment chooses the
+     * point in the table where the attribute type name scanning stops.
+     */
+    endKind = (strict == CERT_N2A_READABLE) ? SEC_OID_UNKNOWN
+                                            : SEC_OID_AVA_POSTAL_ADDRESS;
     tag = CERT_GetAVATag(ava);
-    while (n2k->kind != tag && n2k->kind != SEC_OID_UNKNOWN) {
-        ++n2k;
-    }
-    if (n2k->kind != SEC_OID_UNKNOWN) {
-        tagName = n2k->name;
-    } else {
-	/* handle unknown attribute types per RFC 2253 */
-	tagName = unknownTag = CERT_GetOidString(&ava->type);
-	if (!tagName)
-	    return SECFailure;
-    }
-    maxLen = n2k->maxLen;
-
-#ifdef NSS_STRICT_RFC_2253_VALUES_ONLY
-    if (!unknownTag)
-#endif
-    avaValue = CERT_DecodeAVAValue(&ava->value);
-    if(!avaValue) {
-	/* the attribute value is not recognized, get the hex value */
-	avaValue = get_hex_string(&ava->value);
-	if(!avaValue) {
-	    if (unknownTag) PR_smprintf_free(unknownTag);
-	    return SECFailure;
-	}
-	hexValue = PR_TRUE;
+    while (pn2k->kind != tag && pn2k->kind != endKind) {
+        ++pn2k;
     }
 
-    /* Check value length */
-    if (avaValue->len > maxLen + 3) {  /* must be room for "..." */
-	/* avaValue is a UTF8 string, freshly allocated and returned to us 
-	** by CERT_DecodeAVAValue or get_hex_string just above, so we can
-	** modify it here.  See if we're in the middle of a multi-byte
-	** UTF8 character.
-	*/
-	while (((avaValue->data[maxLen] & 0xc0) == 0x80) && maxLen > 0) {
-	   maxLen--;
+    if (pn2k->kind != endKind ) {
+        n2k = *pn2k;
+    } else if (strict != CERT_N2A_READABLE) {
+        useHex = PR_TRUE;
+    }
+    /* For invertable form, force Directory Strings to use hex form. */
+    if (strict == CERT_N2A_INVERTIBLE && vt == SEC_ASN1_DS) {
+	tagName = NULL;      /* must use OID.N form */
+	useHex = PR_TRUE;    /* must use hex string */
+    }
+    if (!useHex) {
+	avaValue = CERT_DecodeAVAValue(&ava->value);
+	if (!avaValue) {
+	    useHex = PR_TRUE;
+	    if (strict != CERT_N2A_READABLE) {
+		tagName = NULL;  /* must use OID.N form */
+	    }
 	}
-	/* add elipsis to signify truncation. */
-	avaValue->data[maxLen++] = '.'; 
-	avaValue->data[maxLen++] = '.';
-	avaValue->data[maxLen++] = '.';
-	avaValue->data[maxLen]   = 0;
-	avaValue->len = maxLen;
+    }
+    if (!tagName) {
+	/* handle unknown attribute types per RFC 2253 */
+	tagName = unknownTag = CERT_GetOidString(&ava->type);
+	if (!tagName) {
+	    if (avaValue)
+		SECITEM_FreeItem(avaValue, PR_TRUE);
+	    return SECFailure;
+	}
+    }
+    if (useHex) {
+	avaValue = get_hex_string(&ava->value);
+	if (!avaValue) {
+	    if (unknownTag) 
+	    	PR_smprintf_free(unknownTag);
+	    return SECFailure;
+	}
     }
 
-    len = PORT_Strlen(tagName);
-    if (len+1 > sizeof(tmpBuf)) {
-	if (unknownTag) PR_smprintf_free(unknownTag);
+    if (strict == CERT_N2A_READABLE) {
+    	if (maxBytes > sizeof(tmpBuf) - 4)
+	    maxBytes = sizeof(tmpBuf) - 4;
+	/* Check value length.  Must be room for "..." */
+	if (avaValue->len > maxBytes + 3) {
+	    /* avaValue is a UTF8 string, freshly allocated and returned to us 
+	    ** by CERT_DecodeAVAValue or get_hex_string just above, so we can
+	    ** modify it here.  See if we're in the middle of a multi-byte
+	    ** UTF8 character.
+	    */
+	    len = maxBytes;
+	    while (((avaValue->data[len] & 0xc0) == 0x80) && len > 0) {
+	       len--;
+	    }
+	    /* add elipsis to signify truncation. */
+	    avaValue->data[len++] = '.'; 
+	    avaValue->data[len++] = '.';
+	    avaValue->data[len++] = '.';
+	    avaValue->data[len]   = 0;
+	    avaValue->len = len;
+	}
+    }
+
+    nameLen  = strlen(tagName);
+    valueLen = (useHex ? avaValue->len : 
+            cert_RFC1485_GetRequiredLen(avaValue->data, avaValue->len, NULL));
+    len = nameLen + valueLen + 2; /* Add 2 for '=' and trailing NUL */
+
+    if (len <= sizeof(tmpBuf)) {
+    	encodedAVA = tmpBuf;
+    } else if (strict == CERT_N2A_READABLE) {
+	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+    } else {
+	encodedAVA = PORT_Alloc(len);
+    }
+    if (!encodedAVA) {
 	SECITEM_FreeItem(avaValue, PR_TRUE);
-	PORT_SetError(SEC_ERROR_OUTPUT_LEN);
+	if (unknownTag) 
+	    PR_smprintf_free(unknownTag);
 	return SECFailure;
     }
-    PORT_Memcpy(tmpBuf, tagName, len);
-    if (unknownTag) PR_smprintf_free(unknownTag);
-    tmpBuf[len++] = '=';
+    memcpy(encodedAVA, tagName, nameLen);
+    if (unknownTag) 
+    	PR_smprintf_free(unknownTag);
+    encodedAVA[nameLen++] = '=';
     
     /* escape and quote as necessary - don't quote hex strings */
-    if (hexValue) {
-        /* appent avaValue to tmpBuf */
-	if (avaValue->len + len + 1 > sizeof tmpBuf) {
-	    PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
-	    rv = SECFailure;
-    	} else {
-	    PORT_Strncpy(tmpBuf+len, (char *)avaValue->data, avaValue->len + 1);
-	    rv = SECSuccess;
-	}
+    if (useHex) {
+	memcpy(encodedAVA + nameLen, (char *)avaValue->data, avaValue->len);
+	encodedAVA[nameLen + avaValue->len] = '\0';
+	rv = SECSuccess;
     } else 
-	rv = CERT_RFC1485_EscapeAndQuote(tmpBuf+len, sizeof(tmpBuf)-len, 
-		    		     (char *)avaValue->data, avaValue->len);
+	rv = CERT_RFC1485_EscapeAndQuote(encodedAVA + nameLen, len - nameLen, 
+		    		        (char *)avaValue->data, avaValue->len);
     SECITEM_FreeItem(avaValue, PR_TRUE);
-    if (rv) return SECFailure;
-    
-    rv = AppendStr(bufp, tmpBuf);
+    if (rv == SECSuccess)
+	rv = AppendStr(bufp, encodedAVA);
+    if (encodedAVA != tmpBuf)
+    	PORT_Free(encodedAVA);
     return rv;
 }
 
+#undef tagName
+#undef maxBytes
+#undef tag
+#undef vt
+
 char *
-CERT_NameToAscii(CERTName *name)
+CERT_NameToAsciiInvertible(CERTName *name, CertStrictnessLevel strict)
 {
     CERTRDN** rdns;
     CERTRDN** lastRdn;
     CERTRDN** rdn;
     PRBool first = PR_TRUE;
     stringBuf strBuf = { NULL, 0, 0 };
     
     rdns = name->rdns;
@@ -849,29 +973,35 @@ CERT_NameToAscii(CERTName *name)
 		/* Use of spaces is deprecated in RFC 2253. */
 		rv = AppendStr(&strBuf, newRDN ? "," : "+");
 		if (rv) goto loser;
 	    } else {
 		first = PR_FALSE;
 	    }
 	    
 	    /* Add in tag type plus value into buf */
-	    rv = AppendAVA(&strBuf, ava);
+	    rv = AppendAVA(&strBuf, ava, strict);
 	    if (rv) goto loser;
 	    newRDN = PR_FALSE;
 	}
     }
     return strBuf.buffer;
 loser:
     if (strBuf.buffer) {
 	PORT_Free(strBuf.buffer);
     }
     return NULL;
 }
 
+char *
+CERT_NameToAscii(CERTName *name)
+{
+    return CERT_NameToAsciiInvertible(name, CERT_N2A_READABLE);
+}
+
 /*
  * Return the string representation of a DER encoded distinguished name
  * "dername" - The DER encoded name to convert
  */
 char *
 CERT_DerNameToAscii(SECItem *dername)
 {
     int rv;
--- a/security/nss/lib/certdb/cert.h
+++ b/security/nss/lib/certdb/cert.h
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * cert.h - public data structures and prototypes for the certificate library
  *
- * $Id: cert.h,v 1.68 2008/03/15 02:15:34 alexei.volkov.bugs%sun.com Exp $
+ * $Id: cert.h,v 1.74 2008/08/04 22:31:54 nelson%bolyard.com Exp $
  */
 
 #ifndef _CERT_H_
 #define _CERT_H_
 
 #include "utilrename.h"
 #include "plarena.h"
 #include "plhash.h"
@@ -66,20 +66,30 @@ SEC_BEGIN_PROTOS
 /*
 ** Convert an ascii RFC1485 encoded name into its CERTName equivalent.
 */
 extern CERTName *CERT_AsciiToName(char *string);
 
 /*
 ** Convert an CERTName into its RFC1485 encoded equivalent.
 ** Returns a string that must be freed with PORT_Free().
+** This version produces a string for maximum human readability,
+** not for strict RFC compliance.
 */
 extern char *CERT_NameToAscii(CERTName *name);
 
-extern CERTAVA *CERT_CopyAVA(PRArenaPool *arena, CERTAVA *src);
+/*
+** Convert an CERTName into its RFC1485 encoded equivalent.
+** Returns a string that must be freed with PORT_Free().
+** Caller chooses encoding rules.
+*/
+extern char *CERT_NameToAsciiInvertible(CERTName *name, 
+                                        CertStrictnessLevel strict);
+
+extern CERTAVA *CERT_CopyAVA(PLArenaPool *arena, CERTAVA *src);
 
 /* convert an OID to dotted-decimal representation */
 /* Returns a string that must be freed with PR_smprintf_free(). */
 extern char * CERT_GetOidString(const SECItem *oid);
 
 /*
 ** Examine an AVA and return the tag that refers to it. The AVA tags are
 ** defined as SEC_OID_AVA*.
@@ -90,36 +100,36 @@ extern SECOidTag CERT_GetAVATag(CERTAVA 
 ** Compare two AVA's, returning the difference between them.
 */
 extern SECComparison CERT_CompareAVA(const CERTAVA *a, const CERTAVA *b);
 
 /*
 ** Create an RDN (relative-distinguished-name). The argument list is a
 ** NULL terminated list of AVA's.
 */
-extern CERTRDN *CERT_CreateRDN(PRArenaPool *arena, CERTAVA *avas, ...);
+extern CERTRDN *CERT_CreateRDN(PLArenaPool *arena, CERTAVA *avas, ...);
 
 /*
 ** Make a copy of "src" storing it in "dest".
 */
-extern SECStatus CERT_CopyRDN(PRArenaPool *arena, CERTRDN *dest, CERTRDN *src);
+extern SECStatus CERT_CopyRDN(PLArenaPool *arena, CERTRDN *dest, CERTRDN *src);
 
 /*
 ** Destory an RDN object.
 **	"rdn" the RDN to destroy
 **	"freeit" if PR_TRUE then free the object as well as its sub-objects
 */
 extern void CERT_DestroyRDN(CERTRDN *rdn, PRBool freeit);
 
 /*
 ** Add an AVA to an RDN.
 **	"rdn" the RDN to add to
 **	"ava" the AVA to add
 */
-extern SECStatus CERT_AddAVA(PRArenaPool *arena, CERTRDN *rdn, CERTAVA *ava);
+extern SECStatus CERT_AddAVA(PLArenaPool *arena, CERTRDN *rdn, CERTAVA *ava);
 
 /*
 ** Compare two RDN's, returning the difference between them.
 */
 extern SECComparison CERT_CompareRDN(CERTRDN *a, CERTRDN *b);
 
 /*
 ** Create an X.500 style name using a NULL terminated list of RDN's.
@@ -127,17 +137,17 @@ extern SECComparison CERT_CompareRDN(CER
 extern CERTName *CERT_CreateName(CERTRDN *rdn, ...);
 
 /*
 ** Make a copy of "src" storing it in "dest". Memory is allocated in
 ** "dest" for each of the appropriate sub objects. Memory is not freed in
 ** "dest" before allocation is done (use CERT_DestroyName(dest, PR_FALSE) to
 ** do that).
 */
-extern SECStatus CERT_CopyName(PRArenaPool *arena, CERTName *dest, CERTName *src);
+extern SECStatus CERT_CopyName(PLArenaPool *arena, CERTName *dest, CERTName *src);
 
 /*
 ** Destroy a Name object.
 **	"name" the CERTName to destroy
 **	"freeit" if PR_TRUE then free the object as well as its sub-objects
 */
 extern void CERT_DestroyName(CERTName *name);
 
@@ -170,33 +180,33 @@ extern char *CERT_Hexify (SECItem *i, in
  *
  *****************************************************************************/
 
 /*
 ** Create a new validity object given two unix time values.
 **	"notBefore" the time before which the validity is not valid
 **	"notAfter" the time after which the validity is not valid
 */
-extern CERTValidity *CERT_CreateValidity(int64 notBefore, int64 notAfter);
+extern CERTValidity *CERT_CreateValidity(PRTime notBefore, PRTime notAfter);
 
 /*
 ** Destroy a validity object.
 **	"v" the validity to destroy
 **	"freeit" if PR_TRUE then free the object as well as its sub-objects
 */
 extern void CERT_DestroyValidity(CERTValidity *v);
 
 /*
 ** Copy the "src" object to "dest". Memory is allocated in "dest" for
 ** each of the appropriate sub-objects. Memory in "dest" is not freed
 ** before memory is allocated (use CERT_DestroyValidity(v, PR_FALSE) to do
 ** that).
 */
 extern SECStatus CERT_CopyValidity
-   (PRArenaPool *arena, CERTValidity *dest, CERTValidity *src);
+   (PLArenaPool *arena, CERTValidity *dest, CERTValidity *src);
 
 /*
 ** The cert lib considers a cert or CRL valid if the "notBefore" time is
 ** in the not-too-distant future, e.g. within the next 24 hours. This 
 ** prevents freshly issued certificates from being considered invalid
 ** because the local system's time zone is incorrectly set.  
 ** The amount of "pending slop time" is adjustable by the application.
 ** Units of SlopTime are seconds.  Default is 86400  (24 hours).
@@ -300,17 +310,17 @@ extern int CERT_GetDBContentVersion(CERT
 /*
 ** Default certificate database routines
 */
 extern void CERT_SetDefaultCertDB(CERTCertDBHandle *handle);
 
 extern CERTCertDBHandle *CERT_GetDefaultCertDB(void);
 
 extern CERTCertList *CERT_GetCertChainFromCert(CERTCertificate *cert, 
-					       int64 time, 
+					       PRTime time, 
 					       SECCertUsage usage);
 extern CERTCertificate *
 CERT_NewTempCertificate (CERTCertDBHandle *handle, SECItem *derCert,
                          char *nickname, PRBool isperm, PRBool copyDER);
 
 
 /******************************************************************************
  *
@@ -322,17 +332,17 @@ CERT_NewTempCertificate (CERTCertDBHandl
 ** Create an AVA (attribute-value-assertion)
 **	"arena" the memory arena to alloc from
 **	"kind" is one of SEC_OID_AVA_*
 **	"valueType" is one of DER_PRINTABLE_STRING, DER_IA5_STRING, or
 **	   DER_T61_STRING
 **	"value" is the null terminated string containing the value
 */
 extern CERTAVA *CERT_CreateAVA
-   (PRArenaPool *arena, SECOidTag kind, int valueType, char *value);
+   (PLArenaPool *arena, SECOidTag kind, int valueType, char *value);
 
 /*
 ** Extract the Distinguished Name from a DER encoded certificate
 **	"derCert" is the DER encoded certificate
 **	"derName" is the SECItem that the name is returned in
 */
 extern SECStatus CERT_NameFromDERCert(SECItem *derCert, SECItem *derName);
 
@@ -341,49 +351,49 @@ extern SECStatus CERT_NameFromDERCert(SE
 **	"derCert" is the DER encoded certificate
 **	"derName" is the SECItem that the name is returned in
 */
 extern SECStatus CERT_IssuerNameFromDERCert(SECItem *derCert, 
 					    SECItem *derName);
 
 extern SECItem *
 CERT_EncodeGeneralName(CERTGeneralName *genName, SECItem *dest,
-		       PRArenaPool *arena);
+		       PLArenaPool *arena);
 
 extern CERTGeneralName *
-CERT_DecodeGeneralName(PRArenaPool *reqArena, SECItem *encodedName,
+CERT_DecodeGeneralName(PLArenaPool *reqArena, SECItem *encodedName,
 		       CERTGeneralName  *genName);
 
 
 
 /*
 ** Generate a database search key for a certificate, based on the
 ** issuer and serial number.
 **	"arena" the memory arena to alloc from
 **	"derCert" the DER encoded certificate
 **	"key" the returned key
 */
-extern SECStatus CERT_KeyFromDERCert(PRArenaPool *reqArena, SECItem *derCert,
+extern SECStatus CERT_KeyFromDERCert(PLArenaPool *reqArena, SECItem *derCert,
                                      SECItem *key);
 
-extern SECStatus CERT_KeyFromIssuerAndSN(PRArenaPool *arena, SECItem *issuer,
+extern SECStatus CERT_KeyFromIssuerAndSN(PLArenaPool *arena, SECItem *issuer,
 					 SECItem *sn, SECItem *key);
 
 extern SECStatus CERT_SerialNumberFromDERCert(SECItem *derCert, 
 						SECItem *derName);
 
 
 /*
 ** Generate a database search key for a crl, based on the
 ** issuer.
 **	"arena" the memory arena to alloc from
 **	"derCrl" the DER encoded crl
 **	"key" the returned key
 */
-extern SECStatus CERT_KeyFromDERCrl(PRArenaPool *arena, SECItem *derCrl, SECItem *key);
+extern SECStatus CERT_KeyFromDERCrl(PLArenaPool *arena, SECItem *derCrl, SECItem *key);
 
 /*
 ** Open the certificate database.  Use callback to get name of database.
 */
 extern SECStatus CERT_OpenCertDB(CERTCertDBHandle *handle, PRBool readOnly,
 				 CERTDBNameFunc namecb, void *cbarg);
 
 /* Open the certificate database.  Use given filename for database. */
@@ -432,24 +442,24 @@ CERT_DecodeDERCertificate (SECItem *derS
 ** Decode a DER encoded CRL/KRL into an CERTSignedCrl structure
 **	"derSignedCrl" is the DER encoded signed crl/krl.
 **	"type" is this a CRL or KRL.
 */
 #define SEC_CRL_TYPE	1
 #define SEC_KRL_TYPE	0
 
 extern CERTSignedCrl *
-CERT_DecodeDERCrl (PRArenaPool *arena, SECItem *derSignedCrl,int type);
+CERT_DecodeDERCrl (PLArenaPool *arena, SECItem *derSignedCrl,int type);
 
 /*
  * same as CERT_DecodeDERCrl, plus allow options to be passed in
  */
 
 extern CERTSignedCrl *
-CERT_DecodeDERCrlWithFlags(PRArenaPool *narena, SECItem *derSignedCrl,
+CERT_DecodeDERCrlWithFlags(PLArenaPool *narena, SECItem *derSignedCrl,
                           int type, PRInt32 options);
 
 /* CRL options to pass */
 
 #define CRL_DECODE_DEFAULT_OPTIONS          0x00000000
 
 /* when CRL_DECODE_DONT_COPY_DER is set, the DER is not copied . The
    application must then keep derSignedCrl until it destroys the
@@ -545,16 +555,24 @@ CERT_FindCertByIssuerAndSN (CERTCertDBHa
 /*
 ** Find a certificate in the database by a subject key ID
 **	"subjKeyID" is the subject Key ID to look for
 */
 extern CERTCertificate *
 CERT_FindCertBySubjectKeyID (CERTCertDBHandle *handle, SECItem *subjKeyID);
 
 /*
+** Encode Certificate SKID (Subject Key ID) extension.
+**
+*/
+extern SECStatus 
+CERT_EncodeSubjectKeyID(PLArenaPool *arena, const SECItem* srcString,
+                        SECItem *encodedValue);
+
+/*
 ** Find a certificate in the database by a nickname
 **	"nickname" is the ascii string nickname to look for
 */
 extern CERTCertificate *
 CERT_FindCertByNickname (CERTCertDBHandle *handle, const char *nickname);
 
 /*
 ** Find a certificate in the database by a DER encoded certificate
@@ -583,32 +601,32 @@ CERT_FindCertByNicknameOrEmailAddr(CERTC
 */
 extern CERTCertificate *
 CERT_FindCertBySPKDigest(CERTCertDBHandle *handle, SECItem *spkDigest);
 
 /*
  * Find the issuer of a cert
  */
 CERTCertificate *
-CERT_FindCertIssuer(CERTCertificate *cert, int64 validTime, SECCertUsage usage);
+CERT_FindCertIssuer(CERTCertificate *cert, PRTime validTime, SECCertUsage usage);
 
 /*
 ** Check the validity times of a certificate vs. time 't', allowing
 ** some slop for broken clocks and stuff.
 **	"cert" is the certificate to be checked
 **	"t" is the time to check against
 **	"allowOverride" if true then check to see if the invalidity has
 **		been overridden by the user.
 */
 extern SECCertTimeValidity CERT_CheckCertValidTimes(CERTCertificate *cert,
 						    PRTime t,
 						    PRBool allowOverride);
 
 /*
-** WARNING - this function is depricated, and will either go away or have
+** WARNING - this function is deprecated, and will either go away or have
 **		a new API in the near future.
 **
 ** Check the validity times of a certificate vs. the current time, allowing
 ** some slop for broken clocks and stuff.
 **	"cert" is the certificate to be checked
 */
 extern SECStatus CERT_CertTimesValid(CERTCertificate *cert);
 
@@ -619,27 +637,27 @@ extern SECStatus CERT_CertTimesValid(CER
 **	"notAfter" is the end of the validity period
 */
 extern SECStatus
 CERT_GetCertTimes (CERTCertificate *c, PRTime *notBefore, PRTime *notAfter);
 
 /*
 ** Extract the issuer and serial number from a certificate
 */
-extern CERTIssuerAndSN *CERT_GetCertIssuerAndSN(PRArenaPool *, 
+extern CERTIssuerAndSN *CERT_GetCertIssuerAndSN(PLArenaPool *, 
 							CERTCertificate *);
 
 /*
 ** verify the signature of a signed data object with a given certificate
 **	"sd" the signed data object to be verified
 **	"cert" the certificate to use to check the signature
 */
 extern SECStatus CERT_VerifySignedData(CERTSignedData *sd,
 				       CERTCertificate *cert,
-				       int64 t,
+				       PRTime t,
 				       void *wincx);
 /*
 ** verify the signature of a signed data object with the given DER publickey
 */
 extern SECStatus
 CERT_VerifySignedDataWithPublicKeyInfo(CERTSignedData *sd,
                                        CERTSubjectPublicKeyInfo *pubKeyInfo,
                                        void *wincx);
@@ -657,56 +675,56 @@ CERT_VerifySignedDataWithPublicKey(CERTS
 ** that we trust the issuer, and that the signature on the certificate is
 ** valid.
 **	"cert" the certificate to verify
 **	"checkSig" only check signatures if true
 */
 extern SECStatus
 CERT_VerifyCertificate(CERTCertDBHandle *handle, CERTCertificate *cert,
 		PRBool checkSig, SECCertificateUsage requiredUsages,
-                int64 t, void *wincx, CERTVerifyLog *log,
+                PRTime t, void *wincx, CERTVerifyLog *log,
                 SECCertificateUsage* returnedUsages);
 
 /* same as above, but uses current time */
 extern SECStatus
 CERT_VerifyCertificateNow(CERTCertDBHandle *handle, CERTCertificate *cert,
 		   PRBool checkSig, SECCertificateUsage requiredUsages,
                    void *wincx, SECCertificateUsage* returnedUsages);
 
 /*
 ** Verify that a CA cert can certify some (unspecified) leaf cert for a given
 ** purpose. This is used by UI code to help identify where a chain may be
 ** broken and why. This takes identical parameters to CERT_VerifyCert
 */
 extern SECStatus
 CERT_VerifyCACertForUsage(CERTCertDBHandle *handle, CERTCertificate *cert,
-		PRBool checkSig, SECCertUsage certUsage, int64 t,
+		PRBool checkSig, SECCertUsage certUsage, PRTime t,
 		void *wincx, CERTVerifyLog *log);
 
 /*
 ** OLD OBSOLETE FUNCTIONS with enum SECCertUsage - DO NOT USE FOR NEW CODE
 ** verify a certificate by checking validity times against a certain time,
 ** that we trust the issuer, and that the signature on the certificate is
 ** valid.
 **	"cert" the certificate to verify
 **	"checkSig" only check signatures if true
 */
 extern SECStatus
 CERT_VerifyCert(CERTCertDBHandle *handle, CERTCertificate *cert,
-		PRBool checkSig, SECCertUsage certUsage, int64 t,
+		PRBool checkSig, SECCertUsage certUsage, PRTime t,
 		void *wincx, CERTVerifyLog *log);
 
 /* same as above, but uses current time */
 extern SECStatus
 CERT_VerifyCertNow(CERTCertDBHandle *handle, CERTCertificate *cert,
 		   PRBool checkSig, SECCertUsage certUsage, void *wincx);
 
 SECStatus
 CERT_VerifyCertChain(CERTCertDBHandle *handle, CERTCertificate *cert,
-		     PRBool checkSig, SECCertUsage certUsage, int64 t,
+		     PRBool checkSig, SECCertUsage certUsage, PRTime t,
 		     void *wincx, CERTVerifyLog *log);
 
 /*
 ** Read a base64 ascii encoded DER certificate and convert it to our
 ** internal format.
 **	"certstr" is a null-terminated string containing the certificate
 */
 extern CERTCertificate *CERT_ConvertAndDecodeCertificate(char *certstr);
@@ -829,17 +847,17 @@ extern SECStatus CERT_EncodeAndAddExtens
    (void *exthandle, int idtag, void *value, PRBool critical,
     const SEC_ASN1Template *atemplate);
 
 extern SECStatus CERT_EncodeAndAddBitStrExtension
    (void *exthandle, int idtag, SECItem *value, PRBool critical);
 
 
 extern SECStatus
-CERT_EncodeAltNameExtension(PRArenaPool *arena,  CERTGeneralName  *value, SECItem *encodedValue);
+CERT_EncodeAltNameExtension(PLArenaPool *arena,  CERTGeneralName  *value, SECItem *encodedValue);
 
 
 /*
 ** Finish adding cert extensions.  Does final processing on extension
 ** data, putting it in the right format, and freeing any temporary
 ** storage.
 **	"exthandle" is the handle used to add extensions to a certificate
 */
@@ -869,57 +887,57 @@ CERT_DestroyOidSequence(CERTOidSequence 
  ****************************************************************************/
 
 /* Encode the value of the basicConstraint extension.
 **	arena - where to allocate memory for the encoded value.
 **	value - extension value to encode
 **	encodedValue - output encoded value
 */
 extern SECStatus CERT_EncodeBasicConstraintValue
-   (PRArenaPool *arena, CERTBasicConstraints *value, SECItem *encodedValue);
+   (PLArenaPool *arena, CERTBasicConstraints *value, SECItem *encodedValue);
 
 /*
 ** Encode the value of the authorityKeyIdentifier extension.
 */
 extern SECStatus CERT_EncodeAuthKeyID
-   (PRArenaPool *arena, CERTAuthKeyID *value, SECItem *encodedValue);
+   (PLArenaPool *arena, CERTAuthKeyID *value, SECItem *encodedValue);
 
 /*
 ** Encode the value of the crlDistributionPoints extension.
 */
 extern SECStatus CERT_EncodeCRLDistributionPoints
-   (PRArenaPool *arena, CERTCrlDistributionPoints *value,SECItem *derValue);
+   (PLArenaPool *arena, CERTCrlDistributionPoints *value,SECItem *derValue);
 
 /*
 ** Decodes a DER encoded basicConstaint extension value into a readable format
 **	value - decoded value
 **	encodedValue - value to decoded
 */
 extern SECStatus CERT_DecodeBasicConstraintValue
    (CERTBasicConstraints *value, SECItem *encodedValue);
 
 /* Decodes a DER encoded authorityKeyIdentifier extension value into a
 ** readable format.
 **	arena - where to allocate memory for the decoded value
 **	encodedValue - value to be decoded
 **	Returns a CERTAuthKeyID structure which contains the decoded value
 */
 extern CERTAuthKeyID *CERT_DecodeAuthKeyID 
-			(PRArenaPool *arena, SECItem *encodedValue);
+			(PLArenaPool *arena, SECItem *encodedValue);
 
 
 /* Decodes a DER encoded crlDistributionPoints extension value into a 
 ** readable format.
 **	arena - where to allocate memory for the decoded value
 **	der - value to be decoded
 **	Returns a CERTCrlDistributionPoints structure which contains the 
 **          decoded value
 */
 extern CERTCrlDistributionPoints * CERT_DecodeCRLDistributionPoints
-   (PRArenaPool *arena, SECItem *der);
+   (PLArenaPool *arena, SECItem *der);
 
 /* Extract certain name type from a generalName */
 extern void *CERT_GetGeneralNameByType
    (CERTGeneralName *genNames, CERTGeneralNameType type, PRBool derFormat);
 
 
 extern CERTOidSequence *
 CERT_DecodeOidSequence(SECItem *seqItem);
@@ -948,17 +966,17 @@ extern SECStatus CERT_FindCertExtensionB
    (CERTCertificate *cert, SECItem *oid, SECItem *value);
 
 extern char *CERT_FindCertURLExtension (CERTCertificate *cert, int tag, 
 								int catag);
 
 /* Returns the decoded value of the authKeyID extension.
 **   Note that this uses passed in the arena to allocate storage for the result
 */
-extern CERTAuthKeyID * CERT_FindAuthKeyIDExten (PRArenaPool *arena,CERTCertificate *cert);
+extern CERTAuthKeyID * CERT_FindAuthKeyIDExten (PLArenaPool *arena,CERTCertificate *cert);
 
 /* Returns the decoded value of the basicConstraint extension.
  */
 extern SECStatus CERT_FindBasicConstraintExten
    (CERTCertificate *cert, CERTBasicConstraints *value);
 
 /* Returns the decoded value of the crlDistributionPoints extension.
 **  Note that the arena in cert is used to allocate storage for the result
@@ -999,17 +1017,17 @@ extern SECStatus CERT_CheckCertUsage (CE
 
 extern SECStatus CERT_FindCRLExtensionByOID
    (CERTCrl *crl, SECItem *oid, SECItem *value);
 
 extern SECStatus CERT_FindCRLExtension
    (CERTCrl *crl, int tag, SECItem *value);
 
 extern SECStatus
-   CERT_FindInvalidDateExten (CERTCrl *crl, int64 *value);
+   CERT_FindInvalidDateExten (CERTCrl *crl, PRTime *value);
 
 /*
 ** Set up a crl for adding X509v3 extensions.  Returns an opaque handle
 ** used by routines that take an exthandle (void*) argument .
 **	"crl" is the CRL we are adding extensions to
 */
 extern void *CERT_StartCRLExtensions(CERTCrl *crl);
 
@@ -1022,17 +1040,17 @@ extern void *CERT_StartCRLExtensions(CER
 extern void *CERT_StartCRLEntryExtensions(CERTCrl *crl, CERTCrlEntry *entry);
 
 extern CERTCertNicknames *CERT_GetCertNicknames (CERTCertDBHandle *handle,
 						 int what, void *wincx);
 
 /*
 ** Finds the crlNumber extension and decodes its value into 'value'
 */
-extern SECStatus CERT_FindCRLNumberExten (PRArenaPool *arena, CERTCrl *crl,
+extern SECStatus CERT_FindCRLNumberExten (PLArenaPool *arena, CERTCrl *crl,
                                           SECItem *value);
 
 extern SECStatus CERT_FindCRLEntryReasonExten (CERTCrlEntry *crlEntry,
 					       CERTCRLEntryReasonCode *value);
 
 extern void CERT_FreeNicknames(CERTCertNicknames *nicknames);
 
 extern PRBool CERT_CompareCerts(CERTCertificate *c1, CERTCertificate *c2);
@@ -1132,19 +1150,16 @@ CERT_SaveSMimeProfile(CERTCertificate *c
  * find the smime symmetric capabilities profile for a given cert
  */
 SECItem *
 CERT_FindSMimeProfile(CERTCertificate *cert);
 
 SECStatus
 CERT_AddNewCerts(CERTCertDBHandle *handle);
 
-CERTPackageType
-CERT_CertPackageType(SECItem *package, SECItem *certitem);
-
 CERTCertificatePolicies *
 CERT_DecodeCertificatePoliciesExtension(SECItem *extnValue);
 
 void
 CERT_DestroyCertificatePoliciesExtension(CERTCertificatePolicies *policies);
 
 CERTCertificatePolicyMappings *
 CERT_DecodePolicyMappingsExtension(SECItem *encodedCertPolicyMaps);
@@ -1158,25 +1173,25 @@ CERT_DecodePolicyConstraintsExtension(
 
 SECStatus CERT_DecodeInhibitAnyExtension
     (CERTCertificateInhibitAny *decodedValue, SECItem *extnValue);
 
 CERTUserNotice *
 CERT_DecodeUserNotice(SECItem *noticeItem);
 
 extern CERTGeneralName *
-CERT_DecodeAltNameExtension(PRArenaPool *reqArena, SECItem *EncodedAltName);
+CERT_DecodeAltNameExtension(PLArenaPool *reqArena, SECItem *EncodedAltName);
 
 extern CERTNameConstraints *
-CERT_DecodeNameConstraintsExtension(PRArenaPool *arena, 
+CERT_DecodeNameConstraintsExtension(PLArenaPool *arena, 
                                     SECItem *encodedConstraints);
 
 /* returns addr of a NULL termainated array of pointers to CERTAuthInfoAccess */
 extern CERTAuthInfoAccess **
-CERT_DecodeAuthInfoAccessExtension(PRArenaPool *reqArena,
+CERT_DecodeAuthInfoAccessExtension(PLArenaPool *reqArena,
 				   SECItem     *encodedExtension);
 
 extern CERTPrivKeyUsagePeriod *
 CERT_DecodePrivKeyUsagePeriodExtension(PLArenaPool *arena, SECItem *extnValue);
 
 extern CERTGeneralName *
 CERT_GetNextGeneralName(CERTGeneralName *current);
 
@@ -1251,47 +1266,29 @@ PRBool
 CERT_SortCBValidity(CERTCertificate *certa,
 		    CERTCertificate *certb,
 		    void *arg);
 
 SECStatus
 CERT_CheckForEvilCert(CERTCertificate *cert);
 
 CERTGeneralName *
-CERT_GetCertificateNames(CERTCertificate *cert, PRArenaPool *arena);
+CERT_GetCertificateNames(CERTCertificate *cert, PLArenaPool *arena);
 
 char *
-CERT_GetNickName(CERTCertificate   *cert, CERTCertDBHandle *handle, PRArenaPool *nicknameArena);
+CERT_GetNickName(CERTCertificate   *cert, CERTCertDBHandle *handle, PLArenaPool *nicknameArena);
 
 /*
  * Creates or adds to a list of all certs with a give subject name, sorted by
  * validity time, newest first.  Invalid certs are considered older than
  * valid certs. If validOnly is set, do not include invalid certs on list.
  */
 CERTCertList *
 CERT_CreateSubjectCertList(CERTCertList *certList, CERTCertDBHandle *handle,
-			   SECItem *name, int64 sorttime, PRBool validOnly);
-
-/*
- * Creates or adds to a list of all certs with a give nickname, sorted by
- * validity time, newest first.  Invalid certs are considered older than valid
- * certs. If validOnly is set, do not include invalid certs on list.
- */
-CERTCertList *
-CERT_CreateNicknameCertList(CERTCertList *certList, CERTCertDBHandle *handle,
-			    char *nickname, int64 sorttime, PRBool validOnly);
-
-/*
- * Creates or adds to a list of all certs with a give email addr, sorted by
- * validity time, newest first.  Invalid certs are considered older than valid
- * certs. If validOnly is set, do not include invalid certs on list.
- */
-CERTCertList *
-CERT_CreateEmailAddrCertList(CERTCertList *certList, CERTCertDBHandle *handle,
-			     char *emailAddr, int64 sorttime, PRBool validOnly);
+			   SECItem *name, PRTime sorttime, PRBool validOnly);
 
 /*
  * remove certs from a list that don't have keyUsage and certType
  * that match the given usage.
  */
 SECStatus
 CERT_FilterCertListByUsage(CERTCertList *certList, SECCertUsage usage,
 			   PRBool ca);
@@ -1409,17 +1406,17 @@ CERT_ExtractNicknameString(char *namestr
  *	is used.
  * "cert" - the cert to get nickname from
  * "expiredString" - the string to append to the nickname if the cert is
  *		expired.
  * "notYetGoodString" - the string to append to the nickname if the cert is
  *		not yet good.
  */
 char *
-CERT_GetCertNicknameWithValidity(PRArenaPool *arena, CERTCertificate *cert,
+CERT_GetCertNicknameWithValidity(PLArenaPool *arena, CERTCertificate *cert,
 				 char *expiredString, char *notYetGoodString);
 
 /*
  * Return the string representation of a DER encoded distinguished name
  * "dername" - The DER encoded name to convert
  */
 char *
 CERT_DerNameToAscii(SECItem *dername);
@@ -1432,17 +1429,17 @@ CERT_DerNameToAscii(SECItem *dername);
  *	certUsageEmailSigner
  *	certUsageEmailRecipient
  *	certUsageObjectSigner
  */
 
 CERTCertificate *
 CERT_FindMatchingCert(CERTCertDBHandle *handle, SECItem *derName,
 		      CERTCertOwner owner, SECCertUsage usage,
-		      PRBool preferTrusted, int64 validTime, PRBool validOnly);
+		      PRBool preferTrusted, PRTime validTime, PRBool validOnly);
 
 /*
  * Acquire the global lock on the cert database.
  * This lock is currently used for the following operations:
  *	adding or deleting a cert to either the temp or perm databases
  *	converting a temp to perm or perm to temp
  *	changing(maybe just adding?) the trust of a cert
  *	adjusting the reference count of a cert
@@ -1507,99 +1504,99 @@ CERT_UnlockCertTrust(CERTCertificate *ce
 /*
  * Digest the cert's subject public key using the specified algorithm.
  * The necessary storage for the digest data is allocated.  If "fill" is
  * non-null, the data is put there, otherwise a SECItem is allocated.
  * Allocation from "arena" if it is non-null, heap otherwise.  Any problem
  * results in a NULL being returned (and an appropriate error set).
  */ 
 extern SECItem *
-CERT_GetSPKIDigest(PRArenaPool *arena, const CERTCertificate *cert,
+CERT_GetSPKIDigest(PLArenaPool *arena, const CERTCertificate *cert,
                    SECOidTag digestAlg, SECItem *fill);
 
 
 SECStatus CERT_CheckCRL(CERTCertificate* cert, CERTCertificate* issuer,
-                        SECItem* dp, int64 t, void* wincx);
+                        SECItem* dp, PRTime t, void* wincx);
 
 
 /*
  * Add a CERTNameConstraint to the CERTNameConstraint list
  */
 extern CERTNameConstraint *
 CERT_AddNameConstraint(CERTNameConstraint *list, 
 		       CERTNameConstraint *constraint);
 
 /*
  * Allocate space and copy CERTNameConstraint from src to dest.
  * Arena is used to allocate result(if dest eq NULL) and its members
  * SECItem data.
  */
 extern CERTNameConstraint *
-CERT_CopyNameConstraint(PRArenaPool         *arena, 
+CERT_CopyNameConstraint(PLArenaPool         *arena, 
 			CERTNameConstraint  *dest, 
 			CERTNameConstraint  *src);
 
 /*
  * Verify name against all the constraints relevant to that type of
  * the name.
  */
 extern SECStatus
-CERT_CheckNameSpace(PRArenaPool          *arena,
+CERT_CheckNameSpace(PLArenaPool          *arena,
 		    CERTNameConstraints  *constraints,
 		    CERTGeneralName      *currentName);
 
 /*
  * Extract and allocate the name constraints extension from the CA cert.
  */
 extern SECStatus
-CERT_FindNameConstraintsExten(PRArenaPool      *arena,
+CERT_FindNameConstraintsExten(PLArenaPool      *arena,
 			      CERTCertificate  *cert,
 			      CERTNameConstraints **constraints);
 
 /*
  * Initialize a new GERTGeneralName fields (link)
  */
 extern CERTGeneralName *
 CERT_NewGeneralName(PLArenaPool *arena, CERTGeneralNameType type);
 
 /*
  * PKIX extension encoding routines
  */
 extern SECStatus
-CERT_EncodePolicyConstraintsExtension(PRArenaPool *arena,
+CERT_EncodePolicyConstraintsExtension(PLArenaPool *arena,
                                       CERTCertificatePolicyConstraints *constr,
                                       SECItem *dest);
 extern SECStatus
-CERT_EncodeInhibitAnyExtension(PRArenaPool *arena,
+CERT_EncodeInhibitAnyExtension(PLArenaPool *arena,
                                CERTCertificateInhibitAny *inhibitAny,
                                SECItem *dest);
 extern SECStatus
-CERT_EncodePolicyMappingExtension(PRArenaPool *arena,
+CERT_EncodePolicyMappingExtension(PLArenaPool *arena,
                                   CERTCertificatePolicyMappings *maps,
                                   SECItem *dest);
 
-extern SECStatus CERT_EncodeInfoAccessExtension(PRArenaPool *arena,
+extern SECStatus CERT_EncodeInfoAccessExtension(PLArenaPool *arena,
                                                     CERTAuthInfoAccess **info,
                                                     SECItem *dest);
 extern SECStatus
-CERT_EncodeUserNotice(PRArenaPool *arena,
+CERT_EncodeUserNotice(PLArenaPool *arena,
                       CERTUserNotice *notice,
                       SECItem *dest);
 
 extern SECStatus
-CERT_EncodeDisplayText(PRArenaPool *arena,
+CERT_EncodeDisplayText(PLArenaPool *arena,
                        SECItem *text,
                        SECItem *dest);
 
 extern SECStatus
-CERT_EncodeCertPoliciesExtension(PRArenaPool *arena,
+CERT_EncodeCertPoliciesExtension(PLArenaPool *arena,
                                  CERTPolicyInfo **info,
                                  SECItem *dest);
 extern SECStatus
-CERT_EncodeNoticeReference(PRArenaPool *arena,
+CERT_EncodeNoticeReference(PLArenaPool *arena,
                            CERTNoticeReference *reference,
                            SECItem *dest);
 
 /*
  * Returns a pointer to a static structure.
  */
 extern const CERTRevocationFlags*
 CERT_GetPKIXVerifyNistRevocationPolicy();
--- a/security/nss/lib/certdb/certdb.c
+++ b/security/nss/lib/certdb/certdb.c
@@ -33,17 +33,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Certificate handling code
  *
- * $Id: certdb.c,v 1.91 2008/03/15 02:15:34 alexei.volkov.bugs%sun.com Exp $
+ * $Id: certdb.c,v 1.92 2008/05/16 03:38:39 nelson%bolyard.com Exp $
  */
 
 #include "nssilock.h"
 #include "prmon.h"
 #include "prtime.h"
 #include "cert.h"
 #include "certi.h"
 #include "secder.h"
@@ -1484,55 +1484,55 @@ cert_VerifySubjectAltName(CERTCertificat
     PRArenaPool *     arena          = NULL;
     CERTGeneralName * nameList       = NULL;
     CERTGeneralName * current;
     char *            cn;
     int               cnBufLen;
     unsigned int      hnLen;
     int               DNSextCount    = 0;
     int               IPextCount     = 0;
-    PRBool            isIPaddr;
+    PRBool            isIPaddr       = PR_FALSE;
     SECStatus         rv             = SECFailure;
     SECItem           subAltName;
     PRNetAddr         netAddr;
     char              cnbuf[128];
 
     subAltName.data = NULL;
     hnLen    = strlen(hn);
     cn       = cnbuf;
     cnBufLen = sizeof cnbuf;
 
     rv = CERT_FindCertExtension(cert, SEC_OID_X509_SUBJECT_ALT_NAME, 
 				&subAltName);
     if (rv != SECSuccess) {
-	goto finish;
+	goto fail;
     }
     isIPaddr = (PR_SUCCESS == PR_StringToNetAddr(hn, &netAddr));
     rv = SECFailure;
     arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
     if (!arena) 
-	goto finish;
+	goto fail;
 
     nameList = current = CERT_DecodeAltNameExtension(arena, &subAltName);
     if (!current)
-    	goto finish;
+    	goto fail;
 
     do {
 	switch (current->type) {
 	case certDNSName:
 	    if (!isIPaddr) {
 		/* DNS name current->name.other.data is not null terminated.
 		** so must copy it.  
 		*/
 		int cnLen = current->name.other.len;
 		if (cnLen + 1 > cnBufLen) {
 		    cnBufLen = cnLen + 1;
 		    cn = (char *)PORT_ArenaAlloc(arena, cnBufLen);
 		    if (!cn)
-			goto finish;
+			goto fail;
 		}
 		PORT_Memcpy(cn, current->name.other.data, cnLen);
 		cn[cnLen] = 0;
 		rv = cert_TestHostName(cn ,hn);
 		if (rv == SECSuccess)
 		    goto finish;
 	    }
 	    DNSextCount++;
@@ -1574,17 +1574,19 @@ cert_VerifySubjectAltName(CERTCertificat
 	    IPextCount++;
 	    break;
 	default:
 	    break;
 	}
 	current = CERT_GetNextGeneralName(current);
     } while (current != nameList);
 
-    if ((!isIPaddr && !DNSextCount) || (isIPaddr && !IPextCount)) {
+fail:
+
+    if (!(isIPaddr ? IPextCount : DNSextCount)) {
 	/* no relevant value in the extension was found. */
 	PORT_SetError(SEC_ERROR_EXTENSION_NOT_FOUND);
     } else {
 	PORT_SetError(SSL_ERROR_BAD_CERT_DOMAIN);
     }
     rv = SECFailure;
 
 finish:
--- a/security/nss/lib/certdb/certdb.h
+++ b/security/nss/lib/certdb/certdb.h
@@ -87,85 +87,11 @@ CERT_AddTempCertToPerm(CERTCertificate *
 SECStatus SEC_DeletePermCertificate(CERTCertificate *cert);
 
 PRBool
 SEC_CrlIsNewer(CERTCrl *inNew, CERTCrl *old);
 
 SECCertTimeValidity
 SEC_CheckCrlTimes(CERTCrl *crl, PRTime t);
 
-#ifdef notdef
-/*
-** Add a DER encoded certificate to the permanent database.
-**	"derCert" is the DER encoded certificate.
-**	"nickname" is the nickname to use for the cert
-**	"trust" is the trust parameters for the cert
-*/
-SECStatus SEC_AddPermCertificate(PCERTCertDBHandle *handle, SECItem *derCert,
-				char *nickname, PCERTCertTrust *trust);
-
-certDBEntryCert *
-SEC_FindPermCertByKey(PCERTCertDBHandle *handle, SECItem *certKey);
-
-certDBEntryCert
-*SEC_FindPermCertByName(PCERTCertDBHandle *handle, SECItem *name);
-
-SECStatus SEC_OpenPermCertDB(PCERTCertDBHandle *handle,
-			     PRBool readOnly,
-			     PCERTDBNameFunc namecb,
-			     void *cbarg);
-
-
-typedef SECStatus (PR_CALLBACK * PermCertCallback)(PCERTCertificate *cert,
-                                                   SECItem *k, void *pdata);
-/*
-** Traverse the entire permanent database, and pass the certs off to a
-** user supplied function.
-**	"certfunc" is the user function to call for each certificate
-**	"udata" is the user's data, which is passed through to "certfunc"
-*/
-SECStatus
-PCERT_TraversePermCerts(PCERTCertDBHandle *handle,
-		      PermCertCallback certfunc,
-		      void *udata );
-
-SECStatus
-SEC_AddTempNickname(PCERTCertDBHandle *handle, char *nickname, SECItem *certKey);
-
-SECStatus
-SEC_DeleteTempNickname(PCERTCertDBHandle *handle, char *nickname);
-
-
-PRBool
-SEC_CertDBKeyConflict(SECItem *derCert, PCERTCertDBHandle *handle);
-
-SECStatus
-SEC_GetCrlTimes(PCERTCrl *dates, PRTime *notBefore, PRTime *notAfter);
-
-PCERTSignedCrl *
-SEC_AddPermCrlToTemp(PCERTCertDBHandle *handle, certDBEntryRevocation *entry);
-
-SECStatus
-SEC_DeleteTempCrl(PCERTSignedCrl *crl);
-
-
-SECStatus
-SEC_CheckKRL(PCERTCertDBHandle *handle,SECKEYLowPublicKey *key,
-	     PCERTCertificate *rootCert, int64 t, void *wincx);
-
-SECStatus
-SEC_CheckCRL(PCERTCertDBHandle *handle,PCERTCertificate *cert,
-	     PCERTCertificate *caCert, int64 t, void *wincx);
-
-SECStatus
-SEC_CrlReplaceUrl(PCERTSignedCrl *crl,char *url);
-
-/* Compare two certificate validity structures and return which cert should be
-** preferred, based first on newer notAfter, then on newer notBefore.
-*/
-CERTCompareValidityStatus
-CERT_CompareValidityTimes(CERTValidity* val_a, CERTValidity* val_b);
-
-#endif
-
 SEC_END_PROTOS
 
 #endif /* _CERTDB_H_ */
--- a/security/nss/lib/certdb/certi.h
+++ b/security/nss/lib/certdb/certi.h
@@ -31,17 +31,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 /*
  * certi.h - private data structures for the certificate library
  *
- * $Id: certi.h,v 1.25 2008/03/25 22:13:25 alexei.volkov.bugs%sun.com Exp $
+ * $Id: certi.h,v 1.26 2008/06/18 01:00:40 wtc%google.com Exp $
  */
 #ifndef _CERTI_H_
 #define _CERTI_H_
 
 #include "certt.h"
 #include "nssrwlkt.h"
 
 /*
@@ -277,17 +277,17 @@ SECStatus DPCache_GetCRLEntry(CRLDPCache
 void CERT_MapStanError();
 
 /* Interface function for libpkix cert validation engine:
  * cert_verify wrapper. */
 SECStatus
 cert_VerifyCertChainPkix(CERTCertificate *cert,
                          PRBool checkSig,
                          SECCertUsage     requiredUsage,
-                         PRUint64         time,
+                         PRTime           time,
                          void            *wincx,
                          CERTVerifyLog   *log,
                          PRBool          *sigError,
                          PRBool          *revoked);
 
 SECStatus cert_InitLocks(void);
 
 SECStatus cert_DestroyLocks(void);
--- a/security/nss/lib/certdb/certt.h
+++ b/security/nss/lib/certdb/certt.h
@@ -31,17 +31,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 /*
  * certt.h - public data structures for the certificate library
  *
- * $Id: certt.h,v 1.44 2008/03/27 21:56:24 alexei.volkov.bugs%sun.com Exp $
+ * $Id: certt.h,v 1.47 2008/06/20 16:57:03 nelson%bolyard.com Exp $
  */
 #ifndef _CERTT_H_
 #define _CERTT_H_
 
 #include "prclist.h"
 #include "pkcs11t.h"
 #include "seccomon.h"
 #include "secmodt.h"
@@ -118,25 +118,25 @@ struct CERTAVAStr {
 struct CERTRDNStr {
     CERTAVA **avas;
 };
 
 /*
 ** An X.500 name object
 */
 struct CERTNameStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTRDN **rdns;
 };
 
 /*
 ** An X.509 validity object
 */
 struct CERTValidityStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     SECItem notBefore;
     SECItem notAfter;
 };
 
 /*
  * A serial number and issuer name, which is used as a database key
  */
 struct CERTCertKeyStr {
@@ -153,17 +153,17 @@ struct CERTSignedDataStr {
     SECAlgorithmID signatureAlgorithm;
     SECItem signature;
 };
 
 /*
 ** An X.509 subject-public-key-info object
 */
 struct CERTSubjectPublicKeyInfoStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     SECAlgorithmID algorithm;
     SECItem subjectPublicKey;
 };
 
 struct CERTPublicKeyAndChallengeStr {
     SECItem spki;
     SECItem challenge;
 };
@@ -201,17 +201,17 @@ struct CERTCertExtensionStr {
 struct CERTSubjectNodeStr {
     struct CERTSubjectNodeStr *next;
     struct CERTSubjectNodeStr *prev;
     SECItem certKey;
     SECItem keyID;
 };
 
 struct CERTSubjectListStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     int ncerts;
     char *emailAddr;
     CERTSubjectNode *head;
     CERTSubjectNode *tail; /* do we need tail? */
     void *entry;
 };
 
 /*
@@ -219,17 +219,17 @@ struct CERTSubjectListStr {
 */
 struct CERTCertificateStr {
     /* the arena is used to allocate any data structures that have the same
      * lifetime as the cert.  This is all stuff that hangs off of the cert
      * structure, and is all freed at the same time.  I is used when the
      * cert is decoded, destroyed, and at some times when it changes
      * state
      */
-    PRArenaPool *arena;
+    PLArenaPool *arena;
 
     /* The following fields are static after the cert has been decoded */
     char *subjectName;
     char *issuerName;
     CERTSignedData signatureWrap;	/* XXX */
     SECItem derCert;			/* original DER for the cert */
     SECItem derIssuer;			/* DER for issuer name */
     SECItem derSubject;			/* DER for subject name */
@@ -322,17 +322,17 @@ struct CERTCertificateStr {
  * used to identify class of cert in mime stream code
  */
 #define SEC_CERT_CLASS_CA	1
 #define SEC_CERT_CLASS_SERVER	2
 #define SEC_CERT_CLASS_USER	3
 #define SEC_CERT_CLASS_EMAIL	4
 
 struct CERTDERCertsStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     int numcerts;
     SECItem *rawCerts;
 };
 
 /*
 ** A PKCS ? Attribute
 ** XXX this is duplicated through out the code, it *should* be moved
 ** to a central location.  Where would be appropriate?
@@ -341,58 +341,58 @@ struct CERTAttributeStr {
     SECItem attrType;
     SECItem **attrValue;
 };
 
 /*
 ** A PKCS#10 certificate-request object (the unsigned form)
 */
 struct CERTCertificateRequestStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     SECItem version;
     CERTName subject;
     CERTSubjectPublicKeyInfo subjectPublicKeyInfo;
     CERTAttribute **attributes;
 };
 #define SEC_CERTIFICATE_REQUEST_VERSION		0	/* what we *create* */
 
 
 /*
 ** A certificate list object.
 */
 struct CERTCertificateListStr {
     SECItem *certs;
     int len;					/* number of certs */
-    PRArenaPool *arena;
+    PLArenaPool *arena;
 };
 
 struct CERTCertListNodeStr {
     PRCList links;
     CERTCertificate *cert;
     void *appData;
 };
 
 struct CERTCertListStr {
     PRCList list;
-    PRArenaPool *arena;
+    PLArenaPool *arena;
 };
 
 #define CERT_LIST_HEAD(l) ((CERTCertListNode *)PR_LIST_HEAD(&l->list))
 #define CERT_LIST_NEXT(n) ((CERTCertListNode *)n->links.next)
 #define CERT_LIST_END(n,l) (((void *)n) == ((void *)&l->list))
 #define CERT_LIST_EMPTY(l) CERT_LIST_END(CERT_LIST_HEAD(l), l)
 
 struct CERTCrlEntryStr {
     SECItem serialNumber;
     SECItem revocationDate;
     CERTCertExtension **extensions;    
 };
 
 struct CERTCrlStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     SECItem version;
     SECAlgorithmID signatureAlg;
     SECItem derName;
     CERTName name;
     SECItem lastUpdate;
     SECItem nextUpdate;				/* optional for x.509 CRL  */
     CERTCrlEntry **entries;
     CERTCertExtension **extensions;    
@@ -403,17 +403,17 @@ struct CERTCrlKeyStr {
     SECItem derName;
     SECItem dummy;			/* The decoder can not skip a primitive,
 					   this serves as a place holder for the
 					   decoder to finish its task only
 					*/
 };
 
 struct CERTSignedCrlStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTCrl crl;
     void *reserved1;
     PRBool reserved2;
     PRBool isperm;
     PRBool istemp;
     int referenceCount;
     CERTCertDBHandle *dbhandle;
     CERTSignedData signatureWrap;	/* XXX */
@@ -421,17 +421,17 @@ struct CERTSignedCrlStr {
     SECItem *derCrl;
     PK11SlotInfo *slot;
     CK_OBJECT_HANDLE pkcs11ID;
     void* opaque; /* do not touch */
 };
 
 
 struct CERTCrlHeadNodeStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTCertDBHandle *dbhandle;
     CERTCrlNode *first;
     CERTCrlNode *last;
 };
 
 
 struct CERTCrlNodeStr {
     CERTCrlNode *next;
@@ -439,17 +439,17 @@ struct CERTCrlNodeStr {
     CERTSignedCrl *crl;
 };
 
 
 /*
  * Array of X.500 Distinguished Names
  */
 struct CERTDistNamesStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     int nnames;
     SECItem  *names;
     void *head; /* private */
 };
 
 
 #define NS_CERT_TYPE_SSL_CLIENT		(0x80)	/* bit 0 */
 #define NS_CERT_TYPE_SSL_SERVER		(0x40)  /* bit 1 */
@@ -546,17 +546,17 @@ typedef enum CERTCompareValidityStatusEn
 
 /* these are values for the what argument below */
 #define SEC_CERT_NICKNAMES_ALL		1
 #define SEC_CERT_NICKNAMES_USER		2
 #define SEC_CERT_NICKNAMES_SERVER	3
 #define SEC_CERT_NICKNAMES_CA		4
 
 struct CERTCertNicknamesStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     void *head;
     int numnicknames;
     char **nicknames;
     int what;
     int totallen;
 };
 
 struct CERTIssuerAndSNStr {
@@ -672,17 +672,17 @@ struct CERTGeneralNameStr {
 	SECItem other;                  /* the rest of the name forms */
     }name;
     SECItem derDirectoryName;		/* this is saved to simplify directory name
 					   comparison */
     PRCList l;
 };
 
 struct CERTGeneralNameListStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTGeneralName *name;
     int refCount;
     int len;
     PZLock *lock;
 };
 
 struct CERTNameConstraintStr {
     CERTGeneralName  name;
@@ -700,17 +700,17 @@ struct CERTNameConstraintsStr {
     SECItem             **DERExcluded;
 };
 
 
 /* Private Key Usage Period extension struct. */
 struct CERTPrivKeyUsagePeriodStr {
     SECItem notBefore;
     SECItem notAfter;
-    PRArenaPool *arena;
+    PLArenaPool *arena;
 };
 
 /* X.509 v3 Authority Key Identifier extension.  For the authority certificate
    issuer field, we only support URI now.
  */
 struct CERTAuthKeyIDStr {
     SECItem keyID;			/* unique key identifier */
     CERTGeneralName *authCertIssuer;	/* CA's issuer name.  End with a NULL */
@@ -764,32 +764,32 @@ struct CERTVerifyLogNodeStr {
     unsigned int depth;		/* how far up the chain are we */
     void *arg;			/* error specific argument */
     struct CERTVerifyLogNodeStr *next; /* next in the list */
     struct CERTVerifyLogNodeStr *prev; /* next in the list */
 };
 
 
 struct CERTVerifyLogStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     unsigned int count;
     struct CERTVerifyLogNodeStr *head;
     struct CERTVerifyLogNodeStr *tail;
 };
 
 
 struct CERTOKDomainNameStr {
     CERTOKDomainName *next;
     char              name[1]; /* actual length may be longer. */
 };
 
 
 typedef SECStatus (PR_CALLBACK *CERTStatusChecker) (CERTCertDBHandle *handle,
 						    CERTCertificate *cert,
-						    int64 time,
+						    PRTime time,
 						    void *pwArg);
 
 typedef SECStatus (PR_CALLBACK *CERTStatusDestroy) (CERTStatusConfig *handle);
 
 struct CERTStatusConfigStr {
     CERTStatusChecker statusChecker;	/* NULL means no checking enabled */
     CERTStatusDestroy statusDestroy;	/* enabled or no, will clean up */
     void *statusContext;		/* cx specific to checking protocol */
@@ -828,47 +828,47 @@ typedef struct {
 
 typedef struct {
     SECOidTag oid;
     SECItem policyID;
     CERTPolicyQualifier **policyQualifiers;
 } CERTPolicyInfo;
 
 typedef struct {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTPolicyInfo **policyInfos;
 } CERTCertificatePolicies;
 
 typedef struct {
     SECItem organization;
     SECItem **noticeNumbers;
 } CERTNoticeReference;
 
 typedef struct {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTNoticeReference noticeReference;
     SECItem derNoticeReference;
     SECItem displayText;
 } CERTUserNotice;
 
 typedef struct {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     SECItem **oids;
 } CERTOidSequence;
 
 /*
  * these types are for the PKIX Policy Mappings extension
  */
 typedef struct {
     SECItem issuerDomainPolicy;
     SECItem subjectDomainPolicy;
 } CERTPolicyMap;
 
 typedef struct {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     CERTPolicyMap **policyMaps;
 } CERTCertificatePolicyMappings;
 
 /*
  * these types are for the PKIX inhibitAnyPolicy extension
  */
 typedef struct {
     SECItem inhibitAnySkipCerts;
@@ -934,20 +934,23 @@ typedef enum {
    cert_pi_date            = 8, /* validate certificate is valid as of date 
 				 * specified in value.scalar.time. A special 
 				 * value '0' indicates 'now'. default is '0' */
    cert_pi_revocationFlags = 9, /* Specify what revocation checking to do.
 				 * See CERT_REV_FLAG_* macros below
 				 * Set in value.pointer.revocation */
    cert_pi_certStores      = 10,/* Bitmask of Cert Store flags (see below)
 				 * Set in value.scalar.ui */
-   cert_pi_trustAnchors    = 11,/* specify the list of trusted roots to 
+   cert_pi_trustAnchors    = 11,/* Specify the list of trusted roots to 
 				 * validate against. If the list in NULL all
 				 * default trusted roots are used.
 				 * Specified in value.pointer.chain */
+   cert_pi_useAIACertFetch = 12, /* Enables cert fetching using AIA extension.
+				 * Default is off.
+                                     * Value is in value.scalar.b */
    cert_pi_max                  /* SPECIAL: signifies maximum allowed value,
 				 *  can increase in future releases */
 } CERTValParamInType;
 
 /*
  * for all out parameters:
  *  out parameters are only returned if the caller asks for them in
  *  the CERTValOutParam array. Caller is responsible for the CERTValOutParam
@@ -1223,16 +1226,26 @@ typedef struct {
 } CERTValInParam;
 
 typedef struct {
     CERTValParamOutType type;
     CERTValParamOutValue value;
 } CERTValOutParam;
 
 /*
+ * Levels of standards conformance strictness for CERT_NameToAsciiInvertible
+ */
+typedef enum CertStrictnessLevels {
+    CERT_N2A_READABLE   =  0, /* maximum human readability */
+    CERT_N2A_STRICT     = 10, /* strict RFC compliance    */
+    CERT_N2A_INVERTIBLE = 20  /* maximum invertibility,
+                                 all DirectoryStrings encoded in hex */
+} CertStrictnessLevel;
+
+/*
  * policy flag defines
  */
 #define CERT_POLICY_FLAG_NO_MAPPING    1
 #define CERT_POLICY_FLAG_EXPLICIT      2
 #define CERT_POLICY_FLAG_NO_ANY        4
 
 /*
  * CertStore flags
--- a/security/nss/lib/certdb/secname.c
+++ b/security/nss/lib/certdb/secname.c
@@ -200,17 +200,16 @@ SetupAVAValue(PRArenaPool *arena, int va
 }
 
 CERTAVA *
 CERT_CreateAVAFromRaw(PRArenaPool *pool, const SECItem * OID, 
                       const SECItem * value)
 {
     CERTAVA *ava;
     int rv;
-    unsigned maxLen;
 
     ava = PORT_ArenaZNew(pool, CERTAVA);
     if (ava) {
 	rv = SECITEM_CopyItem(pool, &ava->type, OID);
 	if (rv) 
 	    return NULL;
 
 	rv = SECITEM_CopyItem(pool, &ava->value, value);
--- a/security/nss/lib/certdb/stanpcertdb.c
+++ b/security/nss/lib/certdb/stanpcertdb.c
@@ -303,17 +303,16 @@ SECStatus
     }
     if (!stanNick && nickname) {
 	stanNick = nssUTF8_Duplicate((NSSUTF8 *)nickname, c->object.arena);
     }
     /* Delete the temp instance */
     nssCertificateStore_Lock(context->certStore, &lockTrace);
     nssCertificateStore_RemoveCertLOCKED(context->certStore, c);
     nssCertificateStore_Unlock(context->certStore, &lockTrace, &unlockTrace);
-    nssCertificateStore_Check(&lockTrace, &unlockTrace);
     c->object.cryptoContext = NULL;
     /* Import the perm instance onto the internal token */
     slot = PK11_GetInternalKeySlot();
     internal = PK11Slot_GetNSSToken(slot);
     permInstance = nssToken_ImportCertificate(internal, NULL,
                                               NSSCertificateType_PKIX,
                                               &c->id,
                                               stanNick,
@@ -975,55 +974,55 @@ CERT_FindSMimeProfile(CERTCertificate *c
 	PK11_FindSMimeProfile(&slot, cert->emailAddr, &cert->derSubject, NULL);
     if (slot) {
     	PK11_FreeSlot(slot);
     }
     return rvItem;
 }
 
 /*
- * depricated functions that are now just stubs.
+ * deprecated functions that are now just stubs.
  */
 /*
  * Close the database
  */
 void
 __CERT_ClosePermCertDB(CERTCertDBHandle *handle)
 {
-    PORT_Assert("CERT_ClosePermCertDB is Depricated" == NULL);
+    PORT_Assert("CERT_ClosePermCertDB is Deprecated" == NULL);
     return;
 }
 
 SECStatus
 CERT_OpenCertDBFilename(CERTCertDBHandle *handle, char *certdbname,
                         PRBool readOnly)
 {
-    PORT_Assert("CERT_OpenCertDBFilename is Depricated" == NULL);
+    PORT_Assert("CERT_OpenCertDBFilename is Deprecated" == NULL);
     return SECFailure;
 }
 
 SECItem *
 SECKEY_HashPassword(char *pw, SECItem *salt)
 {
-    PORT_Assert("SECKEY_HashPassword is Depricated" == NULL);
+    PORT_Assert("SECKEY_HashPassword is Deprecated" == NULL);
     return NULL;
 }
 
 SECStatus
 __CERT_TraversePermCertsForSubject(CERTCertDBHandle *handle,
                                  SECItem *derSubject,
                                  void *cb, void *cbarg)
 {
-    PORT_Assert("CERT_TraversePermCertsForSubject is Depricated" == NULL);
+    PORT_Assert("CERT_TraversePermCertsForSubject is Deprecated" == NULL);
     return SECFailure;
 }
 
 
 SECStatus
 __CERT_TraversePermCertsForNickname(CERTCertDBHandle *handle, char *nickname,
                                   void *cb, void *cbarg)
 {
-    PORT_Assert("CERT_TraversePermCertsForNickname is Depricated" == NULL);
+    PORT_Assert("CERT_TraversePermCertsForNickname is Deprecated" == NULL);
     return SECFailure;
 }
 
 
 
--- a/security/nss/lib/certdb/xconst.h
+++ b/security/nss/lib/certdb/xconst.h
@@ -52,20 +52,16 @@ CERT_EncodePrivateKeyUsagePeriod(PRArena
 				SECItem *encodedValue);
 
 extern SECStatus
 CERT_EncodeNameConstraintsExtension(PRArenaPool *arena, 
                                     CERTNameConstraints  *value,
 			            SECItem *encodedValue);
 
 extern SECStatus 
-CERT_EncodeSubjectKeyID(PRArenaPool *arena, const SECItem* srcString,
-                        SECItem *encodedValue);
-
-extern SECStatus 
 CERT_EncodeIA5TypeExtension(PRArenaPool *arena, char *value, 
                             SECItem *encodedValue);
 
 SECStatus
 cert_EncodeAuthInfoAccessExtension(PRArenaPool *arena,
 				   CERTAuthInfoAccess **info,
 				   SECItem *dest);
 SEC_END_PROTOS
--- a/security/nss/lib/certhigh/certvfy.c
+++ b/security/nss/lib/certhigh/certvfy.c
@@ -890,17 +890,16 @@ CERT_VerifyCACertForUsage(CERTCertDBHand
 		PRBool checkSig, SECCertUsage certUsage, int64 t,
 		void *wincx, CERTVerifyLog *log)
 {
     SECTrustType trustType;
     CERTBasicConstraints basicConstraint;
     PRBool isca;
     PRBool validCAOverride = PR_FALSE;
     SECStatus rv;
-    SECComparison rvCompare;
     SECStatus rvFinal = SECSuccess;
     int flags;
     unsigned int caCertType;
     unsigned int requiredCAKeyUsage;
     unsigned int requiredFlags;
     CERTCertificate *issuerCert;
 
 
--- a/security/nss/lib/certhigh/certvfypkix.c
+++ b/security/nss/lib/certhigh/certvfypkix.c
@@ -79,17 +79,16 @@ cert_PrintCertChain(PKIX_List *pkixCertC
 
 extern PKIX_UInt32
 pkix_pl_lifecycle_ObjectLeakCheck(int *);
 
 extern SECStatus
 pkix_pl_lifecycle_ObjectTableUpdate(int *objCountTable);
 
 PRInt32 parallelFnInvocationCount;
-
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
 
 static PRBool usePKIXValidationEngine = PR_FALSE;
 
 /*
  * FUNCTION: CERT_SetUsePKIXForValidation
  * DESCRIPTION:
@@ -841,17 +840,17 @@ cert_PkixErrorToNssCode(
     /* Loop until we find at least one error with non-null
      * plErr code, that is going to be nss error code. */
     while (errPtr) {
         if (errPtr->plErr && !nssErr) {
             nssErr = errPtr->plErr;
             if (!pkixLog) break;
         }
         if (pkixLog) {
-            PR_LOG(pkixLog, 1, ("Error at level %d: %s\n", errLevel,
+            PR_LOG(pkixLog, 2, ("Error at level %d: %s\n", errLevel,
                                 PKIX_ErrorText[errPtr->errCode]));
         }
         errPtr = errPtr->cause;
         errLevel += 1; 
     }
     PORT_Assert(nssErr);
     if (!nssErr) {
         *pNssErr = SEC_ERROR_LIBPKIX_INTERNAL;
@@ -1015,26 +1014,25 @@ cert_GetBuildResults(
 
     if (error) {
         SECErrorCodes nssErrorCode = 0;
 #ifdef DEBUG_volkov        
         char *temp = pkix_Error2ASCII(error, plContext);
         fprintf(stderr, "BUILD ERROR:\n%s\n", temp);
         PKIX_PL_Free(temp, NULL);
 #endif /* DEBUG */
-        cert_PkixErrorToNssCode(error, &nssErrorCode, plContext);
-        PORT_SetError(nssErrorCode);
-        
         if (verifyNode) {
             PKIX_Error *tmpError =
                 cert_GetLogFromVerifyNode(log, verifyNode, plContext);
             if (tmpError) {
                 PKIX_PL_Object_DecRef((PKIX_PL_Object *)tmpError, plContext);
             }
         }
+        cert_PkixErrorToNssCode(error, &nssErrorCode, plContext);
+        PORT_SetError(nssErrorCode);
         goto cleanup;
     }
 
     if (pvalidChain) {
         PKIX_CHECK(
             PKIX_BuildResult_GetCertChain(buildResult, &pkixCertChain,
                                           plContext),
             PKIX_BUILDRESULTGETCERTCHAINFAILED);
@@ -1142,17 +1140,17 @@ cleanup:
  * RETURNS:
  *  SECFailure is chain building process has failed. SECSuccess otherwise.
  */
 SECStatus
 cert_VerifyCertChainPkix(
     CERTCertificate *cert,
     PRBool           checkSig,
     SECCertUsage     requiredUsage,
-    PRUint64         time,
+    PRTime           time,
     void            *wincx,
     CERTVerifyLog   *log,
     PRBool          *pSigerror,
     PRBool          *pRevoked)
 {
     PKIX_ProcessingParams *procParams = NULL;
     PKIX_BuildResult      *result = NULL;
     PKIX_VerifyNode       *verifyNode = NULL;
@@ -1166,16 +1164,17 @@ cert_VerifyCertChainPkix(
 #endif /* DEBUG */
 
 #ifdef PKIX_OBJECT_LEAK_TEST
     int  leakedObjNum = 0;
     int  memLeakLoopCount = 0;
     int  objCountTable[PKIX_NUMTYPES]; 
     int  fnInvLocalCount = 0;
 
+    testStartFnStackPosition = 2;
     fnStackNameArr[0] = "cert_VerifyCertChainPkix";
     fnStackInvCountArr[0] = 0;
     PKIX_Boolean abortOnLeak = 
         (PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") == NULL) ?
                                                    PKIX_FALSE : PKIX_TRUE;
     runningLeakTest = PKIX_TRUE;
 
     /* Prevent multi-threaded run of object leak test */
@@ -1195,17 +1194,17 @@ do {
 #endif /* DEBUG */
     errorGenerated = PKIX_FALSE;
     stackPosition = 0;
 
     if (leakedObjNum) {
         pkix_pl_lifecycle_ObjectTableUpdate(objCountTable); 
     }
 
-    PR_LOG(pkixLog, 1, ("Memory leak test: Loop %d\n", memLeakLoopCount));
+    PR_LOG(pkixLog, 1, ("Memory leak test: Loop %d\n", memLeakLoopCount++));
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
     error =
         cert_CreatePkixProcessingParams(cert, checkSig, time, wincx,
                                         PR_FALSE/*use arena*/,
 #ifdef DEBUG_volkov
                                         /* If in DEBUG_volkov, then enable OCSP
                                          * check for all certs in the chain
@@ -1271,16 +1270,22 @@ cleanup:
     if (plContext) {
         PKIX_PL_NssContext_Destroy(plContext);
     }
 
 #ifdef PKIX_OBJECT_LEAK_TEST
     leakedObjNum =
         pkix_pl_lifecycle_ObjectLeakCheck(leakedObjNum ? objCountTable : NULL);
     
+    if (pkixLog && leakedObjNum) {
+        PR_LOG(pkixLog, 1, ("The generated error caused an object leaks. "
+                            "Stack %s\n", errorFnStackString));
+    }
+    PR_Free(errorFnStackString);
+    errorFnStackString = NULL;
     if (abortOnLeak) {
         PORT_Assert(leakedObjNum == 0);
     }
 
 } while (errorGenerated);
 
     runningLeakTest = PKIX_FALSE; 
     PR_AtomicDecrement(&parallelFnInvocationCount);
@@ -1734,16 +1739,23 @@ cert_pkixSetParam(PKIX_ProcessingParams 
                 PKIX_PL_Object_DecRef((PKIX_PL_Object *)certPkix, plContext);
                 certPkix = NULL;
             }
             error =
                 PKIX_ProcessingParams_SetTrustAnchors(procParams, certListPkix,
                                                       plContext);
             break;
 
+        case cert_pi_useAIACertFetch:
+            error =
+                PKIX_ProcessingParams_SetUseAIAForCertFetching(procParams,
+                                     (PRBool)(param->value.scalar.b != 0),
+                                                               plContext);
+            break;
+            
         default:
             PORT_SetError(errCode);
             r = SECFailure;
     }
 
     if (policyOIDList != NULL)
         PKIX_PL_Object_DecRef((PKIX_PL_Object *)policyOIDList, plContext);
 
@@ -1789,16 +1801,20 @@ cert_pkixDestroyValOutParam(CERTValOutPa
             }
             break;
 
         case cert_po_certList:
             if (i->value.pointer.chain) {
                 CERT_DestroyCertList(i->value.pointer.chain);
                 i->value.pointer.chain = NULL;
             }
+            break;
+
+        default:
+            break;
         }
     }
 }
 
 static PRUint64 certRev_NSS_3_11_Ocsp_Enabled_Soft_Policy_LeafFlags[2] = {
   /* crl */
   CERT_REV_M_TEST_USING_THIS_METHOD 
   | CERT_REV_M_FORBID_NETWORK_FETCHING
@@ -2035,20 +2051,21 @@ SECStatus CERT_PKIXVerifyCert(
 
     void *plContext = NULL;
 
 #ifdef PKIX_OBJECT_LEAK_TEST
     int  leakedObjNum = 0;
     int  memLeakLoopCount = 0;
     int  objCountTable[PKIX_NUMTYPES];
     int  fnInvLocalCount = 0;
+    testStartFnStackPosition = 1;
     fnStackNameArr[0] = "CERT_PKIXVerifyCert";
     fnStackInvCountArr[0] = 0;
     PKIX_Boolean abortOnLeak = 
-        PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") ?
+        (PR_GetEnv("PKIX_OBJECT_LEAK_TEST_ABORT_ON_LEAK") == NULL) ?
                                                    PKIX_FALSE : PKIX_TRUE;
     runningLeakTest = PKIX_TRUE;
 
     /* Prevent multi-threaded run of object leak test */
     fnInvLocalCount = PR_AtomicIncrement(&parallelFnInvocationCount);
     PORT_Assert(fnInvLocalCount == 1);
 
 do {
@@ -2056,28 +2073,30 @@ do {
     error = NULL;
     procParams = NULL;
     buildResult = NULL;
     nbioContext = NULL;  /* for non-blocking IO */
     buildState = NULL;   /* for non-blocking IO */
     certSelector = NULL;
     certStores = NULL;
     valResult = NULL;
+    verifyNode = NULL;
     trustAnchor = NULL;
     trustAnchorCert = NULL;
+    builtCertList = NULL;
     oparam = NULL;
     i=0;
     errorGenerated = PKIX_FALSE;
     stackPosition = 0;
 
     if (leakedObjNum) {
         pkix_pl_lifecycle_ObjectTableUpdate(objCountTable);
     }
 
-    PR_LOG(pkixLog, 1, ("Memory leak test: Loop %d\n", memLeakLoopCount));
+    PR_LOG(pkixLog, 1, ("Memory leak test: Loop %d\n", memLeakLoopCount++));
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
     error = PKIX_PL_NssContext_Create(
             0, PR_FALSE /*use arena*/, wincx, &plContext);
     if (error != NULL) {        /* need pkix->nss error map */
         PORT_SetError(SEC_ERROR_CERT_NOT_VALID);
         goto cleanup;
     }
@@ -2153,16 +2172,20 @@ do {
     }
 
     error = PKIX_TrustAnchor_GetTrustedCert( trustAnchor, &trustAnchorCert,
                                                 plContext);
     if (error != NULL) {
         goto cleanup;
     }
 
+#ifdef PKIX_OBJECT_LEAK_TEST
+    PORT_Assert(!errorGenerated);
+#endif /* PKIX_OBJECT_LEAK_TEST */
+
     oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_trustAnchor);
     if (oparam != NULL) {
         oparam->value.pointer.cert = 
                 cert_NSSCertFromPKIXCert(trustAnchorCert,plContext);
     }
 
     error = PKIX_BuildResult_GetCertChain( buildResult, &builtCertList,
                                                 plContext);
@@ -2179,16 +2202,19 @@ do {
     }
 
     r = SECSuccess;
 
 cleanup:
     if (verifyNode) {
         /* Return validation log only upon error. */
         oparam = cert_pkix_FindOutputParam(paramsOut, cert_po_errorLog);
+#ifdef PKIX_OBJECT_LEAK_TEST
+        if (!errorGenerated)
+#endif /* PKIX_OBJECT_LEAK_TEST */
         if (r && oparam != NULL) {
             PKIX_Error *tmpError =
                 cert_GetLogFromVerifyNode(oparam->value.pointer.log,
                                           verifyNode, plContext);
             if (tmpError) {
                 PKIX_PL_Object_DecRef((PKIX_PL_Object *)tmpError, plContext);
             }
         }
@@ -2229,21 +2255,26 @@ cleanup:
     }
 
     PKIX_PL_NssContext_Destroy(plContext);
 
 #ifdef PKIX_OBJECT_LEAK_TEST
     leakedObjNum =
         pkix_pl_lifecycle_ObjectLeakCheck(leakedObjNum ? objCountTable : NULL);
 
+    if (pkixLog && leakedObjNum) {
+        PR_LOG(pkixLog, 1, ("The generated error caused an object leaks. "
+                            "Stack %s\n", errorFnStackString));
+    }
+    PR_Free(errorFnStackString);
+    errorFnStackString = NULL;
     if (abortOnLeak) {
         PORT_Assert(leakedObjNum == 0);
     }
     
 } while (errorGenerated);
 
     runningLeakTest = PKIX_FALSE; 
     PR_AtomicDecrement(&parallelFnInvocationCount);
 #endif /* PKIX_OBJECT_LEAK_TEST */
 
     return r;
 }
-
--- a/security/nss/lib/certhigh/ocsp.c
+++ b/security/nss/lib/certhigh/ocsp.c
@@ -34,17 +34,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Implementation of OCSP services, for both client and server.
  * (XXX, really, mostly just for client right now, but intended to do both.)
  *
- * $Id: ocsp.c,v 1.50.6.1 2008/05/28 18:03:11 kaie%kuix.de Exp $
+ * $Id: ocsp.c,v 1.54 2008/07/08 21:34:32 alexei.volkov.bugs%sun.com Exp $
  */
 
 #include "prerror.h"
 #include "prprf.h"
 #include "plarena.h"
 #include "prnetdb.h"
 
 #include "seccomon.h"
@@ -1641,17 +1641,16 @@ cert_GetSubjectNameDigest(PRArenaPool *a
  * finding the certificate issuer (SEC_ERROR_UNKNOWN_ISSUER).
  * Other errors are low-level problems (no memory, bad database, etc.).
  */
 static CERTOCSPCertID *
 ocsp_CreateCertID(PRArenaPool *arena, CERTCertificate *cert, int64 time)
 {
     CERTOCSPCertID *certID;
     CERTCertificate *issuerCert = NULL;
-    SECItem *tempItem = NULL;
     void *mark = PORT_ArenaMark(arena);
     SECStatus rv;
 
     PORT_Assert(arena != NULL);
 
     certID = PORT_ArenaZNew(arena, CERTOCSPCertID);
     if (certID == NULL) {
 	goto loser;
@@ -1713,19 +1712,16 @@ ocsp_CreateCertID(PRArenaPool *arena, CE
 
     PORT_ArenaUnmark(arena, mark);
     return certID;
 
 loser:
     if (issuerCert != NULL) {
 	CERT_DestroyCertificate(issuerCert);
     }
-    if (tempItem != NULL) {
-	SECITEM_FreeItem(tempItem, PR_TRUE);
-    }
     PORT_ArenaRelease(arena, mark);
     return NULL;
 }
 
 CERTOCSPCertID*
 CERT_CreateOCSPCertID(CERTCertificate *cert, int64 time)
 {
     PRArenaPool *arena = PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
@@ -2717,17 +2713,17 @@ CERT_DestroyOCSPResponse(CERTOCSPRespons
  * of hostname and path, which are copies of the values found in the url.
  */
 static SECStatus
 ocsp_ParseURL(const char *url, char **pHostname, PRUint16 *pPort, char **pPath)
 {
     unsigned short port = 80;		/* default, in case not in url */
     char *hostname = NULL;
     char *path = NULL;
-    char *save;
+    const char *save;
     char c;
     int len;
 
     if (url == NULL)
 	goto loser;
 
     /*
      * Skip beginning whitespace.
@@ -4480,17 +4476,17 @@ loser:
  * extension for OCSP, and return the value of that.  Otherwise return NULL.
  * We also let our caller know whether or not the responder chosen was
  * a default responder or not through the output variable isDefault;
  * its value has no meaning unless a good (non-null) value is returned
  * for the location.
  *
  * The result needs to be freed (PORT_Free) when no longer in use.
  */
-static char *
+char *
 ocsp_GetResponderLocation(CERTCertDBHandle *handle, CERTCertificate *cert,
 			  PRBool *isDefault)
 {
     ocspCheckingContext *ocspcx;
 
     ocspcx = ocsp_GetCheckingContext(handle);
     if (ocspcx != NULL && ocspcx->useDefaultResponder) {
 	/*
--- a/security/nss/lib/certhigh/ocsp.h
+++ b/security/nss/lib/certhigh/ocsp.h
@@ -32,17 +32,17 @@
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 /*
  * Interface to the OCSP implementation.
  *
- * $Id: ocsp.h,v 1.11 2007/05/25 07:28:32 alexei.volkov.bugs%sun.com Exp $
+ * $Id: ocsp.h,v 1.13 2008/06/14 14:19:53 wtc%google.com Exp $
  */
 
 #ifndef _OCSP_H_
 #define _OCSP_H_
 
 
 #include "plarena.h"
 #include "seccomon.h"
@@ -95,16 +95,22 @@ CERT_OCSPCacheSettings(PRInt32 maxCacheE
 /*
  * Set the desired behaviour on OCSP failures.
  * See definition of ocspFailureMode for allowed choices.
  */
 extern SECStatus
 CERT_SetOCSPFailureMode(SEC_OcspFailureMode ocspFailureMode);
 
 /*
+ * Configure the maximum time NSS will wait for an OCSP response.
+ */
+extern SECStatus
+CERT_SetOCSPTimeout(PRUint32 seconds);
+
+/*
  * Removes all items currently stored in the OCSP cache.
  */
 extern SECStatus
 CERT_ClearOCSPCache(void);
 
 /*
  * FUNCTION: CERT_EnableOCSPChecking
  *   Turns on OCSP checking for the given certificate database.
@@ -216,17 +222,17 @@ CERT_DisableOCSPDefaultResponder(CERTCer
  *   CERTCertList *certList
  *     A list of certs for which status will be requested.
  *     Note that all of these certificates should have the same issuer,
  *     or it's expected the response will be signed by a trusted responder.
  *     If the certs need to be broken up into multiple requests, that
  *     must be handled by the caller (and thus by having multiple calls
  *     to this routine), who knows about where the request(s) are being
  *     sent and whether there are any trusted responders in place.
- *   int64 time
+ *   PRTime time
  *     Indicates the time for which the certificate status is to be 
  *     determined -- this may be used in the search for the cert's issuer
  *     but has no effect on the request itself.
  *   PRBool addServiceLocator
  *     If true, the Service Locator extension should be added to the
  *     single request(s) for each cert.
  *   CERTCertificate *signerCert
  *     If non-NULL, means sign the request using this cert.  Otherwise,
@@ -235,17 +241,17 @@ CERT_DisableOCSPDefaultResponder(CERTCer
  * RETURN:
  *   A pointer to a CERTOCSPRequest structure containing an OCSP request
  *   for the cert list.  On error, null is returned, with an error set
  *   indicating the reason.  This is likely SEC_ERROR_UNKNOWN_ISSUER.
  *   (The issuer is needed to create a request for the certificate.)
  *   Other errors are low-level problems (no memory, bad database, etc.).
  */
 extern CERTOCSPRequest *
-CERT_CreateOCSPRequest(CERTCertList *certList, int64 time, 
+CERT_CreateOCSPRequest(CERTCertList *certList, PRTime time, 
 		       PRBool addServiceLocator,
 		       CERTCertificate *signerCert);
 
 /*
  * FUNCTION: CERT_AddOCSPAcceptableResponses
  *   Add the AcceptableResponses extension to an OCSP Request.
  * INPUTS:
  *   CERTOCSPRequest *request
@@ -264,31 +270,31 @@ extern SECStatus
 CERT_AddOCSPAcceptableResponses(CERTOCSPRequest *request,
 				SECOidTag responseType0, ...);
 
 /* 
  * FUNCTION: CERT_EncodeOCSPRequest
  *   DER encodes an OCSP Request, possibly adding a signature as well.
  *   XXX Signing is not yet supported, however; see comments in code.
  * INPUTS: 
- *   PRArenaPool *arena
+ *   PLArenaPool *arena
  *     The return value is allocated from here.
  *     If a NULL is passed in, allocation is done from the heap instead.
  *   CERTOCSPRequest *request
  *     The request to be encoded.
  *   void *pwArg
  *     Pointer to argument for password prompting, if needed.  (Definitely
  *     not needed if not signing.)
  * RETURN:
  *   Returns a NULL on error and a pointer to the SECItem with the
  *   encoded value otherwise.  Any error is likely to be low-level
  *   (e.g. no memory).
  */
 extern SECItem *
-CERT_EncodeOCSPRequest(PRArenaPool *arena, CERTOCSPRequest *request, 
+CERT_EncodeOCSPRequest(PLArenaPool *arena, CERTOCSPRequest *request, 
 		       void *pwArg);
 
 /*
  * FUNCTION: CERT_DecodeOCSPRequest
  *   Decode a DER encoded OCSP Request.
  * INPUTS:
  *   SECItem *src
  *     Pointer to a SECItem holding DER encoded OCSP Request.
@@ -340,31 +346,31 @@ CERT_DecodeOCSPResponse(SECItem *src);
 extern void
 CERT_DestroyOCSPResponse(CERTOCSPResponse *response);
 
 /*
  * FUNCTION: CERT_GetEncodedOCSPResponse
  *   Creates and sends a request to an OCSP responder, then reads and
  *   returns the (encoded) response.
  * INPUTS:
- *   PRArenaPool *arena
+ *   PLArenaPool *arena
  *     Pointer to arena from which return value will be allocated.
  *     If NULL, result will be allocated from the heap (and thus should
  *     be freed via SECITEM_FreeItem).
  *   CERTCertList *certList
  *     A list of certs for which status will be requested.
  *     Note that all of these certificates should have the same issuer,
  *     or it's expected the response will be signed by a trusted responder.
  *     If the certs need to be broken up into multiple requests, that
  *     must be handled by the caller (and thus by having multiple calls
  *     to this routine), who knows about where the request(s) are being
  *     sent and whether there are any trusted responders in place.
  *   char *location
  *     The location of the OCSP responder (a URL).
- *   int64 time
+ *   PRTime time
  *     Indicates the time for which the certificate status is to be 
  *     determined -- this may be used in the search for the cert's issuer
  *     but has no other bearing on the operation.
  *   PRBool addServiceLocator
  *     If true, the Service Locator extension should be added to the
  *     single request(s) for each cert.
  *   CERTCertificate *signerCert
  *     If non-NULL, means sign the request using this cert.  Otherwise,
@@ -382,18 +388,18 @@ CERT_DestroyOCSPResponse(CERTOCSPRespons
  *   Returns a pointer to the SECItem holding the response.
  *   On error, returns null with error set describing the reason:
  *	SEC_ERROR_UNKNOWN_ISSUER
  *	SEC_ERROR_CERT_BAD_ACCESS_LOCATION
  *	SEC_ERROR_OCSP_BAD_HTTP_RESPONSE
  *   Other errors are low-level problems (no memory, bad database, etc.).
  */
 extern SECItem *
-CERT_GetEncodedOCSPResponse(PRArenaPool *arena, CERTCertList *certList,
-			    char *location, int64 time,
+CERT_GetEncodedOCSPResponse(PLArenaPool *arena, CERTCertList *certList,
+			    char *location, PRTime time,
 			    PRBool addServiceLocator,
 			    CERTCertificate *signerCert, void *pwArg,
 			    CERTOCSPRequest **pRequest);
 
 /*
  * FUNCTION: CERT_VerifyOCSPResponseSignature
  *   Check the signature on an OCSP Response.  Will also perform a
  *   verification of the signer's certificate.  Note, however, that a
@@ -483,17 +489,17 @@ CERT_ParseURL(const char *url, char **pH
  * INPUTS:
  *   CERTCertDBHandle *handle
  *     certificate DB of the cert that is being checked
  *   CERTCertificate *cert
  *     the certificate being checked
  *   XXX in the long term also need a boolean parameter that specifies
  *	whether to check the cert chain, as well; for now we check only
  *	the leaf (the specified certificate)
- *   int64 time
+ *   PRTime time
  *     time for which status is to be determined
  *   void *pwArg
  *     argument for password prompting, if needed
  * RETURN:
  *   Returns SECSuccess if an approved OCSP responder "knows" the cert
  *   *and* returns a non-revoked status for it; SECFailure otherwise,
  *   with an error set describing the reason:
  *
@@ -520,42 +526,42 @@ CERT_ParseURL(const char *url, char **pH
  *
  *   Other errors are any of the many possible failures in cert verification
  *   (e.g. SEC_ERROR_REVOKED_CERTIFICATE, SEC_ERROR_UNTRUSTED_ISSUER) when
  *   verifying the signer's cert, or low-level problems (error allocating
  *   memory, error performing ASN.1 decoding, etc.).
  */    
 extern SECStatus 
 CERT_CheckOCSPStatus(CERTCertDBHandle *handle, CERTCertificate *cert,
-		     int64 time, void *pwArg);
+		     PRTime time, void *pwArg);
 /*
  * FUNCTION: CERT_GetOCSPStatusForCertID
  *  Returns the OCSP status contained in the passed in paramter response
  *  that corresponds to the certID passed in.
  * INPUTS:
  *  CERTCertDBHandle *handle
  *    certificate DB of the cert that is being checked
  *  CERTOCSPResponse *response
  *    the OCSP response we want to retrieve status from.
  *  CERTOCSPCertID *certID
  *    the ID we want to look for from the response.
  *  CERTCertificate *signerCert
  *    the certificate that was used to sign the OCSP response.
  *    must be obtained via a call to CERT_VerifyOCSPResponseSignature.
- *  int64 time
+ *  PRTime time
  *    The time at which we're checking the status for.
  *  RETURN:
  *    Return values are the same as those for CERT_CheckOCSPStatus
  */
 extern SECStatus
 CERT_GetOCSPStatusForCertID(CERTCertDBHandle *handle, 
 			    CERTOCSPResponse *response,
 			    CERTOCSPCertID   *certID,
 			    CERTCertificate  *signerCert,
-                            int64             time);
+                            PRTime            time);
 
 /*
  * FUNCTION CERT_GetOCSPResponseStatus
  *   Returns the response status for the response passed.
  * INPUTS:
  *   CERTOCSPResponse *response
  *     The response to query for status
  *  RETURN:
@@ -573,27 +579,27 @@ extern SECStatus
 CERT_GetOCSPResponseStatus(CERTOCSPResponse *response);
 
 /*
  * FUNCTION CERT_CreateOCSPCertID
  *  Returns the OCSP certID for the certificate passed in.
  * INPUTS:
  *  CERTCertificate *cert
  *    The certificate for which to create the certID for.
- *  int64 time
+ *  PRTime time
  *    The time at which the id is requested for.  This is used
  *    to determine the appropriate issuer for the cert since
  *    the issuing CA may be an older expired certificate.
  *  RETURN:
  *    A new copy of a CERTOCSPCertID*.  The memory for this certID
  *    should be freed by calling CERT_DestroyOCSPCertID when the 
  *    certID is no longer necessary.
  */
 extern CERTOCSPCertID*
-CERT_CreateOCSPCertID(CERTCertificate *cert, int64 time);
+CERT_CreateOCSPCertID(CERTCertificate *cert, PRTime time);
 
 /*
  * FUNCTION: CERT_DestroyOCSPCertID
  *  Frees the memory associated with the certID passed in.
  * INPUTS:
  *  CERTOCSPCertID* certID
  *    The certID that the caller no longer needs and wants to 
  *    free the associated memory.
--- a/security/nss/lib/certhigh/ocspi.h
+++ b/security/nss/lib/certhigh/ocspi.h
@@ -31,17 +31,17 @@
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 /*
  * ocspi.h - NSS internal interfaces to OCSP code
  *
- * $Id: ocspi.h,v 1.9 2008/02/06 17:27:48 kaie%kuix.de Exp $
+ * $Id: ocspi.h,v 1.10 2008/07/08 21:34:32 alexei.volkov.bugs%sun.com Exp $
  */
 
 #ifndef _OCSPI_H_
 #define _OCSPI_H_
 
 SECStatus OCSP_InitGlobal(void);
 SECStatus OCSP_ShutdownGlobal(void);
 
@@ -133,9 +133,30 @@ cert_ProcessOCSPResponse(CERTCertDBHandl
  *  RETURN:
  *    Status of the cache update operation.
  */
 
 SECStatus
 cert_RememberOCSPProcessingFailure(CERTOCSPCertID *certID,
                                    PRBool         *certIDWasConsumed);
 
+/*
+ * FUNCTION: ocsp_GetResponderLocation
+ *  Check ocspx context for user-designated responder URI first. If not
+ *  found, checks cert AIA extension.
+ * INPUTS:
+ *  CERTCertDBHandle *handle
+ *    certificate DB of the cert that is being checked
+ *  CERTCertificate *cert
+ *     The certificate being examined.
+ *  PRBool *certIDWasConsumed
+ *    Out parameter, if set to true, URI of default responder is
+ *    returned.
+ *  RETURN:
+ *    Responder URI.
+ */
+char *
+ocsp_GetResponderLocation(CERTCertDBHandle *handle,
+                          CERTCertificate *cert,
+                          PRBool *isDefault);
+
+
 #endif /* _OCSPI_H_ */
--- a/security/nss/lib/certhigh/xcrldist.c
+++ b/security/nss/lib/certhigh/xcrldist.c
@@ -43,49 +43,66 @@
 
 SEC_ASN1_MKSUB(SEC_AnyTemplate)
 SEC_ASN1_MKSUB(SEC_BitStringTemplate)
 
 extern void PrepareBitStringForEncoding (SECItem *bitMap, SECItem *value);
 
 static const SEC_ASN1Template FullNameTemplate[] = {
     {SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0,
-	offsetof (CRLDistributionPoint,derFullName), CERT_GeneralNamesTemplate}
+	offsetof (CRLDistributionPoint,derFullName), 
+	CERT_GeneralNamesTemplate}
 };
 
 static const SEC_ASN1Template RelativeNameTemplate[] = {
     {SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, 
-	offsetof (CRLDistributionPoint,distPoint.relativeName), CERT_RDNTemplate}
+	offsetof (CRLDistributionPoint,distPoint.relativeName), 
+	CERT_RDNTemplate}
 };
-	 
+
+static const SEC_ASN1Template DistributionPointNameTemplate[] = {
+    { SEC_ASN1_CHOICE,
+	offsetof(CRLDistributionPoint, distPointType), NULL,
+	sizeof(CRLDistributionPoint) },
+    { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 0,
+	offsetof (CRLDistributionPoint, derFullName), 
+	CERT_GeneralNamesTemplate, generalName },
+    { SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_CONSTRUCTED | 1, 
+	offsetof (CRLDistributionPoint, distPoint.relativeName), 
+	CERT_RDNTemplate, relativeDistinguishedName },
+    { 0 }
+};
+
 static const SEC_ASN1Template CRLDistributionPointTemplate[] = {
     { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(CRLDistributionPoint) },
 	{ SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC |
 	    SEC_ASN1_CONSTRUCTED | SEC_ASN1_EXPLICIT | SEC_ASN1_XTRN | 0,
 	    offsetof(CRLDistributionPoint,derDistPoint),
             SEC_ASN1_SUB(SEC_AnyTemplate)},
 	{ SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC | SEC_ASN1_XTRN | 1,
 	    offsetof(CRLDistributionPoint,bitsmap),
             SEC_ASN1_SUB(SEC_BitStringTemplate) },
 	{ SEC_ASN1_OPTIONAL | SEC_ASN1_CONTEXT_SPECIFIC |
 	    SEC_ASN1_CONSTRUCTED | 2,
-	    offsetof(CRLDistributionPoint, derCrlIssuer), CERT_GeneralNamesTemplate},
+	    offsetof(CRLDistributionPoint, derCrlIssuer), 
+	    CERT_GeneralNamesTemplate},
     { 0 }
 };
 
 const SEC_ASN1Template CERTCRLDistributionPointsTemplate[] = {
     {SEC_ASN1_SEQUENCE_OF, 0, CRLDistributionPointTemplate}
 };
 
 SECStatus
-CERT_EncodeCRLDistributionPoints (PRArenaPool *arena, CERTCrlDistributionPoints *value,
+CERT_EncodeCRLDistributionPoints (PLArenaPool *arena, 
+				  CERTCrlDistributionPoints *value,
 				  SECItem *derValue)
 {
     CRLDistributionPoint **pointList, *point;
-    PRArenaPool *ourPool = NULL;
+    PLArenaPool *ourPool = NULL;
     SECStatus rv = SECSuccess;
 
     PORT_Assert (derValue);
     PORT_Assert (value && value->distPoints);
 
     do {
 	ourPool = PORT_NewArena (SEC_ASN1_DEFAULT_ARENA_SIZE);
 	if (ourPool == NULL) {
@@ -94,145 +111,139 @@ CERT_EncodeCRLDistributionPoints (PRAren
 	}    
 	
 	pointList = value->distPoints;
 	while (*pointList) {
 	    point = *pointList;
 	    point->derFullName = NULL;
 	    point->derDistPoint.data = NULL;
 
-	    if (point->distPointType == generalName) {
+	    switch (point->distPointType) {
+	    case generalName:
 		point->derFullName = cert_EncodeGeneralNames
 		    (ourPool, point->distPoint.fullName);
 		
-		if (point->derFullName) {
-		    rv = (SEC_ASN1EncodeItem (ourPool, &point->derDistPoint,
-			  point, FullNameTemplate) == NULL) ? SECFailure : SECSuccess;
-		} else {
+		if (!point->derFullName ||
+		    !SEC_ASN1EncodeItem (ourPool, &point->derDistPoint,
+			  point, FullNameTemplate))
 		    rv = SECFailure;
-		}
-	    }
-	    else if (point->distPointType == relativeDistinguishedName) {
-		if (SEC_ASN1EncodeItem
-		     (ourPool, &point->derDistPoint, 
-		      point, RelativeNameTemplate) == NULL) 
+		break;
+
+	    case relativeDistinguishedName:
+		if (!SEC_ASN1EncodeItem(ourPool, &point->derDistPoint, 
+		      point, RelativeNameTemplate)) 
 		    rv = SECFailure;
-	    }
+		break;
+
 	    /* distributionPointName is omitted */
-	    else if (point->distPointType != 0) {
+	    case 0: break;
+
+	    default:
 		PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID);
 		rv = SECFailure;
+		break;
 	    }
+
 	    if (rv != SECSuccess)
 		break;
 
 	    if (point->reasons.data)
 		PrepareBitStringForEncoding (&point->bitsmap, &point->reasons);
 
 	    if (point->crlIssuer) {
 		point->derCrlIssuer = cert_EncodeGeneralNames
 		    (ourPool, point->crlIssuer);
-		if (!point->crlIssuer)
+		if (!point->derCrlIssuer) {
+		    rv = SECFailure;
 		    break;
+	    	}
 	    }
-	    
 	    ++pointList;
 	}
 	if (rv != SECSuccess)
 	    break;
-	if (SEC_ASN1EncodeItem
-	     (arena, derValue, value, CERTCRLDistributionPointsTemplate) == NULL) {
+	if (!SEC_ASN1EncodeItem(arena, derValue, value, 
+		CERTCRLDistributionPointsTemplate)) {
 	    rv = SECFailure;
 	    break;
 	}
     } while (0);
     PORT_FreeArena (ourPool, PR_FALSE);
-    return (rv);
+    return rv;
 }
 
 CERTCrlDistributionPoints *
-CERT_DecodeCRLDistributionPoints (PRArenaPool *arena, SECItem *encodedValue)
+CERT_DecodeCRLDistributionPoints (PLArenaPool *arena, SECItem *encodedValue)
 {
    CERTCrlDistributionPoints *value = NULL;    
    CRLDistributionPoint **pointList, *point;    
-   SECStatus rv;
+   SECStatus rv = SECSuccess;
    SECItem newEncodedValue;
 
    PORT_Assert (arena);
    do {
-	value = (CERTCrlDistributionPoints*)PORT_ArenaZAlloc (arena, sizeof (*value));
+	value = PORT_ArenaZNew(arena, CERTCrlDistributionPoints);
 	if (value == NULL) {
 	    rv = SECFailure;
 	    break;
 	}
 
         /* copy the DER into the arena, since Quick DER returns data that points
            into the DER input, which may get freed by the caller */
         rv = SECITEM_CopyItem(arena, &newEncodedValue, encodedValue);
-        if ( rv != SECSuccess ) {
+        if (rv != SECSuccess)
 	    break;
-        }
 
-	rv = SEC_QuickDERDecodeItem
-	     (arena, &value->distPoints, CERTCRLDistributionPointsTemplate,
-	      &newEncodedValue);
+	rv = SEC_QuickDERDecodeItem(arena, &value->distPoints, 
+		CERTCRLDistributionPointsTemplate, &newEncodedValue);
 	if (rv != SECSuccess)
 	    break;
 
 	pointList = value->distPoints;
-	while (*pointList) {
-	    point = *pointList;
+	while (NULL != (point = *pointList)) {
 
 	    /* get the data if the distributionPointName is not omitted */
 	    if (point->derDistPoint.data != NULL) {
-		point->distPointType = (DistributionPointTypes)
-					((point->derDistPoint.data[0] & 0x1f) +1);
-		if (point->distPointType == generalName) {
-		    SECItem innerDER;
-		
-		    innerDER.data = NULL;
-		    rv = SEC_QuickDERDecodeItem
-			 (arena, point, FullNameTemplate, &(point->derDistPoint));
-		    if (rv != SECSuccess)
-			break;
-		    point->distPoint.fullName = cert_DecodeGeneralNames
-			(arena, point->derFullName);
+		rv = SEC_QuickDERDecodeItem(arena, point, 
+			DistributionPointNameTemplate, &(point->derDistPoint));
+		if (rv != SECSuccess)
+		    break;
+
+		switch (point->distPointType) {
+		case generalName:
+		    point->distPoint.fullName = 
+			cert_DecodeGeneralNames(arena, point->derFullName);
+		    rv = point->distPoint.fullName ? SECSuccess : SECFailure;
+		    break;
 
-		    if (!point->distPoint.fullName)
-			break;
-		}
-		else if ( relativeDistinguishedName) {
-		    rv = SEC_QuickDERDecodeItem
-			 (arena, point, RelativeNameTemplate, &(point->derDistPoint));
-		    if (rv != SECSuccess)
-			break;
-		}
-		else {
+		case relativeDistinguishedName:
+		    break;
+
+		default:
 		    PORT_SetError (SEC_ERROR_EXTENSION_VALUE_INVALID);
+		    rv = SECFailure;
 		    break;
-		}
-	    }
+		} /* end switch */
+		if (rv != SECSuccess)
+		    break;
+	    } /* end if */
 
 	    /* Get the reason code if it's not omitted in the encoding */
 	    if (point->bitsmap.data != NULL) {
-		point->reasons.data = (unsigned char*) PORT_ArenaAlloc
-				      (arena, (point->bitsmap.len + 7) >> 3);
-		if (!point->reasons.data) {
-		    rv = SECFailure;
+	    	SECItem bitsmap = point->bitsmap;
+		DER_ConvertBitString(&bitsmap);
+		rv = SECITEM_CopyItem(arena, &point->reasons, &bitsmap);
+		if (rv != SECSuccess)
 		    break;
-		}
-		PORT_Memcpy (point->reasons.data, point->bitsmap.data,
-			     point->reasons.len = ((point->bitsmap.len + 7) >> 3));
 	    }
 
 	    /* Get the crl issuer name if it's not omitted in the encoding */
 	    if (point->derCrlIssuer != NULL) {
-		point->crlIssuer = cert_DecodeGeneralNames
-		    (arena, point->derCrlIssuer);
-
+		point->crlIssuer = cert_DecodeGeneralNames(arena, 
+			           point->derCrlIssuer);
 		if (!point->crlIssuer)
 		    break;
 	    }
 	    ++pointList;
-	}
+	} /* end while points remain */
    } while (0);
    return (rv == SECSuccess ? value : NULL);
 }
--- a/security/nss/lib/ckfw/builtins/certdata.c
+++ b/security/nss/lib/ckfw/builtins/certdata.c
@@ -30,17 +30,17 @@
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: certdata.c,v $ $Revision: 1.48.2.1 $ $Date: 2008/05/03 03:13:22 $""; @(#) $RCSfile: certdata.c,v $ $Revision: 1.48.2.1 $ $Date: 2008/05/03 03:13:22 $";
+static const char CVS_ID[] = "@(#) $RCSfile: certdata.c,v $ $Revision: 1.50 $ $Date: 2008/08/14 18:15:56 $""; @(#) $RCSfile: certdata.c,v $ $Revision: 1.50 $ $Date: 2008/08/14 18:15:56 $";
 #endif /* DEBUG */
 
 #ifndef BUILTINS_H
 #include "builtins.h"
 #endif /* BUILTINS_H */
 
 static const CK_BBOOL ck_false = CK_FALSE;
 static const CK_BBOOL ck_true = CK_TRUE;
@@ -792,25 +792,31 @@ static const CK_ATTRIBUTE_TYPE nss_built
  CKA_CLASS,  CKA_TOKEN,  CKA_PRIVATE,  CKA_MODIFIABLE,  CKA_LABEL,  CKA_CERT_SHA1_HASH,  CKA_CERT_MD5_HASH,  CKA_ISSUER,  CKA_SERIAL_NUMBER,  CKA_TRUST_SERVER_AUTH,  CKA_TRUST_EMAIL_PROTECTION,  CKA_TRUST_CODE_SIGNING,  CKA_TRUST_STEP_UP_APPROVED
 };
 static const CK_ATTRIBUTE_TYPE nss_builtins_types_246 [] = {
  CKA_CLASS,  CKA_TOKEN,  CKA_PRIVATE,  CKA_MODIFIABLE,  CKA_LABEL,  CKA_CERTIFICATE_TYPE,  CKA_SUBJECT,  CKA_ID,  CKA_ISSUER,  CKA_SERIAL_NUMBER,  CKA_VALUE
 };
 static const CK_ATTRIBUTE_TYPE nss_builtins_types_247 [] = {
  CKA_CLASS,  CKA_TOKEN,  CKA_PRIVATE,  CKA_MODIFIABLE,  CKA_LABEL,  CKA_CERT_SHA1_HASH,  CKA_CERT_MD5_HASH,  CKA_ISSUER,  CKA_SERIAL_NUMBER,  CKA_TRUST_SERVER_AUTH,  CKA_TRUST_EMAIL_PROTECTION,  CKA_TRUST_CODE_SIGNING,  CKA_TRUST_STEP_UP_APPROVED
 };
+static const CK_ATTRIBUTE_TYPE nss_builtins_types_248 [] = {
+ CKA_CLASS,  CKA_TOKEN,  CKA_PRIVATE,  CKA_MODIFIABLE,  CKA_LABEL,  CKA_CERTIFICATE_TYPE,  CKA_SUBJECT,  CKA_ID,  CKA_ISSUER,  CKA_SERIAL_NUMBER,  CKA_VALUE
+};
+static const CK_ATTRIBUTE_TYPE nss_builtins_types_249 [] = {
+ CKA_CLASS,  CKA_TOKEN,  CKA_PRIVATE,  CKA_MODIFIABLE,  CKA_LABEL,  CKA_CERT_SHA1_HASH,  CKA_CERT_MD5_HASH,  CKA_ISSUER,  CKA_SERIAL_NUMBER,  CKA_TRUST_SERVER_AUTH,  CKA_TRUST_EMAIL_PROTECTION,  CKA_TRUST_CODE_SIGNING,  CKA_TRUST_STEP_UP_APPROVED
+};
 #ifdef DEBUG
 static const NSSItem nss_builtins_items_0 [] = {
   { (void *)&cko_data, (PRUint32)sizeof(CK_OBJECT_CLASS) },
   { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)"CVS ID", (PRUint32)7 },
   { (void *)"NSS", (PRUint32)4 },
-  { (void *)"@(#) $RCSfile: certdata.c,v $ $Revision: 1.48.2.1 $ $Date: 2008/05/03 03:13:22 $""; @(#) $RCSfile: certdata.c,v $ $Revision: 1.48.2.1 $ $Date: 2008/05/03 03:13:22 $", (PRUint32)160 }
+  { (void *)"@(#) $RCSfile: certdata.c,v $ $Revision: 1.50 $ $Date: 2008/08/14 18:15:56 $""; @(#) $RCSfile: certdata.c,v $ $Revision: 1.50 $ $Date: 2008/08/14 18:15:56 $", (PRUint32)160 }
 };
 #endif /* DEBUG */
 static const NSSItem nss_builtins_items_1 [] = {
   { (void *)&cko_netscape_builtin_root_list, (PRUint32)sizeof(CK_OBJECT_CLASS) },
   { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)"Mozilla Builtin Roots", (PRUint32)22 }
@@ -3171,28 +3177,28 @@ static const NSSItem nss_builtins_items_
   { (void *)"0", (PRUint32)2 },
   { (void *)"\060\127\061\013\060\011\006\003\125\004\006\023\002\102\105\061"
 "\031\060\027\006\003\125\004\012\023\020\107\154\157\142\141\154"
 "\123\151\147\156\040\156\166\055\163\141\061\020\060\016\006\003"
 "\125\004\013\023\007\122\157\157\164\040\103\101\061\033\060\031"
 "\006\003\125\004\003\023\022\107\154\157\142\141\154\123\151\147"
 "\156\040\122\157\157\164\040\103\101"
 , (PRUint32)89 },
-  { (void *)"\002\013\002\000\000\000\000\000\326\170\267\224\005"
+  { (void *)"\002\013\004\000\000\000\000\001\025\113\132\303\224"
 , (PRUint32)13 },
-  { (void *)"\060\202\003\165\060\202\002\135\240\003\002\001\002\002\013\002"
-"\000\000\000\000\000\326\170\267\224\005\060\015\006\011\052\206"
-"\110\206\367\015\001\001\004\005\000\060\127\061\013\060\011\006"
+  { (void *)"\060\202\003\165\060\202\002\135\240\003\002\001\002\002\013\004"
+"\000\000\000\000\001\025\113\132\303\224\060\015\006\011\052\206"
+"\110\206\367\015\001\001\005\005\000\060\127\061\013\060\011\006"
 "\003\125\004\006\023\002\102\105\061\031\060\027\006\003\125\004"
 "\012\023\020\107\154\157\142\141\154\123\151\147\156\040\156\166"
 "\055\163\141\061\020\060\016\006\003\125\004\013\023\007\122\157"
 "\157\164\040\103\101\061\033\060\031\006\003\125\004\003\023\022"
 "\107\154\157\142\141\154\123\151\147\156\040\122\157\157\164\040"
 "\103\101\060\036\027\015\071\070\060\071\060\061\061\062\060\060"
-"\060\060\132\027\015\061\064\060\061\062\070\061\062\060\060\060"
+"\060\060\132\027\015\062\070\060\061\062\070\061\062\060\060\060"
 "\060\132\060\127\061\013\060\011\006\003\125\004\006\023\002\102"
 "\105\061\031\060\027\006\003\125\004\012\023\020\107\154\157\142"
 "\141\154\123\151\147\156\040\156\166\055\163\141\061\020\060\016"
 "\006\003\125\004\013\023\007\122\157\157\164\040\103\101\061\033"
 "\060\031\006\003\125\004\003\023\022\107\154\157\142\141\154\123"
 "\151\147\156\040\122\157\157\164\040\103\101\060\202\001\042\060"
 "\015\006\011\052\206\110\206\367\015\001\001\001\005\000\003\202"
 "\001\017\000\060\202\001\012\002\202\001\001\000\332\016\346\231"
@@ -3208,58 +3214,58 @@ static const NSSItem nss_builtins_items_
 "\262\165\016\206\350\031\212\325\155\154\325\170\026\225\242\351"
 "\310\012\070\353\362\044\023\117\163\124\223\023\205\072\033\274"
 "\036\064\265\213\005\214\271\167\213\261\333\037\040\221\253\011"
 "\123\156\220\316\173\067\164\271\160\107\221\042\121\143\026\171"
 "\256\261\256\101\046\010\310\031\053\321\106\252\110\326\144\052"
 "\327\203\064\377\054\052\301\154\031\103\112\007\205\347\323\174"
 "\366\041\150\357\352\362\122\237\177\223\220\317\002\003\001\000"
 "\001\243\102\060\100\060\016\006\003\125\035\017\001\001\377\004"
-"\004\003\002\000\006\060\035\006\003\125\035\016\004\026\004\024"
-"\140\173\146\032\105\015\227\312\211\120\057\175\004\315\064\250"
-"\377\374\375\113\060\017\006\003\125\035\023\001\001\377\004\005"
-"\060\003\001\001\377\060\015\006\011\052\206\110\206\367\015\001"
-"\001\004\005\000\003\202\001\001\000\256\252\237\374\267\322\313"
-"\037\137\071\051\050\030\236\064\311\154\117\157\032\360\144\242"
-"\160\112\117\023\206\233\140\050\236\350\201\111\230\175\012\273"
-"\345\260\235\075\066\333\217\005\121\377\011\061\052\037\335\211"
-"\167\236\017\056\154\225\004\355\206\313\264\000\077\204\002\115"
-"\200\152\052\055\170\013\256\157\053\242\203\104\203\037\315\120"
-"\202\114\044\257\275\367\245\264\310\132\017\364\347\107\136\111"
-"\216\067\226\376\232\210\005\072\331\300\333\051\207\346\031\226"
-"\107\247\072\246\214\213\074\167\376\106\143\247\123\332\041\321"
-"\254\176\111\242\113\346\303\147\131\057\263\212\016\273\054\275"
-"\251\252\102\174\065\301\330\177\325\247\061\072\116\143\103\071"
-"\257\010\260\141\064\214\323\230\251\103\064\366\017\207\051\073"
-"\235\302\126\130\230\167\303\367\033\254\366\235\370\076\252\247"
-"\124\105\360\365\371\325\061\145\376\153\130\234\161\263\036\327"
-"\122\352\062\027\374\100\140\035\311\171\044\262\366\154\375\250"
-"\146\016\202\335\230\313\332\302\104\117\056\240\173\362\367\153"
-"\054\166\021\204\106\212\170\243\343"
+"\004\003\002\001\006\060\017\006\003\125\035\023\001\001\377\004"
+"\005\060\003\001\001\377\060\035\006\003\125\035\016\004\026\004"
+"\024\140\173\146\032\105\015\227\312\211\120\057\175\004\315\064"
+"\250\377\374\375\113\060\015\006\011\052\206\110\206\367\015\001"
+"\001\005\005\000\003\202\001\001\000\326\163\347\174\117\166\320"
+"\215\277\354\272\242\276\064\305\050\062\265\174\374\154\234\054"
+"\053\275\011\236\123\277\153\136\252\021\110\266\345\010\243\263"
+"\312\075\141\115\323\106\011\263\076\303\240\343\143\125\033\362"
+"\272\357\255\071\341\103\271\070\243\346\057\212\046\073\357\240"
+"\120\126\371\306\012\375\070\315\304\013\160\121\224\227\230\004"
+"\337\303\137\224\325\025\311\024\101\234\304\135\165\144\025\015"
+"\377\125\060\354\206\217\377\015\357\054\271\143\106\366\252\374"
+"\337\274\151\375\056\022\110\144\232\340\225\360\246\357\051\217"
+"\001\261\025\265\014\035\245\376\151\054\151\044\170\036\263\247"
+"\034\161\142\356\312\310\227\254\027\135\212\302\370\107\206\156"
+"\052\304\126\061\225\320\147\211\205\053\371\154\246\135\106\235"
+"\014\252\202\344\231\121\335\160\267\333\126\075\141\344\152\341"
+"\134\326\366\376\075\336\101\314\007\256\143\122\277\123\123\364"
+"\053\351\307\375\266\367\202\137\205\322\101\030\333\201\263\004"
+"\034\305\037\244\200\157\025\040\311\336\014\210\012\035\326\146"
+"\125\342\374\110\311\051\046\151\340"
 , (PRUint32)889 }
 };
 static const NSSItem nss_builtins_items_45 [] = {
   { (void *)&cko_netscape_trust, (PRUint32)sizeof(CK_OBJECT_CLASS) },
   { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
   { (void *)"GlobalSign Root CA", (PRUint32)19 },
-  { (void *)"\057\027\077\175\351\226\147\257\245\172\370\012\242\321\261\057"
-"\254\203\003\070"
-, (PRUint32)20 },
-  { (void *)"\253\277\352\343\153\051\246\314\246\170\065\231\357\255\053\200"
+  { (void *)"\261\274\226\213\324\364\235\142\052\250\232\201\362\025\001\122"
+"\244\035\202\234"
+, (PRUint32)20 },
+  { (void *)"\076\105\122\025\011\121\222\341\267\135\067\237\261\207\051\212"
 , (PRUint32)16 },
   { (void *)"\060\127\061\013\060\011\006\003\125\004\006\023\002\102\105\061"
 "\031\060\027\006\003\125\004\012\023\020\107\154\157\142\141\154"
 "\123\151\147\156\040\156\166\055\163\141\061\020\060\016\006\003"
 "\125\004\013\023\007\122\157\157\164\040\103\101\061\033\060\031"
 "\006\003\125\004\003\023\022\107\154\157\142\141\154\123\151\147"
 "\156\040\122\157\157\164\040\103\101"
 , (PRUint32)89 },
-  { (void *)"\002\013\002\000\000\000\000\000\326\170\267\224\005"
+  { (void *)"\002\013\004\000\000\000\000\001\025\113\132\303\224"
 , (PRUint32)13 },
   { (void *)&ckt_netscape_trusted_delegator, (PRUint32)sizeof(CK_TRUST) },
   { (void *)&ckt_netscape_trusted_delegator, (PRUint32)sizeof(CK_TRUST) },
   { (void *)&ckt_netscape_trusted_delegator, (PRUint32)sizeof(CK_TRUST) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }
 };
 static const NSSItem nss_builtins_items_46 [] = {
   { (void *)&cko_certificate, (PRUint32)sizeof(CK_OBJECT_CLASS) },
@@ -16720,16 +16726,153 @@ static const NSSItem nss_builtins_items_
   { (void *)"\002\020\127\313\063\157\302\134\026\346\107\026\027\343\220\061"
 "\150\340"
 , (PRUint32)18 },
   { (void *)&ckt_netscape_trusted_delegator, (PRUint32)sizeof(CK_TRUST) },
   { (void *)&ckt_netscape_trust_unknown, (PRUint32)sizeof(CK_TRUST) },
   { (void *)&ckt_netscape_trust_unknown, (PRUint32)sizeof(CK_TRUST) },
   { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }
 };
+static const NSSItem nss_builtins_items_248 [] = {
+  { (void *)&cko_certificate, (PRUint32)sizeof(CK_OBJECT_CLASS) },
+  { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) },
+  { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
+  { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
+  { (void *)"WellsSecure Public Root Certificate Authority", (PRUint32)46 },
+  { (void *)&ckc_x_509, (PRUint32)sizeof(CK_CERTIFICATE_TYPE) },
+  { (void *)"\060\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123"
+"\061\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163"
+"\040\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165"
+"\162\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154"
+"\154\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101"
+"\061\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163"
+"\123\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157"
+"\157\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101"
+"\165\164\150\157\162\151\164\171"
+, (PRUint32)136 },
+  { (void *)"0", (PRUint32)2 },
+  { (void *)"\060\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123"
+"\061\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163"
+"\040\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165"
+"\162\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154"
+"\154\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101"
+"\061\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163"
+"\123\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157"
+"\157\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101"
+"\165\164\150\157\162\151\164\171"
+, (PRUint32)136 },
+  { (void *)"\002\001\001"
+, (PRUint32)3 },
+  { (void *)"\060\202\004\275\060\202\003\245\240\003\002\001\002\002\001\001"
+"\060\015\006\011\052\206\110\206\367\015\001\001\005\005\000\060"
+"\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123\061"
+"\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163\040"
+"\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165\162"
+"\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154\154"
+"\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101\061"
+"\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163\123"
+"\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157\157"
+"\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101\165"
+"\164\150\157\162\151\164\171\060\036\027\015\060\067\061\062\061"
+"\063\061\067\060\067\065\064\132\027\015\062\062\061\062\061\064"
+"\060\060\060\067\065\064\132\060\201\205\061\013\060\011\006\003"
+"\125\004\006\023\002\125\123\061\040\060\036\006\003\125\004\012"
+"\014\027\127\145\154\154\163\040\106\141\162\147\157\040\127\145"
+"\154\154\163\123\145\143\165\162\145\061\034\060\032\006\003\125"
+"\004\013\014\023\127\145\154\154\163\040\106\141\162\147\157\040"
+"\102\141\156\153\040\116\101\061\066\060\064\006\003\125\004\003"
+"\014\055\127\145\154\154\163\123\145\143\165\162\145\040\120\165"
+"\142\154\151\143\040\122\157\157\164\040\103\145\162\164\151\146"
+"\151\143\141\164\145\040\101\165\164\150\157\162\151\164\171\060"
+"\202\001\042\060\015\006\011\052\206\110\206\367\015\001\001\001"
+"\005\000\003\202\001\017\000\060\202\001\012\002\202\001\001\000"
+"\356\157\264\275\171\342\217\010\041\236\070\004\101\045\357\253"
+"\133\034\123\222\254\155\236\335\302\304\056\105\224\003\065\210"
+"\147\164\127\343\337\214\270\247\166\217\073\367\250\304\333\051"
+"\143\016\221\150\066\212\227\216\212\161\150\011\007\344\350\324"
+"\016\117\370\326\053\114\244\026\371\357\103\230\217\263\236\122"
+"\337\155\221\071\217\070\275\167\213\103\143\353\267\223\374\060"
+"\114\034\001\223\266\023\373\367\241\037\277\045\341\164\067\054"
+"\036\244\136\074\150\370\113\277\015\271\036\056\066\350\251\344"
+"\247\370\017\313\202\165\174\065\055\042\326\302\277\013\363\264"
+"\374\154\225\141\036\127\327\004\201\062\203\122\171\346\203\143"
+"\317\267\313\143\213\021\342\275\136\353\366\215\355\225\162\050"
+"\264\254\022\142\351\112\063\346\203\062\256\005\165\225\275\204"
+"\225\333\052\134\233\216\056\014\270\201\053\101\346\070\126\237"
+"\111\233\154\166\372\212\135\367\001\171\201\174\301\203\100\005"
+"\376\161\375\014\077\314\116\140\011\016\145\107\020\057\001\300"
+"\005\077\217\370\263\101\357\132\102\176\131\357\322\227\014\145"
+"\002\003\001\000\001\243\202\001\064\060\202\001\060\060\017\006"
+"\003\125\035\023\001\001\377\004\005\060\003\001\001\377\060\071"
+"\006\003\125\035\037\004\062\060\060\060\056\240\054\240\052\206"
+"\050\150\164\164\160\072\057\057\143\162\154\056\160\153\151\056"
+"\167\145\154\154\163\146\141\162\147\157\056\143\157\155\057\167"
+"\163\160\162\143\141\056\143\162\154\060\016\006\003\125\035\017"
+"\001\001\377\004\004\003\002\001\306\060\035\006\003\125\035\016"
+"\004\026\004\024\046\225\031\020\331\350\241\227\221\377\334\031"
+"\331\265\004\076\322\163\012\152\060\201\262\006\003\125\035\043"
+"\004\201\252\060\201\247\200\024\046\225\031\020\331\350\241\227"
+"\221\377\334\031\331\265\004\076\322\163\012\152\241\201\213\244"
+"\201\210\060\201\205\061\013\060\011\006\003\125\004\006\023\002"
+"\125\123\061\040\060\036\006\003\125\004\012\014\027\127\145\154"
+"\154\163\040\106\141\162\147\157\040\127\145\154\154\163\123\145"
+"\143\165\162\145\061\034\060\032\006\003\125\004\013\014\023\127"
+"\145\154\154\163\040\106\141\162\147\157\040\102\141\156\153\040"
+"\116\101\061\066\060\064\006\003\125\004\003\014\055\127\145\154"
+"\154\163\123\145\143\165\162\145\040\120\165\142\154\151\143\040"
+"\122\157\157\164\040\103\145\162\164\151\146\151\143\141\164\145"
+"\040\101\165\164\150\157\162\151\164\171\202\001\001\060\015\006"
+"\011\052\206\110\206\367\015\001\001\005\005\000\003\202\001\001"
+"\000\271\025\261\104\221\314\043\310\053\115\167\343\370\232\173"
+"\047\015\315\162\273\231\000\312\174\146\031\120\306\325\230\355"
+"\253\277\003\132\345\115\345\036\310\117\161\227\206\325\343\035"
+"\375\220\311\074\165\167\127\172\175\370\336\364\324\325\367\225"
+"\346\164\156\035\074\256\174\235\333\002\003\005\054\161\113\045"
+"\076\007\343\136\232\365\146\027\051\210\032\070\237\317\252\101"
+"\003\204\227\153\223\070\172\312\060\104\033\044\104\063\320\344"
+"\321\334\050\070\364\023\103\065\065\051\143\250\174\242\265\255"
+"\070\244\355\255\375\306\232\037\377\227\163\376\373\263\065\247"
+"\223\206\306\166\221\000\346\254\121\026\304\047\062\134\333\163"
+"\332\245\223\127\216\076\155\065\046\010\131\325\347\104\327\166"
+"\040\143\347\254\023\147\303\155\261\160\106\174\325\226\021\075"
+"\211\157\135\250\241\353\215\012\332\303\035\063\154\243\352\147"
+"\031\232\231\177\113\075\203\121\052\035\312\057\206\014\242\176"
+"\020\055\053\324\026\225\013\007\252\056\024\222\111\267\051\157"
+"\330\155\061\175\365\374\241\020\007\207\316\057\131\334\076\130"
+"\333"
+, (PRUint32)1217 }
+};
+static const NSSItem nss_builtins_items_249 [] = {
+  { (void *)&cko_netscape_trust, (PRUint32)sizeof(CK_OBJECT_CLASS) },
+  { (void *)&ck_true, (PRUint32)sizeof(CK_BBOOL) },
+  { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
+  { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) },
+  { (void *)"WellsSecure Public Root Certificate Authority", (PRUint32)46 },
+  { (void *)"\347\264\366\235\141\354\220\151\333\176\220\247\100\032\074\364"
+"\175\117\350\356"
+, (PRUint32)20 },
+  { (void *)"\025\254\245\302\222\055\171\274\350\177\313\147\355\002\317\066"
+, (PRUint32)16 },
+  { (void *)"\060\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123"
+"\061\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163"
+"\040\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165"
+"\162\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154"
+"\154\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101"
+"\061\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163"
+"\123\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157"
+"\157\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101"
+"\165\164\150\157\162\151\164\171"
+, (PRUint32)136 },
+  { (void *)"\002\001\001"
+, (PRUint32)3 },
+  { (void *)&ckt_netscape_trusted_delegator, (PRUint32)sizeof(CK_TRUST) },
+  { (void *)&ckt_netscape_trust_unknown, (PRUint32)sizeof(CK_TRUST) },
+  { (void *)&ckt_netscape_trust_unknown, (PRUint32)sizeof(CK_TRUST) },
+  { (void *)&ck_false, (PRUint32)sizeof(CK_BBOOL) }
+};
 
 builtinsInternalObject
 nss_builtins_data[] = {
 #ifdef DEBUG
   { 7, nss_builtins_types_0, nss_builtins_items_0, {NULL} },
 #endif /* DEBUG */
   { 5, nss_builtins_types_1, nss_builtins_items_1, {NULL} },
   { 11, nss_builtins_types_2, nss_builtins_items_2, {NULL} },
@@ -16972,16 +17115,18 @@ nss_builtins_data[] = {
   { 13, nss_builtins_types_239, nss_builtins_items_239, {NULL} },
   { 11, nss_builtins_types_240, nss_builtins_items_240, {NULL} },
   { 13, nss_builtins_types_241, nss_builtins_items_241, {NULL} },
   { 11, nss_builtins_types_242, nss_builtins_items_242, {NULL} },
   { 13, nss_builtins_types_243, nss_builtins_items_243, {NULL} },
   { 11, nss_builtins_types_244, nss_builtins_items_244, {NULL} },
   { 13, nss_builtins_types_245, nss_builtins_items_245, {NULL} },
   { 11, nss_builtins_types_246, nss_builtins_items_246, {NULL} },
-  { 13, nss_builtins_types_247, nss_builtins_items_247, {NULL} }
+  { 13, nss_builtins_types_247, nss_builtins_items_247, {NULL} },
+  { 11, nss_builtins_types_248, nss_builtins_items_248, {NULL} },
+  { 13, nss_builtins_types_249, nss_builtins_items_249, {NULL} }
 };
 const PRUint32
 #ifdef DEBUG
-  nss_builtins_nObjects = 247+1;
+  nss_builtins_nObjects = 249+1;
 #else
-  nss_builtins_nObjects = 247;
+  nss_builtins_nObjects = 249;
 #endif /* DEBUG */
--- a/security/nss/lib/ckfw/builtins/certdata.txt
+++ b/security/nss/lib/ckfw/builtins/certdata.txt
@@ -29,17 +29,17 @@
 # under the terms of either the GPL or the LGPL, and not to allow others to
 # use your version of this file under the terms of the MPL, indicate your
 # decision by deleting the provisions above and replace them with the notice
 # and other provisions required by the GPL or the LGPL. If you do not delete
 # the provisions above, a recipient may use your version of this file under
 # the terms of any one of the MPL, the GPL or the LGPL.
 #
 # ***** END LICENSE BLOCK *****
-CVS_ID "@(#) $RCSfile: certdata.txt,v $ $Revision: 1.47.2.1 $ $Date: 2008/05/03 03:13:22 $"
+CVS_ID "@(#) $RCSfile: certdata.txt,v $ $Revision: 1.49 $ $Date: 2008/08/14 18:15:56 $"
 
 #
 # certdata.txt
 #
 # This file contains the object definitions for the certs and other
 # information "built into" NSS.
 #
 # Object definitions:
@@ -2673,29 +2673,29 @@ CKA_ISSUER MULTILINE_OCTAL
 \060\127\061\013\060\011\006\003\125\004\006\023\002\102\105\061
 \031\060\027\006\003\125\004\012\023\020\107\154\157\142\141\154
 \123\151\147\156\040\156\166\055\163\141\061\020\060\016\006\003
 \125\004\013\023\007\122\157\157\164\040\103\101\061\033\060\031
 \006\003\125\004\003\023\022\107\154\157\142\141\154\123\151\147
 \156\040\122\157\157\164\040\103\101
 END
 CKA_SERIAL_NUMBER MULTILINE_OCTAL
-\002\013\002\000\000\000\000\000\326\170\267\224\005
-END
-CKA_VALUE MULTILINE_OCTAL
-\060\202\003\165\060\202\002\135\240\003\002\001\002\002\013\002
-\000\000\000\000\000\326\170\267\224\005\060\015\006\011\052\206
-\110\206\367\015\001\001\004\005\000\060\127\061\013\060\011\006
+\002\013\004\000\000\000\000\001\025\113\132\303\224
+END
+CKA_VALUE MULTILINE_OCTAL
+\060\202\003\165\060\202\002\135\240\003\002\001\002\002\013\004
+\000\000\000\000\001\025\113\132\303\224\060\015\006\011\052\206
+\110\206\367\015\001\001\005\005\000\060\127\061\013\060\011\006
 \003\125\004\006\023\002\102\105\061\031\060\027\006\003\125\004
 \012\023\020\107\154\157\142\141\154\123\151\147\156\040\156\166
 \055\163\141\061\020\060\016\006\003\125\004\013\023\007\122\157
 \157\164\040\103\101\061\033\060\031\006\003\125\004\003\023\022
 \107\154\157\142\141\154\123\151\147\156\040\122\157\157\164\040
 \103\101\060\036\027\015\071\070\060\071\060\061\061\062\060\060
-\060\060\132\027\015\061\064\060\061\062\070\061\062\060\060\060
+\060\060\132\027\015\062\070\060\061\062\070\061\062\060\060\060
 \060\132\060\127\061\013\060\011\006\003\125\004\006\023\002\102
 \105\061\031\060\027\006\003\125\004\012\023\020\107\154\157\142
 \141\154\123\151\147\156\040\156\166\055\163\141\061\020\060\016
 \006\003\125\004\013\023\007\122\157\157\164\040\103\101\061\033
 \060\031\006\003\125\004\003\023\022\107\154\157\142\141\154\123
 \151\147\156\040\122\157\157\164\040\103\101\060\202\001\042\060
 \015\006\011\052\206\110\206\367\015\001\001\001\005\000\003\202
 \001\017\000\060\202\001\012\002\202\001\001\000\332\016\346\231
@@ -2711,62 +2711,62 @@ CKA_VALUE MULTILINE_OCTAL
 \262\165\016\206\350\031\212\325\155\154\325\170\026\225\242\351
 \310\012\070\353\362\044\023\117\163\124\223\023\205\072\033\274
 \036\064\265\213\005\214\271\167\213\261\333\037\040\221\253\011
 \123\156\220\316\173\067\164\271\160\107\221\042\121\143\026\171
 \256\261\256\101\046\010\310\031\053\321\106\252\110\326\144\052
 \327\203\064\377\054\052\301\154\031\103\112\007\205\347\323\174
 \366\041\150\357\352\362\122\237\177\223\220\317\002\003\001\000
 \001\243\102\060\100\060\016\006\003\125\035\017\001\001\377\004
-\004\003\002\000\006\060\035\006\003\125\035\016\004\026\004\024
-\140\173\146\032\105\015\227\312\211\120\057\175\004\315\064\250
-\377\374\375\113\060\017\006\003\125\035\023\001\001\377\004\005
-\060\003\001\001\377\060\015\006\011\052\206\110\206\367\015\001
-\001\004\005\000\003\202\001\001\000\256\252\237\374\267\322\313
-\037\137\071\051\050\030\236\064\311\154\117\157\032\360\144\242
-\160\112\117\023\206\233\140\050\236\350\201\111\230\175\012\273
-\345\260\235\075\066\333\217\005\121\377\011\061\052\037\335\211
-\167\236\017\056\154\225\004\355\206\313\264\000\077\204\002\115
-\200\152\052\055\170\013\256\157\053\242\203\104\203\037\315\120
-\202\114\044\257\275\367\245\264\310\132\017\364\347\107\136\111
-\216\067\226\376\232\210\005\072\331\300\333\051\207\346\031\226
-\107\247\072\246\214\213\074\167\376\106\143\247\123\332\041\321
-\254\176\111\242\113\346\303\147\131\057\263\212\016\273\054\275
-\251\252\102\174\065\301\330\177\325\247\061\072\116\143\103\071
-\257\010\260\141\064\214\323\230\251\103\064\366\017\207\051\073
-\235\302\126\130\230\167\303\367\033\254\366\235\370\076\252\247
-\124\105\360\365\371\325\061\145\376\153\130\234\161\263\036\327
-\122\352\062\027\374\100\140\035\311\171\044\262\366\154\375\250
-\146\016\202\335\230\313\332\302\104\117\056\240\173\362\367\153
-\054\166\021\204\106\212\170\243\343
+\004\003\002\001\006\060\017\006\003\125\035\023\001\001\377\004
+\005\060\003\001\001\377\060\035\006\003\125\035\016\004\026\004
+\024\140\173\146\032\105\015\227\312\211\120\057\175\004\315\064
+\250\377\374\375\113\060\015\006\011\052\206\110\206\367\015\001
+\001\005\005\000\003\202\001\001\000\326\163\347\174\117\166\320
+\215\277\354\272\242\276\064\305\050\062\265\174\374\154\234\054
+\053\275\011\236\123\277\153\136\252\021\110\266\345\010\243\263
+\312\075\141\115\323\106\011\263\076\303\240\343\143\125\033\362
+\272\357\255\071\341\103\271\070\243\346\057\212\046\073\357\240
+\120\126\371\306\012\375\070\315\304\013\160\121\224\227\230\004
+\337\303\137\224\325\025\311\024\101\234\304\135\165\144\025\015
+\377\125\060\354\206\217\377\015\357\054\271\143\106\366\252\374
+\337\274\151\375\056\022\110\144\232\340\225\360\246\357\051\217
+\001\261\025\265\014\035\245\376\151\054\151\044\170\036\263\247
+\034\161\142\356\312\310\227\254\027\135\212\302\370\107\206\156
+\052\304\126\061\225\320\147\211\205\053\371\154\246\135\106\235
+\014\252\202\344\231\121\335\160\267\333\126\075\141\344\152\341
+\134\326\366\376\075\336\101\314\007\256\143\122\277\123\123\364
+\053\351\307\375\266\367\202\137\205\322\101\030\333\201\263\004
+\034\305\037\244\200\157\025\040\311\336\014\210\012\035\326\146
+\125\342\374\110\311\051\046\151\340
 END
 
 # Trust for Certificate "GlobalSign Root CA"
 CKA_CLASS CK_OBJECT_CLASS CKO_NETSCAPE_TRUST
 CKA_TOKEN CK_BBOOL CK_TRUE
 CKA_PRIVATE CK_BBOOL CK_FALSE
 CKA_MODIFIABLE CK_BBOOL CK_FALSE
 CKA_LABEL UTF8 "GlobalSign Root CA"
 CKA_CERT_SHA1_HASH MULTILINE_OCTAL
-\057\027\077\175\351\226\147\257\245\172\370\012\242\321\261\057
-\254\203\003\070
-END
-CKA_CERT_MD5_HASH MULTILINE_OCTAL
-\253\277\352\343\153\051\246\314\246\170\065\231\357\255\053\200
+\261\274\226\213\324\364\235\142\052\250\232\201\362\025\001\122
+\244\035\202\234
+END
+CKA_CERT_MD5_HASH MULTILINE_OCTAL
+\076\105\122\025\011\121\222\341\267\135\067\237\261\207\051\212
 END
 CKA_ISSUER MULTILINE_OCTAL
 \060\127\061\013\060\011\006\003\125\004\006\023\002\102\105\061
 \031\060\027\006\003\125\004\012\023\020\107\154\157\142\141\154
 \123\151\147\156\040\156\166\055\163\141\061\020\060\016\006\003
 \125\004\013\023\007\122\157\157\164\040\103\101\061\033\060\031
 \006\003\125\004\003\023\022\107\154\157\142\141\154\123\151\147
 \156\040\122\157\157\164\040\103\101
 END
 CKA_SERIAL_NUMBER MULTILINE_OCTAL
-\002\013\002\000\000\000\000\000\326\170\267\224\005
+\002\013\004\000\000\000\000\001\025\113\132\303\224
 END
 CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NETSCAPE_TRUSTED_DELEGATOR
 CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NETSCAPE_TRUSTED_DELEGATOR
 CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NETSCAPE_TRUSTED_DELEGATOR
 CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
 
 #
 # Certificate "GlobalSign Root CA - R2"
@@ -17236,8 +17236,155 @@ END
 CKA_SERIAL_NUMBER MULTILINE_OCTAL
 \002\020\127\313\063\157\302\134\026\346\107\026\027\343\220\061
 \150\340
 END
 CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NETSCAPE_TRUSTED_DELEGATOR
 CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NETSCAPE_TRUST_UNKNOWN
 CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NETSCAPE_TRUST_UNKNOWN
 CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
+
+#
+# Certificate "WellsSecure Public Root Certificate Authority"
+#
+CKA_CLASS CK_OBJECT_CLASS CKO_CERTIFICATE
+CKA_TOKEN CK_BBOOL CK_TRUE
+CKA_PRIVATE CK_BBOOL CK_FALSE
+CKA_MODIFIABLE CK_BBOOL CK_FALSE
+CKA_LABEL UTF8 "WellsSecure Public Root Certificate Authority"
+CKA_CERTIFICATE_TYPE CK_CERTIFICATE_TYPE CKC_X_509
+CKA_SUBJECT MULTILINE_OCTAL
+\060\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123
+\061\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163
+\040\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165
+\162\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154
+\154\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101
+\061\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163
+\123\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157
+\157\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101
+\165\164\150\157\162\151\164\171
+END
+CKA_ID UTF8 "0"
+CKA_ISSUER MULTILINE_OCTAL
+\060\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123
+\061\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163
+\040\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165
+\162\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154
+\154\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101
+\061\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163
+\123\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157
+\157\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101
+\165\164\150\157\162\151\164\171
+END
+CKA_SERIAL_NUMBER MULTILINE_OCTAL
+\002\001\001
+END
+CKA_VALUE MULTILINE_OCTAL
+\060\202\004\275\060\202\003\245\240\003\002\001\002\002\001\001
+\060\015\006\011\052\206\110\206\367\015\001\001\005\005\000\060
+\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123\061
+\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163\040
+\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165\162
+\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154\154
+\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101\061
+\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163\123
+\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157\157
+\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101\165
+\164\150\157\162\151\164\171\060\036\027\015\060\067\061\062\061
+\063\061\067\060\067\065\064\132\027\015\062\062\061\062\061\064
+\060\060\060\067\065\064\132\060\201\205\061\013\060\011\006\003
+\125\004\006\023\002\125\123\061\040\060\036\006\003\125\004\012
+\014\027\127\145\154\154\163\040\106\141\162\147\157\040\127\145
+\154\154\163\123\145\143\165\162\145\061\034\060\032\006\003\125
+\004\013\014\023\127\145\154\154\163\040\106\141\162\147\157\040
+\102\141\156\153\040\116\101\061\066\060\064\006\003\125\004\003
+\014\055\127\145\154\154\163\123\145\143\165\162\145\040\120\165
+\142\154\151\143\040\122\157\157\164\040\103\145\162\164\151\146
+\151\143\141\164\145\040\101\165\164\150\157\162\151\164\171\060
+\202\001\042\060\015\006\011\052\206\110\206\367\015\001\001\001
+\005\000\003\202\001\017\000\060\202\001\012\002\202\001\001\000
+\356\157\264\275\171\342\217\010\041\236\070\004\101\045\357\253
+\133\034\123\222\254\155\236\335\302\304\056\105\224\003\065\210
+\147\164\127\343\337\214\270\247\166\217\073\367\250\304\333\051
+\143\016\221\150\066\212\227\216\212\161\150\011\007\344\350\324
+\016\117\370\326\053\114\244\026\371\357\103\230\217\263\236\122
+\337\155\221\071\217\070\275\167\213\103\143\353\267\223\374\060
+\114\034\001\223\266\023\373\367\241\037\277\045\341\164\067\054
+\036\244\136\074\150\370\113\277\015\271\036\056\066\350\251\344
+\247\370\017\313\202\165\174\065\055\042\326\302\277\013\363\264
+\374\154\225\141\036\127\327\004\201\062\203\122\171\346\203\143
+\317\267\313\143\213\021\342\275\136\353\366\215\355\225\162\050
+\264\254\022\142\351\112\063\346\203\062\256\005\165\225\275\204
+\225\333\052\134\233\216\056\014\270\201\053\101\346\070\126\237
+\111\233\154\166\372\212\135\367\001\171\201\174\301\203\100\005
+\376\161\375\014\077\314\116\140\011\016\145\107\020\057\001\300
+\005\077\217\370\263\101\357\132\102\176\131\357\322\227\014\145
+\002\003\001\000\001\243\202\001\064\060\202\001\060\060\017\006
+\003\125\035\023\001\001\377\004\005\060\003\001\001\377\060\071
+\006\003\125\035\037\004\062\060\060\060\056\240\054\240\052\206
+\050\150\164\164\160\072\057\057\143\162\154\056\160\153\151\056
+\167\145\154\154\163\146\141\162\147\157\056\143\157\155\057\167
+\163\160\162\143\141\056\143\162\154\060\016\006\003\125\035\017
+\001\001\377\004\004\003\002\001\306\060\035\006\003\125\035\016
+\004\026\004\024\046\225\031\020\331\350\241\227\221\377\334\031
+\331\265\004\076\322\163\012\152\060\201\262\006\003\125\035\043
+\004\201\252\060\201\247\200\024\046\225\031\020\331\350\241\227
+\221\377\334\031\331\265\004\076\322\163\012\152\241\201\213\244
+\201\210\060\201\205\061\013\060\011\006\003\125\004\006\023\002
+\125\123\061\040\060\036\006\003\125\004\012\014\027\127\145\154
+\154\163\040\106\141\162\147\157\040\127\145\154\154\163\123\145
+\143\165\162\145\061\034\060\032\006\003\125\004\013\014\023\127
+\145\154\154\163\040\106\141\162\147\157\040\102\141\156\153\040
+\116\101\061\066\060\064\006\003\125\004\003\014\055\127\145\154
+\154\163\123\145\143\165\162\145\040\120\165\142\154\151\143\040
+\122\157\157\164\040\103\145\162\164\151\146\151\143\141\164\145
+\040\101\165\164\150\157\162\151\164\171\202\001\001\060\015\006
+\011\052\206\110\206\367\015\001\001\005\005\000\003\202\001\001
+\000\271\025\261\104\221\314\043\310\053\115\167\343\370\232\173
+\047\015\315\162\273\231\000\312\174\146\031\120\306\325\230\355
+\253\277\003\132\345\115\345\036\310\117\161\227\206\325\343\035
+\375\220\311\074\165\167\127\172\175\370\336\364\324\325\367\225
+\346\164\156\035\074\256\174\235\333\002\003\005\054\161\113\045
+\076\007\343\136\232\365\146\027\051\210\032\070\237\317\252\101
+\003\204\227\153\223\070\172\312\060\104\033\044\104\063\320\344
+\321\334\050\070\364\023\103\065\065\051\143\250\174\242\265\255
+\070\244\355\255\375\306\232\037\377\227\163\376\373\263\065\247
+\223\206\306\166\221\000\346\254\121\026\304\047\062\134\333\163
+\332\245\223\127\216\076\155\065\046\010\131\325\347\104\327\166
+\040\143\347\254\023\147\303\155\261\160\106\174\325\226\021\075
+\211\157\135\250\241\353\215\012\332\303\035\063\154\243\352\147
+\031\232\231\177\113\075\203\121\052\035\312\057\206\014\242\176
+\020\055\053\324\026\225\013\007\252\056\024\222\111\267\051\157
+\330\155\061\175\365\374\241\020\007\207\316\057\131\334\076\130
+\333
+END
+
+# Trust for Certificate "WellsSecure Public Root Certificate Authority"
+CKA_CLASS CK_OBJECT_CLASS CKO_NETSCAPE_TRUST
+CKA_TOKEN CK_BBOOL CK_TRUE
+CKA_PRIVATE CK_BBOOL CK_FALSE
+CKA_MODIFIABLE CK_BBOOL CK_FALSE
+CKA_LABEL UTF8 "WellsSecure Public Root Certificate Authority"
+CKA_CERT_SHA1_HASH MULTILINE_OCTAL
+\347\264\366\235\141\354\220\151\333\176\220\247\100\032\074\364
+\175\117\350\356
+END
+CKA_CERT_MD5_HASH MULTILINE_OCTAL
+\025\254\245\302\222\055\171\274\350\177\313\147\355\002\317\066
+END
+CKA_ISSUER MULTILINE_OCTAL
+\060\201\205\061\013\060\011\006\003\125\004\006\023\002\125\123
+\061\040\060\036\006\003\125\004\012\014\027\127\145\154\154\163
+\040\106\141\162\147\157\040\127\145\154\154\163\123\145\143\165
+\162\145\061\034\060\032\006\003\125\004\013\014\023\127\145\154
+\154\163\040\106\141\162\147\157\040\102\141\156\153\040\116\101
+\061\066\060\064\006\003\125\004\003\014\055\127\145\154\154\163
+\123\145\143\165\162\145\040\120\165\142\154\151\143\040\122\157
+\157\164\040\103\145\162\164\151\146\151\143\141\164\145\040\101
+\165\164\150\157\162\151\164\171
+END
+CKA_SERIAL_NUMBER MULTILINE_OCTAL
+\002\001\001
+END
+CKA_TRUST_SERVER_AUTH CK_TRUST CKT_NETSCAPE_TRUSTED_DELEGATOR
+CKA_TRUST_EMAIL_PROTECTION CK_TRUST CKT_NETSCAPE_TRUST_UNKNOWN
+CKA_TRUST_CODE_SIGNING CK_TRUST CKT_NETSCAPE_TRUST_UNKNOWN
+CKA_TRUST_STEP_UP_APPROVED CK_BBOOL CK_FALSE
--- a/security/nss/lib/ckfw/builtins/nssckbi.h
+++ b/security/nss/lib/ckfw/builtins/nssckbi.h
@@ -70,18 +70,18 @@
  *     ...
  *   - NSS 3.30 branch: 250-255
  *
  * NSS_BUILTINS_LIBRARY_VERSION_MINOR is a CK_BYTE.  It's not clear
  * whether we may use its full range (0-255) or only 0-99 because
  * of the comment in the CK_VERSION type definition.
  */
 #define NSS_BUILTINS_LIBRARY_VERSION_MAJOR 1
-#define NSS_BUILTINS_LIBRARY_VERSION_MINOR 70
-#define NSS_BUILTINS_LIBRARY_VERSION "1.70"
+#define NSS_BUILTINS_LIBRARY_VERSION_MINOR 71
+#define NSS_BUILTINS_LIBRARY_VERSION "1.71"
 
 /* These version numbers detail the semantic changes to the ckfw engine. */
 #define NSS_BUILTINS_HARDWARE_VERSION_MAJOR 1
 #define NSS_BUILTINS_HARDWARE_VERSION_MINOR 0
 
 /* These version numbers detail the semantic changes to ckbi itself 
  * (new PKCS #11 objects), etc. */
 #define NSS_BUILTINS_FIRMWARE_VERSION_MAJOR 1
--- a/security/nss/lib/ckfw/capi/ckcapi.h
+++ b/security/nss/lib/ckfw/capi/ckcapi.h
@@ -35,17 +35,17 @@
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifndef CKCAPI_H
 #define CKCAPI_H 1
 
 #ifdef DEBUG
-static const char CKCAPI_CVS_ID[] = "@(#) $RCSfile: ckcapi.h,v $ $Revision: 1.2 $ $Date: 2005/11/15 00:13:58 $";
+static const char CKCAPI_CVS_ID[] = "@(#) $RCSfile: ckcapi.h,v $ $Revision: 1.3 $ $Date: 2008/08/11 08:14:10 $";
 #endif /* DEBUG */
 
 #include "nssckmdt.h"
 #include "nssckfw.h"
 
 /*
  * I'm including this for access to the arena functions.
  * Looks like we should publish that API.
@@ -56,18 +56,18 @@ static const char CKCAPI_CVS_ID[] = "@(#
 
 /*
  * This is where the Netscape extensions live, at least for now.
  */
 #ifndef CKT_H
 #include "ckt.h"
 #endif /* CKT_H */
 
-#include "WTypes.h"
-#include "WinCrypt.h"
+#include "wtypes.h"
+#include "wincrypt.h"
 
 /*
  * statically defined raw objects. Allows us to data description objects
  * to this PKCS #11 module.
  */
 struct ckcapiRawObjectStr {
   CK_ULONG n;
   const CK_ATTRIBUTE_TYPE *types;
--- a/security/nss/lib/ckfw/mutex.c
+++ b/security/nss/lib/ckfw/mutex.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: mutex.c,v $ $Revision: 1.7 $ $Date: 2005/08/25 20:08:26 $";
+static const char CVS_ID[] = "@(#) $RCSfile: mutex.c,v $ $Revision: 1.8 $ $Date: 2008/06/06 01:15:32 $";
 #endif /* DEBUG */
 
 /*
  * mutex.c
  *
  * This file implements a mutual-exclusion locking facility for Modules
  * using the NSS Cryptoki Framework.
  */
@@ -106,25 +106,16 @@ nssCKFWMutex_verifyPointer
   const NSSCKFWMutex *fwMutex
 )
 {
   return CKR_OK;
 }
 
 #endif /* DEBUG */
 
-static CK_RV
-mutex_noop
-(
-  CK_VOID_PTR pMutex
-)
-{
-  return CKR_OK;
-}
-
 /*
  * nssCKFWMutex_Create
  *
  */
 NSS_EXTERN NSSCKFWMutex *
 nssCKFWMutex_Create
 (
   CK_C_INITIALIZE_ARGS_PTR pInitArgs,
deleted file mode 100644
--- a/security/nss/lib/ckfw/nsprstub.c
+++ /dev/null
@@ -1,529 +0,0 @@
-/* ***** BEGIN LICENSE BLOCK *****
- * Version: MPL 1.1/GPL 2.0/LGPL 2.1
- *
- * The contents of this file are subject to the Mozilla Public License Version
- * 1.1 (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- * http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS IS" basis,
- * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
- * for the specific language governing rights and limitations under the
- * License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is
- * Netscape Communications Corporation.
- * Portions created by the Initial Developer are Copyright (C) 1994-2000
- * the Initial Developer. All Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the terms of
- * either the GNU General Public License Version 2 or later (the "GPL"), or
- * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
- * in which case the provisions of the GPL or the LGPL are applicable instead
- * of those above. If you wish to allow use of your version of this file only
- * under the terms of either the GPL or the LGPL, and not to allow others to
- * use your version of this file under the terms of the MPL, indicate your
- * decision by deleting the provisions above and replace them with the notice
- * and other provisions required by the GPL or the LGPL. If you do not delete
- * the provisions above, a recipient may use your version of this file under
- * the terms of any one of the MPL, the GPL or the LGPL.
- *
- * ***** END LICENSE BLOCK ***** */
-/*
- * secport.c - portability interfaces for security libraries
- *
- * This file abstracts out libc functionality that libsec depends on
- * 
- * NOTE - These are not public interfaces. These stubs are to allow the 
- * SW FORTEZZA to link with some low level security functions without dragging
- * in NSPR.
- *
- * $Id: nsprstub.c,v 1.7 2007/07/24 16:14:15 biswatosh.chakraborty%sun.com Exp $
- */
-
-#include "seccomon.h"
-#include "prmem.h"
-#include "prerror.h"
-#include "plarena.h"
-#include "secerr.h"
-#include "prmon.h"
-#include "prbit.h"
-#include "ck.h"
-
-#ifdef notdef
-unsigned long port_allocFailures;
-
-/* locations for registering Unicode conversion functions.  
- *  Is this the appropriate location?  or should they be
- *     moved to client/server specific locations?
- */
-PORTCharConversionFunc ucs4Utf8ConvertFunc;
-PORTCharConversionFunc ucs2Utf8ConvertFunc;
-PORTCharConversionWSwapFunc  ucs2AsciiConvertFunc;
-
-void *
-PORT_Alloc(size_t bytes)
-{
-    void *rv;
-
-    /* Always allocate a non-zero amount of bytes */
-    rv = (void *)malloc(bytes ? bytes : 1);
-    if (!rv) {
-	++port_allocFailures;
-	PORT_SetError(SEC_ERROR_NO_MEMORY);
-    }
-    return rv;
-}
-
-void *
-PORT_Realloc(void *oldptr, size_t bytes)
-{
-    void *rv;
-
-    rv = (void *)realloc(oldptr, bytes);
-    if (!rv) {
-	++port_allocFailures;
-	PORT_SetError(SEC_ERROR_NO_MEMORY);
-    }
-    return rv;
-}
-
-void *
-PORT_ZAlloc(size_t bytes)
-{
-    void *rv;
-
-    /* Always allocate a non-zero amount of bytes */
-    rv = (void *)calloc(1, bytes ? bytes : 1);
-    if (!rv) {
-	++port_allocFailures;
-	PORT_SetError(SEC_ERROR_NO_MEMORY);
-    }
-    return rv;
-}
-
-void
-PORT_Free(void *ptr)
-{
-    if (ptr) {
-	free(ptr);
-    }
-}
-
-void
-PORT_ZFree(void *ptr, size_t len)
-{
-    if (ptr) {
-	memset(ptr, 0, len);
-	free(ptr);
-    }
-}
-
-/********************* Arena code follows *****************************/
-
-
-PLArenaPool *
-PORT_NewArena(unsigned long chunksize)
-{
-    PLArenaPool *arena;
-    
-    arena = (PLArenaPool*)PORT_ZAlloc(sizeof(PLArenaPool));
-    if ( arena != NULL ) {
-	PR_InitArenaPool(arena, "security", chunksize, sizeof(double));
-    }
-    return(arena);
-}
-
-void *
-PORT_ArenaAlloc(PLArenaPool *arena, size_t size)
-{
-    void *p;
-
-    PL_ARENA_ALLOCATE(p, arena, size);
-    if (p == NULL) {
-	++port_allocFailures;
-	PORT_SetError(SEC_ERROR_NO_MEMORY);
-    }
-
-    return(p);
-}
-
-void *
-PORT_ArenaZAlloc(PLArenaPool *arena, size_t size)
-{
-    void *p;
-
-    PL_ARENA_ALLOCATE(p, arena, size);
-    if (p == NULL) {
-	++port_allocFailures;
-	PORT_SetError(SEC_ERROR_NO_MEMORY);
-    } else {
-	PORT_Memset(p, 0, size);
-    }
-
-    return(p);
-}
-
-/* need to zeroize!! */
-void
-PORT_FreeArena(PLArenaPool *arena, PRBool zero)
-{
-    PR_FinishArenaPool(arena);
-    PORT_Free(arena);
-}
-
-void *
-PORT_ArenaGrow(PLArenaPool *arena, void *ptr, size_t oldsize, size_t newsize)
-{
-    PORT_Assert(newsize >= oldsize);
-    
-    PL_ARENA_GROW(ptr, arena, oldsize, ( newsize - oldsize ) );
-    
-    if (ptr == NULL) { 
-        ++port_allocFailures;
-        PORT_SetError(SEC_ERROR_NO_MEMORY);
-    }
-    return(ptr);
-}
-
-void *
-PORT_ArenaMark(PLArenaPool *arena)
-{
-    void * result;
-
-    result = PL_ARENA_MARK(arena);
-    return result;
-}
-
-void
-PORT_ArenaRelease(PLArenaPool *arena, void *mark)
-{
-    PL_ARENA_RELEASE(arena, mark);
-}
-
-void
-PORT_ArenaUnmark(PLArenaPool *arena, void *mark)
-{
-    /* do nothing */
-}
-
-char *
-PORT_ArenaStrdup(PLArenaPool *arena,const char *str) {
-    int len = PORT_Strlen(str)+1;
-    char *newstr;
-
-    newstr = (char*)PORT_ArenaAlloc(arena,len);
-    if (newstr) {
-        PORT_Memcpy(newstr,str,len);
-    }
-    return newstr;
-}
-#endif
-
-/*
- * replace the nice thread-safe Error stack code with something
- * that will work without all the NSPR features.
- */
-static PRInt32 stack[2] = {0, 0};
-
-PR_IMPLEMENT(void)
-nss_SetError(PRUint32 value)
-{	
-    stack[0] = value;
-    return;
-}
-
-PR_IMPLEMENT(PRInt32)
-NSS_GetError(void)
-{
-    return(stack[0]);
-}
-
-
-PR_IMPLEMENT(PRInt32 *)
-NSS_GetErrorStack(void)
-{
-    return(&stack[0]);
-}
-
-PR_IMPLEMENT(void)
-nss_ClearErrorStack(void)
-{
-    stack[0] = 0;
-    return;
-}
-
-#ifdef DEBUG
-/*
- * replace the pointer tracking stuff for the same reasons.
- *  If you want to turn pointer tracking on, simply ifdef out this code and 
- *  link with real NSPR.
- */
-PR_IMPLEMENT(PRStatus)
-nssPointerTracker_initialize(nssPointerTracker *tracker)
-{
-    return PR_SUCCESS;
-}
-
-
-PR_IMPLEMENT(PRStatus)
-nssPointerTracker_finalize(nssPointerTracker *tracker)
-{
-    return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus)
-nssPointerTracker_add(nssPointerTracker *tracker, const void *pointer)
-{
-     return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus)
-nssPointerTracker_remove(nssPointerTracker *tracker, const void *pointer)
-{
-     return PR_SUCCESS;
-}
-
-PR_IMPLEMENT(PRStatus)
-nssPointerTracker_verify(nssPointerTracker *tracker, const void *pointer)
-{
-     return PR_SUCCESS;
-}
-#endif
-
-/*
- * Do not use NSPR stubs for MinGW because they can't resolve references
- * to the _imp__PR_XXX symbols.  This is merely an expedient hack and not
- * the right solution.
- */
-#if !(defined(WIN32) && defined(__GNUC__))
-PR_IMPLEMENT(PRThread *)
-PR_GetCurrentThread(void)
-{
-     return (PRThread *)1;
-}
-
-
-
-PR_IMPLEMENT(void)
-PR_Assert(const char *expr, const char *file, int line) {
-    return; 
-}
-
-PR_IMPLEMENT(void *)
-PR_Alloc(PRUint32 bytes) { return malloc(bytes); }
-
-PR_IMPLEMENT(void *)
-PR_Malloc(PRUint32 bytes) { return malloc(bytes); }
-
-PR_IMPLEMENT(void *)
-PR_Calloc(PRUint32 blocks, PRUint32 bytes) { return calloc(blocks,bytes); }
-
-PR_IMPLEMENT(void *)
-PR_Realloc(void * blocks, PRUint32 bytes) { return realloc(blocks,bytes); }
-
-PR_IMPLEMENT(void)
-PR_Free(void *ptr) { free(ptr); }
-
-#ifdef notdef
-/* Old template; want to expunge it eventually. */
-#include "secasn1.h"
-#include "secoid.h"
-
-const SEC_ASN1Template SECOID_AlgorithmIDTemplate[] = {
-    { SEC_ASN1_SEQUENCE,
-	  0, NULL, sizeof(SECAlgorithmID) },
-    { SEC_ASN1_OBJECT_ID,
-	  offsetof(SECAlgorithmID,algorithm), },
-    { SEC_ASN1_OPTIONAL | SEC_ASN1_ANY,
-	  offsetof(SECAlgorithmID,parameters), },
-    { 0, }
-};
-
-PR_IMPLEMENT(PRStatus) PR_Sleep(PRIntervalTime ticks) { return PR_SUCCESS; }
-
-/* This is not atomic! */
-PR_IMPLEMENT(PRInt32) PR_AtomicDecrement(PRInt32 *val) { return --(*val); }
-
-PR_IMPLEMENT(PRInt32) PR_AtomicSet(PRInt32 *val) { return ++(*val); }
-
-#endif
-
-/* now make the RNG happy */ /* This is not atomic! */
-PR_IMPLEMENT(PRInt32) PR_AtomicIncrement(PRInt32 *val) { return ++(*val); }
-#endif /* ! (WIN32 && GCC) */
-
-static CK_C_INITIALIZE_ARGS_PTR nssstub_pInitArgs = NULL;
-static CK_C_INITIALIZE_ARGS nssstub_initArgs;
-static NSSArena *nssstub_arena = NULL;
-static CryptokiLockingState nssstub_LockingState = SingleThreaded;
-
-PR_IMPLEMENT(CK_RV)
-nssSetLockArgs(CK_C_INITIALIZE_ARGS_PTR pInitArgs, CryptokiLockingState* returned)
-{
-    CK_ULONG count = (CK_ULONG)0;
-    CK_BBOOL os_ok = CK_FALSE;
-    CK_RV rv = CKR_OK;
-    if (nssstub_pInitArgs == NULL) {
-	if (pInitArgs != NULL) {
-	    nssstub_initArgs = *pInitArgs;
-	    nssstub_pInitArgs = &nssstub_initArgs;
-            if( (CK_CREATEMUTEX )NULL != pInitArgs->CreateMutex  ) count++;
-            if( (CK_DESTROYMUTEX)NULL != pInitArgs->DestroyMutex ) count++;
-            if( (CK_LOCKMUTEX   )NULL != pInitArgs->LockMutex    ) count++;
-            if( (CK_UNLOCKMUTEX )NULL != pInitArgs->UnlockMutex  ) count++;
-            os_ok = (pInitArgs->flags & CKF_OS_LOCKING_OK) ? CK_TRUE : CK_FALSE;
-
-            if( (0 != count) && (4 != count) ) {
-                rv = CKR_ARGUMENTS_BAD;
-                goto loser;
-            }
-	} else {
-	    nssstub_pInitArgs = pInitArgs;
-	}
-	/* nssstub_arena = NSSArena_Create(); */
-    }
-
-    if( (0 == count) && (CK_TRUE == os_ok) ) {
-      /*
-       * This is case #2 in the description of C_Initialize:
-       * The library will be called in a multithreaded way, but
-       * no routines were specified: os locking calls should be
-       * used.  Unfortunately, this can be hard.. like, I think
-       * I may have to dynamically look up the entry points in
-       * the instance of NSPR already going in the application.
-       *
-       * I know that *we* always specify routines, so this only
-       * comes up if someone is using NSS to create their own
-       * PCKS#11 modules for other products.  Oh, heck, I'll 
-       * worry about this then.
-       */
-      rv = CKR_CANT_LOCK;
-      goto loser;
-    }
-
-    if( 0 == count ) {
-      /*
-       * With the above test out of the way, we know this is case
-       * #1 in the description of C_Initialize: this library will
-       * not be called in a multithreaded way.
-       */
-
-      nssstub_LockingState = SingleThreaded;
-    } else {
-      /*
-       * We know that we're in either case #3 or #4 in the description
-       * of C_Initialize.  Case #3 says we should use the specified
-       * functions, case #4 cays we can use either the specified ones
-       * or the OS ones.  I'll use the specified ones.
-       */
-      nssstub_LockingState = MultiThreaded;
-    }
-
-    loser:
-    *returned = nssstub_LockingState;
-    return rv;
-}
-
-/*
- * Do not use NSPR stubs for MinGW because they can't resolve references
- * to the _imp__PR_XXX symbols.  This is merely an expedient hack and not
- * the right solution.
- */
-#if !(defined(WIN32) && defined(__GNUC__))
-#include "prlock.h"
-PR_IMPLEMENT(PRLock *)
-PR_NewLock(void) {
-	PRLock *lock = NULL;
-	NSSCKFWMutex *mlock = NULL;
-	CK_RV error;
-
-	mlock = nssCKFWMutex_Create(nssstub_pInitArgs,nssstub_LockingState,nssstub_arena,&error);
-	lock = (PRLock *)mlock;
-
-	/* if we don't have a lock, nssCKFWMutex can deal with things */
-	if (lock == NULL) lock=(PRLock *) 1;
-	return lock;
-}
-
-PR_IMPLEMENT(void) 
-PR_DestroyLock(PRLock *lock) {
-	NSSCKFWMutex *mlock = (NSSCKFWMutex *)lock;
-	if (lock == (PRLock *)1) return;
-	nssCKFWMutex_Destroy(mlock);
-}
-
-PR_IMPLEMENT(void) 
-PR_Lock(PRLock *lock) {
-	NSSCKFWMutex *mlock = (NSSCKFWMutex *)lock;
-	if (lock == (PRLock *)1) return;
-	nssCKFWMutex_Lock(mlock);
-}
-
-PR_IMPLEMENT(PRStatus) 
-PR_Unlock(PRLock *lock) {
-	NSSCKFWMutex *mlock = (NSSCKFWMutex *)lock;
-	if (lock == (PRLock *)1) return PR_SUCCESS;
-	nssCKFWMutex_Unlock(mlock);
-	return PR_SUCCESS;
-}
-
-#ifdef notdef
-#endif
-/* this implementation is here to satisfy the PRMonitor use in plarena.c.
-** It appears that it doesn't need re-entrant locks.  It could have used
-** PRLock instead of PRMonitor.  So, this implementation just uses 
-** PRLock for a PRMonitor.
-*/
-PR_IMPLEMENT(PRMonitor*) 
-PR_NewMonitor(void)
-{
-    return (PRMonitor *) PR_NewLock();
-}
-
-
-PR_IMPLEMENT(void) 
-PR_EnterMonitor(PRMonitor *mon)
-{
-    PR_Lock( (PRLock *)mon );
-}
-
-PR_IMPLEMENT(PRStatus) 
-PR_ExitMonitor(PRMonitor *mon)
-{
-    return PR_Unlock( (PRLock *)mon );
-}
-
-#include "prinit.h"
-
-/* This is NOT threadsafe.  It is merely a pseudo-functional stub.
-*/
-PR_IMPLEMENT(PRStatus) PR_CallOnce(
-    PRCallOnceType *once,
-    PRCallOnceFN    func)
-{
-    /* This is not really atomic! */
-    if (1 == PR_AtomicIncrement(&once->initialized)) {
-	once->status = (*func)();
-    }  else {
-    	/* Should wait to be sure that func has finished before returning. */
-    }
-    return once->status;
-}
-
-/*
-** Compute the log of the least power of 2 greater than or equal to n
-*/
-PRIntn PR_CeilingLog2(PRUint32 i) {
-	PRIntn log2;
-	PR_CEILING_LOG2(log2,i);
-	return log2;
-}
-#endif /* ! (WIN32 && GCC) */
-
-/********************** end of arena functions ***********************/
-
--- a/security/nss/lib/cryptohi/cryptohi.h
+++ b/security/nss/lib/cryptohi/cryptohi.h
@@ -32,17 +32,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: cryptohi.h,v 1.11 2006/03/15 21:42:21 rrelyea%redhat.com Exp $ */
+/* $Id: cryptohi.h,v 1.12 2008/06/14 14:20:00 wtc%google.com Exp $ */
 
 #ifndef _CRYPTOHI_H_
 #define _CRYPTOHI_H_
 
 #include "blapit.h"
 
 #include "seccomon.h"
 #include "secoidt.h"
@@ -157,17 +157,17 @@ extern SECStatus SGN_Digest(SECKEYPrivat
 ** using SEC_SignData, then wraps it with an CERTSignedData and then der
 ** encodes the result.
 **	"arena" is the memory arena to use to allocate data from
 ** 	"result" the final der encoded data (memory is allocated)
 ** 	"buf" the input data to sign
 ** 	"len" the amount of data to sign
 ** 	"pk" the private key to encrypt with
 */
-extern SECStatus SEC_DerSignData(PRArenaPool *arena, SECItem *result,
+extern SECStatus SEC_DerSignData(PLArenaPool *arena, SECItem *result,
 				unsigned char *buf, int len,
 				SECKEYPrivateKey *pk, SECOidTag algid);
 
 /*
 ** Destroy a signed-data object.
 **	"sd" the object
 **	"freeit" if PR_TRUE then free the object as well as its sub-objects
 */
--- a/security/nss/lib/cryptohi/keyhi.h
+++ b/security/nss/lib/cryptohi/keyhi.h
@@ -30,17 +30,17 @@
  * under the terms of either the GPL or the LGPL, and not to allow others to
  * use your version of this file under the terms of the MPL, indicate your
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
-/* $Id: keyhi.h,v 1.16 2006/05/31 23:54:51 wtchang%redhat.com Exp $ */
+/* $Id: keyhi.h,v 1.17 2008/06/14 14:20:00 wtc%google.com Exp $ */
 
 #ifndef _KEYHI_H_
 #define _KEYHI_H_
 
 #include "plarena.h"
 
 #include "seccomon.h"
 #include "secoidt.h"
@@ -56,17 +56,17 @@ SEC_BEGIN_PROTOS
 ** Destroy a subject-public-key-info object.
 */
 extern void SECKEY_DestroySubjectPublicKeyInfo(CERTSubjectPublicKeyInfo *spki);
 
 /*
 ** Copy subject-public-key-info "src" to "dst". "dst" is filled in
 ** appropriately (memory is allocated for each of the sub objects).
 */
-extern SECStatus SECKEY_CopySubjectPublicKeyInfo(PRArenaPool *arena,
+extern SECStatus SECKEY_CopySubjectPublicKeyInfo(PLArenaPool *arena,
 					     CERTSubjectPublicKeyInfo *dst,
 					     CERTSubjectPublicKeyInfo *src);
 
 /*
 ** Update the PQG parameters for a cert's public key.
 ** Only done for DSA and Fortezza certs
 */
 extern SECStatus
@@ -217,33 +217,33 @@ SECKEY_DestroyEncryptedPrivateKeyInfo(SE
  *  poolp is the arena into which the contents of from is to be copied.
  *	NULL is a valid entry.
  *  to is the destination private key info
  *  from is the source private key info
  * if either from or to is NULL or an error occurs, SECFailure is 
  * returned.  otherwise, SECSuccess is returned.
  */
 extern SECStatus
-SECKEY_CopyPrivateKeyInfo(PRArenaPool *poolp,
+SECKEY_CopyPrivateKeyInfo(PLArenaPool *poolp,
 			  SECKEYPrivateKeyInfo *to,
 			  SECKEYPrivateKeyInfo *from);
 
 extern SECStatus
 SECKEY_CacheStaticFlags(SECKEYPrivateKey* key);
 
 /* Copy encrypted private key info structure.  
  *  poolp is the arena into which the contents of from is to be copied.
  *	NULL is a valid entry.
  *  to is the destination encrypted private key info
  *  from is the source encrypted private key info
  * if either from or to is NULL or an error occurs, SECFailure is 
  * returned.  otherwise, SECSuccess is returned.
  */
 extern SECStatus
-SECKEY_CopyEncryptedPrivateKeyInfo(PRArenaPool *poolp,
+SECKEY_CopyEncryptedPrivateKeyInfo(PLArenaPool *poolp,
 				   SECKEYEncryptedPrivateKeyInfo *to,
 				   SECKEYEncryptedPrivateKeyInfo *from);
 /*
  * Accessor functions for key type of public and private keys.
  */
 KeyType SECKEY_GetPrivateKeyType(SECKEYPrivateKey *privKey);
 KeyType SECKEY_GetPublicKeyType(SECKEYPublicKey *pubKey);
 
--- a/security/nss/lib/cryptohi/keythi.h
+++ b/security/nss/lib/cryptohi/keythi.h
@@ -71,29 +71,29 @@ SEC_END_PROTOS
 
 
 /*
 ** RSA Public Key structures
 ** member names from PKCS#1, section 7.1 
 */
 
 struct SECKEYRSAPublicKeyStr {
-    PRArenaPool * arena;
+    PLArenaPool * arena;
     SECItem modulus;
     SECItem publicExponent;
 };
 typedef struct SECKEYRSAPublicKeyStr SECKEYRSAPublicKey;
 
 
 /*
 ** DSA Public Key and related structures
 */
 
 struct SECKEYPQGParamsStr {
-    PRArenaPool *arena;
+    PLArenaPool *arena;
     SECItem prime;    /* p */
     SECItem subPrime; /* q */
     SECItem base;     /* g */
     /* XXX chrisk: this needs to be expanded to hold j and validationParms (RFC2459 7.3.2) */
 };
 typedef struct SECKEYPQGParamsStr SECKEYPQGParams;
 
 struct SECKEYDSAPublicKeyStr {
@@ -103,24 +103,24 @@ struct SECKEYDSAPublicKeyStr {
 typedef struct SECKEYDSAPublicKeyStr SECKEYDSAPublicKey;
 
 
 /*
 ** Diffie-Hellman Public Key structure
 ** Structure member names suggested by PKCS#3.
 */
 struct SECKEYDHParamsStr {
-    PRArenaPool * arena;
+    PLArenaPool * arena;
     SECItem prime; /* p */
     SECItem base; /* g */
 };
 typedef struct SECKEYDHParamsStr SECKEYDHParams;
 
 struct SECKEYDHPublicKeyStr {
-    PRArenaPool * arena;
+    PLArenaPool * arena;
     SECItem prime;
     SECItem base;
     SECItem publicValue;
 };
 typedef struct SECKEYDHPublicKeyStr SECKEYDHPublicKey;
 
 /*
 ** Elliptic curve Public Key structure
@@ -237,22 +237,22 @@ typedef struct SECKEYPrivateKeyStr SECKE
 
 typedef struct {
     PRCList links;
     SECKEYPrivateKey *key;
 } SECKEYPrivateKeyListNode;
 
 typedef struct {
     PRCList list;
-    PRArenaPool *arena;
+    PLArenaPool *arena;
 } SECKEYPrivateKeyList;
 
 typedef struct {
     PRCList links;
     SECKEYPublicKey *key;
 } SECKEYPublicKeyListNode;
 
 typedef struct {
     PRCList list;
-    PRArenaPool *arena;
+    PLArenaPool *arena;
 } SECKEYPublicKeyList;
 #endif /* _KEYTHI_H_ */
 
--- a/security/nss/lib/cryptohi/seckey.c
+++ b/security/nss/lib/cryptohi/seckey.c
@@ -448,17 +448,17 @@ done:
  *      DER encoded format and the fortezza-only wrapped format.  The params
  *      should be copied from issuer to subject cert without modifying the
  *      formats.  The public key extraction code will deal with the different
  *      formats at the time of extraction.  */
 
 static SECStatus
 seckey_UpdateCertPQGChain(CERTCertificate * subjectCert, int count)
 {
-    SECStatus rv, rvCompare;
+    SECStatus rv;
     SECOidData *oid=NULL;
     int tag;
     CERTSubjectPublicKeyInfo * subjectSpki=NULL;
     CERTSubjectPublicKeyInfo * issuerSpki=NULL;
     CERTCertificate *issuerCert = NULL;
 
     rv = SECSuccess;
 
--- a/security/nss/lib/dev/ckhelper.c
+++ b/security/nss/lib/dev/ckhelper.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: ckhelper.c,v $ $Revision: 1.36 $ $Date: 2007/11/16 05:29:25 $";
+static const char CVS_ID[] = "@(#) $RCSfile: ckhelper.c,v $ $Revision: 1.37 $ $Date: 2008/05/29 17:24:15 $";
 #endif /* DEBUG */
 
 #ifndef NSSCKEPV_H
 #include "nssckepv.h"
 #endif /* NSSCKEPV_H */
 
 #ifndef DEVM_H
 #include "devm.h"
@@ -551,17 +551,17 @@ nssCryptokiCRL_GetAttributes (
     }
     return PR_SUCCESS;
 }
 
 NSS_IMPLEMENT PRStatus
 nssCryptokiPrivateKey_SetCertificate (
   nssCryptokiObject *keyObject,
   nssSession *sessionOpt,
-  NSSUTF8 *nickname,
+  const NSSUTF8 *nickname,
   NSSItem *id,
   NSSDER *subject
 )
 {
     CK_RV ckrv;
     CK_ATTRIBUTE_PTR attr;
     CK_ATTRIBUTE key_template[3];
     CK_ULONG key_size;
--- a/security/nss/lib/dev/dev.h
+++ b/security/nss/lib/dev/dev.h
@@ -39,17 +39,17 @@
 
 /*
  * dev.h
  *
  * Low-level methods for interaction with cryptoki devices
  */
 
 #ifdef DEBUG
-static const char DEV_CVS_ID[] = "@(#) $RCSfile: dev.h,v $ $Revision: 1.39 $ $Date: 2007/11/16 05:29:25 $";
+static const char DEV_CVS_ID[] = "@(#) $RCSfile: dev.h,v $ $Revision: 1.41 $ $Date: 2008/05/29 17:24:15 $";
 #endif /* DEBUG */
 
 #ifndef NSSCKT_H
 #include "nssckt.h"
 #endif /* NSSCKT_H */
 
 #ifndef NSSDEV_H
 #include "nssdev.h"
@@ -384,25 +384,23 @@ nssSlot_CreateSession
  * nssToken_GetSlot
  * nssToken_NeedsPINInitialization
  * nssToken_ImportCertificate
  * nssToken_ImportTrust
  * nssToken_ImportCRL
  * nssToken_GenerateKeyPair
  * nssToken_GenerateSymmetricKey
  * nssToken_DeleteStoredObject
- * nssToken_FindCertificates
+ * nssToken_FindObjects
  * nssToken_FindCertificatesBySubject
  * nssToken_FindCertificatesByNickname
  * nssToken_FindCertificatesByEmail
  * nssToken_FindCertificateByIssuerAndSerialNumber
  * nssToken_FindCertificateByEncodedCertificate
- * nssToken_FindTrustObjects
  * nssToken_FindTrustForCertificate
- * nssToken_FindCRLs
  * nssToken_FindCRLsBySubject
  * nssToken_FindPrivateKeys
  * nssToken_FindPrivateKeyByID
  * nssToken_Digest
  * nssToken_BeginDigest
  * nssToken_ContinueDigest
  * nssToken_FinishDigest
  */
@@ -445,17 +443,17 @@ nssToken_NeedsPINInitialization
 
 NSS_EXTERN nssCryptokiObject *
 nssToken_ImportCertificate
 (
   NSSToken *tok,
   nssSession *sessionOpt,
   NSSCertificateType certType,
   NSSItem *id,
-  NSSUTF8 *nickname,
+  const NSSUTF8 *nickname,
   NSSDER *encoding,
   NSSDER *issuer,
   NSSDER *subject,
   NSSDER *serial,
   NSSASCII7 *emailAddr,
   PRBool asTokenObject
 );
 
@@ -490,20 +488,21 @@ nssToken_ImportCRL
 /* Permanently remove an object from the token. */
 NSS_EXTERN PRStatus
 nssToken_DeleteStoredObject
 (
   nssCryptokiObject *instance
 );
 
 NSS_EXTERN nssCryptokiObject **
-nssToken_FindCertificates
+nssToken_FindObjects
 (
   NSSToken *token,
   nssSession *sessionOpt,
+  CK_OBJECT_CLASS objclass,
   nssTokenSearchType searchType,
   PRUint32 maximumOpt,
   PRStatus *statusOpt
 );
 
 NSS_EXTERN nssCryptokiObject **
 nssToken_FindCertificatesBySubject
 (
@@ -564,48 +563,28 @@ nssToken_FindCertificateByEncodedCertifi
 (
   NSSToken *token,
   nssSession *sessionOpt,
   NSSBER *encodedCertificate,
   nssTokenSearchType searchType,
   PRStatus *statusOpt
 );
 
-NSS_EXTERN nssCryptokiObject **
-nssToken_FindTrustObjects
-(
-  NSSToken *token,
-  nssSession *sessionOpt,
-  nssTokenSearchType searchType,
-  PRUint32 maximumOpt,
-  PRStatus *statusOpt
-);
-
 NSS_EXTERN nssCryptokiObject *
 nssToken_FindTrustForCertificate
 (
   NSSToken *token,
   nssSession *sessionOpt,
   NSSDER *certEncoding,
   NSSDER *certIssuer,
   NSSDER *certSerial,
   nssTokenSearchType searchType
 );
 
 NSS_EXTERN nssCryptokiObject **
-nssToken_FindCRLs
-(
-  NSSToken *token,
-  nssSession *sessionOpt,
-  nssTokenSearchType searchType,
-  PRUint32 maximumOpt,
-  PRStatus *statusOpt
-);
-
-NSS_EXTERN nssCryptokiObject **
 nssToken_FindCRLsBySubject
 (
   NSSToken *token,
   nssSession *sessionOpt,
   NSSDER *subject,
   nssTokenSearchType searchType,
   PRUint32 maximumOpt,
   PRStatus *statusOpt
@@ -787,17 +766,17 @@ nssCryptokiCRL_GetAttributes
  * function will set the cert-related attributes of a key, in order to
  * associate it with a cert.  Does it stay like this for 4.0?
  */
 NSS_EXTERN PRStatus
 nssCryptokiPrivateKey_SetCertificate
 (
   nssCryptokiObject *keyObject,
   nssSession *sessionOpt,
-  NSSUTF8 *nickname,
+  const NSSUTF8 *nickname,
   NSSItem *id,
   NSSDER *subject
 );
 
 NSS_EXTERN void
 nssModuleArray_Destroy
 (
   NSSModule **modules
--- a/security/nss/lib/dev/devslot.c
+++ b/security/nss/lib/dev/devslot.c
@@ -30,31 +30,33 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: devslot.c,v $ $Revision: 1.23 $ $Date: 2007/11/16 05:29:25 $";
+static const char CVS_ID[] = "@(#) $RCSfile: devslot.c,v $ $Revision: 1.24 $ $Date: 2008/08/09 01:25:58 $";
 #endif /* DEBUG */
 
 #ifndef NSSCKEPV_H
 #include "nssckepv.h"
 #endif /* NSSCKEPV_H */
 
 #ifndef DEVM_H
 #include "devm.h"
 #endif /* DEVM_H */
 
 #ifndef CKHELPER_H
 #include "ckhelper.h"
 #endif /* CKHELPER_H */
 
+#include "pk11pub.h"
+
 /* measured in seconds */
 #define NSSSLOT_TOKEN_DELAY_TIME 1
 
 /* this should track global and per-transaction login information */
 
 #define NSSSLOT_IS_FRIENDLY(slot) \
   (slot->base.flags & NSSSLOT_FLAGS_FRIENDLY)
 
@@ -158,23 +160,23 @@ nssSlot_IsTokenPresent (
 )
 {
     CK_RV ckrv;
     PRStatus nssrv;
     /* XXX */
     nssSession *session;
     CK_SLOT_INFO slotInfo;
     void *epv;
-    /* permanent slots are always present */
+    /* permanent slots are always present unless they're disabled */
     if (nssSlot_IsPermanent(slot)) {
-	return PR_TRUE;
+	return !PK11_IsDisabled(slot->pk11slot);
     }
     /* avoid repeated calls to check token status within set interval */
     if (within_token_delay_period(slot)) {
-	return (PRBool)((slot->ckFlags & CKF_TOKEN_PRESENT) != 0);
+	return ((slot->ckFlags & CKF_TOKEN_PRESENT) != 0);
     }
 
     /* First obtain the slot info */
     epv = slot->epv;
     if (!epv) {
 	return PR_FALSE;
     }
     nssSlot_EnterMonitor(slot);
@@ -183,72 +185,74 @@ nssSlot_IsTokenPresent (
     if (ckrv != CKR_OK) {
 	slot->token->base.name[0] = 0; /* XXX */
 	return PR_FALSE;
     }
     slot->ckFlags = slotInfo.flags;
     /* check for the presence of the token */
     if ((slot->ckFlags & CKF_TOKEN_PRESENT) == 0) {
 	if (!slot->token) {
-	    /* token was ne'er present */
+	    /* token was never present */
 	    return PR_FALSE;
 	}
 	session = nssToken_GetDefaultSession(slot->token);
-	nssSession_EnterMonitor(session);
-	/* token is not present */
-	if (session->handle != CK_INVALID_SESSION) {
-	    /* session is valid, close and invalidate it */
-	    CKAPI(epv)->C_CloseSession(session->handle);
-	    session->handle = CK_INVALID_SESSION;
+	if (session) {
+	    nssSession_EnterMonitor(session);
+	    /* token is not present */
+	    if (session->handle != CK_INVALID_SESSION) {
+		/* session is valid, close and invalidate it */
+		CKAPI(epv)->C_CloseSession(session->handle);
+		session->handle = CK_INVALID_SESSION;
+	    }
+	    nssSession_ExitMonitor(session);
 	}
-	nssSession_ExitMonitor(session);
 	if (slot->token->base.name[0] != 0) {
 	    /* notify the high-level cache that the token is removed */
 	    slot->token->base.name[0] = 0; /* XXX */
 	    nssToken_NotifyCertsNotVisible(slot->token);
 	}
 	slot->token->base.name[0] = 0; /* XXX */
 	/* clear the token cache */
 	nssToken_Remove(slot->token);
 	return PR_FALSE;
     }
     /* token is present, use the session info to determine if the card
      * has been removed and reinserted.
      */
     session = nssToken_GetDefaultSession(slot->token);
-    nssSession_EnterMonitor(session);
-    if (session->handle != CK_INVALID_SESSION) {
-	CK_SESSION_INFO sessionInfo;
-	ckrv = CKAPI(epv)->C_GetSessionInfo(session->handle, &sessionInfo);
-	if (ckrv != CKR_OK) {
-	    /* session is screwy, close and invalidate it */
-	    CKAPI(epv)->C_CloseSession(session->handle);
-	    session->handle = CK_INVALID_SESSION;
+    if (session) {
+	nssSession_EnterMonitor(session);
+	if (session->handle != CK_INVALID_SESSION) {
+	    CK_SESSION_INFO sessionInfo;
+	    ckrv = CKAPI(epv)->C_GetSessionInfo(session->handle, &sessionInfo);
+	    if (ckrv != CKR_OK) {
+		/* session is screwy, close and invalidate it */
+		CKAPI(epv)->C_CloseSession(session->handle);
+		session->handle = CK_INVALID_SESSION;
+	    }
 	}
+	nssSession_ExitMonitor(session);
+	/* token not removed, finished */
+	if (session->handle != CK_INVALID_SESSION)
+	    return PR_TRUE;
+    } 
+    /* the token has been removed, and reinserted, or the slot contains
+     * a token it doesn't recognize. invalidate all the old
+     * information we had on this token, if we can't refresh, clear
+     * the present flag */
+    nssToken_NotifyCertsNotVisible(slot->token);
+    nssToken_Remove(slot->token);
+    /* token has been removed, need to refresh with new session */
+    nssrv = nssSlot_Refresh(slot);
+    if (nssrv != PR_SUCCESS) {
+        slot->token->base.name[0] = 0; /* XXX */
+        slot->ckFlags &= ~CKF_TOKEN_PRESENT;
+        return PR_FALSE;
     }
-    nssSession_ExitMonitor(session);
-    /* token not removed, finished */
-    if (session->handle != CK_INVALID_SESSION) {
-	return PR_TRUE;
-    } else {
-	/* the token has been removed, and reinserted, or the slot contains
-	 * a token it doesn't recognize. invalidate all the old
-	 * information we had on this token, if we can't refresh, clear
-	 * the present flag */
-	nssToken_NotifyCertsNotVisible(slot->token);
-	nssToken_Remove(slot->token);
-	/* token has been removed, need to refresh with new session */
-	nssrv = nssSlot_Refresh(slot);
-	if (nssrv != PR_SUCCESS) {
-	    slot->token->base.name[0] = 0; /* XXX */
-	    slot->ckFlags &= ~CKF_TOKEN_PRESENT;
-	    return PR_FALSE;
-	}
-	return PR_TRUE;
-    }
+    return PR_TRUE;
 }
 
 NSS_IMPLEMENT void *
 nssSlot_GetCryptokiEPV (
   NSSSlot *slot
 )
 {
     return slot->epv;
--- a/security/nss/lib/dev/devtoken.c
+++ b/security/nss/lib/dev/devtoken.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: devtoken.c,v $ $Revision: 1.43 $ $Date: 2008/02/05 03:22:38 $";
+static const char CVS_ID[] = "@(#) $RCSfile: devtoken.c,v $ $Revision: 1.50 $ $Date: 2008/08/09 01:25:58 $";
 #endif /* DEBUG */
 
 #ifndef NSSCKEPV_H
 #include "nssckepv.h"
 #endif /* NSSCKEPV_H */
 
 #ifndef DEVM_H
 #include "devm.h"
@@ -65,16 +65,20 @@ NSS_IMPLEMENT PRStatus
 nssToken_Destroy (
   NSSToken *tok
 )
 {
     if (tok) {
 	if (PR_AtomicDecrement(&tok->base.refCount) == 0) {
 	    PZ_DestroyLock(tok->base.lock);
 	    nssTokenObjectCache_Destroy(tok->cache);
+	    /* The token holds the first/last reference to the slot.
+	     * When the token is actually destroyed, that ref must go too.
+	     */
+	    (void)nssSlot_Destroy(tok->slot);
 	    return nssArena_Destroy(tok->base.arena);
 	}
     }
     return PR_SUCCESS;
 }
 
 NSS_IMPLEMENT void
 nssToken_Remove (
@@ -290,23 +294,30 @@ find_objects (
   CK_ATTRIBUTE_PTR obj_template,
   CK_ULONG otsize,
   PRUint32 maximumOpt,
   PRStatus *statusOpt
 )
 {
     CK_RV ckrv = CKR_OK;
     CK_ULONG count;
-    CK_OBJECT_HANDLE *objectHandles;
+    CK_OBJECT_HANDLE *objectHandles = NULL;
     CK_OBJECT_HANDLE staticObjects[OBJECT_STACK_SIZE];
     PRUint32 arraySize, numHandles;
     void *epv = nssToken_GetCryptokiEPV(tok);
     nssCryptokiObject **objects;
     nssSession *session = (sessionOpt) ? sessionOpt : tok->defaultSession;
 
+    /* Don't ask the module to use an invalid session handle. */
+    PORT_Assert(session->handle != CK_INVALID_SESSION);
+    if (session->handle == CK_INVALID_SESSION) {
+	ckrv = CKR_SESSION_HANDLE_INVALID;
+	goto loser;                
+    }
+
     /* the arena is only for the array of object handles */
     if (maximumOpt > 0) {
 	arraySize = maximumOpt;
     } else {
 	arraySize = OBJECT_STACK_SIZE;
     }
     numHandles = 0;
     if (arraySize <= OBJECT_STACK_SIZE) {
@@ -458,17 +469,17 @@ find_objects_by_template (
 extern const NSSError NSS_ERROR_INVALID_CERTIFICATE;
 
 NSS_IMPLEMENT nssCryptokiObject *
 nssToken_ImportCertificate (
   NSSToken *tok,
   nssSession *sessionOpt,
   NSSCertificateType certType,
   NSSItem *id,
-  NSSUTF8 *nickname,
+  const NSSUTF8 *nickname,
   NSSDER *encoding,
   NSSDER *issuer,
   NSSDER *subject,
   NSSDER *serial,
   NSSASCII7 *email,
   PRBool asTokenObject
 )
 {
@@ -573,50 +584,51 @@ nssToken_ImportCertificate (
 	 */
 	nssTokenObjectCache_ImportObject(tok->cache, rvObject,
 	                                 CKO_CERTIFICATE,
 	                                 cert_tmpl, ctsize);
     }
     return rvObject;
 }
 
-/* traverse all certificates - this should only happen if the token
- * has been marked as "traversable"
+/* traverse all objects of the given class - this should only happen
+ * if the token has been marked as "traversable"
  */
 NSS_IMPLEMENT nssCryptokiObject **
-nssToken_FindCertificates (
+nssToken_FindObjects (
   NSSToken *token,
   nssSession *sessionOpt,
+  CK_OBJECT_CLASS objclass,
   nssTokenSearchType searchType,
   PRUint32 maximumOpt,
   PRStatus *statusOpt
 )
 {
     CK_ATTRIBUTE_PTR attr;
-    CK_ATTRIBUTE cert_template[2];
-    CK_ULONG ctsize;
+    CK_ATTRIBUTE obj_template[2];
+    CK_ULONG obj_size;
     nssCryptokiObject **objects;
-    NSS_CK_TEMPLATE_START(cert_template, attr, ctsize);
+    NSS_CK_TEMPLATE_START(obj_template, attr, obj_size);
     /* Set the search to token/session only if provided */
     if (searchType == nssTokenSearchType_SessionOnly) {
 	NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false);
     } else if (searchType == nssTokenSearchType_TokenOnly ||
                searchType == nssTokenSearchType_TokenForced) {
 	NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true);
     }
-    NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_CLASS, &g_ck_class_cert);
-    NSS_CK_TEMPLATE_FINISH(cert_template, attr, ctsize);
+    NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, objclass);
+    NSS_CK_TEMPLATE_FINISH(obj_template, attr, obj_size);
 
     if (searchType == nssTokenSearchType_TokenForced) {
 	objects = find_objects(token, sessionOpt,
-	                       cert_template, ctsize,
+	                       obj_template, obj_size,
 	                       maximumOpt, statusOpt);
     } else {
 	objects = find_objects_by_template(token, sessionOpt,
-	                                   cert_template, ctsize,
+	                                   obj_template, obj_size,
 	                                   maximumOpt, statusOpt);
     }
     return objects;
 }
 
 NSS_IMPLEMENT nssCryptokiObject **
 nssToken_FindCertificatesBySubject (
   NSSToken *token,
@@ -1115,54 +1127,16 @@ nssToken_ImportTrust (
     object = import_object(tok, sessionOpt, trust_tmpl, tsize);
     if (object && tok->cache) {
 	nssTokenObjectCache_ImportObject(tok->cache, object, tobjc,
 	                                 trust_tmpl, tsize);
     }
     return object;
 }
 
-NSS_IMPLEMENT nssCryptokiObject **
-nssToken_FindTrustObjects (
-  NSSToken *token,
-  nssSession *sessionOpt,
-  nssTokenSearchType searchType,
-  PRUint32 maximumOpt,
-  PRStatus *statusOpt
-)
-{
-    CK_OBJECT_CLASS tobjc = CKO_NETSCAPE_TRUST;
-    CK_ATTRIBUTE_PTR attr;
-    CK_ATTRIBUTE tobj_template[2];
-    CK_ULONG tobj_size;
-    nssCryptokiObject **objects;
-    nssSession *session = sessionOpt ? sessionOpt : token->defaultSession;
-
-    NSS_CK_TEMPLATE_START(tobj_template, attr, tobj_size);
-    if (searchType == nssTokenSearchType_SessionOnly) {
-	NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false);
-    } else if (searchType == nssTokenSearchType_TokenOnly ||
-               searchType == nssTokenSearchType_TokenForced) {
-	NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true);
-    }
-    NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, tobjc);
-    NSS_CK_TEMPLATE_FINISH(tobj_template, attr, tobj_size);
-
-    if (searchType == nssTokenSearchType_TokenForced) {
-	objects = find_objects(token, session,
-	                       tobj_template, tobj_size,
-	                       maximumOpt, statusOpt);
-    } else {
-	objects = find_objects_by_template(token, session,
-	                                   tobj_template, tobj_size,
-	                                   maximumOpt, statusOpt);
-    }
-    return objects;
-}
-
 NSS_IMPLEMENT nssCryptokiObject *
 nssToken_FindTrustForCertificate (
   NSSToken *token,
   nssSession *sessionOpt,
   NSSDER *certEncoding,
   NSSDER *certIssuer,
   NSSDER *certSerial,
   nssTokenSearchType searchType
@@ -1235,54 +1209,16 @@ nssToken_ImportCRL (
     if (object && token->cache) {
 	nssTokenObjectCache_ImportObject(token->cache, object, crlobjc,
 	                                 crl_tmpl, crlsize);
     }
     return object;
 }
 
 NSS_IMPLEMENT nssCryptokiObject **
-nssToken_FindCRLs (
-  NSSToken *token,
-  nssSession *sessionOpt,
-  nssTokenSearchType searchType,
-  PRUint32 maximumOpt,
-  PRStatus *statusOpt
-)
-{
-    CK_OBJECT_CLASS crlobjc = CKO_NETSCAPE_CRL;
-    CK_ATTRIBUTE_PTR attr;
-    CK_ATTRIBUTE crlobj_template[2];
-    CK_ULONG crlobj_size;
-    nssCryptokiObject **objects;
-    nssSession *session = sessionOpt ? sessionOpt : token->defaultSession;
-
-    NSS_CK_TEMPLATE_START(crlobj_template, attr, crlobj_size);
-    if (searchType == nssTokenSearchType_SessionOnly) {
-	NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_false);
-    } else if (searchType == nssTokenSearchType_TokenOnly ||
-               searchType == nssTokenSearchType_TokenForced) {
-	NSS_CK_SET_ATTRIBUTE_ITEM(attr, CKA_TOKEN, &g_ck_true);
-    }
-    NSS_CK_SET_ATTRIBUTE_VAR( attr, CKA_CLASS, crlobjc);
-    NSS_CK_TEMPLATE_FINISH(crlobj_template, attr, crlobj_size);
-
-    if (searchType == nssTokenSearchType_TokenForced) {
-	objects = find_objects(token, session,
-	                       crlobj_template, crlobj_size,
-	                       maximumOpt, statusOpt);
-    } else {
-	objects = find_objects_by_template(token, session,
-	                                   crlobj_template, crlobj_size,
-	                                   maximumOpt, statusOpt);
-    }
-    return objects;
-}
-
-NSS_IMPLEMENT nssCryptokiObject **
 nssToken_FindCRLsBySubject (
   NSSToken *token,
   nssSession *sessionOpt,
   NSSDER *subject,
   nssTokenSearchType searchType,
   PRUint32 maximumOpt,
   PRStatus *statusOpt
 )
--- a/security/nss/lib/dev/devutil.c
+++ b/security/nss/lib/dev/devutil.c
@@ -30,17 +30,17 @@
  * decision by deleting the provisions above and replace them with the notice
  * and other provisions required by the GPL or the LGPL. If you do not delete
  * the provisions above, a recipient may use your version of this file under
  * the terms of any one of the MPL, the GPL or the LGPL.
  *
  * ***** END LICENSE BLOCK ***** */
 
 #ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile: devutil.c,v $ $Revision: 1.29 $ $Date: 2007/11/16 05:29:25 $";
+static const char CVS_ID[] = "@(#) $RCSfile: devutil.c,v $ $Revision: 1.31 $ $Date: 2008/05/18 01:51:45 $";
 #endif /* DEBUG */
 
 #ifndef DEVM_H
 #include "devm.h"
 #endif /* DEVM_H */
 
 #ifndef CKHELPER_H
 #include "ckhelper.h"
@@ -511,70 +511,16 @@ create_cert (
 	CKA_SERIAL_NUMBER,
 	CKA_SUBJECT,
 	CKA_NETSCAPE_EMAIL
     };
     static const PRUint32 numCertAttr = sizeof(certAttr) / sizeof(certAttr[0]);
     return create_object(object, certAttr, numCertAttr, status);
 }
 
-static PRStatus
-get_token_certs_for_cache (
-  nssTokenObjectCache *cache
-)
-{
-    PRStatus status;
-    nssCryptokiObject **objects;
-    PRBool *doIt = &cache->doObjectType[cachedCerts];
-    PRUint32 i, numObjects;
-
-    if (!search_for_objects(cache) || 
-         cache->searchedObjectType[cachedCerts] || 
-        !cache->doObjectType[cachedCerts]) 
-    {
-	/* Either there was a state change that prevents a search
-	 * (token logged out), or the search was already done,
-	 * or certs are not being cached.
-	 */
-	return PR_SUCCESS;
-    }
-    objects = nssToken_FindCertificates(cache->token, NULL,
-                                        nssTokenSearchType_TokenForced,
-				        MAX_LOCAL_CACHE_OBJECTS, &status);
-    if (status != PR_SUCCESS) {
-	return status;
-    }
-    cache->objects[cachedCerts] = create_object_array(objects,
-                                                      doIt,
-                                                      &numObjects,
-                                                      &status);
-    if (status != PR_SUCCESS) {
-	return status;
-    }
-    for (i=0; i<numObjects; i++) {
-	cache->objects[cachedCerts][i] = create_cert(objects[i], &status);
-	if (status != PR_SUCCESS) {
-	    break;
-	}
-    }
-    if (status == PR_SUCCESS) {
-	nss_ZFreeIf(objects);
-    } else {
-	PRUint32 j;
-	for (j=0; j<i; j++) {
-	    /* sigh */
-	    nssToken_AddRef(cache->objects[cachedCerts][j]->object->token);
-	    nssArena_Destroy(cache->objects[cachedCerts][j]->arena);
-	}
-	nssCryptokiObjectArray_Destroy(objects);
-    }
-    cache->searchedObjectType[cachedCerts] = PR_TRUE;
-    return status;
-}
-
 static nssCryptokiObjectAndAttributes *
 create_trust (
   nssCryptokiObject *object,
   PRStatus *status
 )
 {
     static const CK_ATTRIBUTE_TYPE trustAttr[] = {
 	CKA_CLASS,
@@ -588,70 +534,16 @@ create_trust (
 	CKA_TRUST_CLIENT_AUTH,
 	CKA_TRUST_EMAIL_PROTECTION,
 	CKA_TRUST_CODE_SIGNING
     };
     static const PRUint32 numTrustAttr = sizeof(trustAttr) / sizeof(trustAttr[0]);
     return create_object(object, trustAttr, numTrustAttr, status);
 }
 
-static PRStatus
-get_token_trust_for_cache (
-  nssTokenObjectCache *cache
-)
-{
-    PRStatus status;
-    nssCryptokiObject **objects;
-    PRBool *doIt = &cache->doObjectType[cachedTrust];
-    PRUint32 i, numObjects;
-
-    if (!search_for_objects(cache) || 
-         cache->searchedObjectType[cachedTrust] || 
-        !cache->doObjectType[cachedTrust]) 
-    {
-	/* Either there was a state change that prevents a search
-	 * (token logged out), or the search was already done,
-	 * or trust is not being cached.
-	 */
-	return PR_SUCCESS;
-    }
-    objects = nssToken_FindTrustObjects(cache->token, NULL,
-                                        nssTokenSearchType_TokenForced,
-				        MAX_LOCAL_CACHE_OBJECTS, &status);
-    if (status != PR_SUCCESS) {
-	return status;
-    }
-    cache->objects[cachedTrust] = create_object_array(objects,
-                                                      doIt,
-                                                      &numObjects,
-                                                      &status);
-    if (status != PR_SUCCESS) {
-	return status;
-    }
-    for (i=0; i<numObjects; i++) {
-	cache->objects[cachedTrust][i] = create_trust(objects[i], &status);
-	if (status != PR_SUCCESS) {
-	    break;
-	}
-    }
-    if (status == PR_SUCCESS) {
-	nss_ZFreeIf(objects);
-    } else {
-	PRUint32 j;
-	for (j=0; j<i; j++) {
-	    /* sigh */
-	    nssToken_AddRef(cache->objects[cachedTrust][j]->object->token);
-	    nssArena_Destroy(cache->objects[cachedTrust][j]->arena);
-	}
-	nssCryptokiObjectArray_Destroy(objects);
-    }
-    cache->searchedObjectType[cachedTrust] = PR_TRUE;
-    return status;
-}
-
 static nssCryptokiObjectAndAttributes *
 create_crl (
   nssCryptokiObject *object,
   PRStatus *status