2a00fe
diff --git a/cmd/dbtool/Makefile b/cmd/dbtool/Makefile
2a00fe
new file mode 100644
2a00fe
--- /dev/null
2a00fe
+++ b/cmd/dbtool/Makefile
2a00fe
@@ -0,0 +1,46 @@
2a00fe
+#! gmake
2a00fe
+# 
2a00fe
+# This Source Code Form is subject to the terms of the Mozilla Public
2a00fe
+# License, v. 2.0. If a copy of the MPL was not distributed with this
2a00fe
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (1) Include initial platform-independent assignments (MANDATORY).   #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+include manifest.mn
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (2) Include "global" configuration information. (OPTIONAL)          #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+include $(CORE_DEPTH)/coreconf/config.mk
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (3) Include "component" configuration information. (OPTIONAL)       #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (4) Include "local" platform-dependent assignments (OPTIONAL).      #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+include ../platlibs.mk
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (5) Execute "global" rules. (OPTIONAL)                              #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+include $(CORE_DEPTH)/coreconf/rules.mk
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (6) Execute "component" rules. (OPTIONAL)                           #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+#include ../platlibs.mk
2a00fe
+
2a00fe
+#######################################################################
2a00fe
+# (7) Execute "local" rules. (OPTIONAL).                              #
2a00fe
+#######################################################################
2a00fe
+
2a00fe
+include ../platrules.mk
2a00fe
+
2a00fe
diff --git a/cmd/dbtool/dbtool.c b/cmd/dbtool/dbtool.c
2a00fe
new file mode 100644
2a00fe
--- /dev/null
2a00fe
+++ b/cmd/dbtool/dbtool.c
2a00fe
@@ -0,0 +1,806 @@
2a00fe
+/* This Source Code Form is subject to the terms of the Mozilla Public
2a00fe
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
2a00fe
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
2a00fe
+
2a00fe
+/*
2a00fe
+** dbtool.c
2a00fe
+**
2a00fe
+** tool to dump the underlying encoding of a database. This tool duplicates
2a00fe
+**  some private functions in softoken. It uses libsec and libutil, but no
2a00fe
+**  other portions of NSS. It currently only works on sqlite databases. For
2a00fe
+**  an even more primitive dump, use sqlite3 on the individual files.
2a00fe
+**
2a00fe
+**   TODO: dump the meta data for the databases.
2a00fe
+**         optionally dump more PKCS5 information (KDF/salt/iterations)
2a00fe
+**         take a password and decode encrypted attributes/verify signed
2a00fe
+**             attributes.
2a00fe
+*/
2a00fe
+#include <stdio.h>
2a00fe
+#include <string.h>
2a00fe
+
2a00fe
+#if defined(WIN32)
2a00fe
+#include "fcntl.h"
2a00fe
+#include "io.h"
2a00fe
+#endif
2a00fe
+
2a00fe
+#include "secutil.h"
2a00fe
+#include "pk11pub.h"
2a00fe
+
2a00fe
+#if defined(XP_UNIX)
2a00fe
+#include <unistd.h>
2a00fe
+#endif
2a00fe
+
2a00fe
+#include "nspr.h"
2a00fe
+#include "prtypes.h"
2a00fe
+#include "certdb.h"
2a00fe
+#include "nss.h"
2a00fe
+#include "../modutil/modutil.h"
2a00fe
+#include "pk11table.h"
2a00fe
+#include "sftkdbt.h"
2a00fe
+#include "sdb.h"
2a00fe
+#include "secoid.h"
2a00fe
+
2a00fe
+#include "plgetopt.h"
2a00fe
+
2a00fe
+static char *progName;
2a00fe
+
2a00fe
+char *dbDir = NULL;
2a00fe
+
2a00fe
+static void
2a00fe
+Usage()
2a00fe
+{
2a00fe
+    printf("Usage:  %s [-c certprefix] [-k keyprefix] "
2a00fe
+           "[-V certversion] [-v keyversion]\n"
2a00fe
+           "           [-d dbdir]\n",
2a00fe
+           progName);
2a00fe
+    printf("%-20s Directory with cert database (default is .)\n",
2a00fe
+           "-d certdir");
2a00fe
+    printf("%-20s prefix for the cert database (default is \"\")\n",
2a00fe
+           "-c certprefix");
2a00fe
+    printf("%-20s prefix for the key database (default is \"\")\n",
2a00fe
+           "-k keyprefix");
2a00fe
+    printf("%-20s version of the cert database (default is 9)\n",
2a00fe
+           "-V certversion");
2a00fe
+    printf("%-20s version of the key database (default is 4)\n",
2a00fe
+           "-v keyversion");
2a00fe
+    exit(1);
2a00fe
+}
2a00fe
+#define SFTK_KEYDB_TYPE 0x40000000
2a00fe
+#define SFTK_TOKEN_TYPE 0x80000000
2a00fe
+
2a00fe
+/*
2a00fe
+ * known attributes
2a00fe
+ */
2a00fe
+static const CK_ATTRIBUTE_TYPE known_attributes[] = {
2a00fe
+    CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION,
2a00fe
+    CKA_VALUE, CKA_OBJECT_ID, CKA_CERTIFICATE_TYPE, CKA_ISSUER,
2a00fe
+    CKA_SERIAL_NUMBER, CKA_AC_ISSUER, CKA_OWNER, CKA_ATTR_TYPES, CKA_TRUSTED,
2a00fe
+    CKA_CERTIFICATE_CATEGORY, CKA_JAVA_MIDP_SECURITY_DOMAIN, CKA_URL,
2a00fe
+    CKA_HASH_OF_SUBJECT_PUBLIC_KEY, CKA_HASH_OF_ISSUER_PUBLIC_KEY,
2a00fe
+    CKA_CHECK_VALUE, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE,
2a00fe
+    CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER,
2a00fe
+    CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE,
2a00fe
+    CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT,
2a00fe
+    CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT,
2a00fe
+    CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS,
2a00fe
+    CKA_SUB_PRIME_BITS, CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_EXTRACTABLE,
2a00fe
+    CKA_LOCAL, CKA_NEVER_EXTRACTABLE, CKA_ALWAYS_SENSITIVE,
2a00fe
+    CKA_KEY_GEN_MECHANISM, CKA_MODIFIABLE, CKA_EC_PARAMS,
2a00fe
+    CKA_EC_POINT, CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
2a00fe
+    CKA_ALWAYS_AUTHENTICATE, CKA_WRAP_WITH_TRUSTED, CKA_WRAP_TEMPLATE,
2a00fe
+    CKA_UNWRAP_TEMPLATE, CKA_HW_FEATURE_TYPE, CKA_RESET_ON_INIT,
2a00fe
+    CKA_HAS_RESET, CKA_PIXEL_X, CKA_PIXEL_Y, CKA_RESOLUTION, CKA_CHAR_ROWS,
2a00fe
+    CKA_CHAR_COLUMNS, CKA_COLOR, CKA_BITS_PER_PIXEL, CKA_CHAR_SETS,
2a00fe
+    CKA_ENCODING_METHODS, CKA_MIME_TYPES, CKA_MECHANISM_TYPE,
2a00fe
+    CKA_REQUIRED_CMS_ATTRIBUTES, CKA_DEFAULT_CMS_ATTRIBUTES,
2a00fe
+    CKA_SUPPORTED_CMS_ATTRIBUTES, CKA_NSS_URL, CKA_NSS_EMAIL,
2a00fe
+    CKA_NSS_SMIME_INFO, CKA_NSS_SMIME_TIMESTAMP,
2a00fe
+    CKA_NSS_PKCS8_SALT, CKA_NSS_PASSWORD_CHECK, CKA_NSS_EXPIRES,
2a00fe
+    CKA_NSS_KRL, CKA_NSS_PQG_COUNTER, CKA_NSS_PQG_SEED,
2a00fe
+    CKA_NSS_PQG_H, CKA_NSS_PQG_SEED_BITS, CKA_NSS_MODULE_SPEC,
2a00fe
+    CKA_TRUST_DIGITAL_SIGNATURE, CKA_TRUST_NON_REPUDIATION,
2a00fe
+    CKA_TRUST_KEY_ENCIPHERMENT, CKA_TRUST_DATA_ENCIPHERMENT,
2a00fe
+    CKA_TRUST_KEY_AGREEMENT, CKA_TRUST_KEY_CERT_SIGN, CKA_TRUST_CRL_SIGN,
2a00fe
+    CKA_TRUST_SERVER_AUTH, CKA_TRUST_CLIENT_AUTH, CKA_TRUST_CODE_SIGNING,
2a00fe
+    CKA_TRUST_EMAIL_PROTECTION, CKA_TRUST_IPSEC_END_SYSTEM,
2a00fe
+    CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER, CKA_TRUST_TIME_STAMPING,
2a00fe
+    CKA_TRUST_STEP_UP_APPROVED, CKA_CERT_SHA1_HASH, CKA_CERT_MD5_HASH,
2a00fe
+    CKA_NSS_DB, CKA_NSS_TRUST, CKA_NSS_OVERRIDE_EXTENSIONS,
2a00fe
+    CKA_PUBLIC_KEY_INFO
2a00fe
+};
2a00fe
+
2a00fe
+static unsigned int known_attributes_size = sizeof(known_attributes) /
2a00fe
+                                            sizeof(known_attributes[0]);
2a00fe
+
2a00fe
+PRBool
2a00fe
+isULONGAttribute(CK_ATTRIBUTE_TYPE type)
2a00fe
+{
2a00fe
+    switch (type) {
2a00fe
+        case CKA_CERTIFICATE_CATEGORY:
2a00fe
+        case CKA_CERTIFICATE_TYPE:
2a00fe
+        case CKA_CLASS:
2a00fe
+        case CKA_JAVA_MIDP_SECURITY_DOMAIN:
2a00fe
+        case CKA_KEY_GEN_MECHANISM:
2a00fe
+        case CKA_KEY_TYPE:
2a00fe
+        case CKA_MECHANISM_TYPE:
2a00fe
+        case CKA_MODULUS_BITS:
2a00fe
+        case CKA_PRIME_BITS:
2a00fe
+        case CKA_SUBPRIME_BITS:
2a00fe
+        case CKA_VALUE_BITS:
2a00fe
+        case CKA_VALUE_LEN:
2a00fe
+
2a00fe
+        case CKA_TRUST_DIGITAL_SIGNATURE:
2a00fe
+        case CKA_TRUST_NON_REPUDIATION:
2a00fe
+        case CKA_TRUST_KEY_ENCIPHERMENT:
2a00fe
+        case CKA_TRUST_DATA_ENCIPHERMENT:
2a00fe
+        case CKA_TRUST_KEY_AGREEMENT:
2a00fe
+        case CKA_TRUST_KEY_CERT_SIGN:
2a00fe
+        case CKA_TRUST_CRL_SIGN:
2a00fe
+
2a00fe
+        case CKA_TRUST_SERVER_AUTH:
2a00fe
+        case CKA_TRUST_CLIENT_AUTH:
2a00fe
+        case CKA_TRUST_CODE_SIGNING:
2a00fe
+        case CKA_TRUST_EMAIL_PROTECTION:
2a00fe
+        case CKA_TRUST_IPSEC_END_SYSTEM:
2a00fe
+        case CKA_TRUST_IPSEC_TUNNEL:
2a00fe
+        case CKA_TRUST_IPSEC_USER:
2a00fe
+        case CKA_TRUST_TIME_STAMPING:
2a00fe
+        case CKA_TRUST_STEP_UP_APPROVED:
2a00fe
+            return PR_TRUE;
2a00fe
+        default:
2a00fe
+            break;
2a00fe
+    }
2a00fe
+    return PR_FALSE;
2a00fe
+}
2a00fe
+
2a00fe
+/* are the attributes private? */
2a00fe
+static PRBool
2a00fe
+isPrivateAttribute(CK_ATTRIBUTE_TYPE type)
2a00fe
+{
2a00fe
+    switch (type) {
2a00fe
+        case CKA_VALUE:
2a00fe
+        case CKA_PRIVATE_EXPONENT:
2a00fe
+        case CKA_PRIME_1:
2a00fe
+        case CKA_PRIME_2:
2a00fe
+        case CKA_EXPONENT_1:
2a00fe
+        case CKA_EXPONENT_2:
2a00fe
+        case CKA_COEFFICIENT:
2a00fe
+            return PR_TRUE;
2a00fe
+        default:
2a00fe
+            break;
2a00fe
+    }
2a00fe
+    return PR_FALSE;
2a00fe
+}
2a00fe
+
2a00fe
+/* These attributes must be authenticated with an hmac. */
2a00fe
+static PRBool
2a00fe
+isAuthenticatedAttribute(CK_ATTRIBUTE_TYPE type)
2a00fe
+{
2a00fe
+    switch (type) {
2a00fe
+        case CKA_MODULUS:
2a00fe
+        case CKA_PUBLIC_EXPONENT:
2a00fe
+        case CKA_CERT_SHA1_HASH:
2a00fe
+        case CKA_CERT_MD5_HASH:
2a00fe
+        case CKA_TRUST_SERVER_AUTH:
2a00fe
+        case CKA_TRUST_CLIENT_AUTH:
2a00fe
+        case CKA_TRUST_EMAIL_PROTECTION:
2a00fe
+        case CKA_TRUST_CODE_SIGNING:
2a00fe
+        case CKA_TRUST_STEP_UP_APPROVED:
2a00fe
+        case CKA_NSS_OVERRIDE_EXTENSIONS:
2a00fe
+            return PR_TRUE;
2a00fe
+        default:
2a00fe
+            break;
2a00fe
+    }
2a00fe
+    return PR_FALSE;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * convert a database ulong back to a native ULONG. (reverse of the above
2a00fe
+ * function.
2a00fe
+ */
2a00fe
+static CK_ULONG
2a00fe
+sdbULong2ULong(unsigned char *data)
2a00fe
+{
2a00fe
+    int i;
2a00fe
+    CK_ULONG value = 0;
2a00fe
+
2a00fe
+    for (i = 0; i < SDB_ULONG_SIZE; i++) {
2a00fe
+        value |= (((CK_ULONG)data[i]) << (SDB_ULONG_SIZE - 1 - i)
2a00fe
+                 * PR_BITS_PER_BYTE);
2a00fe
+    }
2a00fe
+    return value;
2a00fe
+}
2a00fe
+
2a00fe
+/* PBE defines and functions */
2a00fe
+
2a00fe
+typedef struct EncryptedDataInfoStr {
2a00fe
+    SECAlgorithmID algorithm;
2a00fe
+    SECItem encryptedData;
2a00fe
+} EncryptedDataInfo;
2a00fe
+
2a00fe
+static const SEC_ASN1Template encryptedDataInfoTemplate[] = {
2a00fe
+    { SEC_ASN1_SEQUENCE,
2a00fe
+      0, NULL, sizeof(EncryptedDataInfo) },
2a00fe
+    { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
2a00fe
+      offsetof(EncryptedDataInfo, algorithm),
2a00fe
+      SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
2a00fe
+    { SEC_ASN1_OCTET_STRING,
2a00fe
+      offsetof(EncryptedDataInfo, encryptedData) },
2a00fe
+    { 0 }
2a00fe
+};
2a00fe
+
2a00fe
+typedef struct PBEParameterStr {
2a00fe
+    SECAlgorithmID prfAlg;
2a00fe
+    SECItem salt;
2a00fe
+    SECItem iteration;
2a00fe
+    SECItem keyLength;
2a00fe
+} PBEParameter;
2a00fe
+
2a00fe
+static const SEC_ASN1Template pkcs5V1PBEParameterTemplate[] =
2a00fe
+    {
2a00fe
+      { SEC_ASN1_SEQUENCE,
2a00fe
+        0, NULL, sizeof(PBEParameter) },
2a00fe
+      { SEC_ASN1_OCTET_STRING,
2a00fe
+        offsetof(PBEParameter, salt) },
2a00fe
+      { SEC_ASN1_INTEGER,
2a00fe
+        offsetof(PBEParameter, iteration) },
2a00fe
+      { 0 }
2a00fe
+    };
2a00fe
+
2a00fe
+static const SEC_ASN1Template pkcs12V2PBEParameterTemplate[] =
2a00fe
+    {
2a00fe
+      { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PBEParameter) },
2a00fe
+      { SEC_ASN1_OCTET_STRING, offsetof(PBEParameter, salt) },
2a00fe
+      { SEC_ASN1_INTEGER, offsetof(PBEParameter, iteration) },
2a00fe
+      { 0 }
2a00fe
+    };
2a00fe
+
2a00fe
+
2a00fe
+static const SEC_ASN1Template pkcs5V2PBEParameterTemplate[] =
2a00fe
+    {
2a00fe
+      { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(PBEParameter) },
2a00fe
+      /* this is really a choice, but since we don't understand any other
2a00fe
+       * choice, just inline it. */
2a00fe
+      { SEC_ASN1_OCTET_STRING, offsetof(PBEParameter, salt) },
2a00fe
+      { SEC_ASN1_INTEGER, offsetof(PBEParameter, iteration) },
2a00fe
+      { SEC_ASN1_INTEGER, offsetof(PBEParameter, keyLength) },
2a00fe
+      { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
2a00fe
+        offsetof(PBEParameter, prfAlg),
2a00fe
+        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
2a00fe
+      { 0 }
2a00fe
+    };
2a00fe
+
2a00fe
+typedef struct Pkcs5v2PBEParameterStr {
2a00fe
+    SECAlgorithmID keyParams; /* parameters of the key generation */
2a00fe
+    SECAlgorithmID algParams; /* parameters for the encryption or mac op */
2a00fe
+} Pkcs5v2PBEParameter;
2a00fe
+
2a00fe
+static const SEC_ASN1Template pkcs5v2PBES2ParameterTemplate[] = {
2a00fe
+      { SEC_ASN1_SEQUENCE, 0, NULL, sizeof(Pkcs5v2PBEParameter) },
2a00fe
+      { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
2a00fe
+        offsetof(Pkcs5v2PBEParameter, keyParams),
2a00fe
+        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
2a00fe
+      { SEC_ASN1_INLINE | SEC_ASN1_XTRN,
2a00fe
+        offsetof(Pkcs5v2PBEParameter, algParams),
2a00fe
+        SEC_ASN1_SUB(SECOID_AlgorithmIDTemplate) },
2a00fe
+      { 0 }
2a00fe
+};
2a00fe
+
2a00fe
+static inline PRBool
2a00fe
+isPKCS12PBE(SECOidTag alg) {
2a00fe
+    switch (alg) {
2a00fe
+    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_2KEY_TRIPLE_DES_CBC:
2a00fe
+    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_3KEY_TRIPLE_DES_CBC:
2a00fe
+    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC2_CBC:
2a00fe
+    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC2_CBC:
2a00fe
+    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_128_BIT_RC4:
2a00fe
+    case SEC_OID_PKCS12_V2_PBE_WITH_SHA1_AND_40_BIT_RC4:
2a00fe
+        return PR_TRUE;
2a00fe
+    default:
2a00fe
+        break;
2a00fe
+    }
2a00fe
+    return PR_FALSE;
2a00fe
+}
2a00fe
+
2a00fe
+
2a00fe
+/* helper functions */
2a00fe
+
2a00fe
+/* output an NSS specific attribute or name that wasn't found in our
2a00fe
+ * pkcs #11 table */
2a00fe
+const char *
2a00fe
+makeNSSVendorName(CK_ATTRIBUTE_TYPE attribute, const char *nameType)
2a00fe
+{
2a00fe
+    static char nss_name[256];
2a00fe
+    const char *name = NULL;
2a00fe
+    if ((attribute >= CKA_NSS) && (attribute <= 0xffffffff)) {
2a00fe
+        sprintf(nss_name,"%s+%d", nameType, (int)(attribute-CKA_NSS));
2a00fe
+        name = nss_name;
2a00fe
+    }
2a00fe
+    return name;
2a00fe
+}
2a00fe
+
2a00fe
+/*  turn and attribute into a name */
2a00fe
+const char *
2a00fe
+AttributeName(CK_ATTRIBUTE_TYPE attribute)
2a00fe
+{
2a00fe
+    const char *name = getNameFromAttribute(attribute);
2a00fe
+    if (!name) {
2a00fe
+        name = makeNSSVendorName(attribute, "CKA_NSS");
2a00fe
+    }
2a00fe
+
2a00fe
+    return name ? name : "UNKNOWN_ATTRIBUTE_TYPE";
2a00fe
+}
2a00fe
+
2a00fe
+/*  turn and error code into a name */
2a00fe
+const char *
2a00fe
+ErrorName(CK_RV crv)
2a00fe
+{
2a00fe
+    const char *error = getName(crv, ConstResult);
2a00fe
+    if (!error) {
2a00fe
+        error = makeNSSVendorName(crv, "CKR_NSS");
2a00fe
+    }
2a00fe
+    return error ? error : "UNKNOWN_ERROR";
2a00fe
+}
2a00fe
+
2a00fe
+/* turn an oud tag into a string */
2a00fe
+const char *
2a00fe
+oid2string(SECOidTag alg)
2a00fe
+{
2a00fe
+    const char *oidstring = SECOID_FindOIDTagDescription(alg);
2a00fe
+    const char *def="Invalid oid tag"; /* future build a dotted oid string value here */
2a00fe
+    return oidstring ? oidstring : def;
2a00fe
+}
2a00fe
+
2a00fe
+/* dump an arbitary data blob. Dump it has hex with ascii on the side */
2a00fe
+#define ASCCHAR(val) ((val) >= ' ' && (val) <= 0x7e ? (val) : '.')
2a00fe
+#define LINE_LENGTH 16
2a00fe
+void
2a00fe
+dumpValue(const unsigned char *v, int len)
2a00fe
+{
2a00fe
+    int i, next = 0;
2a00fe
+    char string[LINE_LENGTH+1];
2a00fe
+    char space[LINE_LENGTH*2+1];
2a00fe
+    char *nl = "";
2a00fe
+    char *sp = "";
2a00fe
+    PORT_Memset(string, 0, sizeof(string));
2a00fe
+
2a00fe
+    for (i=0; i < len; i++) {
2a00fe
+        if ((i % LINE_LENGTH) == 0) {
2a00fe
+            printf("%s%s%s        ", sp, string, nl);
2a00fe
+            PORT_Memset(string, 0, sizeof(string));
2a00fe
+            next = 0;
2a00fe
+            nl = "\n";
2a00fe
+            sp = " ";
2a00fe
+        }
2a00fe
+        printf("%02x", v[i]);
2a00fe
+        string[next++] = ASCCHAR(v[i]);
2a00fe
+    }
2a00fe
+    PORT_Memset(space, 0, sizeof(space));
2a00fe
+    i = LINE_LENGTH - (len % LINE_LENGTH);
2a00fe
+    if (i != LINE_LENGTH) {
2a00fe
+        int j;
2a00fe
+        for (j=0 ; j < i; j++) {
2a00fe
+            space[j*2] = ' ';
2a00fe
+            space[j*2+1] = ' ';
2a00fe
+        }
2a00fe
+     }
2a00fe
+    printf("%s%s%s%s", space, sp, string, nl);
2a00fe
+}
2a00fe
+
2a00fe
+/* dump a PKCS5/12 PBE blob */
2a00fe
+void
2a00fe
+dumpPKCS(unsigned char *val, CK_ULONG len, PRBool *hasSig)
2a00fe
+{
2a00fe
+    EncryptedDataInfo edi;
2a00fe
+    SECStatus rv;
2a00fe
+    SECItem data;
2a00fe
+    PLArenaPool *arena;
2a00fe
+    SECOidTag alg, prfAlg;
2a00fe
+    PBEParameter pbeParam;
2a00fe
+    unsigned char zero = 0;
2a00fe
+    const SEC_ASN1Template *template = pkcs5V1PBEParameterTemplate;
2a00fe
+    int iter, keyLen, i;
2a00fe
+
2a00fe
+    if (hasSig) { *hasSig = PR_FALSE; }
2a00fe
+
2a00fe
+
2a00fe
+    data.data = val;
2a00fe
+    data.len = len;
2a00fe
+    arena =  PORT_NewArena(DER_DEFAULT_CHUNKSIZE);
2a00fe
+    if (arena == NULL) {
2a00fe
+        printf("Couldn't allocate arena\n");
2a00fe
+        return;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* initialize default values */
2a00fe
+    PORT_Memset(&pbeParam, 0, sizeof(pbeParam));
2a00fe
+    pbeParam.keyLength.data = &zer;;
2a00fe
+    pbeParam.keyLength.len = sizeof(zero);
2a00fe
+    SECOID_SetAlgorithmID(arena, &pbeParam.prfAlg, SEC_OID_SHA1, NULL);
2a00fe
+
2a00fe
+    /* first crack the encrypted data from the PBE algorithm ID */
2a00fe
+    rv = SEC_QuickDERDecodeItem(arena, &edi, encryptedDataInfoTemplate, &data);
2a00fe
+    if (rv != SECSuccess) {
2a00fe
+        printf("Encrypted Data, failed to decode\n");
2a00fe
+        dumpValue(val,len);
2a00fe
+        PORT_FreeArena(arena, PR_FALSE);
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    /* now use the pbe secalg to dump info on the pbe */
2a00fe
+    alg = SECOID_GetAlgorithmTag(&edi.algorithm);
2a00fe
+    if ((alg == SEC_OID_PKCS5_PBES2) || (alg == SEC_OID_PKCS5_PBMAC1)){
2a00fe
+        Pkcs5v2PBEParameter param;
2a00fe
+        SECOidTag palg;
2a00fe
+        const char *typeName = (alg == SEC_OID_PKCS5_PBES2) ?
2a00fe
+                               "Encrypted Data PBES2" :
2a00fe
+                               "Mac Data PBMAC1";
2a00fe
+
2a00fe
+        rv = SEC_QuickDERDecodeItem(arena, &param,
2a00fe
+                                    pkcs5v2PBES2ParameterTemplate,
2a00fe
+                                    &edi.algorithm.parameters);
2a00fe
+        if (rv != SECSuccess) {
2a00fe
+            printf("%s, failed to decode\n", typeName);
2a00fe
+            dumpValue(val,len);
2a00fe
+            PORT_FreeArena(arena, PR_FALSE);
2a00fe
+            return;
2a00fe
+        }
2a00fe
+        palg = SECOID_GetAlgorithmTag(&param.algParams);
2a00fe
+        printf("%s alg=%s ", typeName, oid2string(palg));
2a00fe
+        if (hasSig && palg == SEC_OID_AES_256_CBC) {
2a00fe
+            *hasSig = PR_TRUE;
2a00fe
+        }
2a00fe
+        template = pkcs5V2PBEParameterTemplate;
2a00fe
+        edi.algorithm.parameters = param.keyParams.parameters;
2a00fe
+    } else {
2a00fe
+        printf("Encrypted Data alg=%s ", oid2string(alg));
2a00fe
+        if (alg == SEC_OID_PKCS5_PBKDF2) {
2a00fe
+            template = pkcs5V2PBEParameterTemplate;
2a00fe
+        } else if (isPKCS12PBE(alg)) {
2a00fe
+            template = pkcs12V2PBEParameterTemplate;
2a00fe
+        } else {
2a00fe
+            template = pkcs5V1PBEParameterTemplate;
2a00fe
+        }
2a00fe
+    }
2a00fe
+    rv = SEC_QuickDERDecodeItem(arena, &pbeParam,
2a00fe
+                                template,
2a00fe
+                                &edi.algorithm.parameters);
2a00fe
+    if (rv != SECSuccess) {
2a00fe
+        printf("( failed to decode params)\n");
2a00fe
+        PORT_FreeArena(arena, PR_FALSE);
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    /* dump the pbe parmeters */
2a00fe
+    iter = DER_GetInteger(&pbeParam.iteration);
2a00fe
+    keyLen = DER_GetInteger(&pbeParam.keyLength);
2a00fe
+    prfAlg = SECOID_GetAlgorithmTag(&pbeParam.prfAlg);
2a00fe
+    printf("(prf=%s iter=%d keyLen=%d salt=0x", 
2a00fe
+           oid2string(prfAlg), iter, keyLen);
2a00fe
+    for(i=0;i < pbeParam.salt.len; i++) printf("%02x",pbeParam.salt.data[i]);
2a00fe
+    printf(")\n");
2a00fe
+    /* finally dump the raw encrypted data */
2a00fe
+    dumpValue(edi.encryptedData.data, edi.encryptedData.len);
2a00fe
+    PORT_FreeArena(arena, PR_FALSE);
2a00fe
+}
2a00fe
+
2a00fe
+/* dump a long attribute, convert to an unsigned long. PKCS #11 Longs are
2a00fe
+ * limited to 32 bits by the spec, even if the CK_ULONG is longer */
2a00fe
+void
2a00fe
+dumpLongAttribute(CK_ATTRIBUTE_TYPE type, CK_ULONG value)
2a00fe
+{
2a00fe
+    const char *nameType = "CK_NSS";
2a00fe
+    ConstType constType = ConstNone;
2a00fe
+    const char *valueName = NULL;
2a00fe
+
2a00fe
+    switch (type) {
2a00fe
+    case CKA_CLASS:
2a00fe
+        nameType = "CKO_NSS";
2a00fe
+        constType = ConstObject;
2a00fe
+        break;
2a00fe
+    case CKA_CERTIFICATE_TYPE:
2a00fe
+        nameType = "CKC_NSS";
2a00fe
+        constType = ConstCertType;
2a00fe
+        break;
2a00fe
+    case CKA_KEY_TYPE:
2a00fe
+        nameType = "CKK_NSS";
2a00fe
+        constType = ConstKeyType;
2a00fe
+        break;
2a00fe
+    case CKA_MECHANISM_TYPE:
2a00fe
+        nameType = "CKM_NSS";
2a00fe
+        constType = ConstMechanism;
2a00fe
+        break;
2a00fe
+    case CKA_TRUST_SERVER_AUTH:
2a00fe
+    case CKA_TRUST_CLIENT_AUTH:
2a00fe
+    case CKA_TRUST_CODE_SIGNING:
2a00fe
+    case CKA_TRUST_EMAIL_PROTECTION:
2a00fe
+    case CKA_TRUST_IPSEC_END_SYSTEM:
2a00fe
+    case CKA_TRUST_IPSEC_TUNNEL:
2a00fe
+    case CKA_TRUST_IPSEC_USER:
2a00fe
+    case CKA_TRUST_TIME_STAMPING:
2a00fe
+        nameType = "CKT_NSS";
2a00fe
+        constType = ConstTrust;
2a00fe
+        break;
2a00fe
+    default:
2a00fe
+        break;
2a00fe
+    }
2a00fe
+    /* if value has a symbolic name, use it */
2a00fe
+    if (constType != ConstNone) {
2a00fe
+        valueName = getName(value, constType);
2a00fe
+    }
2a00fe
+    if (!valueName) {
2a00fe
+        valueName = makeNSSVendorName(value, nameType);
2a00fe
+    }
2a00fe
+    if (!valueName) {
2a00fe
+        printf("%d (0x%08x)\n", (int) value, (int)value);
2a00fe
+    } else {
2a00fe
+        printf("%s (0x%08x)\n", valueName, (int)value);
2a00fe
+    }
2a00fe
+}
2a00fe
+
2a00fe
+/* dump a signature for an object */
2a00fe
+static const char META_SIG_TEMPLATE[] = "sig_%s_%08x_%08x";
2a00fe
+void
2a00fe
+dumpSignature(CK_ATTRIBUTE_TYPE attribute, SDB *keydb, PRBool isKey,
2a00fe
+               CK_OBJECT_HANDLE objectID, PRBool force)
2a00fe
+{
2a00fe
+    char id[30];
2a00fe
+    CK_RV crv;
2a00fe
+    SECItem signText;
2a00fe
+    unsigned char signData[SDB_MAX_META_DATA_LEN];
2a00fe
+
2a00fe
+    if (!force && !isAuthenticatedAttribute(attribute)) {
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    sprintf(id, META_SIG_TEMPLATE,
2a00fe
+            isKey ? "key" : "cert",
2a00fe
+            (unsigned int)objectID, (unsigned int)attribute);
2a00fe
+    printf("        Signature %s:",id);
2a00fe
+    signText.data = signData;
2a00fe
+    signText.len = sizeof(signData);
2a00fe
+
2a00fe
+
2a00fe
+    crv = (*keydb->sdb_GetMetaData)(keydb, id, &signText, NULL);
2a00fe
+    if ((crv != CKR_OK) && isKey) {
2a00fe
+        sprintf(id, META_SIG_TEMPLATE,
2a00fe
+                isKey ? "key" : "cert", (unsigned int)
2a00fe
+                (objectID | SFTK_KEYDB_TYPE | SFTK_TOKEN_TYPE),
2a00fe
+                (unsigned int)attribute);
2a00fe
+        crv = (*keydb->sdb_GetMetaData)(keydb, id, &signText, NULL);
2a00fe
+    }
2a00fe
+    if (crv != CKR_OK) {
2a00fe
+        printf(" FAILED %s with %s (0x%08x)\n", id, ErrorName(crv), (int) crv);
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    dumpPKCS(signText.data, signText.len, NULL);
2a00fe
+    return;
2a00fe
+}
2a00fe
+
2a00fe
+/* dump an attribute. use the helper functions above */
2a00fe
+void
2a00fe
+dumpAttribute(CK_ATTRIBUTE *template, SDB *keydb, PRBool isKey,
2a00fe
+              CK_OBJECT_HANDLE id)
2a00fe
+{
2a00fe
+    CK_ATTRIBUTE_TYPE attribute = template->type;
2a00fe
+    printf("      %s(0x%08x): ", AttributeName(attribute), (int)attribute);
2a00fe
+    if (template->pValue == NULL) {
2a00fe
+        printf("NULL (%d)\n", (int)template->ulValueLen);
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    if (template->ulValueLen == SDB_ULONG_SIZE
2a00fe
+        && isULONGAttribute(attribute)) {
2a00fe
+        CK_ULONG value=sdbULong2ULong(template->pValue);
2a00fe
+        dumpLongAttribute(attribute, value);
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    if (template->ulValueLen == 1) {
2a00fe
+        unsigned char val = *(unsigned char *)template->pValue;
2a00fe
+        switch (val) {
2a00fe
+        case 0:
2a00fe
+           printf("CK_FALSE\n");
2a00fe
+           break;
2a00fe
+        case 1:
2a00fe
+           printf("CK_TRUE\n");
2a00fe
+           break;
2a00fe
+        default:
2a00fe
+           printf("%d 0x%02x %c\n", val, val, ASCCHAR(val));
2a00fe
+           break;
2a00fe
+        }
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    if (isKey && isPrivateAttribute(attribute)) {
2a00fe
+        PRBool hasSig = PR_FALSE;
2a00fe
+        dumpPKCS(template->pValue, template->ulValueLen, &hasSig);
2a00fe
+        if (hasSig) {
2a00fe
+            dumpSignature(attribute, keydb, isKey, id, PR_TRUE);
2a00fe
+        }
2a00fe
+        return;
2a00fe
+    }
2a00fe
+    if (template->ulValueLen == 0) { printf("empty"); }
2a00fe
+    printf("\n");
2a00fe
+    dumpValue(template->pValue, template->ulValueLen);
2a00fe
+}
2a00fe
+
2a00fe
+/* dump all the attributes in an object */
2a00fe
+void
2a00fe
+dumpObject(CK_OBJECT_HANDLE id, SDB *db, SDB *keydb, PRBool isKey)
2a00fe
+{
2a00fe
+    CK_RV crv;
2a00fe
+    int i;
2a00fe
+    CK_ATTRIBUTE template;
2a00fe
+    char buffer[2048];
2a00fe
+    char * alloc = NULL;
2a00fe
+
2a00fe
+    printf("  Object 0x%08x:\n", (int)id);
2a00fe
+    for (i = 0; i < known_attributes_size; i++) {
2a00fe
+        CK_ATTRIBUTE_TYPE attribute = known_attributes[i];
2a00fe
+        template.type = attribute;
2a00fe
+        template.pValue = NULL;
2a00fe
+        template.ulValueLen = 0;
2a00fe
+        crv = (*db->sdb_GetAttributeValue)(db, id, &template, 1);
2a00fe
+
2a00fe
+        if (crv != CKR_OK) {
2a00fe
+            if (crv != CKR_ATTRIBUTE_TYPE_INVALID) {
2a00fe
+                PR_fprintf(PR_STDERR, "    "
2a00fe
+                           "Get Attribute %s (0x%08x):FAILED\"%s\"(0x%08x)\n",
2a00fe
+                            AttributeName(attribute), (int)attribute,
2a00fe
+                            ErrorName(crv), (int)crv);
2a00fe
+            }
2a00fe
+            continue;
2a00fe
+        }
2a00fe
+
2a00fe
+        if (template.ulValueLen < sizeof(buffer)) {
2a00fe
+            template.pValue = buffer;
2a00fe
+        } else {
2a00fe
+            alloc = PORT_Alloc(template.ulValueLen);
2a00fe
+            template.pValue = alloc;
2a00fe
+        }
2a00fe
+        if (template.pValue == NULL) {
2a00fe
+            PR_fprintf(PR_STDERR, "    "
2a00fe
+                       "Could allocate %d bytes for  Attribute %s (0x%08x)\n",
2a00fe
+                        (int) template.ulValueLen,
2a00fe
+                        AttributeName(attribute), (int)attribute);
2a00fe
+             continue;
2a00fe
+        }
2a00fe
+        crv = (*db->sdb_GetAttributeValue)(db, id, &template, 1);
2a00fe
+
2a00fe
+        if (crv != CKR_OK) {
2a00fe
+            if (crv != CKR_ATTRIBUTE_TYPE_INVALID) {
2a00fe
+                PR_fprintf(PR_STDERR, "    "
2a00fe
+                           "Get Attribute %s (0x%08x):FAILED\"%s\"(0x%08x)\n",
2a00fe
+                            AttributeName(attribute), (int)attribute,
2a00fe
+                            ErrorName(crv), (int)crv);
2a00fe
+            }
2a00fe
+            if (alloc) {
2a00fe
+                PORT_Free(alloc);
2a00fe
+                alloc = NULL;
2a00fe
+            }
2a00fe
+            continue;
2a00fe
+        }
2a00fe
+
2a00fe
+        dumpAttribute(&template, keydb, isKey, id);
2a00fe
+        dumpSignature(template.type, keydb, isKey, id, PR_FALSE);
2a00fe
+        if (alloc) {
2a00fe
+            PORT_Free(alloc);
2a00fe
+            alloc = NULL;
2a00fe
+        }
2a00fe
+    }
2a00fe
+}
2a00fe
+
2a00fe
+/* dump all the objects in a database */
2a00fe
+void
2a00fe
+dumpDB(SDB *db, const char *name, SDB *keydb, PRBool isKey)
2a00fe
+{
2a00fe
+    SDBFind *findHandle= NULL;
2a00fe
+    CK_BBOOL isTrue = 1;
2a00fe
+    CK_ATTRIBUTE allObjectTemplate = {CKA_TOKEN, NULL, 1 };
2a00fe
+    CK_ULONG allObjectTemplateCount = 1;
2a00fe
+    PRBool recordFound = PR_FALSE;
2a00fe
+    CK_RV crv = CKR_OK;
2a00fe
+    CK_ULONG objectCount = 0;
2a00fe
+    printf("%s:\n",name);
2a00fe
+
2a00fe
+    allObjectTemplate.pValue = &isTrue;
2a00fe
+    crv = (*db->sdb_FindObjectsInit)(db, &allObjectTemplate,
2a00fe
+                                         allObjectTemplateCount, &findHandle);
2a00fe
+    do {
2a00fe
+       CK_OBJECT_HANDLE id;
2a00fe
+       recordFound = PR_FALSE;
2a00fe
+       crv =(*db->sdb_FindObjects)(db, findHandle, &id, 1, &objectCount);
2a00fe
+       if ((crv == CKR_OK) && (objectCount == 1)) {
2a00fe
+           recordFound = PR_TRUE;
2a00fe
+           dumpObject(id, db, keydb, isKey);
2a00fe
+       }
2a00fe
+     } while (recordFound);
2a00fe
+     if (crv != CKR_OK) {
2a00fe
+         PR_fprintf(PR_STDERR,
2a00fe
+                    "Last record return PKCS #11 error = %s (0x%08x)\n",
2a00fe
+                    ErrorName(crv), (int)crv);
2a00fe
+     }
2a00fe
+     (*db->sdb_FindObjectsFinal)(db,findHandle);
2a00fe
+}
2a00fe
+
2a00fe
+int
2a00fe
+main(int argc, char **argv)
2a00fe
+{
2a00fe
+    PLOptState *optstate;
2a00fe
+    PLOptStatus optstatus;
2a00fe
+    char *certPrefix="", *keyPrefix="";
2a00fe
+    int cert_version = 9;
2a00fe
+    int key_version = 4;
2a00fe
+    SDB *certdb = NULL;
2a00fe
+    SDB *keydb = NULL;
2a00fe
+    PRBool isNew = PR_FALSE;
2a00fe
+
2a00fe
+    CK_RV crv;
2a00fe
+
2a00fe
+    progName = strrchr(argv[0], '/');
2a00fe
+    if (!progName)
2a00fe
+        progName = strrchr(argv[0], '\\');
2a00fe
+    progName = progName ? progName + 1 : argv[0];
2a00fe
+
2a00fe
+    optstate = PL_CreateOptState(argc, argv, "d:c:k:v:V:h");
2a00fe
+
2a00fe
+    while ((optstatus = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
2a00fe
+        switch (optstate->option) {
2a00fe
+            case 'h':
2a00fe
+            default:
2a00fe
+                Usage();
2a00fe
+                break;
2a00fe
+
2a00fe
+            case 'd':
2a00fe
+                dbDir = PORT_Strdup(optstate->value);
2a00fe
+                break;
2a00fe
+
2a00fe
+            case 'c':
2a00fe
+                certPrefix = PORT_Strdup(optstate->value);
2a00fe
+                break;
2a00fe
+
2a00fe
+            case 'k':
2a00fe
+                keyPrefix = PORT_Strdup(optstate->value);
2a00fe
+                break;
2a00fe
+
2a00fe
+            case 'v':
2a00fe
+                key_version = atoi(optstate->value);
2a00fe
+                break;
2a00fe
+
2a00fe
+            case 'V':
2a00fe
+                cert_version = atoi(optstate->value);
2a00fe
+                break;
2a00fe
+       
2a00fe
+        }
2a00fe
+    }
2a00fe
+    PL_DestroyOptState(optstate);
2a00fe
+    if (optstatus == PL_OPT_BAD)
2a00fe
+        Usage();
2a00fe
+
2a00fe
+    if (dbDir) {
2a00fe
+        char *tmp = dbDir;
2a00fe
+        dbDir = SECU_ConfigDirectory(tmp);
2a00fe
+        PORT_Free(tmp);
2a00fe
+    } else {
2a00fe
+        /* Look in $SSL_DIR */
2a00fe
+        dbDir = SECU_ConfigDirectory(SECU_DefaultSSLDir());
2a00fe
+    }
2a00fe
+    PR_fprintf(PR_STDERR, "dbdir selected is %s\n\n", dbDir);
2a00fe
+
2a00fe
+    if (dbDir[0] == '\0') {
2a00fe
+        PR_fprintf(PR_STDERR, errStrings[DIR_DOESNT_EXIST_ERR], dbDir);
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+
2a00fe
+    PR_Init(PR_USER_THREAD, PR_PRIORITY_NORMAL, 0);
2a00fe
+    SECOID_Init();
2a00fe
+
2a00fe
+    crv = s_open(dbDir, certPrefix, keyPrefix, cert_version, key_version,
2a00fe
+                 SDB_RDONLY, &certdb, &keydb, &isNew);
2a00fe
+    if (crv != CKR_OK) {
2a00fe
+        PR_fprintf(PR_STDERR,
2a00fe
+                   "Couldn't open databased in %s, error=%s (0x%08x)\n",
2a00fe
+                    dbDir, ErrorName(crv), (int)crv);
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* now dump the objects in the cert database */
2a00fe
+    dumpDB(certdb, "CertDB", keydb, PR_FALSE);
2a00fe
+    dumpDB(keydb, "KeyDB", keydb, PR_TRUE);
2a00fe
+    return 0;
2a00fe
+}
2a00fe
diff --git a/cmd/dbtool/dbtool.gyp b/cmd/dbtool/dbtool.gyp
2a00fe
new file mode 100644
2a00fe
--- /dev/null
2a00fe
+++ b/cmd/dbtool/dbtool.gyp
2a00fe
@@ -0,0 +1,25 @@
2a00fe
+# This Source Code Form is subject to the terms of the Mozilla Public
2a00fe
+# License, v. 2.0. If a copy of the MPL was not distributed with this
2a00fe
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
2a00fe
+{
2a00fe
+  'includes': [
2a00fe
+    '../../coreconf/config.gypi',
2a00fe
+    '../../cmd/platlibs.gypi'
2a00fe
+  ],
2a00fe
+  'targets': [
2a00fe
+    {
2a00fe
+      'target_name': 'dbtest',
2a00fe
+      'type': 'executable',
2a00fe
+      'sources': [
2a00fe
+        'dbtest.c'
2a00fe
+      ],
2a00fe
+      'dependencies': [
2a00fe
+        '<(DEPTH)/exports.gyp:dbm_exports',
2a00fe
+        '<(DEPTH)/exports.gyp:nss_exports'
2a00fe
+      ]
2a00fe
+    }
2a00fe
+  ],
2a00fe
+  'variables': {
2a00fe
+    'module': 'nss'
2a00fe
+  }
2a00fe
+}
2a00fe
\ No newline at end of file
2a00fe
diff --git a/cmd/dbtool/manifest.mn b/cmd/dbtool/manifest.mn
2a00fe
new file mode 100644
2a00fe
--- /dev/null
2a00fe
+++ b/cmd/dbtool/manifest.mn
2a00fe
@@ -0,0 +1,18 @@
2a00fe
+# 
2a00fe
+# This Source Code Form is subject to the terms of the Mozilla Public
2a00fe
+# License, v. 2.0. If a copy of the MPL was not distributed with this
2a00fe
+# file, You can obtain one at http://mozilla.org/MPL/2.0/.
2a00fe
+
2a00fe
+CORE_DEPTH = ../..
2a00fe
+
2a00fe
+# MODULE public and private header  directories are implicitly REQUIRED.
2a00fe
+MODULE = nss
2a00fe
+
2a00fe
+USE_STATIC_LIBS = 1
2a00fe
+
2a00fe
+# DIRS = 
2a00fe
+
2a00fe
+CSRCS	= dbtool.c  sdb.c
2a00fe
+
2a00fe
+PROGRAM	= dbtool
2a00fe
+
2a00fe
diff --git a/cmd/dbtool/sdb.c b/cmd/dbtool/sdb.c
2a00fe
new file mode 100644
2a00fe
--- /dev/null
2a00fe
+++ b/cmd/dbtool/sdb.c
2a00fe
@@ -0,0 +1,2469 @@
2a00fe
+/* This Source Code Form is subject to the terms of the Mozilla Public
2a00fe
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
2a00fe
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
2a00fe
+/*
2a00fe
+ * This file implements PKCS 11 on top of our existing security modules
2a00fe
+ *
2a00fe
+ * For more information about PKCS 11 See PKCS 11 Token Inteface Standard.
2a00fe
+ *   This implementation has two slots:
2a00fe
+ *      slot 1 is our generic crypto support. It does not require login.
2a00fe
+ *   It supports Public Key ops, and all they bulk ciphers and hashes.
2a00fe
+ *   It can also support Private Key ops for imported Private keys. It does
2a00fe
+ *   not have any token storage.
2a00fe
+ *      slot 2 is our private key support. It requires a login before use. It
2a00fe
+ *   can store Private Keys and Certs as token objects. Currently only private
2a00fe
+ *   keys and their associated Certificates are saved on the token.
2a00fe
+ *
2a00fe
+ *   In this implementation, session objects are only visible to the session
2a00fe
+ *   that created or generated them.
2a00fe
+ */
2a00fe
+
2a00fe
+#include "sdb.h"
2a00fe
+#include "pkcs11t.h"
2a00fe
+#include "seccomon.h"
2a00fe
+#include <sqlite3.h>
2a00fe
+#include "prthread.h"
2a00fe
+#include "prio.h"
2a00fe
+#include <stdio.h>
2a00fe
+#include "secport.h"
2a00fe
+#include "prmon.h"
2a00fe
+#include "prenv.h"
2a00fe
+#include "prprf.h"
2a00fe
+#include "prsystem.h" /* for PR_GetDirectorySeparator() */
2a00fe
+#include <sys/stat.h>
2a00fe
+#if defined(_WIN32)
2a00fe
+#include <io.h>
2a00fe
+#include <windows.h>
2a00fe
+#elif defined(XP_UNIX)
2a00fe
+#include <unistd.h>
2a00fe
+#endif
2a00fe
+#if defined(LINUX) && !defined(ANDROID)
2a00fe
+#include <linux/magic.h>
2a00fe
+#include <sys/vfs.h>
2a00fe
+#endif
2a00fe
+#include "utilpars.h"
2a00fe
+
2a00fe
+#ifdef SQLITE_UNSAFE_THREADS
2a00fe
+#include "prlock.h"
2a00fe
+/*
2a00fe
+ * SQLite can be compiled to be thread safe or not.
2a00fe
+ * turn on SQLITE_UNSAFE_THREADS if the OS does not support
2a00fe
+ * a thread safe version of sqlite.
2a00fe
+ */
2a00fe
+static PRLock *sqlite_lock = NULL;
2a00fe
+
2a00fe
+#define LOCK_SQLITE() PR_Lock(sqlite_lock);
2a00fe
+#define UNLOCK_SQLITE() PR_Unlock(sqlite_lock);
2a00fe
+#else
2a00fe
+#define LOCK_SQLITE()
2a00fe
+#define UNLOCK_SQLITE()
2a00fe
+#endif
2a00fe
+
2a00fe
+typedef enum {
2a00fe
+    SDB_CERT = 1,
2a00fe
+    SDB_KEY = 2
2a00fe
+} sdbDataType;
2a00fe
+
2a00fe
+/*
2a00fe
+ * defines controlling how long we wait to acquire locks.
2a00fe
+ *
2a00fe
+ * SDB_SQLITE_BUSY_TIMEOUT specifies how long (in milliseconds)
2a00fe
+ *  sqlite will wait on lock. If that timeout expires, sqlite will
2a00fe
+ *  return SQLITE_BUSY.
2a00fe
+ * SDB_BUSY_RETRY_TIME specifies how many seconds the sdb_ code waits
2a00fe
+ *  after receiving a busy before retrying.
2a00fe
+ * SDB_MAX_BUSY_RETRIES specifies how many times the sdb_ will retry on
2a00fe
+ *  a busy condition.
2a00fe
+ *
2a00fe
+ * SDB_SQLITE_BUSY_TIMEOUT affects all opertions, both manual
2a00fe
+ *   (prepare/step/reset/finalize) and automatic (sqlite3_exec()).
2a00fe
+ * SDB_BUSY_RETRY_TIME and SDB_MAX_BUSY_RETRIES only affect manual operations
2a00fe
+ *
2a00fe
+ * total wait time for automatic operations:
2a00fe
+ *   1 second (SDB_SQLITE_BUSY_TIMEOUT/1000).
2a00fe
+ * total wait time for manual operations:
2a00fe
+ *   (1 second + SDB_BUSY_RETRY_TIME) * 30 = 30 seconds.
2a00fe
+ * (SDB_SQLITE_BUSY_TIMEOUT/1000 + SDB_BUSY_RETRY_TIME)*SDB_MAX_BUSY_RETRIES
2a00fe
+ */
2a00fe
+#define SDB_SQLITE_BUSY_TIMEOUT 1000 /* milliseconds */
2a00fe
+#define SDB_BUSY_RETRY_TIME 5        /* 'ticks', varies by platforms */
2a00fe
+#define SDB_MAX_BUSY_RETRIES 30
2a00fe
+
2a00fe
+/*
2a00fe
+ * known attributes
2a00fe
+ */
2a00fe
+static const CK_ATTRIBUTE_TYPE known_attributes[] = {
2a00fe
+    CKA_CLASS, CKA_TOKEN, CKA_PRIVATE, CKA_LABEL, CKA_APPLICATION,
2a00fe
+    CKA_VALUE, CKA_OBJECT_ID, CKA_CERTIFICATE_TYPE, CKA_ISSUER,
2a00fe
+    CKA_SERIAL_NUMBER, CKA_AC_ISSUER, CKA_OWNER, CKA_ATTR_TYPES, CKA_TRUSTED,
2a00fe
+    CKA_CERTIFICATE_CATEGORY, CKA_JAVA_MIDP_SECURITY_DOMAIN, CKA_URL,
2a00fe
+    CKA_HASH_OF_SUBJECT_PUBLIC_KEY, CKA_HASH_OF_ISSUER_PUBLIC_KEY,
2a00fe
+    CKA_CHECK_VALUE, CKA_KEY_TYPE, CKA_SUBJECT, CKA_ID, CKA_SENSITIVE,
2a00fe
+    CKA_ENCRYPT, CKA_DECRYPT, CKA_WRAP, CKA_UNWRAP, CKA_SIGN, CKA_SIGN_RECOVER,
2a00fe
+    CKA_VERIFY, CKA_VERIFY_RECOVER, CKA_DERIVE, CKA_START_DATE, CKA_END_DATE,
2a00fe
+    CKA_MODULUS, CKA_MODULUS_BITS, CKA_PUBLIC_EXPONENT, CKA_PRIVATE_EXPONENT,
2a00fe
+    CKA_PRIME_1, CKA_PRIME_2, CKA_EXPONENT_1, CKA_EXPONENT_2, CKA_COEFFICIENT,
2a00fe
+    CKA_PUBLIC_KEY_INFO, CKA_PRIME, CKA_SUBPRIME, CKA_BASE, CKA_PRIME_BITS,
2a00fe
+    CKA_SUB_PRIME_BITS, CKA_VALUE_BITS, CKA_VALUE_LEN, CKA_EXTRACTABLE,
2a00fe
+    CKA_LOCAL, CKA_NEVER_EXTRACTABLE, CKA_ALWAYS_SENSITIVE,
2a00fe
+    CKA_KEY_GEN_MECHANISM, CKA_MODIFIABLE, CKA_EC_PARAMS,
2a00fe
+    CKA_EC_POINT, CKA_SECONDARY_AUTH, CKA_AUTH_PIN_FLAGS,
2a00fe
+    CKA_ALWAYS_AUTHENTICATE, CKA_WRAP_WITH_TRUSTED, CKA_HW_FEATURE_TYPE,
2a00fe
+    CKA_RESET_ON_INIT, CKA_HAS_RESET, CKA_PIXEL_X, CKA_PIXEL_Y,
2a00fe
+    CKA_RESOLUTION, CKA_CHAR_ROWS, CKA_CHAR_COLUMNS, CKA_COLOR,
2a00fe
+    CKA_BITS_PER_PIXEL, CKA_CHAR_SETS, CKA_ENCODING_METHODS, CKA_MIME_TYPES,
2a00fe
+    CKA_MECHANISM_TYPE, CKA_REQUIRED_CMS_ATTRIBUTES,
2a00fe
+    CKA_DEFAULT_CMS_ATTRIBUTES, CKA_SUPPORTED_CMS_ATTRIBUTES,
2a00fe
+    CKA_WRAP_TEMPLATE, CKA_UNWRAP_TEMPLATE, CKA_NSS_TRUST, CKA_NSS_URL,
2a00fe
+    CKA_NSS_EMAIL, CKA_NSS_SMIME_INFO, CKA_NSS_SMIME_TIMESTAMP,
2a00fe
+    CKA_NSS_PKCS8_SALT, CKA_NSS_PASSWORD_CHECK, CKA_NSS_EXPIRES,
2a00fe
+    CKA_NSS_KRL, CKA_NSS_PQG_COUNTER, CKA_NSS_PQG_SEED,
2a00fe
+    CKA_NSS_PQG_H, CKA_NSS_PQG_SEED_BITS, CKA_NSS_MODULE_SPEC,
2a00fe
+    CKA_NSS_OVERRIDE_EXTENSIONS, CKA_NSS_SERVER_DISTRUST_AFTER,
2a00fe
+    CKA_NSS_EMAIL_DISTRUST_AFTER, CKA_TRUST_DIGITAL_SIGNATURE,
2a00fe
+    CKA_TRUST_NON_REPUDIATION, CKA_TRUST_KEY_ENCIPHERMENT,
2a00fe
+    CKA_TRUST_DATA_ENCIPHERMENT, CKA_TRUST_KEY_AGREEMENT,
2a00fe
+    CKA_TRUST_KEY_CERT_SIGN, CKA_TRUST_CRL_SIGN, CKA_TRUST_SERVER_AUTH,
2a00fe
+    CKA_TRUST_CLIENT_AUTH, CKA_TRUST_CODE_SIGNING, CKA_TRUST_EMAIL_PROTECTION,
2a00fe
+    CKA_TRUST_IPSEC_END_SYSTEM, CKA_TRUST_IPSEC_TUNNEL, CKA_TRUST_IPSEC_USER,
2a00fe
+    CKA_TRUST_TIME_STAMPING, CKA_TRUST_STEP_UP_APPROVED, CKA_CERT_SHA1_HASH,
2a00fe
+    CKA_CERT_MD5_HASH, CKA_NSS_DB
2a00fe
+};
2a00fe
+
2a00fe
+static const int known_attributes_size = PR_ARRAY_SIZE(known_attributes);
2a00fe
+
2a00fe
+/*
2a00fe
+ * Note on use of sqlReadDB: Only one thread at a time may have an actual
2a00fe
+ * operation going on given sqlite3 * database. An operation is defined as
2a00fe
+ * the time from a sqlite3_prepare() until the sqlite3_finalize().
2a00fe
+ * Multiple sqlite3 * databases can be open and have simultaneous operations
2a00fe
+ * going. We use the sqlXactDB for all write operations. This database
2a00fe
+ * is only opened when we first create a transaction and closed when the
2a00fe
+ * transaction is complete. sqlReadDB is open when we first opened the database
2a00fe
+ * and is used for all read operation. It's use is protected by a monitor. This
2a00fe
+ * is because an operation can span the use of FindObjectsInit() through the
2a00fe
+ * call to FindObjectsFinal(). In the intermediate time it is possible to call
2a00fe
+ * other operations like NSC_GetAttributeValue */
2a00fe
+
2a00fe
+struct SDBPrivateStr {
2a00fe
+    char *sqlDBName;                /* invariant, path to this database */
2a00fe
+    sqlite3 *sqlXactDB;             /* access protected by dbMon, use protected
2a00fe
+                                    * by the transaction. Current transaction db*/
2a00fe
+    PRThread *sqlXactThread;        /* protected by dbMon,
2a00fe
+                                    * current transaction thread */
2a00fe
+    sqlite3 *sqlReadDB;             /* use protected by dbMon, value invariant */
2a00fe
+    PRIntervalTime lastUpdateTime;  /* last time the cache was updated */
2a00fe
+    PRIntervalTime updateInterval;  /* how long the cache can go before it
2a00fe
+                                    * must be updated again */
2a00fe
+    sdbDataType type;               /* invariant, database type */
2a00fe
+    char *table;                    /* invariant, SQL table which contains the db */
2a00fe
+    char *cacheTable;               /* invariant, SQL table cache of db */
2a00fe
+    PRMonitor *dbMon;               /* invariant, monitor to protect
2a00fe
+                                    * sqlXact* fields, and use of the sqlReadDB */
2a00fe
+    CK_ATTRIBUTE_TYPE *schemaAttrs; /* Attribute columns that exist in the table. */
2a00fe
+    unsigned int numSchemaAttrs;
2a00fe
+};
2a00fe
+
2a00fe
+typedef struct SDBPrivateStr SDBPrivate;
2a00fe
+
2a00fe
+/* Magic for an explicit NULL. NOTE: ideally this should be
2a00fe
+ * out of band data. Since it's not completely out of band, pick
2a00fe
+ * a value that has no meaning to any existing PKCS #11 attributes.
2a00fe
+ * This value is 1) not a valid string (imbedded '\0'). 2) not a U_LONG
2a00fe
+ * or a normal key (too short). 3) not a bool (too long). 4) not an RSA
2a00fe
+ * public exponent (too many bits).
2a00fe
+ */
2a00fe
+const unsigned char SQLITE_EXPLICIT_NULL[] = { 0xa5, 0x0, 0x5a };
2a00fe
+#define SQLITE_EXPLICIT_NULL_LEN 3
2a00fe
+
2a00fe
+/*
2a00fe
+ * determine when we've completed our tasks
2a00fe
+ */
2a00fe
+static int
2a00fe
+sdb_done(int err, int *count)
2a00fe
+{
2a00fe
+    /* allow as many rows as the database wants to give */
2a00fe
+    if (err == SQLITE_ROW) {
2a00fe
+        *count = 0;
2a00fe
+        return 0;
2a00fe
+    }
2a00fe
+    if (err != SQLITE_BUSY) {
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+    /* err == SQLITE_BUSY, Dont' retry forever in this case */
2a00fe
+    if (++(*count) >= SDB_MAX_BUSY_RETRIES) {
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+    return 0;
2a00fe
+}
2a00fe
+
2a00fe
+#if defined(_WIN32)
2a00fe
+/*
2a00fe
+ * NSPR functions and narrow CRT functions do not handle UTF-8 file paths that
2a00fe
+ * sqlite3 expects.
2a00fe
+ */
2a00fe
+
2a00fe
+static int
2a00fe
+sdb_chmod(const char *filename, int pmode)
2a00fe
+{
2a00fe
+    int result;
2a00fe
+
2a00fe
+    if (!filename) {
2a00fe
+        return -1;
2a00fe
+    }
2a00fe
+
2a00fe
+    wchar_t *filenameWide = _NSSUTIL_UTF8ToWide(filename);
2a00fe
+    if (!filenameWide) {
2a00fe
+        return -1;
2a00fe
+    }
2a00fe
+    result = _wchmod(filenameWide, pmode);
2a00fe
+    PORT_Free(filenameWide);
2a00fe
+
2a00fe
+    return result;
2a00fe
+}
2a00fe
+#else
2a00fe
+#define sdb_chmod(filename, pmode) chmod((filename), (pmode))
2a00fe
+#endif
2a00fe
+
2a00fe
+/*
2a00fe
+ * find out where sqlite stores the temp tables. We do this by replicating
2a00fe
+ * the logic from sqlite.
2a00fe
+ */
2a00fe
+#if defined(_WIN32)
2a00fe
+static char *
2a00fe
+sdb_getFallbackTempDir(void)
2a00fe
+{
2a00fe
+    /* sqlite uses sqlite3_temp_directory if it is not NULL. We don't have
2a00fe
+     * access to sqlite3_temp_directory because it is not exported from
2a00fe
+     * sqlite3.dll. Assume sqlite3_win32_set_directory isn't called and
2a00fe
+     * sqlite3_temp_directory is NULL.
2a00fe
+     */
2a00fe
+    char path[MAX_PATH];
2a00fe
+    DWORD rv;
2a00fe
+    size_t len;
2a00fe
+
2a00fe
+    rv = GetTempPathA(MAX_PATH, path);
2a00fe
+    if (rv > MAX_PATH || rv == 0)
2a00fe
+        return NULL;
2a00fe
+    len = strlen(path);
2a00fe
+    if (len == 0)
2a00fe
+        return NULL;
2a00fe
+    /* The returned string ends with a backslash, for example, "C:\TEMP\". */
2a00fe
+    if (path[len - 1] == '\\')
2a00fe
+        path[len - 1] = '\0';
2a00fe
+    return PORT_Strdup(path);
2a00fe
+}
2a00fe
+#elif defined(XP_UNIX)
2a00fe
+static char *
2a00fe
+sdb_getFallbackTempDir(void)
2a00fe
+{
2a00fe
+    const char *azDirs[] = {
2a00fe
+        NULL,
2a00fe
+        NULL,
2a00fe
+        "/var/tmp",
2a00fe
+        "/usr/tmp",
2a00fe
+        "/tmp",
2a00fe
+        NULL /* List terminator */
2a00fe
+    };
2a00fe
+    unsigned int i;
2a00fe
+    struct stat buf;
2a00fe
+    const char *zDir = NULL;
2a00fe
+
2a00fe
+    azDirs[0] = sqlite3_temp_directory;
2a00fe
+    azDirs[1] = PR_GetEnvSecure("TMPDIR");
2a00fe
+
2a00fe
+    for (i = 0; i < PR_ARRAY_SIZE(azDirs); i++) {
2a00fe
+        zDir = azDirs[i];
2a00fe
+        if (zDir == NULL)
2a00fe
+            continue;
2a00fe
+        if (stat(zDir, &buf))
2a00fe
+            continue;
2a00fe
+        if (!S_ISDIR(buf.st_mode))
2a00fe
+            continue;
2a00fe
+        if (access(zDir, 07))
2a00fe
+            continue;
2a00fe
+        break;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (zDir == NULL)
2a00fe
+        return NULL;
2a00fe
+    return PORT_Strdup(zDir);
2a00fe
+}
2a00fe
+#else
2a00fe
+#error "sdb_getFallbackTempDir not implemented"
2a00fe
+#endif
2a00fe
+
2a00fe
+#ifndef SQLITE_FCNTL_TEMPFILENAME
2a00fe
+/* SQLITE_FCNTL_TEMPFILENAME was added in SQLite 3.7.15 */
2a00fe
+#define SQLITE_FCNTL_TEMPFILENAME 16
2a00fe
+#endif
2a00fe
+
2a00fe
+static char *
2a00fe
+sdb_getTempDir(sqlite3 *sqlDB)
2a00fe
+{
2a00fe
+    int sqlrv;
2a00fe
+    char *result = NULL;
2a00fe
+    char *tempName = NULL;
2a00fe
+    char *foundSeparator = NULL;
2a00fe
+
2a00fe
+    /* Obtain temporary filename in sqlite's directory for temporary tables */
2a00fe
+    sqlrv = sqlite3_file_control(sqlDB, 0, SQLITE_FCNTL_TEMPFILENAME,
2a00fe
+                                 (void *)&tempName);
2a00fe
+    if (sqlrv == SQLITE_NOTFOUND) {
2a00fe
+        /* SQLITE_FCNTL_TEMPFILENAME not implemented because we are using
2a00fe
+         * an older SQLite. */
2a00fe
+        return sdb_getFallbackTempDir();
2a00fe
+    }
2a00fe
+    if (sqlrv != SQLITE_OK) {
2a00fe
+        return NULL;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* We'll extract the temporary directory from tempName */
2a00fe
+    foundSeparator = PORT_Strrchr(tempName, PR_GetDirectorySeparator());
2a00fe
+    if (foundSeparator) {
2a00fe
+        /* We shorten the temp filename string to contain only
2a00fe
+         * the directory name (including the trailing separator).
2a00fe
+         * We know the byte after the foundSeparator position is
2a00fe
+         * safe to use, in the shortest scenario it contains the
2a00fe
+         * end-of-string byte.
2a00fe
+         * By keeping the separator at the found position, it will
2a00fe
+         * even work if tempDir consists of the separator, only.
2a00fe
+         * (In this case the toplevel directory will be used for
2a00fe
+         * access speed testing). */
2a00fe
+        ++foundSeparator;
2a00fe
+        *foundSeparator = 0;
2a00fe
+
2a00fe
+        /* Now we copy the directory name for our caller */
2a00fe
+        result = PORT_Strdup(tempName);
2a00fe
+    }
2a00fe
+
2a00fe
+    sqlite3_free(tempName);
2a00fe
+    return result;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * Map SQL_LITE errors to PKCS #11 errors as best we can.
2a00fe
+ */
2a00fe
+static CK_RV
2a00fe
+sdb_mapSQLError(sdbDataType type, int sqlerr)
2a00fe
+{
2a00fe
+    switch (sqlerr) {
2a00fe
+        /* good matches */
2a00fe
+        case SQLITE_OK:
2a00fe
+        case SQLITE_DONE:
2a00fe
+            return CKR_OK;
2a00fe
+        case SQLITE_NOMEM:
2a00fe
+            return CKR_HOST_MEMORY;
2a00fe
+        case SQLITE_READONLY:
2a00fe
+            return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+        /* close matches */
2a00fe
+        case SQLITE_AUTH:
2a00fe
+        case SQLITE_PERM:
2a00fe
+        /*return CKR_USER_NOT_LOGGED_IN; */
2a00fe
+        case SQLITE_CANTOPEN:
2a00fe
+        case SQLITE_NOTFOUND:
2a00fe
+            /* NSS distiguishes between failure to open the cert and the key db */
2a00fe
+            return type == SDB_CERT ? CKR_NSS_CERTDB_FAILED : CKR_NSS_KEYDB_FAILED;
2a00fe
+        case SQLITE_IOERR:
2a00fe
+            return CKR_DEVICE_ERROR;
2a00fe
+        default:
2a00fe
+            break;
2a00fe
+    }
2a00fe
+    return CKR_GENERAL_ERROR;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * build up database name from a directory, prefix, name, version and flags.
2a00fe
+ */
2a00fe
+static char *
2a00fe
+sdb_BuildFileName(const char *directory,
2a00fe
+                  const char *prefix, const char *type,
2a00fe
+                  int version)
2a00fe
+{
2a00fe
+    char *dbname = NULL;
2a00fe
+    /* build the full dbname */
2a00fe
+    dbname = sqlite3_mprintf("%s%c%s%s%d.db", directory,
2a00fe
+                             (int)(unsigned char)PR_GetDirectorySeparator(),
2a00fe
+                             prefix, type, version);
2a00fe
+    return dbname;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * find out how expensive the access system call is for non-existant files
2a00fe
+ * in the given directory.  Return the number of operations done in 33 ms.
2a00fe
+ */
2a00fe
+static PRUint32
2a00fe
+sdb_measureAccess(const char *directory)
2a00fe
+{
2a00fe
+    PRUint32 i;
2a00fe
+    PRIntervalTime time;
2a00fe
+    PRIntervalTime delta;
2a00fe
+    PRIntervalTime duration = PR_MillisecondsToInterval(33);
2a00fe
+    const char *doesntExistName = "_dOeSnotExist_.db";
2a00fe
+    char *temp, *tempStartOfFilename;
2a00fe
+    size_t maxTempLen, maxFileNameLen, directoryLength, tmpdirLength = 0;
2a00fe
+#ifdef SDB_MEASURE_USE_TEMP_DIR
2a00fe
+    /*
2a00fe
+     * on some OS's and Filesystems, creating a bunch of files and deleting
2a00fe
+     * them messes up the systems's caching, but if we create the files in
2a00fe
+     * a temp directory which we later delete, then the cache gets cleared
2a00fe
+     * up. This code uses several OS dependent calls, and it's not clear
2a00fe
+     * that temp directory use won't mess up other filesystems and OS caching,
2a00fe
+     * so if you need this for your OS, you can turn on the
2a00fe
+     * 'SDB_MEASURE_USE_TEMP_DIR' define in coreconf
2a00fe
+     */
2a00fe
+    const char template[] = "dbTemp.XXXXXX";
2a00fe
+    tmpdirLength = sizeof(template);
2a00fe
+#endif
2a00fe
+    /* no directory, just return one */
2a00fe
+    if (directory == NULL) {
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* our calculation assumes time is a 4 bytes == 32 bit integer */
2a00fe
+    PORT_Assert(sizeof(time) == 4);
2a00fe
+
2a00fe
+    directoryLength = strlen(directory);
2a00fe
+
2a00fe
+    maxTempLen = directoryLength + 1       /* dirname + / */
2a00fe
+                 + tmpdirLength            /* tmpdirname includes / */
2a00fe
+                 + strlen(doesntExistName) /* filename base */
2a00fe
+                 + 11                      /* max chars for 32 bit int plus potential sign */
2a00fe
+                 + 1;                      /* zero terminator */
2a00fe
+
2a00fe
+    temp = PORT_ZAlloc(maxTempLen);
2a00fe
+    if (!temp) {
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* We'll copy directory into temp just once, then ensure it ends
2a00fe
+     * with the directory separator. */
2a00fe
+
2a00fe
+    strcpy(temp, directory);
2a00fe
+    if (directory[directoryLength - 1] != PR_GetDirectorySeparator()) {
2a00fe
+        temp[directoryLength++] = PR_GetDirectorySeparator();
2a00fe
+    }
2a00fe
+
2a00fe
+#ifdef SDB_MEASURE_USE_TEMP_DIR
2a00fe
+    /* add the template for a temporary subdir, and create it */
2a00fe
+    strcat(temp, template);
2a00fe
+    if (!mkdtemp(temp)) {
2a00fe
+        PORT_Free(temp);
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+    /* and terminate that tmp subdir with a / */
2a00fe
+    strcat(temp, "/");
2a00fe
+#endif
2a00fe
+
2a00fe
+    /* Remember the position after the last separator, and calculate the
2a00fe
+     * number of remaining bytes. */
2a00fe
+    tempStartOfFilename = temp + directoryLength + tmpdirLength;
2a00fe
+    maxFileNameLen = maxTempLen - directoryLength;
2a00fe
+
2a00fe
+    /* measure number of Access operations that can be done in 33 milliseconds
2a00fe
+     * (1/30'th of a second), or 10000 operations, which ever comes first.
2a00fe
+     */
2a00fe
+    time = PR_IntervalNow();
2a00fe
+    for (i = 0; i < 10000u; i++) {
2a00fe
+        PRIntervalTime next;
2a00fe
+
2a00fe
+        /* We'll use the variable part first in the filename string, just in
2a00fe
+         * case it's longer than assumed, so if anything gets cut off, it
2a00fe
+         * will be cut off from the constant part.
2a00fe
+         * This code assumes the directory name at the beginning of
2a00fe
+         * temp remains unchanged during our loop. */
2a00fe
+        PR_snprintf(tempStartOfFilename, maxFileNameLen,
2a00fe
+                    ".%lu%s", (PRUint32)(time + i), doesntExistName);
2a00fe
+        PR_Access(temp, PR_ACCESS_EXISTS);
2a00fe
+        next = PR_IntervalNow();
2a00fe
+        delta = next - time;
2a00fe
+        if (delta >= duration)
2a00fe
+            break;
2a00fe
+    }
2a00fe
+
2a00fe
+#ifdef SDB_MEASURE_USE_TEMP_DIR
2a00fe
+    /* turn temp back into our tmpdir path by removing doesntExistName, and
2a00fe
+     * remove the tmp dir */
2a00fe
+    *tempStartOfFilename = '\0';
2a00fe
+    (void)rmdir(temp);
2a00fe
+#endif
2a00fe
+    PORT_Free(temp);
2a00fe
+
2a00fe
+    /* always return 1 or greater */
2a00fe
+    return i ? i : 1u;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * some file sytems are very slow to run sqlite3 on, particularly if the
2a00fe
+ * access count is pretty high. On these filesystems is faster to create
2a00fe
+ * a temporary database on the local filesystem and access that. This
2a00fe
+ * code uses a temporary table to create that cache. Temp tables are
2a00fe
+ * automatically cleared when the database handle it was created on
2a00fe
+ * Is freed.
2a00fe
+ */
2a00fe
+static const char DROP_CACHE_CMD[] = "DROP TABLE %s";
2a00fe
+static const char CREATE_CACHE_CMD[] =
2a00fe
+    "CREATE TEMPORARY TABLE %s AS SELECT * FROM %s";
2a00fe
+static const char CREATE_ISSUER_INDEX_CMD[] =
2a00fe
+    "CREATE INDEX issuer ON %s (a81)";
2a00fe
+static const char CREATE_SUBJECT_INDEX_CMD[] =
2a00fe
+    "CREATE INDEX subject ON %s (a101)";
2a00fe
+static const char CREATE_LABEL_INDEX_CMD[] = "CREATE INDEX label ON %s (a3)";
2a00fe
+static const char CREATE_ID_INDEX_CMD[] = "CREATE INDEX ckaid ON %s (a102)";
2a00fe
+
2a00fe
+static CK_RV
2a00fe
+sdb_buildCache(sqlite3 *sqlDB, sdbDataType type,
2a00fe
+               const char *cacheTable, const char *table)
2a00fe
+{
2a00fe
+    char *newStr;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+
2a00fe
+    newStr = sqlite3_mprintf(CREATE_CACHE_CMD, cacheTable, table);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        return CKR_HOST_MEMORY;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        return sdb_mapSQLError(type, sqlerr);
2a00fe
+    }
2a00fe
+    /* failure to create the indexes is not an issue */
2a00fe
+    newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, cacheTable);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, cacheTable);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, cacheTable);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, cacheTable);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    return CKR_OK;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * update the cache and the data records describing it.
2a00fe
+ *  The cache is updated by dropping the temp database and recreating it.
2a00fe
+ */
2a00fe
+static CK_RV
2a00fe
+sdb_updateCache(SDBPrivate *sdb_p)
2a00fe
+{
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    char *newStr;
2a00fe
+
2a00fe
+    /* drop the old table */
2a00fe
+    newStr = sqlite3_mprintf(DROP_CACHE_CMD, sdb_p->cacheTable);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        return CKR_HOST_MEMORY;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_exec(sdb_p->sqlReadDB, newStr, NULL, 0, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    if ((sqlerr != SQLITE_OK) && (sqlerr != SQLITE_ERROR)) {
2a00fe
+        /* something went wrong with the drop, don't try to refresh...
2a00fe
+         * NOTE: SQLITE_ERROR is returned if the table doesn't exist. In
2a00fe
+         * that case, we just continue on and try to reload it */
2a00fe
+        return sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+    }
2a00fe
+
2a00fe
+    /* set up the new table */
2a00fe
+    error = sdb_buildCache(sdb_p->sqlReadDB, sdb_p->type,
2a00fe
+                           sdb_p->cacheTable, sdb_p->table);
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        /* we have a new cache! */
2a00fe
+        sdb_p->lastUpdateTime = PR_IntervalNow();
2a00fe
+    }
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ *  The sharing of sqlite3 handles across threads is tricky. Older versions
2a00fe
+ *  couldn't at all, but newer ones can under strict conditions. Basically
2a00fe
+ *  no 2 threads can use the same handle while another thread has an open
2a00fe
+ *  stmt running. Once the sqlite3_stmt is finalized, another thread can then
2a00fe
+ *  use the database handle.
2a00fe
+ *
2a00fe
+ *  We use monitors to protect against trying to use a database before
2a00fe
+ *  it's sqlite3_stmt is finalized. This is preferable to the opening and
2a00fe
+ *  closing the database each operation because there is significant overhead
2a00fe
+ *  in the open and close. Also continually opening and closing the database
2a00fe
+ *  defeats the cache code as the cache table is lost on close (thus
2a00fe
+ *  requiring us to have to reinitialize the cache every operation).
2a00fe
+ *
2a00fe
+ *  An execption to the shared handle is transations. All writes happen
2a00fe
+ *  through a transaction. When we are in  a transaction, we must use the
2a00fe
+ *  same database pointer for that entire transation. In this case we save
2a00fe
+ *  the transaction database and use it for all accesses on the transaction
2a00fe
+ *  thread. Other threads use the common database.
2a00fe
+ *
2a00fe
+ *  There can only be once active transaction on the database at a time.
2a00fe
+ *
2a00fe
+ *  sdb_openDBLocal() provides us with a valid database handle for whatever
2a00fe
+ *  state we are in (reading or in a transaction), and acquires any locks
2a00fe
+ *  appropriate to that state. It also decides when it's time to refresh
2a00fe
+ *  the cache before we start an operation. Any database handle returned
2a00fe
+ *  just eventually be closed with sdb_closeDBLocal().
2a00fe
+ *
2a00fe
+ *  The table returned either points to the database's physical table, or
2a00fe
+ *  to the cached shadow. Tranactions always return the physical table
2a00fe
+ *  and read operations return either the physical table or the cache
2a00fe
+ *  depending on whether or not the cache exists.
2a00fe
+ */
2a00fe
+static CK_RV
2a00fe
+sdb_openDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB, const char **table)
2a00fe
+{
2a00fe
+    *sqlDB = NULL;
2a00fe
+
2a00fe
+    PR_EnterMonitor(sdb_p->dbMon);
2a00fe
+
2a00fe
+    if (table) {
2a00fe
+        *table = sdb_p->table;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* We're in a transaction, use the transaction DB */
2a00fe
+    if ((sdb_p->sqlXactDB) && (sdb_p->sqlXactThread == PR_GetCurrentThread())) {
2a00fe
+        *sqlDB = sdb_p->sqlXactDB;
2a00fe
+        /* only one thread can get here, safe to unlock */
2a00fe
+        PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+
2a00fe
+    /*
2a00fe
+     * if we are just reading from the table, we may have the table
2a00fe
+     * cached in a temporary table (especially if it's on a shared FS).
2a00fe
+     * In that case we want to see updates to the table, the the granularity
2a00fe
+     * is on order of human scale, not computer scale.
2a00fe
+     */
2a00fe
+    if (table && sdb_p->cacheTable) {
2a00fe
+        PRIntervalTime now = PR_IntervalNow();
2a00fe
+        if ((now - sdb_p->lastUpdateTime) > sdb_p->updateInterval) {
2a00fe
+            sdb_updateCache(sdb_p);
2a00fe
+        }
2a00fe
+        *table = sdb_p->cacheTable;
2a00fe
+    }
2a00fe
+
2a00fe
+    *sqlDB = sdb_p->sqlReadDB;
2a00fe
+
2a00fe
+    /* leave holding the lock. only one thread can actually use a given
2a00fe
+     * database connection at once */
2a00fe
+
2a00fe
+    return CKR_OK;
2a00fe
+}
2a00fe
+
2a00fe
+/* closing the local database currenly means unlocking the monitor */
2a00fe
+static CK_RV
2a00fe
+sdb_closeDBLocal(SDBPrivate *sdb_p, sqlite3 *sqlDB)
2a00fe
+{
2a00fe
+    if (sdb_p->sqlXactDB != sqlDB) {
2a00fe
+        /* if we weren't in a transaction, we got a lock */
2a00fe
+        PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+    }
2a00fe
+    return CKR_OK;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * wrapper to sqlite3_open which also sets the busy_timeout
2a00fe
+ */
2a00fe
+static int
2a00fe
+sdb_openDB(const char *name, sqlite3 **sqlDB, int flags)
2a00fe
+{
2a00fe
+    int sqlerr;
2a00fe
+    int openFlags;
2a00fe
+
2a00fe
+    *sqlDB = NULL;
2a00fe
+
2a00fe
+    if (flags & SDB_RDONLY) {
2a00fe
+        openFlags = SQLITE_OPEN_READONLY;
2a00fe
+    } else {
2a00fe
+        openFlags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
2a00fe
+        /* sqlite 3.34 seem to incorrectly open readwrite.
2a00fe
+        * when the file is readonly. Explicitly reject that issue here */
2a00fe
+        if ((_NSSUTIL_Access(name, PR_ACCESS_EXISTS) == PR_SUCCESS) && (_NSSUTIL_Access(name, PR_ACCESS_WRITE_OK) != PR_SUCCESS)) {
2a00fe
+            return SQLITE_READONLY;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    /* Requires SQLite 3.5.0 or newer. */
2a00fe
+    sqlerr = sqlite3_open_v2(name, sqlDB, openFlags, NULL);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        return sqlerr;
2a00fe
+    }
2a00fe
+
2a00fe
+    sqlerr = sqlite3_busy_timeout(*sqlDB, SDB_SQLITE_BUSY_TIMEOUT);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        sqlite3_close(*sqlDB);
2a00fe
+        *sqlDB = NULL;
2a00fe
+        return sqlerr;
2a00fe
+    }
2a00fe
+    return SQLITE_OK;
2a00fe
+}
2a00fe
+
2a00fe
+/* Sigh, if we created a new table since we opened the database,
2a00fe
+ * the database handle will not see the new table, we need to close this
2a00fe
+ * database and reopen it. Caller must be in a transaction or holding
2a00fe
+ * the dbMon. sqlDB is changed on success. */
2a00fe
+static int
2a00fe
+sdb_reopenDBLocal(SDBPrivate *sdb_p, sqlite3 **sqlDB)
2a00fe
+{
2a00fe
+    sqlite3 *newDB;
2a00fe
+    int sqlerr;
2a00fe
+
2a00fe
+    /* open a new database */
2a00fe
+    sqlerr = sdb_openDB(sdb_p->sqlDBName, &newDB, SDB_RDONLY);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        return sqlerr;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* if we are in a transaction, we may not be holding the monitor.
2a00fe
+     * grab it before we update the transaction database. This is
2a00fe
+     * safe since are using monitors. */
2a00fe
+    PR_EnterMonitor(sdb_p->dbMon);
2a00fe
+    /* update our view of the database */
2a00fe
+    if (sdb_p->sqlReadDB == *sqlDB) {
2a00fe
+        sdb_p->sqlReadDB = newDB;
2a00fe
+    } else if (sdb_p->sqlXactDB == *sqlDB) {
2a00fe
+        sdb_p->sqlXactDB = newDB;
2a00fe
+    }
2a00fe
+    PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+
2a00fe
+    /* close the old one */
2a00fe
+    sqlite3_close(*sqlDB);
2a00fe
+
2a00fe
+    *sqlDB = newDB;
2a00fe
+    return SQLITE_OK;
2a00fe
+}
2a00fe
+
2a00fe
+struct SDBFindStr {
2a00fe
+    sqlite3 *sqlDB;
2a00fe
+    sqlite3_stmt *findstmt;
2a00fe
+};
2a00fe
+
2a00fe
+static const char FIND_OBJECTS_CMD[] = "SELECT ALL id FROM %s WHERE %s;";
2a00fe
+static const char FIND_OBJECTS_ALL_CMD[] = "SELECT ALL id FROM %s;";
2a00fe
+CK_RV
2a00fe
+sdb_FindObjectsInit(SDB *sdb, const CK_ATTRIBUTE *template, CK_ULONG count,
2a00fe
+                    SDBFind **find)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    const char *table;
2a00fe
+    char *newStr, *findStr = NULL;
2a00fe
+    sqlite3_stmt *findstmt = NULL;
2a00fe
+    char *join = "";
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    unsigned int i;
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    *find = NULL;
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, &table);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    findStr = sqlite3_mprintf("");
2a00fe
+    for (i = 0; findStr && i < count; i++) {
2a00fe
+        newStr = sqlite3_mprintf("%s%sa%x=$DATA%d", findStr, join,
2a00fe
+                                 template[i].type, i);
2a00fe
+        join = " AND ";
2a00fe
+        sqlite3_free(findStr);
2a00fe
+        findStr = newStr;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (findStr == NULL) {
2a00fe
+        error = CKR_HOST_MEMORY;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (count == 0) {
2a00fe
+        newStr = sqlite3_mprintf(FIND_OBJECTS_ALL_CMD, table);
2a00fe
+    } else {
2a00fe
+        newStr = sqlite3_mprintf(FIND_OBJECTS_CMD, table, findStr);
2a00fe
+    }
2a00fe
+    sqlite3_free(findStr);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        error = CKR_HOST_MEMORY;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &findstmt, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    for (i = 0; sqlerr == SQLITE_OK && i < count; i++) {
2a00fe
+        const void *blobData = template[i].pValue;
2a00fe
+        unsigned int blobSize = template[i].ulValueLen;
2a00fe
+        if (blobSize == 0) {
2a00fe
+            blobSize = SQLITE_EXPLICIT_NULL_LEN;
2a00fe
+            blobData = SQLITE_EXPLICIT_NULL;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_bind_blob(findstmt, i + 1, blobData, blobSize,
2a00fe
+                                   SQLITE_TRANSIENT);
2a00fe
+    }
2a00fe
+    if (sqlerr == SQLITE_OK) {
2a00fe
+        *find = PORT_New(SDBFind);
2a00fe
+        if (*find == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        (*find)->findstmt = findstmt;
2a00fe
+        (*find)->sqlDB = sqlDB;
2a00fe
+        UNLOCK_SQLITE()
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+    error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+
2a00fe
+loser:
2a00fe
+    if (findstmt) {
2a00fe
+        sqlite3_reset(findstmt);
2a00fe
+        sqlite3_finalize(findstmt);
2a00fe
+    }
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_FindObjects(SDB *sdb, SDBFind *sdbFind, CK_OBJECT_HANDLE *object,
2a00fe
+                CK_ULONG arraySize, CK_ULONG *count)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3_stmt *stmt = sdbFind->findstmt;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    int retry = 0;
2a00fe
+
2a00fe
+    *count = 0;
2a00fe
+
2a00fe
+    if (arraySize == 0) {
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+    LOCK_SQLITE()
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+        if (sqlerr == SQLITE_ROW) {
2a00fe
+            /* only care about the id */
2a00fe
+            *object++ = sqlite3_column_int(stmt, 0);
2a00fe
+            arraySize--;
2a00fe
+            (*count)++;
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry) && (arraySize > 0));
2a00fe
+
2a00fe
+    /* we only have some of the objects, there is probably more,
2a00fe
+     * set the sqlerr to an OK value so we return CKR_OK */
2a00fe
+    if (sqlerr == SQLITE_ROW && arraySize == 0) {
2a00fe
+        sqlerr = SQLITE_DONE;
2a00fe
+    }
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+
2a00fe
+    return sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_FindObjectsFinal(SDB *sdb, SDBFind *sdbFind)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3_stmt *stmt = sdbFind->findstmt;
2a00fe
+    sqlite3 *sqlDB = sdbFind->sqlDB;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlerr = sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+    PORT_Free(sdbFind);
2a00fe
+
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+}
2a00fe
+
2a00fe
+static CK_RV
2a00fe
+sdb_GetValidAttributeValueNoLock(SDB *sdb, CK_OBJECT_HANDLE object_id,
2a00fe
+                                 CK_ATTRIBUTE *template, CK_ULONG count)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    const char *table = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int found = 0;
2a00fe
+    int retry = 0;
2a00fe
+    unsigned int i;
2a00fe
+
2a00fe
+    if (count == 0) {
2a00fe
+        error = CKR_OBJECT_HANDLE_INVALID;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* open a new db if necessary */
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, &table);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    char *columns = NULL;
2a00fe
+    for (i = 0; i < count; i++) {
2a00fe
+        char *newColumns;
2a00fe
+        if (columns) {
2a00fe
+            newColumns = sqlite3_mprintf("%s, a%x", columns, template[i].type);
2a00fe
+            sqlite3_free(columns);
2a00fe
+            columns = NULL;
2a00fe
+        } else {
2a00fe
+            newColumns = sqlite3_mprintf("a%x", template[i].type);
2a00fe
+        }
2a00fe
+        if (!newColumns) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        columns = newColumns;
2a00fe
+    }
2a00fe
+
2a00fe
+    PORT_Assert(columns);
2a00fe
+
2a00fe
+    char *statement = sqlite3_mprintf("SELECT DISTINCT %s FROM %s where id=$ID LIMIT 1;",
2a00fe
+                                      columns, table);
2a00fe
+    sqlite3_free(columns);
2a00fe
+    columns = NULL;
2a00fe
+    if (!statement) {
2a00fe
+        error = CKR_HOST_MEMORY;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, statement, -1, &stmt, NULL);
2a00fe
+    sqlite3_free(statement);
2a00fe
+    statement = NULL;
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    // NB: indices in sqlite3_bind_int are 1-indexed
2a00fe
+    sqlerr = sqlite3_bind_int(stmt, 1, object_id);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+        if (sqlerr == SQLITE_ROW) {
2a00fe
+            PORT_Assert(!found);
2a00fe
+            for (i = 0; i < count; i++) {
2a00fe
+                unsigned int blobSize;
2a00fe
+                const char *blobData;
2a00fe
+
2a00fe
+                // NB: indices in sqlite_column_{bytes,blob} are 0-indexed
2a00fe
+                blobSize = sqlite3_column_bytes(stmt, i);
2a00fe
+                blobData = sqlite3_column_blob(stmt, i);
2a00fe
+                if (blobData == NULL) {
2a00fe
+                    /* PKCS 11 requires that get attributes process all the
2a00fe
+                     * attributes in the template, marking the attributes with
2a00fe
+                     * issues with -1. Mark the error but continue */
2a00fe
+                    template[i].ulValueLen = -1;
2a00fe
+                    error = CKR_ATTRIBUTE_TYPE_INVALID;
2a00fe
+                    continue;
2a00fe
+                }
2a00fe
+                /* If the blob equals our explicit NULL value, then the
2a00fe
+                 * attribute is a NULL. */
2a00fe
+                if ((blobSize == SQLITE_EXPLICIT_NULL_LEN) &&
2a00fe
+                    (PORT_Memcmp(blobData, SQLITE_EXPLICIT_NULL,
2a00fe
+                                 SQLITE_EXPLICIT_NULL_LEN) == 0)) {
2a00fe
+                    blobSize = 0;
2a00fe
+                }
2a00fe
+                if (template[i].pValue) {
2a00fe
+                    if (template[i].ulValueLen < blobSize) {
2a00fe
+                        /* like CKR_ATTRIBUTE_TYPE_INVALID, continue processing */
2a00fe
+                        template[i].ulValueLen = -1;
2a00fe
+                        error = CKR_BUFFER_TOO_SMALL;
2a00fe
+                        continue;
2a00fe
+                    }
2a00fe
+                    PORT_Memcpy(template[i].pValue, blobData, blobSize);
2a00fe
+                }
2a00fe
+                template[i].ulValueLen = blobSize;
2a00fe
+            }
2a00fe
+            found = 1;
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+    sqlite3_reset(stmt);
2a00fe
+    sqlite3_finalize(stmt);
2a00fe
+    stmt = NULL;
2a00fe
+
2a00fe
+loser:
2a00fe
+    /* fix up the error if necessary */
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+        if (!found && error == CKR_OK) {
2a00fe
+            error = CKR_OBJECT_HANDLE_INVALID;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    /* if we had to open a new database, free it now */
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+/* NOTE: requires sdb_p->schemaAttrs to be sorted asc. */
2a00fe
+inline static PRBool
2a00fe
+sdb_attributeExists(SDB *sdb, CK_ATTRIBUTE_TYPE attr)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    int first = 0;
2a00fe
+    int last = (int)sdb_p->numSchemaAttrs - 1;
2a00fe
+    while (last >= first) {
2a00fe
+        int mid = first + (last - first) / 2;
2a00fe
+        if (sdb_p->schemaAttrs[mid] == attr) {
2a00fe
+            return PR_TRUE;
2a00fe
+        }
2a00fe
+        if (attr > sdb_p->schemaAttrs[mid]) {
2a00fe
+            first = mid + 1;
2a00fe
+        } else {
2a00fe
+            last = mid - 1;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    return PR_FALSE;
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_GetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id,
2a00fe
+                      CK_ATTRIBUTE *template, CK_ULONG count)
2a00fe
+{
2a00fe
+    CK_RV crv = CKR_OK;
2a00fe
+    unsigned int tmplIdx;
2a00fe
+    unsigned int resIdx = 0;
2a00fe
+    unsigned int validCount = 0;
2a00fe
+    unsigned int i;
2a00fe
+
2a00fe
+    if (count == 0) {
2a00fe
+        return crv;
2a00fe
+    }
2a00fe
+
2a00fe
+    CK_ATTRIBUTE *validTemplate;
2a00fe
+    PRBool invalidExists = PR_FALSE;
2a00fe
+    for (tmplIdx = 0; tmplIdx < count; tmplIdx++) {
2a00fe
+        if (!sdb_attributeExists(sdb, template[tmplIdx].type)) {
2a00fe
+            template[tmplIdx].ulValueLen = -1;
2a00fe
+            crv = CKR_ATTRIBUTE_TYPE_INVALID;
2a00fe
+            invalidExists = PR_TRUE;
2a00fe
+            break;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    if (!invalidExists) {
2a00fe
+        validTemplate = template;
2a00fe
+        validCount = count;
2a00fe
+    } else {
2a00fe
+        /* Create a new template containing only the valid subset of
2a00fe
+         * input |template|, and query with that. */
2a00fe
+        validCount = tmplIdx;
2a00fe
+        validTemplate = malloc(sizeof(CK_ATTRIBUTE) * count);
2a00fe
+        if (!validTemplate) {
2a00fe
+            return CKR_HOST_MEMORY;
2a00fe
+        }
2a00fe
+        /* Copy in what we already know is valid. */
2a00fe
+        for (i = 0; i < validCount; i++) {
2a00fe
+            validTemplate[i] = template[i];
2a00fe
+        }
2a00fe
+
2a00fe
+        /* tmplIdx was left at the index of the first invalid
2a00fe
+         * attribute, which has been handled. We only need to
2a00fe
+         * deal with the remainder. */
2a00fe
+        tmplIdx++;
2a00fe
+        for (; tmplIdx < count; tmplIdx++) {
2a00fe
+            if (sdb_attributeExists(sdb, template[tmplIdx].type)) {
2a00fe
+                validTemplate[validCount++] = template[tmplIdx];
2a00fe
+            } else {
2a00fe
+                template[tmplIdx].ulValueLen = -1;
2a00fe
+            }
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    if (validCount) {
2a00fe
+        LOCK_SQLITE()
2a00fe
+        CK_RV crv2 = sdb_GetValidAttributeValueNoLock(sdb, object_id, validTemplate, validCount);
2a00fe
+        UNLOCK_SQLITE()
2a00fe
+
2a00fe
+        /* If an invalid attribute was removed above, let
2a00fe
+         * the caller know. Any other error from the actual
2a00fe
+         * query should propogate. */
2a00fe
+        crv = (crv2 == CKR_OK) ? crv : crv2;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (invalidExists) {
2a00fe
+        /* Copy out valid lengths. */
2a00fe
+        tmplIdx = 0;
2a00fe
+        for (resIdx = 0; resIdx < validCount; resIdx++) {
2a00fe
+            for (; tmplIdx < count; tmplIdx++) {
2a00fe
+                if (template[tmplIdx].type != validTemplate[resIdx].type) {
2a00fe
+                    continue;
2a00fe
+                }
2a00fe
+                template[tmplIdx].ulValueLen = validTemplate[resIdx].ulValueLen;
2a00fe
+                tmplIdx++;
2a00fe
+                break;
2a00fe
+            }
2a00fe
+        }
2a00fe
+        free(validTemplate);
2a00fe
+    }
2a00fe
+
2a00fe
+    return crv;
2a00fe
+}
2a00fe
+
2a00fe
+static const char SET_ATTRIBUTE_CMD[] = "UPDATE %s SET %s WHERE id=$ID;";
2a00fe
+CK_RV
2a00fe
+sdb_SetAttributeValue(SDB *sdb, CK_OBJECT_HANDLE object_id,
2a00fe
+                      const CK_ATTRIBUTE *template, CK_ULONG count)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    char *setStr = NULL;
2a00fe
+    char *newStr = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    int retry = 0;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    unsigned int i;
2a00fe
+
2a00fe
+    if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
2a00fe
+        return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (count == 0) {
2a00fe
+        return CKR_OK;
2a00fe
+    }
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    setStr = sqlite3_mprintf("");
2a00fe
+    for (i = 0; setStr && i < count; i++) {
2a00fe
+        if (i == 0) {
2a00fe
+            sqlite3_free(setStr);
2a00fe
+            setStr = sqlite3_mprintf("a%x=$VALUE%d",
2a00fe
+                                     template[i].type, i);
2a00fe
+            continue;
2a00fe
+        }
2a00fe
+        newStr = sqlite3_mprintf("%s,a%x=$VALUE%d", setStr,
2a00fe
+                                 template[i].type, i);
2a00fe
+        sqlite3_free(setStr);
2a00fe
+        setStr = newStr;
2a00fe
+    }
2a00fe
+    newStr = NULL;
2a00fe
+
2a00fe
+    if (setStr == NULL) {
2a00fe
+        return CKR_HOST_MEMORY;
2a00fe
+    }
2a00fe
+    newStr = sqlite3_mprintf(SET_ATTRIBUTE_CMD, sdb_p->table, setStr);
2a00fe
+    sqlite3_free(setStr);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        UNLOCK_SQLITE()
2a00fe
+        return CKR_HOST_MEMORY;
2a00fe
+    }
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    for (i = 0; i < count; i++) {
2a00fe
+        if (template[i].ulValueLen != 0) {
2a00fe
+            sqlerr = sqlite3_bind_blob(stmt, i + 1, template[i].pValue,
2a00fe
+                                       template[i].ulValueLen, SQLITE_STATIC);
2a00fe
+        } else {
2a00fe
+            sqlerr = sqlite3_bind_blob(stmt, i + 1, SQLITE_EXPLICIT_NULL,
2a00fe
+                                       SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC);
2a00fe
+        }
2a00fe
+        if (sqlerr != SQLITE_OK)
2a00fe
+            goto loser;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_bind_int(stmt, i + 1, object_id);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+loser:
2a00fe
+    if (newStr) {
2a00fe
+        sqlite3_free(newStr);
2a00fe
+    }
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * check to see if a candidate object handle already exists.
2a00fe
+ */
2a00fe
+static PRBool
2a00fe
+sdb_objectExists(SDB *sdb, CK_OBJECT_HANDLE candidate)
2a00fe
+{
2a00fe
+    CK_RV crv;
2a00fe
+    CK_ATTRIBUTE template = { CKA_LABEL, NULL, 0 };
2a00fe
+
2a00fe
+    crv = sdb_GetValidAttributeValueNoLock(sdb, candidate, &template, 1);
2a00fe
+    if (crv == CKR_OBJECT_HANDLE_INVALID) {
2a00fe
+        return PR_FALSE;
2a00fe
+    }
2a00fe
+    return PR_TRUE;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * if we're here, we are in a transaction, so it's safe
2a00fe
+ * to examine the current state of the database
2a00fe
+ */
2a00fe
+static CK_OBJECT_HANDLE
2a00fe
+sdb_getObjectId(SDB *sdb)
2a00fe
+{
2a00fe
+    CK_OBJECT_HANDLE candidate;
2a00fe
+    static CK_OBJECT_HANDLE next_obj = CK_INVALID_HANDLE;
2a00fe
+    int count;
2a00fe
+    /*
2a00fe
+     * get an initial object handle to use
2a00fe
+     */
2a00fe
+    if (next_obj == CK_INVALID_HANDLE) {
2a00fe
+        PRTime time;
2a00fe
+        time = PR_Now();
2a00fe
+
2a00fe
+        next_obj = (CK_OBJECT_HANDLE)(time & 0x3fffffffL);
2a00fe
+    }
2a00fe
+    candidate = next_obj++;
2a00fe
+    /* detect that we've looped through all the handles... */
2a00fe
+    for (count = 0; count < 0x40000000; count++, candidate = next_obj++) {
2a00fe
+        /* mask off excess bits */
2a00fe
+        candidate &= 0x3fffffff;
2a00fe
+        /* if we hit zero, go to the next entry */
2a00fe
+        if (candidate == CK_INVALID_HANDLE) {
2a00fe
+            continue;
2a00fe
+        }
2a00fe
+        /* make sure we aren't already using */
2a00fe
+        if (!sdb_objectExists(sdb, candidate)) {
2a00fe
+            /* this one is free */
2a00fe
+            return candidate;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    /* no handle is free, fail */
2a00fe
+    return CK_INVALID_HANDLE;
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_GetNewObjectID(SDB *sdb, CK_OBJECT_HANDLE *object)
2a00fe
+{
2a00fe
+    CK_OBJECT_HANDLE id;
2a00fe
+
2a00fe
+    id = sdb_getObjectId(sdb);
2a00fe
+    if (id == CK_INVALID_HANDLE) {
2a00fe
+        return CKR_DEVICE_MEMORY; /* basically we ran out of resources */
2a00fe
+    }
2a00fe
+    *object = id;
2a00fe
+    return CKR_OK;
2a00fe
+}
2a00fe
+
2a00fe
+static const char CREATE_CMD[] = "INSERT INTO %s (id%s) VALUES($ID%s);";
2a00fe
+CK_RV
2a00fe
+sdb_CreateObject(SDB *sdb, CK_OBJECT_HANDLE *object_id,
2a00fe
+                 const CK_ATTRIBUTE *template, CK_ULONG count)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    char *columnStr = NULL;
2a00fe
+    char *valueStr = NULL;
2a00fe
+    char *newStr = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    CK_OBJECT_HANDLE this_object = CK_INVALID_HANDLE;
2a00fe
+    int retry = 0;
2a00fe
+    unsigned int i;
2a00fe
+
2a00fe
+    if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
2a00fe
+        return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+    }
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    if ((*object_id != CK_INVALID_HANDLE) &&
2a00fe
+        !sdb_objectExists(sdb, *object_id)) {
2a00fe
+        this_object = *object_id;
2a00fe
+    } else {
2a00fe
+        this_object = sdb_getObjectId(sdb);
2a00fe
+    }
2a00fe
+    if (this_object == CK_INVALID_HANDLE) {
2a00fe
+        UNLOCK_SQLITE();
2a00fe
+        return CKR_HOST_MEMORY;
2a00fe
+    }
2a00fe
+    columnStr = sqlite3_mprintf("");
2a00fe
+    valueStr = sqlite3_mprintf("");
2a00fe
+    *object_id = this_object;
2a00fe
+    for (i = 0; columnStr && valueStr && i < count; i++) {
2a00fe
+        newStr = sqlite3_mprintf("%s,a%x", columnStr, template[i].type);
2a00fe
+        sqlite3_free(columnStr);
2a00fe
+        columnStr = newStr;
2a00fe
+        newStr = sqlite3_mprintf("%s,$VALUE%d", valueStr, i);
2a00fe
+        sqlite3_free(valueStr);
2a00fe
+        valueStr = newStr;
2a00fe
+    }
2a00fe
+    newStr = NULL;
2a00fe
+    if ((columnStr == NULL) || (valueStr == NULL)) {
2a00fe
+        if (columnStr) {
2a00fe
+            sqlite3_free(columnStr);
2a00fe
+        }
2a00fe
+        if (valueStr) {
2a00fe
+            sqlite3_free(valueStr);
2a00fe
+        }
2a00fe
+        UNLOCK_SQLITE()
2a00fe
+        return CKR_HOST_MEMORY;
2a00fe
+    }
2a00fe
+    newStr = sqlite3_mprintf(CREATE_CMD, sdb_p->table, columnStr, valueStr);
2a00fe
+    sqlite3_free(columnStr);
2a00fe
+    sqlite3_free(valueStr);
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    sqlerr = sqlite3_bind_int(stmt, 1, *object_id);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    for (i = 0; i < count; i++) {
2a00fe
+        if (template[i].ulValueLen) {
2a00fe
+            sqlerr = sqlite3_bind_blob(stmt, i + 2, template[i].pValue,
2a00fe
+                                       template[i].ulValueLen, SQLITE_STATIC);
2a00fe
+        } else {
2a00fe
+            sqlerr = sqlite3_bind_blob(stmt, i + 2, SQLITE_EXPLICIT_NULL,
2a00fe
+                                       SQLITE_EXPLICIT_NULL_LEN, SQLITE_STATIC);
2a00fe
+        }
2a00fe
+        if (sqlerr != SQLITE_OK)
2a00fe
+            goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+loser:
2a00fe
+    if (newStr) {
2a00fe
+        sqlite3_free(newStr);
2a00fe
+    }
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ *  Generic destroy that can destroy metadata or objects
2a00fe
+ */
2a00fe
+static const char DESTROY_CMD[] = "DELETE FROM %s WHERE (id=$ID);";
2a00fe
+CK_RV
2a00fe
+sdb_destroyAnyObject(SDB *sdb, const char *table,
2a00fe
+                     CK_OBJECT_HANDLE object_id, const char *string_id)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    char *newStr = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int retry = 0;
2a00fe
+
2a00fe
+    if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
2a00fe
+        return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+    }
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    newStr = sqlite3_mprintf(DESTROY_CMD, table);
2a00fe
+    if (newStr == NULL) {
2a00fe
+        error = CKR_HOST_MEMORY;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, newStr, -1, &stmt, NULL);
2a00fe
+    sqlite3_free(newStr);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    if (string_id == NULL) {
2a00fe
+        sqlerr = sqlite3_bind_int(stmt, 1, object_id);
2a00fe
+    } else {
2a00fe
+        sqlerr = sqlite3_bind_text(stmt, 1, string_id,
2a00fe
+                                   PORT_Strlen(string_id), SQLITE_STATIC);
2a00fe
+    }
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+loser:
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_DestroyObject(SDB *sdb, CK_OBJECT_HANDLE object_id)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    return sdb_destroyAnyObject(sdb, sdb_p->table, object_id, NULL);
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_DestroyMetaData(SDB *sdb, const char *id)
2a00fe
+{
2a00fe
+    return sdb_destroyAnyObject(sdb, "metaData", 0, id);
2a00fe
+}
2a00fe
+
2a00fe
+static const char BEGIN_CMD[] = "BEGIN IMMEDIATE TRANSACTION;";
2a00fe
+
2a00fe
+/*
2a00fe
+ * start a transaction.
2a00fe
+ *
2a00fe
+ * We need to open a new database, then store that new database into
2a00fe
+ * the private data structure. We open the database first, then use locks
2a00fe
+ * to protect storing the data to prevent deadlocks.
2a00fe
+ */
2a00fe
+CK_RV
2a00fe
+sdb_Begin(SDB *sdb)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int retry = 0;
2a00fe
+
2a00fe
+    if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
2a00fe
+        return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+    }
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+
2a00fe
+    /* get a new version that we will use for the entire transaction */
2a00fe
+    sqlerr = sdb_openDB(sdb_p->sqlDBName, &sqlDB, SDB_RDWR);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, BEGIN_CMD, -1, &stmt, NULL);
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+        /* don't retry BEGIN transaction*/
2a00fe
+        retry = 0;
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+loser:
2a00fe
+    error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+
2a00fe
+    /* we are starting a new transaction,
2a00fe
+     * and if we succeeded, then save this database for the rest of
2a00fe
+     * our transaction */
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        /* we hold a 'BEGIN TRANSACTION' and a sdb_p->lock. At this point
2a00fe
+         * sdb_p->sqlXactDB MUST be null */
2a00fe
+        PR_EnterMonitor(sdb_p->dbMon);
2a00fe
+        PORT_Assert(sdb_p->sqlXactDB == NULL);
2a00fe
+        sdb_p->sqlXactDB = sqlDB;
2a00fe
+        sdb_p->sqlXactThread = PR_GetCurrentThread();
2a00fe
+        PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+    } else {
2a00fe
+        /* we failed to start our transaction,
2a00fe
+         * free any databases we opened. */
2a00fe
+        if (sqlDB) {
2a00fe
+            sqlite3_close(sqlDB);
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * Complete a transaction. Basically undo everything we did in begin.
2a00fe
+ * There are 2 flavors Abort and Commit. Basically the only differerence between
2a00fe
+ * these 2 are what the database will show. (no change in to former, change in
2a00fe
+ * the latter).
2a00fe
+ */
2a00fe
+static CK_RV
2a00fe
+sdb_complete(SDB *sdb, const char *cmd)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int retry = 0;
2a00fe
+
2a00fe
+    if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
2a00fe
+        return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* We must have a transation database, or we shouldn't have arrived here */
2a00fe
+    PR_EnterMonitor(sdb_p->dbMon);
2a00fe
+    PORT_Assert(sdb_p->sqlXactDB);
2a00fe
+    if (sdb_p->sqlXactDB == NULL) {
2a00fe
+        PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+        return CKR_GENERAL_ERROR; /* shouldn't happen */
2a00fe
+    }
2a00fe
+    PORT_Assert(sdb_p->sqlXactThread == PR_GetCurrentThread());
2a00fe
+    if (sdb_p->sqlXactThread != PR_GetCurrentThread()) {
2a00fe
+        PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+        return CKR_GENERAL_ERROR; /* shouldn't happen */
2a00fe
+    }
2a00fe
+    sqlDB = sdb_p->sqlXactDB;
2a00fe
+    sdb_p->sqlXactDB = NULL; /* no one else can get to this DB,
2a00fe
+                              * safe to unlock */
2a00fe
+    sdb_p->sqlXactThread = NULL;
2a00fe
+    PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL);
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+    /* Pending BEGIN TRANSACTIONS Can move forward at this point. */
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    /* we we have a cached DB image, update it as well */
2a00fe
+    if (sdb_p->cacheTable) {
2a00fe
+        PR_EnterMonitor(sdb_p->dbMon);
2a00fe
+        sdb_updateCache(sdb_p);
2a00fe
+        PR_ExitMonitor(sdb_p->dbMon);
2a00fe
+    }
2a00fe
+
2a00fe
+    error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+
2a00fe
+    /* We just finished a transaction.
2a00fe
+     * Free the database, and remove it from the list */
2a00fe
+    sqlite3_close(sqlDB);
2a00fe
+
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+static const char COMMIT_CMD[] = "COMMIT TRANSACTION;";
2a00fe
+CK_RV
2a00fe
+sdb_Commit(SDB *sdb)
2a00fe
+{
2a00fe
+    CK_RV crv;
2a00fe
+    LOCK_SQLITE()
2a00fe
+    crv = sdb_complete(sdb, COMMIT_CMD);
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return crv;
2a00fe
+}
2a00fe
+
2a00fe
+static const char ROLLBACK_CMD[] = "ROLLBACK TRANSACTION;";
2a00fe
+CK_RV
2a00fe
+sdb_Abort(SDB *sdb)
2a00fe
+{
2a00fe
+    CK_RV crv;
2a00fe
+    LOCK_SQLITE()
2a00fe
+    crv = sdb_complete(sdb, ROLLBACK_CMD);
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return crv;
2a00fe
+}
2a00fe
+
2a00fe
+static int tableExists(sqlite3 *sqlDB, const char *tableName);
2a00fe
+
2a00fe
+static const char GET_PW_CMD[] = "SELECT ALL * FROM metaData WHERE id=$ID;";
2a00fe
+CK_RV
2a00fe
+sdb_GetMetaData(SDB *sdb, const char *id, SECItem *item1, SECItem *item2)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = sdb_p->sqlXactDB;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int found = 0;
2a00fe
+    int retry = 0;
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* handle 'test' versions of the sqlite db */
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, GET_PW_CMD, -1, &stmt, NULL);
2a00fe
+    /* Sigh, if we created a new table since we opened the database,
2a00fe
+     * the database handle will not see the new table, we need to close this
2a00fe
+     * database and reopen it. This is safe because we are holding the lock
2a00fe
+     * still. */
2a00fe
+    if (sqlerr == SQLITE_SCHEMA) {
2a00fe
+        sqlerr = sdb_reopenDBLocal(sdb_p, &sqlDB);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_prepare_v2(sqlDB, GET_PW_CMD, -1, &stmt, NULL);
2a00fe
+    }
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    sqlerr = sqlite3_bind_text(stmt, 1, id, PORT_Strlen(id), SQLITE_STATIC);
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+        if (sqlerr == SQLITE_ROW) {
2a00fe
+            const char *blobData;
2a00fe
+            unsigned int len = item1->len;
2a00fe
+            item1->len = sqlite3_column_bytes(stmt, 1);
2a00fe
+            if (item1->len > len) {
2a00fe
+                error = CKR_BUFFER_TOO_SMALL;
2a00fe
+                continue;
2a00fe
+            }
2a00fe
+            blobData = sqlite3_column_blob(stmt, 1);
2a00fe
+            PORT_Memcpy(item1->data, blobData, item1->len);
2a00fe
+            if (item2) {
2a00fe
+                len = item2->len;
2a00fe
+                item2->len = sqlite3_column_bytes(stmt, 2);
2a00fe
+                if (item2->len > len) {
2a00fe
+                    error = CKR_BUFFER_TOO_SMALL;
2a00fe
+                    continue;
2a00fe
+                }
2a00fe
+                blobData = sqlite3_column_blob(stmt, 2);
2a00fe
+                PORT_Memcpy(item2->data, blobData, item2->len);
2a00fe
+            }
2a00fe
+            found = 1;
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+loser:
2a00fe
+    /* fix up the error if necessary */
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+        if (!found && error == CKR_OK) {
2a00fe
+            error = CKR_OBJECT_HANDLE_INVALID;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+static const char PW_CREATE_TABLE_CMD[] =
2a00fe
+    "CREATE TABLE metaData (id PRIMARY KEY UNIQUE ON CONFLICT REPLACE, item1, item2);";
2a00fe
+static const char PW_CREATE_CMD[] =
2a00fe
+    "INSERT INTO metaData (id,item1,item2) VALUES($ID,$ITEM1,$ITEM2);";
2a00fe
+static const char MD_CREATE_CMD[] =
2a00fe
+    "INSERT INTO metaData (id,item1) VALUES($ID,$ITEM1);";
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_PutMetaData(SDB *sdb, const char *id, const SECItem *item1,
2a00fe
+                const SECItem *item2)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = sdb_p->sqlXactDB;
2a00fe
+    sqlite3_stmt *stmt = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int retry = 0;
2a00fe
+    const char *cmd = PW_CREATE_CMD;
2a00fe
+
2a00fe
+    if ((sdb->sdb_flags & SDB_RDONLY) != 0) {
2a00fe
+        return CKR_TOKEN_WRITE_PROTECTED;
2a00fe
+    }
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (!tableExists(sqlDB, "metaData")) {
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, PW_CREATE_TABLE_CMD, NULL, 0, NULL);
2a00fe
+        if (sqlerr != SQLITE_OK)
2a00fe
+            goto loser;
2a00fe
+    }
2a00fe
+    if (item2 == NULL) {
2a00fe
+        cmd = MD_CREATE_CMD;
2a00fe
+    }
2a00fe
+    sqlerr = sqlite3_prepare_v2(sqlDB, cmd, -1, &stmt, NULL);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    sqlerr = sqlite3_bind_text(stmt, 1, id, PORT_Strlen(id), SQLITE_STATIC);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    sqlerr = sqlite3_bind_blob(stmt, 2, item1->data, item1->len, SQLITE_STATIC);
2a00fe
+    if (sqlerr != SQLITE_OK)
2a00fe
+        goto loser;
2a00fe
+    if (item2) {
2a00fe
+        sqlerr = sqlite3_bind_blob(stmt, 3, item2->data,
2a00fe
+                                   item2->len, SQLITE_STATIC);
2a00fe
+        if (sqlerr != SQLITE_OK)
2a00fe
+            goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    do {
2a00fe
+        sqlerr = sqlite3_step(stmt);
2a00fe
+        if (sqlerr == SQLITE_BUSY) {
2a00fe
+            PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+        }
2a00fe
+    } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+loser:
2a00fe
+    /* fix up the error if necessary */
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (stmt) {
2a00fe
+        sqlite3_reset(stmt);
2a00fe
+        sqlite3_finalize(stmt);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+static const char RESET_CMD[] = "DELETE FROM %s;";
2a00fe
+CK_RV
2a00fe
+sdb_Reset(SDB *sdb)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    char *newStr;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+
2a00fe
+    /* only Key databases can be reset */
2a00fe
+    if (sdb_p->type != SDB_KEY) {
2a00fe
+        return CKR_OBJECT_HANDLE_INVALID;
2a00fe
+    }
2a00fe
+
2a00fe
+    LOCK_SQLITE()
2a00fe
+    error = sdb_openDBLocal(sdb_p, &sqlDB, NULL);
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (tableExists(sqlDB, sdb_p->table)) {
2a00fe
+        /* delete the contents of the key table */
2a00fe
+        newStr = sqlite3_mprintf(RESET_CMD, sdb_p->table);
2a00fe
+        if (newStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+        sqlite3_free(newStr);
2a00fe
+
2a00fe
+        if (sqlerr != SQLITE_OK)
2a00fe
+            goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* delete the password entry table */
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, "DROP TABLE IF EXISTS metaData;",
2a00fe
+                          NULL, 0, NULL);
2a00fe
+
2a00fe
+loser:
2a00fe
+    /* fix up the error if necessary */
2a00fe
+    if (error == CKR_OK) {
2a00fe
+        error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (sqlDB) {
2a00fe
+        sdb_closeDBLocal(sdb_p, sqlDB);
2a00fe
+    }
2a00fe
+
2a00fe
+    UNLOCK_SQLITE()
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_Close(SDB *sdb)
2a00fe
+{
2a00fe
+    SDBPrivate *sdb_p = sdb->private;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    sdbDataType type = sdb_p->type;
2a00fe
+
2a00fe
+    sqlerr = sqlite3_close(sdb_p->sqlReadDB);
2a00fe
+    PORT_Free(sdb_p->sqlDBName);
2a00fe
+    if (sdb_p->cacheTable) {
2a00fe
+        sqlite3_free(sdb_p->cacheTable);
2a00fe
+    }
2a00fe
+    if (sdb_p->dbMon) {
2a00fe
+        PR_DestroyMonitor(sdb_p->dbMon);
2a00fe
+    }
2a00fe
+    free(sdb_p->schemaAttrs);
2a00fe
+    free(sdb_p);
2a00fe
+    free(sdb);
2a00fe
+    return sdb_mapSQLError(type, sqlerr);
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * functions to support open
2a00fe
+ */
2a00fe
+
2a00fe
+static const char CHECK_TABLE_CMD[] = "SELECT ALL * FROM %s LIMIT 0;";
2a00fe
+
2a00fe
+/* return 1 if sqlDB contains table 'tableName */
2a00fe
+static int
2a00fe
+tableExists(sqlite3 *sqlDB, const char *tableName)
2a00fe
+{
2a00fe
+    char *cmd = sqlite3_mprintf(CHECK_TABLE_CMD, tableName);
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+
2a00fe
+    if (cmd == NULL) {
2a00fe
+        return 0;
2a00fe
+    }
2a00fe
+
2a00fe
+    sqlerr = sqlite3_exec(sqlDB, cmd, NULL, 0, 0);
2a00fe
+    sqlite3_free(cmd);
2a00fe
+
2a00fe
+    return (sqlerr == SQLITE_OK) ? 1 : 0;
2a00fe
+}
2a00fe
+
2a00fe
+void
2a00fe
+sdb_SetForkState(PRBool forked)
2a00fe
+{
2a00fe
+    /* XXXright now this is a no-op. The global fork state in the softokn3
2a00fe
+     * shared library is already taken care of at the PKCS#11 level.
2a00fe
+     * If and when we add fork state to the sqlite shared library and extern
2a00fe
+     * interface, we will need to set it and reset it from here */
2a00fe
+}
2a00fe
+
2a00fe
+static int
2a00fe
+sdb_attributeComparator(const void *a, const void *b)
2a00fe
+{
2a00fe
+    if (*(CK_ATTRIBUTE_TYPE *)a < *(CK_ATTRIBUTE_TYPE *)b) {
2a00fe
+        return -1;
2a00fe
+    }
2a00fe
+    if (*(CK_ATTRIBUTE_TYPE *)a > *(CK_ATTRIBUTE_TYPE *)b) {
2a00fe
+        return 1;
2a00fe
+    }
2a00fe
+    return 0;
2a00fe
+}
2a00fe
+
2a00fe
+/*
2a00fe
+ * initialize a single database
2a00fe
+ */
2a00fe
+static const char INIT_CMD[] =
2a00fe
+    "CREATE TABLE %s (id PRIMARY KEY UNIQUE ON CONFLICT ABORT%s)";
2a00fe
+
2a00fe
+CK_RV
2a00fe
+sdb_init(char *dbname, char *table, sdbDataType type, int *inUpdate,
2a00fe
+         int *newInit, int inFlags, PRUint32 accessOps, SDB **pSdb)
2a00fe
+{
2a00fe
+    int i;
2a00fe
+    char *initStr = NULL;
2a00fe
+    char *newStr;
2a00fe
+    char *queryStr = NULL;
2a00fe
+    int inTransaction = 0;
2a00fe
+    SDB *sdb = NULL;
2a00fe
+    SDBPrivate *sdb_p = NULL;
2a00fe
+    sqlite3 *sqlDB = NULL;
2a00fe
+    int sqlerr = SQLITE_OK;
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    char *cacheTable = NULL;
2a00fe
+    PRIntervalTime now = 0;
2a00fe
+    char *env;
2a00fe
+    PRBool enableCache = PR_FALSE;
2a00fe
+    PRBool checkFSType = PR_FALSE;
2a00fe
+    PRBool measureSpeed = PR_FALSE;
2a00fe
+    PRBool create;
2a00fe
+    int flags = inFlags & 0x7;
2a00fe
+
2a00fe
+    *pSdb = NULL;
2a00fe
+    *inUpdate = 0;
2a00fe
+
2a00fe
+    /* sqlite3 doesn't have a flag to specify that we want to
2a00fe
+     * open the database read only. If the db doesn't exist,
2a00fe
+     * sqlite3 will always create it.
2a00fe
+     */
2a00fe
+    LOCK_SQLITE();
2a00fe
+    create = (_NSSUTIL_Access(dbname, PR_ACCESS_EXISTS) != PR_SUCCESS);
2a00fe
+    if ((flags == SDB_RDONLY) && create) {
2a00fe
+        error = sdb_mapSQLError(type, SQLITE_CANTOPEN);
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    sqlerr = sdb_openDB(dbname, &sqlDB, flags);
2a00fe
+    if (sqlerr != SQLITE_OK) {
2a00fe
+        error = sdb_mapSQLError(type, sqlerr);
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    /*
2a00fe
+     * SQL created the file, but it doesn't set appropriate modes for
2a00fe
+     * a database.
2a00fe
+     *
2a00fe
+     * NO NSPR call for chmod? :(
2a00fe
+     */
2a00fe
+    if (create && sdb_chmod(dbname, 0600) != 0) {
2a00fe
+        error = sdb_mapSQLError(type, SQLITE_CANTOPEN);
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (flags != SDB_RDONLY) {
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, BEGIN_CMD, NULL, 0, NULL);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        inTransaction = 1;
2a00fe
+    }
2a00fe
+    if (!tableExists(sqlDB, table)) {
2a00fe
+        *newInit = 1;
2a00fe
+        if (flags != SDB_CREATE) {
2a00fe
+            error = sdb_mapSQLError(type, SQLITE_CANTOPEN);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        initStr = sqlite3_mprintf("");
2a00fe
+        for (i = 0; initStr && i < known_attributes_size; i++) {
2a00fe
+            newStr = sqlite3_mprintf("%s, a%x", initStr, known_attributes[i]);
2a00fe
+            sqlite3_free(initStr);
2a00fe
+            initStr = newStr;
2a00fe
+        }
2a00fe
+        if (initStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+
2a00fe
+        newStr = sqlite3_mprintf(INIT_CMD, table, initStr);
2a00fe
+        sqlite3_free(initStr);
2a00fe
+        if (newStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+        sqlite3_free(newStr);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+
2a00fe
+        newStr = sqlite3_mprintf(CREATE_ISSUER_INDEX_CMD, table);
2a00fe
+        if (newStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+        sqlite3_free(newStr);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+
2a00fe
+        newStr = sqlite3_mprintf(CREATE_SUBJECT_INDEX_CMD, table);
2a00fe
+        if (newStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+        sqlite3_free(newStr);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+
2a00fe
+        newStr = sqlite3_mprintf(CREATE_LABEL_INDEX_CMD, table);
2a00fe
+        if (newStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+        sqlite3_free(newStr);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+
2a00fe
+        newStr = sqlite3_mprintf(CREATE_ID_INDEX_CMD, table);
2a00fe
+        if (newStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, newStr, NULL, 0, NULL);
2a00fe
+        sqlite3_free(newStr);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+    }
2a00fe
+    /*
2a00fe
+     * detect the case where we have created the database, but have
2a00fe
+     * not yet updated it.
2a00fe
+     *
2a00fe
+     * We only check the Key database because only the key database has
2a00fe
+     * a metaData table. The metaData table is created when a password
2a00fe
+     * is set, or in the case of update, when a password is supplied.
2a00fe
+     * If no key database exists, then the update would have happened immediately
2a00fe
+     * on noticing that the cert database didn't exist (see newInit set above).
2a00fe
+     */
2a00fe
+    if (type == SDB_KEY && !tableExists(sqlDB, "metaData")) {
2a00fe
+        *newInit = 1;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* access to network filesystems are significantly slower than local ones
2a00fe
+     * for database operations. In those cases we need to create a cached copy
2a00fe
+     * of the database in a temporary location on the local disk. SQLITE
2a00fe
+     * already provides a way to create a temporary table and initialize it,
2a00fe
+     * so we use it for the cache (see sdb_buildCache for how it's done).*/
2a00fe
+
2a00fe
+    /*
2a00fe
+     * we decide whether or not to use the cache based on the following input.
2a00fe
+     *
2a00fe
+     * NSS_SDB_USE_CACHE environment variable is set to anything other than
2a00fe
+     *   "yes" or "no" (for instance, "auto"): NSS will measure the performance
2a00fe
+     *   of access to the temp database versus the access to the user's
2a00fe
+     *   passed-in database location. If the temp database location is
2a00fe
+     *   "significantly" faster we will use the cache.
2a00fe
+     *
2a00fe
+     * NSS_SDB_USE_CACHE environment variable is nonexistent or set to "no":
2a00fe
+     *   cache will not be used.
2a00fe
+     *
2a00fe
+     * NSS_SDB_USE_CACHE environment variable is set to "yes": cache will
2a00fe
+     *   always be used.
2a00fe
+     *
2a00fe
+     * It is expected that most applications will not need this feature, and
2a00fe
+     * thus it is disabled by default.
2a00fe
+     */
2a00fe
+
2a00fe
+    env = PR_GetEnvSecure("NSS_SDB_USE_CACHE");
2a00fe
+
2a00fe
+    /* Variables enableCache, checkFSType, measureSpeed are PR_FALSE by default,
2a00fe
+     * which is the expected behavior for NSS_SDB_USE_CACHE="no".
2a00fe
+     * We don't need to check for "no" here. */
2a00fe
+    if (!env) {
2a00fe
+        /* By default, with no variable set, we avoid expensive measuring for
2a00fe
+         * most FS types. We start with inexpensive FS type checking, and
2a00fe
+         * might perform measuring for some types. */
2a00fe
+        checkFSType = PR_TRUE;
2a00fe
+    } else if (PORT_Strcasecmp(env, "yes") == 0) {
2a00fe
+        enableCache = PR_TRUE;
2a00fe
+    } else if (PORT_Strcasecmp(env, "no") != 0) { /* not "no" => "auto" */
2a00fe
+        measureSpeed = PR_TRUE;
2a00fe
+    }
2a00fe
+
2a00fe
+    if (checkFSType) {
2a00fe
+#if defined(LINUX) && !defined(ANDROID)
2a00fe
+        struct statfs statfs_s;
2a00fe
+        if (statfs(dbname, &statfs_s) == 0) {
2a00fe
+            switch (statfs_s.f_type) {
2a00fe
+                case SMB_SUPER_MAGIC:
2a00fe
+                case 0xff534d42: /* CIFS_MAGIC_NUMBER */
2a00fe
+                case NFS_SUPER_MAGIC:
2a00fe
+                    /* We assume these are slow. */
2a00fe
+                    enableCache = PR_TRUE;
2a00fe
+                    break;
2a00fe
+                case CODA_SUPER_MAGIC:
2a00fe
+                case 0x65735546: /* FUSE_SUPER_MAGIC */
2a00fe
+                case NCP_SUPER_MAGIC:
2a00fe
+                    /* It's uncertain if this FS is fast or slow.
2a00fe
+                     * It seems reasonable to perform slow measuring for users
2a00fe
+                     * with questionable FS speed. */
2a00fe
+                    measureSpeed = PR_TRUE;
2a00fe
+                    break;
2a00fe
+                case AFS_SUPER_MAGIC: /* Already implements caching. */
2a00fe
+                default:
2a00fe
+                    break;
2a00fe
+            }
2a00fe
+        }
2a00fe
+#endif
2a00fe
+    }
2a00fe
+
2a00fe
+    if (measureSpeed) {
2a00fe
+        char *tempDir = NULL;
2a00fe
+        PRUint32 tempOps = 0;
2a00fe
+        /*
2a00fe
+         *  Use PR_Access to determine how expensive it
2a00fe
+         * is to check for the existance of a local file compared to the same
2a00fe
+         * check in the temp directory. If the temp directory is faster, cache
2a00fe
+         * the database there. */
2a00fe
+        tempDir = sdb_getTempDir(sqlDB);
2a00fe
+        if (tempDir) {
2a00fe
+            tempOps = sdb_measureAccess(tempDir);
2a00fe
+            PORT_Free(tempDir);
2a00fe
+
2a00fe
+            /* There is a cost to continually copying the database.
2a00fe
+             * Account for that cost  with the arbitrary factor of 10 */
2a00fe
+            enableCache = (PRBool)(tempOps > accessOps * 10);
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    if (enableCache) {
2a00fe
+        /* try to set the temp store to memory.*/
2a00fe
+        sqlite3_exec(sqlDB, "PRAGMA temp_store=MEMORY", NULL, 0, NULL);
2a00fe
+        /* Failure to set the temp store to memory is not fatal,
2a00fe
+         * ignore the error */
2a00fe
+
2a00fe
+        cacheTable = sqlite3_mprintf("%sCache", table);
2a00fe
+        if (cacheTable == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        /* build the cache table */
2a00fe
+        error = sdb_buildCache(sqlDB, type, cacheTable, table);
2a00fe
+        if (error != CKR_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        /* initialize the last cache build time */
2a00fe
+        now = PR_IntervalNow();
2a00fe
+    }
2a00fe
+
2a00fe
+    sdb = (SDB *)malloc(sizeof(SDB));
2a00fe
+    if (!sdb) {
2a00fe
+        error = CKR_HOST_MEMORY;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+    sdb_p = (SDBPrivate *)malloc(sizeof(SDBPrivate));
2a00fe
+    if (!sdb_p) {
2a00fe
+        error = CKR_HOST_MEMORY;
2a00fe
+        goto loser;
2a00fe
+    }
2a00fe
+
2a00fe
+    /* Cache the attributes that are held in the table, so we can later check
2a00fe
+     * that queried attributes actually exist. We don't assume the schema
2a00fe
+     * to be exactly |known_attributes|, as it may change over time. */
2a00fe
+    sdb_p->schemaAttrs = NULL;
2a00fe
+    if (!PORT_Strcmp("nssPublic", table) ||
2a00fe
+        !PORT_Strcmp("nssPrivate", table)) {
2a00fe
+        sqlite3_stmt *stmt = NULL;
2a00fe
+        int retry = 0;
2a00fe
+        unsigned int backedAttrs = 0;
2a00fe
+
2a00fe
+        /* Can't bind parameters to a PRAGMA. */
2a00fe
+        queryStr = sqlite3_mprintf("PRAGMA table_info(%s);", table);
2a00fe
+        if (queryStr == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_prepare_v2(sqlDB, queryStr, -1, &stmt, NULL);
2a00fe
+        sqlite3_free(queryStr);
2a00fe
+        queryStr = NULL;
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        unsigned int schemaAttrsCapacity = known_attributes_size;
2a00fe
+        sdb_p->schemaAttrs = malloc(schemaAttrsCapacity * sizeof(CK_ATTRIBUTE_TYPE));
2a00fe
+        if (!sdb_p->schemaAttrs) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        do {
2a00fe
+            sqlerr = sqlite3_step(stmt);
2a00fe
+            if (sqlerr == SQLITE_BUSY) {
2a00fe
+                PR_Sleep(SDB_BUSY_RETRY_TIME);
2a00fe
+            }
2a00fe
+            if (sqlerr == SQLITE_ROW) {
2a00fe
+                if (backedAttrs == schemaAttrsCapacity) {
2a00fe
+                    schemaAttrsCapacity += known_attributes_size;
2a00fe
+                    sdb_p->schemaAttrs = realloc(sdb_p->schemaAttrs,
2a00fe
+                                                 schemaAttrsCapacity * sizeof(CK_ATTRIBUTE_TYPE));
2a00fe
+                    if (!sdb_p->schemaAttrs) {
2a00fe
+                        error = CKR_HOST_MEMORY;
2a00fe
+                        goto loser;
2a00fe
+                    }
2a00fe
+                }
2a00fe
+                /* Record the ULONG attribute value. */
2a00fe
+                char *val = (char *)sqlite3_column_text(stmt, 1);
2a00fe
+                if (val && val[0] == 'a') {
2a00fe
+                    CK_ATTRIBUTE_TYPE attr = strtoul(&val[1], NULL, 16);
2a00fe
+                    sdb_p->schemaAttrs[backedAttrs++] = attr;
2a00fe
+                }
2a00fe
+            }
2a00fe
+        } while (!sdb_done(sqlerr, &retry));
2a00fe
+
2a00fe
+        if (sqlerr != SQLITE_DONE) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_reset(stmt);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        sqlerr = sqlite3_finalize(stmt);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+
2a00fe
+        sdb_p->numSchemaAttrs = backedAttrs;
2a00fe
+
2a00fe
+        /* Sort these once so we can shortcut invalid attribute searches. */
2a00fe
+        qsort(sdb_p->schemaAttrs, sdb_p->numSchemaAttrs,
2a00fe
+              sizeof(CK_ATTRIBUTE_TYPE), sdb_attributeComparator);
2a00fe
+    }
2a00fe
+
2a00fe
+    /* invariant fields */
2a00fe
+    sdb_p->sqlDBName = PORT_Strdup(dbname);
2a00fe
+    sdb_p->type = type;
2a00fe
+    sdb_p->table = table;
2a00fe
+    sdb_p->cacheTable = cacheTable;
2a00fe
+    sdb_p->lastUpdateTime = now;
2a00fe
+    /* set the cache delay time. This is how long we will wait before we
2a00fe
+     * decide the existing cache is stale. Currently set to 10 sec */
2a00fe
+    sdb_p->updateInterval = PR_SecondsToInterval(10);
2a00fe
+    sdb_p->dbMon = PR_NewMonitor();
2a00fe
+    /* these fields are protected by the lock */
2a00fe
+    sdb_p->sqlXactDB = NULL;
2a00fe
+    sdb_p->sqlXactThread = NULL;
2a00fe
+    sdb->private = sdb_p;
2a00fe
+    sdb->version = 1;
2a00fe
+    sdb->sdb_flags = inFlags | SDB_HAS_META;
2a00fe
+    sdb->app_private = NULL;
2a00fe
+    sdb->sdb_FindObjectsInit = sdb_FindObjectsInit;
2a00fe
+    sdb->sdb_FindObjects = sdb_FindObjects;
2a00fe
+    sdb->sdb_FindObjectsFinal = sdb_FindObjectsFinal;
2a00fe
+    sdb->sdb_GetAttributeValue = sdb_GetAttributeValue;
2a00fe
+    sdb->sdb_SetAttributeValue = sdb_SetAttributeValue;
2a00fe
+    sdb->sdb_CreateObject = sdb_CreateObject;
2a00fe
+    sdb->sdb_DestroyObject = sdb_DestroyObject;
2a00fe
+    sdb->sdb_GetMetaData = sdb_GetMetaData;
2a00fe
+    sdb->sdb_PutMetaData = sdb_PutMetaData;
2a00fe
+    sdb->sdb_DestroyMetaData = sdb_DestroyMetaData;
2a00fe
+    sdb->sdb_Begin = sdb_Begin;
2a00fe
+    sdb->sdb_Commit = sdb_Commit;
2a00fe
+    sdb->sdb_Abort = sdb_Abort;
2a00fe
+    sdb->sdb_Reset = sdb_Reset;
2a00fe
+    sdb->sdb_Close = sdb_Close;
2a00fe
+    sdb->sdb_SetForkState = sdb_SetForkState;
2a00fe
+    sdb->sdb_GetNewObjectID = sdb_GetNewObjectID;
2a00fe
+
2a00fe
+    if (inTransaction) {
2a00fe
+        sqlerr = sqlite3_exec(sqlDB, COMMIT_CMD, NULL, 0, NULL);
2a00fe
+        if (sqlerr != SQLITE_OK) {
2a00fe
+            error = sdb_mapSQLError(sdb_p->type, sqlerr);
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+        inTransaction = 0;
2a00fe
+    }
2a00fe
+
2a00fe
+    sdb_p->sqlReadDB = sqlDB;
2a00fe
+
2a00fe
+    *pSdb = sdb;
2a00fe
+    UNLOCK_SQLITE();
2a00fe
+    return CKR_OK;
2a00fe
+
2a00fe
+loser:
2a00fe
+    /* lots of stuff to do */
2a00fe
+    if (inTransaction) {
2a00fe
+        sqlite3_exec(sqlDB, ROLLBACK_CMD, NULL, 0, NULL);
2a00fe
+    }
2a00fe
+    if (sdb) {
2a00fe
+        free(sdb);
2a00fe
+    }
2a00fe
+    if (sdb_p) {
2a00fe
+        if (sdb_p->schemaAttrs) {
2a00fe
+            free(sdb_p->schemaAttrs);
2a00fe
+        }
2a00fe
+        free(sdb_p);
2a00fe
+    }
2a00fe
+    if (sqlDB) {
2a00fe
+        sqlite3_close(sqlDB);
2a00fe
+    }
2a00fe
+    UNLOCK_SQLITE();
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+/* sdbopen */
2a00fe
+CK_RV
2a00fe
+s_open(const char *directory, const char *certPrefix, const char *keyPrefix,
2a00fe
+       int cert_version, int key_version, int flags,
2a00fe
+       SDB **certdb, SDB **keydb, int *newInit)
2a00fe
+{
2a00fe
+    char *cert = sdb_BuildFileName(directory, certPrefix,
2a00fe
+                                   "cert", cert_version);
2a00fe
+    char *key = sdb_BuildFileName(directory, keyPrefix,
2a00fe
+                                  "key", key_version);
2a00fe
+    CK_RV error = CKR_OK;
2a00fe
+    int inUpdate;
2a00fe
+    PRUint32 accessOps;
2a00fe
+
2a00fe
+    if (certdb)
2a00fe
+        *certdb = NULL;
2a00fe
+    if (keydb)
2a00fe
+        *keydb = NULL;
2a00fe
+    *newInit = 0;
2a00fe
+
2a00fe
+#ifdef SQLITE_UNSAFE_THREADS
2a00fe
+    if (sqlite_lock == NULL) {
2a00fe
+        sqlite_lock = PR_NewLock();
2a00fe
+        if (sqlite_lock == NULL) {
2a00fe
+            error = CKR_HOST_MEMORY;
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+    }
2a00fe
+#endif
2a00fe
+
2a00fe
+    /* how long does it take to test for a non-existant file in our working
2a00fe
+     * directory? Allows us to test if we may be on a network file system */
2a00fe
+    accessOps = 1;
2a00fe
+    {
2a00fe
+        char *env;
2a00fe
+        env = PR_GetEnvSecure("NSS_SDB_USE_CACHE");
2a00fe
+        /* If the environment variable is undefined or set to yes or no,
2a00fe
+         * sdb_init() will ignore the value of accessOps, and we can skip the
2a00fe
+         * measuring.*/
2a00fe
+        if (env && PORT_Strcasecmp(env, "no") != 0 &&
2a00fe
+            PORT_Strcasecmp(env, "yes") != 0) {
2a00fe
+            accessOps = sdb_measureAccess(directory);
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    /*
2a00fe
+     * open the cert data base
2a00fe
+     */
2a00fe
+    if (certdb) {
2a00fe
+        /* initialize Certificate database */
2a00fe
+        error = sdb_init(cert, "nssPublic", SDB_CERT, &inUpdate,
2a00fe
+                         newInit, flags, accessOps, certdb);
2a00fe
+        if (error != CKR_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    /*
2a00fe
+     * open the key data base:
2a00fe
+     *  NOTE:if we want to implement a single database, we open
2a00fe
+     *  the same database file as the certificate here.
2a00fe
+     *
2a00fe
+     *  cert an key db's have different tables, so they will not
2a00fe
+     *  conflict.
2a00fe
+     */
2a00fe
+    if (keydb) {
2a00fe
+        /* initialize the Key database */
2a00fe
+        error = sdb_init(key, "nssPrivate", SDB_KEY, &inUpdate,
2a00fe
+                         newInit, flags, accessOps, keydb);
2a00fe
+        if (error != CKR_OK) {
2a00fe
+            goto loser;
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+loser:
2a00fe
+    if (cert) {
2a00fe
+        sqlite3_free(cert);
2a00fe
+    }
2a00fe
+    if (key) {
2a00fe
+        sqlite3_free(key);
2a00fe
+    }
2a00fe
+
2a00fe
+    if (error != CKR_OK) {
2a00fe
+        /* currently redundant, but could be necessary if more code is added
2a00fe
+         * just before loser */
2a00fe
+        if (keydb && *keydb) {
2a00fe
+            sdb_Close(*keydb);
2a00fe
+        }
2a00fe
+        if (certdb && *certdb) {
2a00fe
+            sdb_Close(*certdb);
2a00fe
+        }
2a00fe
+    }
2a00fe
+
2a00fe
+    return error;
2a00fe
+}
2a00fe
+
2a00fe
+CK_RV
2a00fe
+s_shutdown()
2a00fe
+{
2a00fe
+#ifdef SQLITE_UNSAFE_THREADS
2a00fe
+    if (sqlite_lock) {
2a00fe
+        PR_DestroyLock(sqlite_lock);
2a00fe
+        sqlite_lock = NULL;
2a00fe
+    }
2a00fe
+#endif
2a00fe
+    return CKR_OK;
2a00fe
+}
2a00fe
diff --git a/cmd/manifest.mn b/cmd/manifest.mn
2a00fe
--- a/cmd/manifest.mn
2a00fe
+++ b/cmd/manifest.mn
2a00fe
@@ -36,16 +36,17 @@ NSS_SRCDIRS = \
2a00fe
  addbuiltin \
2a00fe
  atob  \
2a00fe
  btoa  \
2a00fe
  certutil  \
2a00fe
  chktest  \
2a00fe
  crlutil  \
2a00fe
  crmftest \
2a00fe
  dbtest \
2a00fe
+ dbtool \
2a00fe
  derdump  \
2a00fe
  digest  \
2a00fe
  httpserv  \
2a00fe
  listsuites \
2a00fe
  makepqg  \
2a00fe
  multinit \
2a00fe
  nss-policy-check \
2a00fe
  ocspclnt  \