summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorcvs2hg <devnull@localhost>2000-06-12 23:43:43 +0000
committercvs2hg <devnull@localhost>2000-06-12 23:43:43 +0000
commit9e88767424046018bd9d0a577e8c54923eebd1f1 (patch)
treeb49076bd511f6daaccfb7a9151688b7422c0b770
parentb4dd7bda56eaf37da6408c8709968458cf3613fc (diff)
downloadnss-hg-9e88767424046018bd9d0a577e8c54923eebd1f1.tar.gz
fixup commit for branch 'NSS_30_BRANCH'
-rw-r--r--dbm/.cvsignore1
-rw-r--r--dbm/Makefile.in36
-rw-r--r--dbm/include/.cvsignore1
-rw-r--r--dbm/include/MANIFEST17
-rw-r--r--dbm/include/Makefile.in55
-rw-r--r--dbm/include/Makefile.win63
-rw-r--r--dbm/include/cdefs.h166
-rw-r--r--dbm/include/extern.h65
-rw-r--r--dbm/include/hash.h334
-rw-r--r--dbm/include/hsearch.h51
-rw-r--r--dbm/include/mcom_db.h453
-rw-r--r--dbm/include/mpool.h99
-rw-r--r--dbm/include/ncompat.h232
-rw-r--r--dbm/include/ndbm.h77
-rw-r--r--dbm/include/nsres.h42
-rw-r--r--dbm/include/page.h96
-rw-r--r--dbm/include/queue.h245
-rw-r--r--dbm/include/search.h51
-rw-r--r--dbm/include/watcomfx.h26
-rw-r--r--dbm/include/winfile.h106
-rw-r--r--dbm/macbuild/DBM.Prefix33
-rw-r--r--dbm/macbuild/DBM.mcpbin116362 -> 0 bytes
-rw-r--r--dbm/macbuild/DBMConfig.h23
-rw-r--r--dbm/macbuild/DBMDebug.Prefix32
-rw-r--r--dbm/macbuild/macstubs.c8
-rw-r--r--dbm/makefile.win38
-rw-r--r--dbm/src/.cvsignore1
-rw-r--r--dbm/src/Makefile.in70
-rw-r--r--dbm/src/Makefile.win96
-rw-r--r--dbm/src/db.c146
-rw-r--r--dbm/src/h_bigkey.c677
-rw-r--r--dbm/src/h_func.c211
-rw-r--r--dbm/src/h_log2.c56
-rw-r--r--dbm/src/h_page.c1237
-rw-r--r--dbm/src/hash.c1188
-rw-r--r--dbm/src/hash_buf.c408
-rw-r--r--dbm/src/hsearch.c108
-rw-r--r--dbm/src/memmove.c150
-rw-r--r--dbm/src/mktemp.c151
-rw-r--r--dbm/src/ndbm.c195
-rw-r--r--dbm/src/nsres.c311
-rw-r--r--dbm/src/snprintf.c75
-rw-r--r--dbm/src/strerror.c78
-rw-r--r--dbm/tests/.cvsignore3
-rw-r--r--dbm/tests/Makefile.in46
-rw-r--r--dbm/tests/lots.c623
-rw-r--r--security/coreconf/tree.mk114
-rw-r--r--security/nss/cmd/bltest/Makefile82
-rw-r--r--security/nss/cmd/bltest/blapitest.c1798
-rw-r--r--security/nss/cmd/bltest/manifest.mn50
-rw-r--r--security/nss/cmd/bltest/tests/README26
-rw-r--r--security/nss/cmd/bltest/tests/des3_cbc/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/des3_cbc/iv01
-rw-r--r--security/nss/cmd/bltest/tests/des3_cbc/key01
-rw-r--r--security/nss/cmd/bltest/tests/des3_cbc/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/des3_cbc/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/des3_ecb/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/des3_ecb/key01
-rw-r--r--security/nss/cmd/bltest/tests/des3_ecb/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/des3_ecb/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/des_cbc/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/des_cbc/iv01
-rw-r--r--security/nss/cmd/bltest/tests/des_cbc/key01
-rw-r--r--security/nss/cmd/bltest/tests/des_cbc/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/des_cbc/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/des_ecb/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/des_ecb/key01
-rw-r--r--security/nss/cmd/bltest/tests/des_ecb/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/des_ecb/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/dsa/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/dsa/key06
-rw-r--r--security/nss/cmd/bltest/tests/dsa/keyseed01
-rw-r--r--security/nss/cmd/bltest/tests/dsa/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/dsa/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/dsa/pqg04
-rw-r--r--security/nss/cmd/bltest/tests/dsa/sigseed01
-rw-r--r--security/nss/cmd/bltest/tests/md2/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/md2/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/md2/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/md5/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/md5/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/md5/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_cbc/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_cbc/iv01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_cbc/key01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_cbc/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/rc2_cbc/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_ecb/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_ecb/key01
-rw-r--r--security/nss/cmd/bltest/tests/rc2_ecb/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/rc2_ecb/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/rc4/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/rc4/key01
-rw-r--r--security/nss/cmd/bltest/tests/rc4/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/rc4/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_cbc/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_cbc/iv01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_cbc/key01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_cbc/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/rc5_cbc/params02
-rw-r--r--security/nss/cmd/bltest/tests/rc5_cbc/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_ecb/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_ecb/key01
-rw-r--r--security/nss/cmd/bltest/tests/rc5_ecb/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/rc5_ecb/params02
-rw-r--r--security/nss/cmd/bltest/tests/rc5_ecb/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/rsa/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/rsa/key04
-rw-r--r--security/nss/cmd/bltest/tests/rsa/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/rsa/plaintext01
-rw-r--r--security/nss/cmd/bltest/tests/sha1/ciphertext01
-rw-r--r--security/nss/cmd/bltest/tests/sha1/numtests1
-rw-r--r--security/nss/cmd/bltest/tests/sha1/plaintext01
-rw-r--r--security/nss/cmd/modutil/Makefile85
-rw-r--r--security/nss/cmd/modutil/installparse.c745
-rw-r--r--security/nss/cmd/modutil/installparse.h3
-rw-r--r--security/nss/cmd/modutil/rules.mk46
-rw-r--r--security/nss/cmd/strsclnt/strsclnt.c1108
-rw-r--r--security/nss/lib/ckfw/dbm/Makefile38
-rw-r--r--security/nss/lib/ckfw/dbm/anchor.c50
-rw-r--r--security/nss/lib/ckfw/dbm/ckdbm.h281
-rw-r--r--security/nss/lib/ckfw/dbm/config.mk37
-rw-r--r--security/nss/lib/ckfw/dbm/db.c1065
-rw-r--r--security/nss/lib/ckfw/dbm/find.c166
-rw-r--r--security/nss/lib/ckfw/dbm/instance.c196
-rw-r--r--security/nss/lib/ckfw/dbm/manifest.mn54
-rw-r--r--security/nss/lib/ckfw/dbm/object.c204
-rw-r--r--security/nss/lib/ckfw/dbm/session.c298
-rw-r--r--security/nss/lib/ckfw/dbm/slot.c214
-rw-r--r--security/nss/lib/ckfw/dbm/token.c315
-rw-r--r--security/nss/lib/fortcrypt/genci.h145
-rw-r--r--security/nss/lib/jar/jarevil.c571
-rw-r--r--security/nss/lib/jar/jarnav.c107
-rw-r--r--security/nss/lib/jar/jarsign.c376
-rw-r--r--security/nss/lib/jar/jarver.c2029
-rw-r--r--security/nss/lib/pk11wrap/pk11skey.c4790
-rwxr-xr-xsecurity/nss/tests/ssl/ssl.sh275
-rw-r--r--security/nss/tests/ssl/sslstress.txt14
138 files changed, 0 insertions, 23537 deletions
diff --git a/dbm/.cvsignore b/dbm/.cvsignore
deleted file mode 100644
index f3c7a7c5d..000000000
--- a/dbm/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-Makefile
diff --git a/dbm/Makefile.in b/dbm/Makefile.in
deleted file mode 100644
index 13779b989..000000000
--- a/dbm/Makefile.in
+++ /dev/null
@@ -1,36 +0,0 @@
-#
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-
-DEPTH = ..
-topsrcdir = @top_srcdir@
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-DIRS = include src
-
-ifdef ENABLE_TESTS
-DIRS += tests
-endif
-
-include $(topsrcdir)/config/rules.mk
-
diff --git a/dbm/include/.cvsignore b/dbm/include/.cvsignore
deleted file mode 100644
index f3c7a7c5d..000000000
--- a/dbm/include/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-Makefile
diff --git a/dbm/include/MANIFEST b/dbm/include/MANIFEST
deleted file mode 100644
index 5626a3e87..000000000
--- a/dbm/include/MANIFEST
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# This is a list of local files which get copied to the mozilla:dist directory
-#
-
-cdefs.h
-extern.h
-hash.h
-hsearch.h
-mcom_db.h
-mpool.h
-ncompat.h
-ndbm.h
-nsres.h
-page.h
-queue.h
-search.h
-watcomfx.h
diff --git a/dbm/include/Makefile.in b/dbm/include/Makefile.in
deleted file mode 100644
index 86fb8f157..000000000
--- a/dbm/include/Makefile.in
+++ /dev/null
@@ -1,55 +0,0 @@
-#
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-
-DEPTH = ../..
-topsrcdir = @top_srcdir@
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE = dbm
-
-EXPORTS = \
- nsres.h \
- cdefs.h \
- mcom_db.h \
- ncompat.h \
- winfile.h \
- $(NULL)
-
-EXPORTS := $(addprefix $(srcdir)/, $(EXPORTS))
-
-PRIVATE_EXPORTS = \
- hsearch.h \
- page.h \
- extern.h \
- ndbm.h \
- queue.h \
- hash.h \
- mpool.h \
- search.h \
- $(NULL)
-
-PRIVATE_EXPORTS := $(addprefix $(srcdir)/, $(PRIVATE_EXPORTS))
-
-include $(topsrcdir)/config/rules.mk
-
diff --git a/dbm/include/Makefile.win b/dbm/include/Makefile.win
deleted file mode 100644
index ac6836222..000000000
--- a/dbm/include/Makefile.win
+++ /dev/null
@@ -1,63 +0,0 @@
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-
-
-#//------------------------------------------------------------------------
-#//
-#// Makefile to build the cert library
-#//
-#//------------------------------------------------------------------------
-
-!if "$(MOZ_BITS)" == "16"
-!ifndef MOZ_DEBUG
-OPTIMIZER=-Os -UDEBUG -DNDEBUG
-!endif
-!endif
-
-#//------------------------------------------------------------------------
-#//
-#// Specify the depth of the current directory relative to the
-#// root of NS
-#//
-#//------------------------------------------------------------------------
-DEPTH= ..\..
-
-!ifndef MAKE_OBJ_TYPE
-MAKE_OBJ_TYPE=EXE
-!endif
-
-#//------------------------------------------------------------------------
-#//
-#// install headers
-#//
-#//------------------------------------------------------------------------
-INSTALL_DIR=$(XPDIST)\include
-INSTALL_FILE_LIST= nsres.h cdefs.h mcom_db.h ncompat.h winfile.h
-
-#//------------------------------------------------------------------------
-#//
-#// Include the common makefile rules
-#//
-#//------------------------------------------------------------------------
-include <$(DEPTH)/config/rules.mak>
-
-CFLAGS = $(CFLAGS) -DMOZILLA_CLIENT
-
-export:: INSTALL_FILES
-
diff --git a/dbm/include/cdefs.h b/dbm/include/cdefs.h
deleted file mode 100644
index 7b5c46f63..000000000
--- a/dbm/include/cdefs.h
+++ /dev/null
@@ -1,166 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * The contents of this file are subject to the Netscape Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/NPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1998 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- */
-
-/*
- * Copyright (c) 1991, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Berkeley Software Design, Inc.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)cdefs.h 8.7 (Berkeley) 1/21/94
- */
-
-#ifndef _CDEFS_H_
-#define _CDEFS_H_
-
-#ifdef __BEGIN_DECLS
-#undef __BEGIN_DECLS
-#endif
-#ifdef __END_DECLS
-#undef __END_DECLS
-#endif
-
-#if defined(__cplusplus)
-#define __BEGIN_DECLS extern "C" {
-#define __END_DECLS }
-#else
-#define __BEGIN_DECLS
-#define __END_DECLS
-#endif
-
-/*
- * The __CONCAT macro is used to concatenate parts of symbol names, e.g.
- * with "#define OLD(foo) __CONCAT(old,foo)", OLD(foo) produces oldfoo.
- * The __CONCAT macro is a bit tricky -- make sure you don't put spaces
- * in between its arguments. __CONCAT can also concatenate double-quoted
- * strings produced by the __STRING macro, but this only works with ANSI C.
- */
-#undef __P
-#undef __CONCAT
-#undef __STRING
-
-#if defined(__STDC__) || defined(__cplusplus) || defined(_WINDOWS) || defined(XP_OS2)
-#define __P(protos) protos /* full-blown ANSI C */
-#define __CONCAT(x,y) x ## y
-#define __STRING(x) #x
-
-#ifndef __const
-#define __const const /* define reserved names to standard */
-#endif /* __const */
-#define __signed signed
-#define __volatile volatile
-#ifndef _WINDOWS
-#if defined(__cplusplus)
-#define __inline inline /* convert to C++ keyword */
-#else
-#ifndef __GNUC__
-#define __inline /* delete GCC keyword */
-#endif /* !__GNUC__ */
-#endif /* !__cplusplus */
-#endif /* !_WINDOWS */
-
-#else /* !(__STDC__ || __cplusplus) */
-#define __P(protos) () /* traditional C preprocessor */
-#define __CONCAT(x,y) x/**/y
-#define __STRING(x) "x"
-
-#ifndef __GNUC__
-#define __const /* delete pseudo-ANSI C keywords */
-#define __inline
-#define __signed
-#define __volatile
-/*
- * In non-ANSI C environments, new programs will want ANSI-only C keywords
- * deleted from the program and old programs will want them left alone.
- * When using a compiler other than gcc, programs using the ANSI C keywords
- * const, inline etc. as normal identifiers should define -DNO_ANSI_KEYWORDS.
- * When using "gcc -traditional", we assume that this is the intent; if
- * __GNUC__ is defined but __STDC__ is not, we leave the new keywords alone.
- */
-#ifndef NO_ANSI_KEYWORDS
-#define const /* delete ANSI C keywords */
-#define inline
-#define signed
-#define volatile
-#endif
-#endif /* !__GNUC__ */
-#endif /* !(__STDC__ || __cplusplus) */
-
-/*
- * GCC1 and some versions of GCC2 declare dead (non-returning) and
- * pure (no side effects) functions using "volatile" and "const";
- * unfortunately, these then cause warnings under "-ansi -pedantic".
- * GCC2 uses a new, peculiar __attribute__((attrs)) style. All of
- * these work for GNU C++ (modulo a slight glitch in the C++ grammar
- * in the distribution version of 2.5.5).
- */
-#if !defined(__GNUC__) || __GNUC__ < 2 || __GNUC_MINOR__ < 5
-#define __attribute__(x) /* delete __attribute__ if non-gcc or gcc1 */
-#if defined(__GNUC__) && !defined(__STRICT_ANSI__)
-#define __dead __volatile
-#define __pure __const
-#endif
-#endif
-
-/* Delete pseudo-keywords wherever they are not available or needed. */
-#ifndef __dead
-#define __dead
-#define __pure
-#endif
-
-#ifdef AIXV3
-/* Wont compile without const. Need a cleaner way to handle this. */
-#ifdef const
-#undef const
-#endif
-#endif
-
-#endif /* !_CDEFS_H_ */
diff --git a/dbm/include/extern.h b/dbm/include/extern.h
deleted file mode 100644
index 8eabc81fe..000000000
--- a/dbm/include/extern.h
+++ /dev/null
@@ -1,65 +0,0 @@
-/*-
- * Copyright (c) 1991, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)extern.h 8.4 (Berkeley) 6/16/94
- */
-
-BUFHEAD *__add_ovflpage (HTAB *, BUFHEAD *);
-int __addel (HTAB *, BUFHEAD *, const DBT *, const DBT *);
-int __big_delete (HTAB *, BUFHEAD *);
-int __big_insert (HTAB *, BUFHEAD *, const DBT *, const DBT *);
-int __big_keydata (HTAB *, BUFHEAD *, DBT *, DBT *, int);
-int __big_return (HTAB *, BUFHEAD *, int, DBT *, int);
-int __big_split (HTAB *, BUFHEAD *, BUFHEAD *, BUFHEAD *,
- uint32, uint32, SPLIT_RETURN *);
-int __buf_free (HTAB *, int, int);
-void __buf_init (HTAB *, int);
-uint32 __call_hash (HTAB *, char *, size_t);
-int __delpair (HTAB *, BUFHEAD *, int);
-int __expand_table (HTAB *);
-int __find_bigpair (HTAB *, BUFHEAD *, int, char *, int);
-uint16 __find_last_page (HTAB *, BUFHEAD **);
-void __free_ovflpage (HTAB *, BUFHEAD *);
-BUFHEAD *__get_buf (HTAB *, uint32, BUFHEAD *, int);
-int __get_page (HTAB *, char *, uint32, int, int, int);
-int __ibitmap (HTAB *, int, int, int);
-uint32 __log2 (uint32);
-int __put_page (HTAB *, char *, uint32, int, int);
-void __reclaim_buf (HTAB *, BUFHEAD *);
-int __split_page (HTAB *, uint32, uint32);
-
-/* Default hash routine. */
-extern uint32 (*__default_hash) (const void *, size_t);
-
-#ifdef HASH_STATISTICS
-extern int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
-#endif
diff --git a/dbm/include/hash.h b/dbm/include/hash.h
deleted file mode 100644
index 70f93e938..000000000
--- a/dbm/include/hash.h
+++ /dev/null
@@ -1,334 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)hash.h 8.3 (Berkeley) 5/31/94
- */
-
-/* Operations */
-
-#include <stdio.h>
-#include "mcom_db.h"
-typedef enum {
- HASH_GET, HASH_PUT, HASH_PUTNEW, HASH_DELETE, HASH_FIRST, HASH_NEXT
-} ACTION;
-
-/* Buffer Management structures */
-typedef struct _bufhead BUFHEAD;
-
-struct _bufhead {
- BUFHEAD *prev; /* LRU links */
- BUFHEAD *next; /* LRU links */
- BUFHEAD *ovfl; /* Overflow page buffer header */
- uint32 addr; /* Address of this page */
- char *page; /* Actual page data */
- char is_disk;
- char flags;
-#define BUF_MOD 0x0001
-#define BUF_DISK 0x0002
-#define BUF_BUCKET 0x0004
-#define BUF_PIN 0x0008
-};
-
-#define IS_BUCKET(X) ((X) & BUF_BUCKET)
-
-typedef BUFHEAD **SEGMENT;
-
-typedef int DBFILE_PTR;
-#define NO_FILE -1
-#ifdef macintosh
-#define DBFILE_OPEN(path, flag,mode) open((path), flag)
-#define EXISTS(path)
-#else
-#define DBFILE_OPEN(path, flag,mode) open((path), (flag), (mode))
-#endif
-/* Hash Table Information */
-typedef struct hashhdr { /* Disk resident portion */
- int32 magic; /* Magic NO for hash tables */
- int32 version; /* Version ID */
- uint32 lorder; /* Byte Order */
- int32 bsize; /* Bucket/Page Size */
- int32 bshift; /* Bucket shift */
- int32 dsize; /* Directory Size */
- int32 ssize; /* Segment Size */
- int32 sshift; /* Segment shift */
- int32 ovfl_point; /* Where overflow pages are being
- * allocated */
- int32 last_freed; /* Last overflow page freed */
- int32 max_bucket; /* ID of Maximum bucket in use */
- int32 high_mask; /* Mask to modulo into entire table */
- int32 low_mask; /* Mask to modulo into lower half of
- * table */
- int32 ffactor; /* Fill factor */
- int32 nkeys; /* Number of keys in hash table */
- int32 hdrpages; /* Size of table header */
- int32 h_charkey; /* value of hash(CHARKEY) */
-#define NCACHED 32 /* number of bit maps and spare
- * points */
- int32 spares[NCACHED];/* spare pages for overflow */
- uint16 bitmaps[NCACHED]; /* address of overflow page
- * bitmaps */
-} HASHHDR;
-
-typedef struct htab { /* Memory resident data structure */
- HASHHDR hdr; /* Header */
- int nsegs; /* Number of allocated segments */
- int exsegs; /* Number of extra allocated
- * segments */
- uint32 /* Hash function */
- (*hash)(const void *, size_t);
- int flags; /* Flag values */
- DBFILE_PTR fp; /* File pointer */
- char *filename;
- char *tmp_buf; /* Temporary Buffer for BIG data */
- char *tmp_key; /* Temporary Buffer for BIG keys */
- BUFHEAD *cpage; /* Current page */
- int cbucket; /* Current bucket */
- int cndx; /* Index of next item on cpage */
- int dbmerrno; /* Error Number -- for DBM
- * compatability */
- int new_file; /* Indicates if fd is backing store
- * or no */
- int save_file; /* Indicates whether we need to flush
- * file at
- * exit */
- uint32 *mapp[NCACHED]; /* Pointers to page maps */
- int nmaps; /* Initial number of bitmaps */
- int nbufs; /* Number of buffers left to
- * allocate */
- BUFHEAD bufhead; /* Header of buffer lru list */
- SEGMENT *dir; /* Hash Bucket directory */
-} HTAB;
-
-/*
- * Constants
- */
-#define DATABASE_CORRUPTED_ERROR -999 /* big ugly abort, delete database */
-#define OLD_MAX_BSIZE 65536 /* 2^16 */
-#define MAX_BSIZE 32l*1024l /* 2^15 */
-#define MIN_BUFFERS 6
-#define MINHDRSIZE 512
-#define DEF_BUFSIZE 65536l /* 64 K */
-#define DEF_BUCKET_SIZE 4096
-#define DEF_BUCKET_SHIFT 12 /* log2(BUCKET) */
-#define DEF_SEGSIZE 256
-#define DEF_SEGSIZE_SHIFT 8 /* log2(SEGSIZE) */
-#define DEF_DIRSIZE 256
-#define DEF_FFACTOR 65536l
-#define MIN_FFACTOR 4
-#define SPLTMAX 8
-#define CHARKEY "%$sniglet^&"
-#define NUMKEY 1038583l
-#define BYTE_SHIFT 3
-#define INT_TO_BYTE 2
-#define INT_BYTE_SHIFT 5
-#define ALL_SET ((uint32)0xFFFFFFFF)
-#define ALL_CLEAR 0
-
-#define PTROF(X) ((ptrdiff_t)(X) == BUF_DISK ? 0 : (X))
-#define ISDISK(X) ((X) ? ((ptrdiff_t)(X) == BUF_DISK ? BUF_DISK \
- : (X)->is_disk) : 0)
-
-#define BITS_PER_MAP 32
-
-/* Given the address of the beginning of a big map, clear/set the nth bit */
-#define CLRBIT(A, N) ((A)[(N)/BITS_PER_MAP] &= ~(1<<((N)%BITS_PER_MAP)))
-#define SETBIT(A, N) ((A)[(N)/BITS_PER_MAP] |= (1<<((N)%BITS_PER_MAP)))
-#define ISSET(A, N) ((A)[(N)/BITS_PER_MAP] & (1<<((N)%BITS_PER_MAP)))
-
-/* Overflow management */
-/*
- * Overflow page numbers are allocated per split point. At each doubling of
- * the table, we can allocate extra pages. So, an overflow page number has
- * the top 5 bits indicate which split point and the lower 11 bits indicate
- * which page at that split point is indicated (pages within split points are
- * numberered starting with 1).
- */
-
-#define SPLITSHIFT 11
-#define SPLITMASK 0x7FF
-#define SPLITNUM(N) (((uint32)(N)) >> SPLITSHIFT)
-#define OPAGENUM(N) ((N) & SPLITMASK)
-#define OADDR_OF(S,O) ((uint32)((uint32)(S) << SPLITSHIFT) + (O))
-
-#define BUCKET_TO_PAGE(B) \
- (B) + hashp->HDRPAGES + ((B) ? hashp->SPARES[__log2((uint32)((B)+1))-1] : 0)
-#define OADDR_TO_PAGE(B) \
- BUCKET_TO_PAGE ( (1 << SPLITNUM((B))) -1 ) + OPAGENUM((B));
-
-/*
- * page.h contains a detailed description of the page format.
- *
- * Normally, keys and data are accessed from offset tables in the top of
- * each page which point to the beginning of the key and data. There are
- * four flag values which may be stored in these offset tables which indicate
- * the following:
- *
- *
- * OVFLPAGE Rather than a key data pair, this pair contains
- * the address of an overflow page. The format of
- * the pair is:
- * OVERFLOW_PAGE_NUMBER OVFLPAGE
- *
- * PARTIAL_KEY This must be the first key/data pair on a page
- * and implies that page contains only a partial key.
- * That is, the key is too big to fit on a single page
- * so it starts on this page and continues on the next.
- * The format of the page is:
- * KEY_OFF PARTIAL_KEY OVFL_PAGENO OVFLPAGE
- *
- * KEY_OFF -- offset of the beginning of the key
- * PARTIAL_KEY -- 1
- * OVFL_PAGENO - page number of the next overflow page
- * OVFLPAGE -- 0
- *
- * FULL_KEY This must be the first key/data pair on the page. It
- * is used in two cases.
- *
- * Case 1:
- * There is a complete key on the page but no data
- * (because it wouldn't fit). The next page contains
- * the data.
- *
- * Page format it:
- * KEY_OFF FULL_KEY OVFL_PAGENO OVFL_PAGE
- *
- * KEY_OFF -- offset of the beginning of the key
- * FULL_KEY -- 2
- * OVFL_PAGENO - page number of the next overflow page
- * OVFLPAGE -- 0
- *
- * Case 2:
- * This page contains no key, but part of a large
- * data field, which is continued on the next page.
- *
- * Page format it:
- * DATA_OFF FULL_KEY OVFL_PAGENO OVFL_PAGE
- *
- * KEY_OFF -- offset of the beginning of the data on
- * this page
- * FULL_KEY -- 2
- * OVFL_PAGENO - page number of the next overflow page
- * OVFLPAGE -- 0
- *
- * FULL_KEY_DATA
- * This must be the first key/data pair on the page.
- * There are two cases:
- *
- * Case 1:
- * This page contains a key and the beginning of the
- * data field, but the data field is continued on the
- * next page.
- *
- * Page format is:
- * KEY_OFF FULL_KEY_DATA OVFL_PAGENO DATA_OFF
- *
- * KEY_OFF -- offset of the beginning of the key
- * FULL_KEY_DATA -- 3
- * OVFL_PAGENO - page number of the next overflow page
- * DATA_OFF -- offset of the beginning of the data
- *
- * Case 2:
- * This page contains the last page of a big data pair.
- * There is no key, only the tail end of the data
- * on this page.
- *
- * Page format is:
- * DATA_OFF FULL_KEY_DATA <OVFL_PAGENO> <OVFLPAGE>
- *
- * DATA_OFF -- offset of the beginning of the data on
- * this page
- * FULL_KEY_DATA -- 3
- * OVFL_PAGENO - page number of the next overflow page
- * OVFLPAGE -- 0
- *
- * OVFL_PAGENO and OVFLPAGE are optional (they are
- * not present if there is no next page).
- */
-
-#define OVFLPAGE 0
-#define PARTIAL_KEY 1
-#define FULL_KEY 2
-#define FULL_KEY_DATA 3
-#define REAL_KEY 4
-
-/* Short hands for accessing structure */
-#undef BSIZE
-#define BSIZE hdr.bsize
-#undef BSHIFT
-#define BSHIFT hdr.bshift
-#define DSIZE hdr.dsize
-#define SGSIZE hdr.ssize
-#define SSHIFT hdr.sshift
-#define LORDER hdr.lorder
-#define OVFL_POINT hdr.ovfl_point
-#define LAST_FREED hdr.last_freed
-#define MAX_BUCKET hdr.max_bucket
-#define FFACTOR hdr.ffactor
-#define HIGH_MASK hdr.high_mask
-#define LOW_MASK hdr.low_mask
-#define NKEYS hdr.nkeys
-#define HDRPAGES hdr.hdrpages
-#define SPARES hdr.spares
-#define BITMAPS hdr.bitmaps
-#define VERSION hdr.version
-#define MAGIC hdr.magic
-#define NEXT_FREE hdr.next_free
-#define H_CHARKEY hdr.h_charkey
-
-extern uint32 (*__default_hash) (const void *, size_t);
-void __buf_init(HTAB *hashp, int32 nbytes);
-int __big_delete(HTAB *hashp, BUFHEAD *bufp);
-BUFHEAD * __get_buf(HTAB *hashp, uint32 addr, BUFHEAD *prev_bp, int newpage);
-uint32 __call_hash(HTAB *hashp, char *k, size_t len);
-#include "page.h"
-extern int __big_split(HTAB *hashp, BUFHEAD *op,BUFHEAD *np,
-BUFHEAD *big_keyp,uint32 addr,uint32 obucket, SPLIT_RETURN *ret);
-void __free_ovflpage(HTAB *hashp, BUFHEAD *obufp);
-BUFHEAD * __add_ovflpage(HTAB *hashp, BUFHEAD *bufp);
-int __big_insert(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT *val);
-int __expand_table(HTAB *hashp);
-uint32 __log2(uint32 num);
-void __reclaim_buf(HTAB *hashp, BUFHEAD *bp);
-int __get_page(HTAB *hashp, char * p, uint32 bucket, int is_bucket, int is_disk, int is_bitmap);
-int __put_page(HTAB *hashp, char *p, uint32 bucket, int is_bucket, int is_bitmap);
-int __ibitmap(HTAB *hashp, int pnum, int nbits, int ndx);
-int __buf_free(HTAB *hashp, int do_free, int to_disk);
-int __find_bigpair(HTAB *hashp, BUFHEAD *bufp, int ndx, char *key, int size);
-uint16 __find_last_page(HTAB *hashp, BUFHEAD **bpp);
-int __addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT * val);
-int __big_return(HTAB *hashp, BUFHEAD *bufp, int ndx, DBT *val, int set_current);
-int __delpair(HTAB *hashp, BUFHEAD *bufp, int ndx);
-int __big_keydata(HTAB *hashp, BUFHEAD *bufp, DBT *key, DBT *val, int set);
-int __split_page(HTAB *hashp, uint32 obucket, uint32 nbucket);
diff --git a/dbm/include/hsearch.h b/dbm/include/hsearch.h
deleted file mode 100644
index ff58b1c15..000000000
--- a/dbm/include/hsearch.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)search.h 8.1 (Berkeley) 6/4/93
- */
-
-/* Backward compatibility to hsearch interface. */
-typedef struct entry {
- char *key;
- char *data;
-} ENTRY;
-
-typedef enum {
- FIND, ENTER
-} ACTION;
-
-int hcreate (unsigned int);
-void hdestroy (void);
-ENTRY *hsearch (ENTRY, ACTION);
diff --git a/dbm/include/mcom_db.h b/dbm/include/mcom_db.h
deleted file mode 100644
index af4e0f9e2..000000000
--- a/dbm/include/mcom_db.h
+++ /dev/null
@@ -1,453 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * The contents of this file are subject to the Netscape Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/NPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1998 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- */
-
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)db.h 8.7 (Berkeley) 6/16/94
- */
-
-#ifndef _DB_H_
-#define _DB_H_
-
-#ifndef HAVE_SYS_CDEFS_H
-#include "cdefs.h"
-#else
-#include <cdefs.h>
-#endif
-#include "prtypes.h"
-
-#ifdef HAVE_SYS_BYTEORDER_H
-#include <sys/types.h>
-#include <sys/byteorder.h>
-#endif
-
-#if defined(__linux) || defined(__BEOS__)
-#include <endian.h>
-#ifndef BYTE_ORDER
-#define BYTE_ORDER __BYTE_ORDER
-#define BIG_ENDIAN __BIG_ENDIAN
-#define LITTLE_ENDIAN __LITTLE_ENDIAN
-#endif
-#endif /* __linux */
-
-#ifdef __sgi
-#define BYTE_ORDER BIG_ENDIAN
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234 /* LSB first: i386, vax, all NT risc */
-#define __BIT_TYPES_DEFINED__
-#endif
-
-#ifdef __sun
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234 /* LSB first: i386, vax, all NT risc */
-
-#ifdef HAVE_COMPAT_H
-#include <compat.h>
-#endif
-
-/* XXX - dp
- * Need to find a general way of defining endian-ness in SunOS 5.3
- * SunOS 5.4 defines _BIG_ENDIAN and _LITTLE_ENDIAN
- * SunOS 5.3 does nothing like this.
- */
-
-#ifndef BYTE_ORDER
-
-#if defined(_BIG_ENDIAN)
-#define BYTE_ORDER BIG_ENDIAN
-#elif defined(_LITTLE_ENDIAN)
-#define BYTE_ORDER LITTLE_ENDIAN
-#elif !defined(SVR4)
-/* 4.1.3 is always BIG_ENDIAN as it was released only on sparc platforms. */
-#define BYTE_ORDER BIG_ENDIAN
-#elif !defined(vax) && !defined(ntohl) && !defined(lint) && !defined(i386)
-/* 5.3 big endian. Copied this above line from sys/byteorder.h */
-/* Now we are in a 5.3 SunOS rather non 5.4 or above SunOS */
-#define BYTE_ORDER BIG_ENDIAN
-#else
-#define BYTE_ORDER LITTLE_ENDIAN
-#endif
-
-#endif /* !BYTE_ORDER */
-#endif /* __sun */
-
-#ifdef NCR
-#include <sys/endian.h>
-#endif
-
-#ifdef __QNX__
-#define LITTLE_ENDIAN 1234
-#define BIG_ENDIAN 4321
-#define BYTE_ORDER LITTLE_ENDIAN
-#endif
-
-#ifdef SCO
-#include <sys/bitypes.h>
-#define MAXPATHLEN 1024
-#endif
-
-#ifdef SNI
-/* #include <sys/hetero.h> */
-#define BYTE_ORDER BIG_ENDIAN
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234
-#endif
-
-#ifdef macintosh
-#include <unix.h>
-#else
-#include <fcntl.h>
-#endif
-
-#if defined(_WINDOWS) || defined(XP_OS2)
-#include <stdio.h>
-#include <io.h>
-#include <limits.h>
-
-#ifndef XP_OS2
-#define MAXPATHLEN 1024
-#else
-#include "os2file.h" /* includes dirent.h */
-#endif
-
-#define EFTYPE EINVAL /* POSIX 1003.1 format errno. */
-
-#ifndef STDERR_FILENO
-#define STDIN_FILENO 0 /* ANSI C #defines */
-#define STDOUT_FILENO 1
-#define STDERR_FILENO 2
-#endif
-
-#ifndef O_ACCMODE /* POSIX 1003.1 access mode mask. */
-#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
-#endif
-
-#ifdef BYTE_ORDER
-#undef BYTE_ORDER
-#endif
-
-#define BYTE_ORDER LITTLE_ENDIAN
-#define LITTLE_ENDIAN 1234 /* LSB first: i386, vax, all NT risc */
-#define BIG_ENDIAN 4321
-#endif
-
-#if defined(_WINDOWS) && !defined(_WIN32)
-/* 16 bit windows defines */
-#define MAX_PAGE_NUMBER 0xffffffff /* >= # of pages in a file */
-#endif
-
-
-#ifdef macintosh
-#include <stdio.h>
-#include "xp_mcom.h"
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234
-#define BYTE_ORDER BIG_ENDIAN
-#define O_ACCMODE 3 /* Mask for file access modes */
-#define EFTYPE 2000
-XP_BEGIN_PROTOS
-int mkstemp(const char *path);
-XP_END_PROTOS
-#endif /* MACINTOSH */
-
-#if defined(XP_OS2)
-#include <xp_mcom.h>
-XP_BEGIN_PROTOS
-int mkstemp(char *path);
-XP_END_PROTOS
-#endif
-
-#ifndef macintosh
-#include <sys/types.h>
-#endif
-
-#if !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2)
-#include <sys/stat.h>
-#include <errno.h>
-#endif
-
-#ifndef HAVE_SYS_CDEFS_H
-#include "cdefs.h"
-#endif
-
-#ifndef _WINDOWS /* included above to prevent spurious warnings chouck 12-Sep-95 */
-#include <limits.h>
-#endif
-
-#define RET_ERROR -1 /* Return values. */
-#define RET_SUCCESS 0
-#define RET_SPECIAL 1
-
-#if defined(__386BSD__) || defined(SCO)
-#define __BIT_TYPES_DEFINED__
-#endif
-
-#define MAX_PAGE_NUMBER 0xffffffff /* >= # of pages in a file */
-
-#ifndef __sgi
-typedef uint32 pgno_t;
-#endif
-
-#define MAX_PAGE_OFFSET 65535 /* >= # of bytes in a page */
-typedef uint16 indx_t;
-#define MAX_REC_NUMBER 0xffffffff /* >= # of records in a tree */
-typedef uint32 recno_t;
-
-/* define EFTYPE since most don't */
-#ifndef EFTYPE
-#define EFTYPE EINVAL /* POSIX 1003.1 format errno. */
-#endif
-
-/* Key/data structure -- a Data-Base Thang. */
-typedef struct {
- void *data; /* data */
- size_t size; /* data length */
-} DBT;
-
-/* Routine flags. */
-#define R_CURSOR 1 /* del, put, seq */
-#define __R_UNUSED 2 /* UNUSED */
-#define R_FIRST 3 /* seq */
-#define R_IAFTER 4 /* put (RECNO) */
-#define R_IBEFORE 5 /* put (RECNO) */
-#define R_LAST 6 /* seq (BTREE, RECNO) */
-#define R_NEXT 7 /* seq */
-#define R_NOOVERWRITE 8 /* put */
-#define R_PREV 9 /* seq (BTREE, RECNO) */
-#define R_SETCURSOR 10 /* put (RECNO) */
-#define R_RECNOSYNC 11 /* sync (RECNO) */
-
-typedef enum { DB_BTREE, DB_HASH, DB_RECNO } DBTYPE;
-
-typedef enum { LockOutDatabase, UnlockDatabase } DBLockFlagEnum;
-
-/*
- * !!!
- * The following flags are included in the dbopen(3) call as part of the
- * open(2) flags. In order to avoid conflicts with the open flags, start
- * at the top of the 16 or 32-bit number space and work our way down. If
- * the open flags were significantly expanded in the future, it could be
- * a problem. Wish I'd left another flags word in the dbopen call.
- *
- * !!!
- * None of this stuff is implemented yet. The only reason that it's here
- * is so that the access methods can skip copying the key/data pair when
- * the DB_LOCK flag isn't set.
- */
-#if UINT_MAX > 65535
-#define DB_LOCK 0x20000000 /* Do locking. */
-#define DB_SHMEM 0x40000000 /* Use shared memory. */
-#define DB_TXN 0x80000000 /* Do transactions. */
-#else
-#define DB_LOCK 0x2000 /* Do locking. */
-#define DB_SHMEM 0x4000 /* Use shared memory. */
-#define DB_TXN 0x8000 /* Do transactions. */
-#endif
-
-/* Access method description structure. */
-typedef struct __db {
- DBTYPE type; /* Underlying db type. */
- int (*close) (struct __db *);
- int (*del) (const struct __db *, const DBT *, uint);
- int (*get) (const struct __db *, const DBT *, DBT *, uint);
- int (*put) (const struct __db *, DBT *, const DBT *, uint);
- int (*seq) (const struct __db *, DBT *, DBT *, uint);
- int (*sync) (const struct __db *, uint);
- void *internal; /* Access method private. */
- int (*fd) (const struct __db *);
-} DB;
-
-#define BTREEMAGIC 0x053162
-#define BTREEVERSION 3
-
-/* Structure used to pass parameters to the btree routines. */
-typedef struct {
-#define R_DUP 0x01 /* duplicate keys */
- uint32 flags;
- uint cachesize; /* bytes to cache */
- int maxkeypage; /* maximum keys per page */
- int minkeypage; /* minimum keys per page */
- uint psize; /* page size */
- int (*compare) /* comparison function */
- (const DBT *, const DBT *);
- size_t (*prefix) /* prefix function */
- (const DBT *, const DBT *);
- int lorder; /* byte order */
-} BTREEINFO;
-
-#define HASHMAGIC 0x061561
-#define HASHVERSION 2
-
-/* Structure used to pass parameters to the hashing routines. */
-typedef struct {
- uint bsize; /* bucket size */
- uint ffactor; /* fill factor */
- uint nelem; /* number of elements */
- uint cachesize; /* bytes to cache */
- uint32 /* hash function */
- (*hash) (const void *, size_t);
- int lorder; /* byte order */
-} HASHINFO;
-
-/* Structure used to pass parameters to the record routines. */
-typedef struct {
-#define R_FIXEDLEN 0x01 /* fixed-length records */
-#define R_NOKEY 0x02 /* key not required */
-#define R_SNAPSHOT 0x04 /* snapshot the input */
- uint32 flags;
- uint cachesize; /* bytes to cache */
- uint psize; /* page size */
- int lorder; /* byte order */
- size_t reclen; /* record length (fixed-length records) */
- uint8 bval; /* delimiting byte (variable-length records */
- char *bfname; /* btree file name */
-} RECNOINFO;
-
-/* #ifdef __DBINTERFACE_PRIVATE */
-/*
- * Little endian <==> big endian 32-bit swap macros.
- * M_32_SWAP swap a memory location
- * P_32_SWAP swap a referenced memory location
- * P_32_COPY swap from one location to another
- */
-#define M_32_SWAP(a) { \
- uint32 _tmp = a; \
- ((char *)&a)[0] = ((char *)&_tmp)[3]; \
- ((char *)&a)[1] = ((char *)&_tmp)[2]; \
- ((char *)&a)[2] = ((char *)&_tmp)[1]; \
- ((char *)&a)[3] = ((char *)&_tmp)[0]; \
-}
-#define P_32_SWAP(a) { \
- uint32 _tmp = *(uint32 *)a; \
- ((char *)a)[0] = ((char *)&_tmp)[3]; \
- ((char *)a)[1] = ((char *)&_tmp)[2]; \
- ((char *)a)[2] = ((char *)&_tmp)[1]; \
- ((char *)a)[3] = ((char *)&_tmp)[0]; \
-}
-#define P_32_COPY(a, b) { \
- ((char *)&(b))[0] = ((char *)&(a))[3]; \
- ((char *)&(b))[1] = ((char *)&(a))[2]; \
- ((char *)&(b))[2] = ((char *)&(a))[1]; \
- ((char *)&(b))[3] = ((char *)&(a))[0]; \
-}
-
-/*
- * Little endian <==> big endian 16-bit swap macros.
- * M_16_SWAP swap a memory location
- * P_16_SWAP swap a referenced memory location
- * P_16_COPY swap from one location to another
- */
-#define M_16_SWAP(a) { \
- uint16 _tmp = a; \
- ((char *)&a)[0] = ((char *)&_tmp)[1]; \
- ((char *)&a)[1] = ((char *)&_tmp)[0]; \
-}
-#define P_16_SWAP(a) { \
- uint16 _tmp = *(uint16 *)a; \
- ((char *)a)[0] = ((char *)&_tmp)[1]; \
- ((char *)a)[1] = ((char *)&_tmp)[0]; \
-}
-#define P_16_COPY(a, b) { \
- ((char *)&(b))[0] = ((char *)&(a))[1]; \
- ((char *)&(b))[1] = ((char *)&(a))[0]; \
-}
-/* #endif */
-
-__BEGIN_DECLS
-#if defined(__WATCOMC__) || defined(__WATCOM_CPLUSPLUS__)
-extern DB *
-#else
-PR_EXTERN(DB *)
-#endif
-dbopen (const char *, int, int, DBTYPE, const void *);
-
-/* set or unset a global lock flag to disable the
- * opening of any DBM file
- */
-void dbSetOrClearDBLock(DBLockFlagEnum type);
-
-/* #ifdef __DBINTERFACE_PRIVATE */
-DB *__bt_open (const char *, int, int, const BTREEINFO *, int);
-DB *__hash_open (const char *, int, int, const HASHINFO *, int);
-DB *__rec_open (const char *, int, int, const RECNOINFO *, int);
-void __dbpanic (DB *dbp);
-/* #endif */
-
-__END_DECLS
-
-#if defined(__hpux) || defined(__hppa)
-#define BYTE_ORDER BIG_ENDIAN
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234 /* LSB first: i386, vax, all NT risc */
-#endif
-
-#if defined(AIXV3) || defined(AIX)
-/* BYTE_ORDER, LITTLE_ENDIAN, BIG_ENDIAN are all defined here */
-#include <sys/machine.h>
-#endif
-
-/* Digital Unix */
-#ifdef __osf__
-#include <machine/endian.h>
-#endif
-
-#ifdef __alpha
-#ifndef WIN32
-#else
-/* Alpha NT */
-#define BYTE_ORDER LITTLE_ENDIAN
-#define BIG_ENDIAN 4321
-#define LITTLE_ENDIAN 1234
-#endif
-#endif
-
-#endif /* !_DB_H_ */
diff --git a/dbm/include/mpool.h b/dbm/include/mpool.h
deleted file mode 100644
index a2fb62b9f..000000000
--- a/dbm/include/mpool.h
+++ /dev/null
@@ -1,99 +0,0 @@
-/*-
- * Copyright (c) 1991, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)mpool.h 8.2 (Berkeley) 7/14/94
- */
-
-#include <sys/queue.h>
-
-/*
- * The memory pool scheme is a simple one. Each in-memory page is referenced
- * by a bucket which is threaded in up to two of three ways. All active pages
- * are threaded on a hash chain (hashed by page number) and an lru chain.
- * Inactive pages are threaded on a free chain. Each reference to a memory
- * pool is handed an opaque MPOOL cookie which stores all of this information.
- */
-#define HASHSIZE 128
-#define HASHKEY(pgno) ((pgno - 1) % HASHSIZE)
-
-/* The BKT structures are the elements of the queues. */
-typedef struct _bkt {
- CIRCLEQ_ENTRY(_bkt) hq; /* hash queue */
- CIRCLEQ_ENTRY(_bkt) q; /* lru queue */
- void *page; /* page */
- pgno_t pgno; /* page number */
-
-#define MPOOL_DIRTY 0x01 /* page needs to be written */
-#define MPOOL_PINNED 0x02 /* page is pinned into memory */
- uint8 flags; /* flags */
-} BKT;
-
-typedef struct MPOOL {
- CIRCLEQ_HEAD(_lqh, _bkt) lqh; /* lru queue head */
- /* hash queue array */
- CIRCLEQ_HEAD(_hqh, _bkt) hqh[HASHSIZE];
- pgno_t curcache; /* current number of cached pages */
- pgno_t maxcache; /* max number of cached pages */
- pgno_t npages; /* number of pages in the file */
- uint32 pagesize; /* file page size */
- int fd; /* file descriptor */
- /* page in conversion routine */
- void (*pgin) (void *, pgno_t, void *);
- /* page out conversion routine */
- void (*pgout) (void *, pgno_t, void *);
- void *pgcookie; /* cookie for page in/out routines */
-#ifdef STATISTICS
- uint32 cachehit;
- uint32 cachemiss;
- uint32 pagealloc;
- uint32 pageflush;
- uint32 pageget;
- uint32 pagenew;
- uint32 pageput;
- uint32 pageread;
- uint32 pagewrite;
-#endif
-} MPOOL;
-
-__BEGIN_DECLS
-MPOOL *mpool_open (void *, int, pgno_t, pgno_t);
-void mpool_filter (MPOOL *, void (*)(void *, pgno_t, void *),
- void (*)(void *, pgno_t, void *), void *);
-void *mpool_new (MPOOL *, pgno_t *);
-void *mpool_get (MPOOL *, pgno_t, uint);
-int mpool_put (MPOOL *, void *, uint);
-int mpool_sync (MPOOL *);
-int mpool_close (MPOOL *);
-#ifdef STATISTICS
-void mpool_stat (MPOOL *);
-#endif
-__END_DECLS
diff --git a/dbm/include/ncompat.h b/dbm/include/ncompat.h
deleted file mode 100644
index 640da046d..000000000
--- a/dbm/include/ncompat.h
+++ /dev/null
@@ -1,232 +0,0 @@
-/*-
- * Copyright (c) 1991, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)compat.h 8.13 (Berkeley) 2/21/94
- */
-
-#ifndef _COMPAT_H_
-#define _COMPAT_H_
-
-#include <sys/types.h>
-
-/*
- * If your system doesn't typedef u_long, u_short, or u_char, change
- * the 0 to a 1.
- */
-#if 0
-typedef unsigned char u_char; /* 4.[34]BSD names. */
-typedef unsigned int u_int;
-typedef unsigned long u_long;
-typedef unsigned short u_short;
-#endif
-
-/* If your system doesn't typedef size_t, change the 0 to a 1. */
-#if 0
-typedef unsigned int size_t; /* POSIX, 4.[34]BSD names. */
-#endif
-
-/* If your system doesn't typedef ssize_t, change the 0 to a 1. */
-#if 0
-typedef int ssize_t; /* POSIX names. */
-#endif
-
-/*
- * If your system doesn't have the POSIX type for a signal mask,
- * change the 0 to a 1.
- */
-#if 0 /* POSIX 1003.1 signal mask type. */
-typedef unsigned int sigset_t;
-#endif
-
-/*
- * If your system's vsprintf returns a char *, not an int,
- * change the 0 to a 1.
- */
-#if defined (__sun) && !defined(SVR4) /* SUNOS */
-#define VSPRINTF_CHARSTAR
-#endif
-/*
- * If you don't have POSIX 1003.1 signals, the signal code surrounding the
- * temporary file creation is intended to block all of the possible signals
- * long enough to create the file and unlink it. All of this stuff is
- * intended to use old-style BSD calls to fake POSIX 1003.1 calls.
- */
-#ifdef NO_POSIX_SIGNALS
-#define sigemptyset(set) (*(set) = 0)
-#define sigfillset(set) (*(set) = ~(sigset_t)0, 0)
-#define sigaddset(set,signo) (*(set) |= sigmask(signo), 0)
-#define sigdelset(set,signo) (*(set) &= ~sigmask(signo), 0)
-#define sigismember(set,signo) ((*(set) & sigmask(signo)) != 0)
-
-#define SIG_BLOCK 1
-#define SIG_UNBLOCK 2
-#define SIG_SETMASK 3
-
-static int __sigtemp; /* For the use of sigprocmask */
-
-/* Repeated test of oset != NULL is to avoid "*0". */
-#define sigprocmask(how, set, oset) \
- ((__sigtemp = \
- (((how) == SIG_BLOCK) ? \
- sigblock(0) | *(set) : \
- (((how) == SIG_UNBLOCK) ? \
- sigblock(0) & ~(*(set)) : \
- ((how) == SIG_SETMASK ? \
- *(set) : sigblock(0))))), \
- ((oset) ? (*(oset ? oset : set) = sigsetmask(__sigtemp)) : \
- sigsetmask(__sigtemp)), 0)
-#endif
-
-/*
- * If your system doesn't have an include file with the appropriate
- * byte order set, make sure you specify the correct one.
- */
-#ifndef BYTE_ORDER
-#define LITTLE_ENDIAN 1234 /* LSB first: i386, vax */
-#define BIG_ENDIAN 4321 /* MSB first: 68000, ibm, net */
-#define BYTE_ORDER BIG_ENDIAN /* Set for your system. */
-#endif
-
-#if defined(SYSV) || defined(SYSTEM5) || defined(__sun)
-#define index(a, b) strchr(a, b)
-#define rindex(a, b) strrchr(a, b)
-#define bzero(a, b) memset(a, 0, b)
-#define bcmp(a, b, n) memcmp(a, b, n)
-#define bcopy(a, b, n) memmove(b, a, n)
-#endif
-
-#if defined(BSD) || defined(BSD4_3)
-#define strchr(a, b) index(a, b)
-#define strrchr(a, b) rindex(a, b)
-#define memcmp(a, b, n) bcmp(a, b, n)
-#define memmove(a, b, n) bcopy(b, a, n)
-#endif
-
-/*
- * 32-bit machine. The db routines are theoretically independent of
- * the size of u_shorts and u_longs, but I don't know that anyone has
- * ever actually tried it. At a minimum, change the following #define's
- * if you are trying to compile on a different type of system.
- */
-#ifndef USHRT_MAX
-#define USHRT_MAX 0xFFFF
-#define ULONG_MAX 0xFFFFFFFF
-#endif
-
-#ifndef O_ACCMODE /* POSIX 1003.1 access mode mask. */
-#define O_ACCMODE (O_RDONLY|O_WRONLY|O_RDWR)
-#endif
-
-#ifndef _POSIX2_RE_DUP_MAX /* POSIX 1003.2 RE limit. */
-#define _POSIX2_RE_DUP_MAX 255
-#endif
-
-/*
- * If you can't provide lock values in the open(2) call. Note, this
- * allows races to happen.
- */
-#ifndef O_EXLOCK /* 4.4BSD extension. */
-#define O_EXLOCK 0
-#endif
-
-#ifndef O_SHLOCK /* 4.4BSD extension. */
-#define O_SHLOCK 0
-#endif
-
-#ifndef EFTYPE
-#define EFTYPE EINVAL /* POSIX 1003.1 format errno. */
-#endif
-
-#ifndef WCOREDUMP /* 4.4BSD extension */
-#define WCOREDUMP(a) 0
-#endif
-
-#ifndef STDERR_FILENO
-#define STDIN_FILENO 0 /* ANSI C #defines */
-#define STDOUT_FILENO 1
-#define STDERR_FILENO 2
-#endif
-
-#ifndef SEEK_END
-#define SEEK_SET 0 /* POSIX 1003.1 seek values */
-#define SEEK_CUR 1
-#define SEEK_END 2
-#endif
-
-#ifndef _POSIX_VDISABLE /* POSIX 1003.1 disabling char. */
-#define _POSIX_VDISABLE 0 /* Some systems used 0. */
-#endif
-
-#ifndef TCSASOFT /* 4.4BSD extension. */
-#define TCSASOFT 0
-#endif
-
-#ifndef _POSIX2_RE_DUP_MAX /* POSIX 1003.2 values. */
-#define _POSIX2_RE_DUP_MAX 255
-#endif
-
-#ifndef NULL /* ANSI C #defines NULL everywhere. */
-#define NULL 0
-#endif
-
-#ifndef MAX /* Usually found in <sys/param.h>. */
-#define MAX(_a,_b) ((_a)<(_b)?(_b):(_a))
-#endif
-#ifndef MIN /* Usually found in <sys/param.h>. */
-#define MIN(_a,_b) ((_a)<(_b)?(_a):(_b))
-#endif
-
-/* Default file permissions. */
-#ifndef DEFFILEMODE /* 4.4BSD extension. */
-#define DEFFILEMODE (S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH)
-#endif
-
-#ifndef __sun
-#ifndef S_ISDIR /* POSIX 1003.1 file type tests. */
-#define S_ISDIR(m) ((m & 0170000) == 0040000) /* directory */
-#define S_ISCHR(m) ((m & 0170000) == 0020000) /* char special */
-#define S_ISBLK(m) ((m & 0170000) == 0060000) /* block special */
-#define S_ISREG(m) ((m & 0170000) == 0100000) /* regular file */
-#define S_ISFIFO(m) ((m & 0170000) == 0010000) /* fifo */
-#endif
-#ifndef S_ISLNK /* BSD POSIX 1003.1 extensions */
-#define S_ISLNK(m) ((m & 0170000) == 0120000) /* symbolic link */
-#define S_ISSOCK(m) ((m & 0170000) == 0140000) /* socket */
-#endif
-#endif /* __sun */
-
-/* The type of a va_list. */
-#ifndef _BSD_VA_LIST_ /* 4.4BSD #define. */
-#define _BSD_VA_LIST_ char *
-#endif
-
-#endif /* !_COMPAT_H_ */
diff --git a/dbm/include/ndbm.h b/dbm/include/ndbm.h
deleted file mode 100644
index 7ad5f1a23..000000000
--- a/dbm/include/ndbm.h
+++ /dev/null
@@ -1,77 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)ndbm.h 8.1 (Berkeley) 6/2/93
- */
-
-#ifndef _NDBM_H_
-#define _NDBM_H_
-
-#include "mcom_db.h"
-
-/* Map dbm interface onto db(3). */
-#define DBM_RDONLY O_RDONLY
-
-/* Flags to dbm_store(). */
-#define DBM_INSERT 0
-#define DBM_REPLACE 1
-
-/*
- * The db(3) support for ndbm(3) always appends this suffix to the
- * file name to avoid overwriting the user's original database.
- */
-#define DBM_SUFFIX ".db"
-
-typedef struct {
- char *dptr;
- int dsize;
-} datum;
-
-typedef DB DBM;
-#define dbm_pagfno(a) DBM_PAGFNO_NOT_AVAILABLE
-
-__BEGIN_DECLS
-void dbm_close (DBM *);
-int dbm_delete (DBM *, datum);
-datum dbm_fetch (DBM *, datum);
-datum dbm_firstkey (DBM *);
-long dbm_forder (DBM *, datum);
-datum dbm_nextkey (DBM *);
-DBM *dbm_open (const char *, int, int);
-int dbm_store (DBM *, datum, datum, int);
-int dbm_dirfno (DBM *);
-__END_DECLS
-
-#endif /* !_NDBM_H_ */
diff --git a/dbm/include/nsres.h b/dbm/include/nsres.h
deleted file mode 100644
index 17f16647a..000000000
--- a/dbm/include/nsres.h
+++ /dev/null
@@ -1,42 +0,0 @@
-#ifndef NSRES_H
-#define NSRES_H
-#include "cdefs.h"
-#include "mcom_db.h"
-
-__BEGIN_DECLS
-
-/* C version */
-#define NSRESHANDLE void *
-
-typedef void (*NSRESTHREADFUNC)(void *);
-
-typedef struct NSRESTHREADINFO
-{
- void *lock;
- NSRESTHREADFUNC fn_lock;
- NSRESTHREADFUNC fn_unlock;
-} NSRESTHREADINFO;
-
-#define MAXBUFNUM 10
-#define MAXSTRINGLEN 300
-
-#define NSRES_CREATE 1
-#define NSRES_OPEN 2
-
-
-
-NSRESHANDLE NSResCreateTable(const char *filename, NSRESTHREADINFO *threadinfo);
-NSRESHANDLE NSResOpenTable(const char *filename, NSRESTHREADINFO *threadinfo);
-void NSResCloseTable(NSRESHANDLE handle);
-
-char *NSResLoadString(NSRESHANDLE handle, const char * library, int32 id,
- unsigned int charsetid, char *retbuf);
-int32 NSResGetSize(NSRESHANDLE handle, const char *library, int32 id);
-int32 NSResLoadResource(NSRESHANDLE handle, const char *library, int32 id, char *retbuf);
-int NSResAddString(NSRESHANDLE handle, const char *library, int32 id, const char *string, unsigned int charset);
-
-__END_DECLS
-
-
-#endif
-
diff --git a/dbm/include/page.h b/dbm/include/page.h
deleted file mode 100644
index faf2b815b..000000000
--- a/dbm/include/page.h
+++ /dev/null
@@ -1,96 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)page.h 8.2 (Berkeley) 5/31/94
- */
-
-/*
- * Definitions for hashing page file format.
- */
-
-/*
- * routines dealing with a data page
- *
- * page format:
- * +------------------------------+
- * p | n | keyoff | datoff | keyoff |
- * +------------+--------+--------+
- * | datoff | free | ptr | --> |
- * +--------+---------------------+
- * | F R E E A R E A |
- * +--------------+---------------+
- * | <---- - - - | data |
- * +--------+-----+----+----------+
- * | key | data | key |
- * +--------+----------+----------+
- *
- * Pointer to the free space is always: p[p[0] + 2]
- * Amount of free space on the page is: p[p[0] + 1]
- */
-
-/*
- * How many bytes required for this pair?
- * 2 shorts in the table at the top of the page + room for the
- * key and room for the data
- *
- * We prohibit entering a pair on a page unless there is also room to append
- * an overflow page. The reason for this it that you can get in a situation
- * where a single key/data pair fits on a page, but you can't append an
- * overflow page and later you'd have to split the key/data and handle like
- * a big pair.
- * You might as well do this up front.
- */
-#ifndef PAGE_H
-#define PAGE_H
-
-#define PAIRSIZE(K,D) (2*sizeof(uint16) + (K)->size + (D)->size)
-#define BIGOVERHEAD (4*sizeof(uint16))
-#define KEYSIZE(K) (4*sizeof(uint16) + (K)->size);
-#define OVFLSIZE (2*sizeof(uint16))
-#define FREESPACE(P) ((P)[(P)[0]+1])
-#define OFFSET(P) ((P)[(P)[0]+2])
-#define PAIRFITS(P,K,D) \
- (((P)[2] >= REAL_KEY) && \
- (PAIRSIZE((K),(D)) + OVFLSIZE) <= FREESPACE((P)))
-#define PAGE_META(N) (((N)+3) * sizeof(uint16))
-
-typedef struct {
- BUFHEAD *newp;
- BUFHEAD *oldp;
- BUFHEAD *nextp;
- uint16 next_addr;
-} SPLIT_RETURN;
-#endif
-
diff --git a/dbm/include/queue.h b/dbm/include/queue.h
deleted file mode 100644
index 40d32ccb6..000000000
--- a/dbm/include/queue.h
+++ /dev/null
@@ -1,245 +0,0 @@
-/*
- * Copyright (c) 1991, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)queue.h 8.3 (Berkeley) 12/13/93
- */
-
-#ifndef _QUEUE_H_
-#define _QUEUE_H_
-
-/*
- * This file defines three types of data structures: lists, tail queues,
- * and circular queues.
- *
- * A list is headed by a single forward pointer (or an array of forward
- * pointers for a hash table header). The elements are doubly linked
- * so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list after
- * an existing element or at the head of the list. A list may only be
- * traversed in the forward direction.
- *
- * A tail queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list after
- * an existing element, at the head of the list, or at the end of the
- * list. A tail queue may only be traversed in the forward direction.
- *
- * A circle queue is headed by a pair of pointers, one to the head of the
- * list and the other to the tail of the list. The elements are doubly
- * linked so that an arbitrary element can be removed without a need to
- * traverse the list. New elements can be added to the list before or after
- * an existing element, at the head of the list, or at the end of the list.
- * A circle queue may be traversed in either direction, but has a more
- * complex end of list detection.
- *
- * For details on the use of these macros, see the queue(3) manual page.
- */
-
-/*
- * List definitions.
- */
-#define LIST_HEAD(name, type) \
-struct name { \
- struct type *lh_first; /* first element */ \
-}
-
-#define LIST_ENTRY(type) \
-struct { \
- struct type *le_next; /* next element */ \
- struct type **le_prev; /* address of previous next element */ \
-}
-
-/*
- * List functions.
- */
-#define LIST_INIT(head) { \
- (head)->lh_first = NULL; \
-}
-
-#define LIST_INSERT_AFTER(listelm, elm, field) { \
- if (((elm)->field.le_next = (listelm)->field.le_next) != NULL) \
- (listelm)->field.le_next->field.le_prev = \
- &(elm)->field.le_next; \
- (listelm)->field.le_next = (elm); \
- (elm)->field.le_prev = &(listelm)->field.le_next; \
-}
-
-#define LIST_INSERT_HEAD(head, elm, field) { \
- if (((elm)->field.le_next = (head)->lh_first) != NULL) \
- (head)->lh_first->field.le_prev = &(elm)->field.le_next;\
- (head)->lh_first = (elm); \
- (elm)->field.le_prev = &(head)->lh_first; \
-}
-
-#define LIST_REMOVE(elm, field) { \
- if ((elm)->field.le_next != NULL) \
- (elm)->field.le_next->field.le_prev = \
- (elm)->field.le_prev; \
- *(elm)->field.le_prev = (elm)->field.le_next; \
-}
-
-/*
- * Tail queue definitions.
- */
-#define TAILQ_HEAD(name, type) \
-struct name { \
- struct type *tqh_first; /* first element */ \
- struct type **tqh_last; /* addr of last next element */ \
-}
-
-#define TAILQ_ENTRY(type) \
-struct { \
- struct type *tqe_next; /* next element */ \
- struct type **tqe_prev; /* address of previous next element */ \
-}
-
-/*
- * Tail queue functions.
- */
-#define TAILQ_INIT(head) { \
- (head)->tqh_first = NULL; \
- (head)->tqh_last = &(head)->tqh_first; \
-}
-
-#define TAILQ_INSERT_HEAD(head, elm, field) { \
- if (((elm)->field.tqe_next = (head)->tqh_first) != NULL) \
- (elm)->field.tqe_next->field.tqe_prev = \
- &(elm)->field.tqe_next; \
- else \
- (head)->tqh_last = &(elm)->field.tqe_next; \
- (head)->tqh_first = (elm); \
- (elm)->field.tqe_prev = &(head)->tqh_first; \
-}
-
-#define TAILQ_INSERT_TAIL(head, elm, field) { \
- (elm)->field.tqe_next = NULL; \
- (elm)->field.tqe_prev = (head)->tqh_last; \
- *(head)->tqh_last = (elm); \
- (head)->tqh_last = &(elm)->field.tqe_next; \
-}
-
-#define TAILQ_INSERT_AFTER(head, listelm, elm, field) { \
- if (((elm)->field.tqe_next = (listelm)->field.tqe_next) != NULL)\
- (elm)->field.tqe_next->field.tqe_prev = \
- &(elm)->field.tqe_next; \
- else \
- (head)->tqh_last = &(elm)->field.tqe_next; \
- (listelm)->field.tqe_next = (elm); \
- (elm)->field.tqe_prev = &(listelm)->field.tqe_next; \
-}
-
-#define TAILQ_REMOVE(head, elm, field) { \
- if (((elm)->field.tqe_next) != NULL) \
- (elm)->field.tqe_next->field.tqe_prev = \
- (elm)->field.tqe_prev; \
- else \
- (head)->tqh_last = (elm)->field.tqe_prev; \
- *(elm)->field.tqe_prev = (elm)->field.tqe_next; \
-}
-
-/*
- * Circular queue definitions.
- */
-#define CIRCLEQ_HEAD(name, type) \
-struct name { \
- struct type *cqh_first; /* first element */ \
- struct type *cqh_last; /* last element */ \
-}
-
-#define CIRCLEQ_ENTRY(type) \
-struct { \
- struct type *cqe_next; /* next element */ \
- struct type *cqe_prev; /* previous element */ \
-}
-
-/*
- * Circular queue functions.
- */
-#define CIRCLEQ_INIT(head) { \
- (head)->cqh_first = (void *)(head); \
- (head)->cqh_last = (void *)(head); \
-}
-
-#define CIRCLEQ_INSERT_AFTER(head, listelm, elm, field) { \
- (elm)->field.cqe_next = (listelm)->field.cqe_next; \
- (elm)->field.cqe_prev = (listelm); \
- if ((listelm)->field.cqe_next == (void *)(head)) \
- (head)->cqh_last = (elm); \
- else \
- (listelm)->field.cqe_next->field.cqe_prev = (elm); \
- (listelm)->field.cqe_next = (elm); \
-}
-
-#define CIRCLEQ_INSERT_BEFORE(head, listelm, elm, field) { \
- (elm)->field.cqe_next = (listelm); \
- (elm)->field.cqe_prev = (listelm)->field.cqe_prev; \
- if ((listelm)->field.cqe_prev == (void *)(head)) \
- (head)->cqh_first = (elm); \
- else \
- (listelm)->field.cqe_prev->field.cqe_next = (elm); \
- (listelm)->field.cqe_prev = (elm); \
-}
-
-#define CIRCLEQ_INSERT_HEAD(head, elm, field) { \
- (elm)->field.cqe_next = (head)->cqh_first; \
- (elm)->field.cqe_prev = (void *)(head); \
- if ((head)->cqh_last == (void *)(head)) \
- (head)->cqh_last = (elm); \
- else \
- (head)->cqh_first->field.cqe_prev = (elm); \
- (head)->cqh_first = (elm); \
-}
-
-#define CIRCLEQ_INSERT_TAIL(head, elm, field) { \
- (elm)->field.cqe_next = (void *)(head); \
- (elm)->field.cqe_prev = (head)->cqh_last; \
- if ((head)->cqh_first == (void *)(head)) \
- (head)->cqh_first = (elm); \
- else \
- (head)->cqh_last->field.cqe_next = (elm); \
- (head)->cqh_last = (elm); \
-}
-
-#define CIRCLEQ_REMOVE(head, elm, field) { \
- if ((elm)->field.cqe_next == (void *)(head)) \
- (head)->cqh_last = (elm)->field.cqe_prev; \
- else \
- (elm)->field.cqe_next->field.cqe_prev = \
- (elm)->field.cqe_prev; \
- if ((elm)->field.cqe_prev == (void *)(head)) \
- (head)->cqh_first = (elm)->field.cqe_next; \
- else \
- (elm)->field.cqe_prev->field.cqe_next = \
- (elm)->field.cqe_next; \
-}
-#endif /* !_QUEUE_H_ */
diff --git a/dbm/include/search.h b/dbm/include/search.h
deleted file mode 100644
index ff58b1c15..000000000
--- a/dbm/include/search.h
+++ /dev/null
@@ -1,51 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- *
- * @(#)search.h 8.1 (Berkeley) 6/4/93
- */
-
-/* Backward compatibility to hsearch interface. */
-typedef struct entry {
- char *key;
- char *data;
-} ENTRY;
-
-typedef enum {
- FIND, ENTER
-} ACTION;
-
-int hcreate (unsigned int);
-void hdestroy (void);
-ENTRY *hsearch (ENTRY, ACTION);
diff --git a/dbm/include/watcomfx.h b/dbm/include/watcomfx.h
deleted file mode 100644
index 3020e9de9..000000000
--- a/dbm/include/watcomfx.h
+++ /dev/null
@@ -1,26 +0,0 @@
-#if defined(__WATCOMC__) || defined(__WATCOM_CPLUSPLUS__)
-#ifndef __WATCOM_FIX_H__
-#define __WATCOM_FIX_H__ 1
-/*
- * WATCOM's C compiler doesn't default to "__cdecl" conventions for external
- * symbols and functions. Rather than adding an explicit __cdecl modifier to
- * every external symbol and function declaration and definition, we use the
- * following pragma to (attempt to) change WATCOM c's default to __cdecl.
- * These pragmas were taken from pages 180-181, 266 & 269 of the
- * Watcom C/C++ version 11 User's Guide, 3rd edition.
- */
-#if defined(XP_WIN16) || defined(WIN16)
-#pragma aux default "_*" \
- parm caller [] \
- value struct float struct routine [ax] \
- modify [ax bx cx dx es]
-#else
-#pragma aux default "_*" \
- parm caller [] \
- value struct float struct routine [eax] \
- modify [eax ecx edx]
-#endif
-#pragma aux default far
-
-#endif /* once */
-#endif /* WATCOM compiler */
diff --git a/dbm/include/winfile.h b/dbm/include/winfile.h
deleted file mode 100644
index 1fd54d578..000000000
--- a/dbm/include/winfile.h
+++ /dev/null
@@ -1,106 +0,0 @@
-
-/* ---------------------------------------------------------------------------
- Stuff to fake unix file I/O on windows boxes
- ------------------------------------------------------------------------*/
-
-#ifndef WINFILE_H
-#define WINFILE_H
-
-#ifdef _WINDOWS
-/* hacked out of <dirent.h> on an SGI */
-#if defined(XP_WIN32) || defined(_WIN32)
-/* 32-bit stuff here */
-#include <windows.h>
-#include <stdlib.h>
-#ifdef __MINGW32__
-#include <sys/types.h>
-#include <sys/stat.h>
-#else
-#include <sys\types.h>
-#include <sys\stat.h>
-#endif
-
-typedef struct DIR_Struct {
- void * directoryPtr;
- WIN32_FIND_DATA data;
-} DIR;
-
-#define _ST_FSTYPSZ 16
-
-#if !defined(__BORLANDC__) && !defined(__GNUC__)
- typedef unsigned long mode_t;
- typedef long uid_t;
- typedef long gid_t;
- typedef long off_t;
- typedef unsigned long nlink_t;
-#endif
-
-typedef struct timestruc {
- time_t tv_sec; /* seconds */
- long tv_nsec; /* and nanoseconds */
-} timestruc_t;
-
-
-struct dirent { /* data from readdir() */
- ino_t d_ino; /* inode number of entry */
- off_t d_off; /* offset of disk direntory entry */
- unsigned short d_reclen; /* length of this record */
- char d_name[_MAX_FNAME]; /* name of file */
-};
-
-#if !defined(__BORLANDC__) && !defined (__GNUC__)
-#define S_ISDIR(s) ((s) & _S_IFDIR)
-#endif
-
-#else /* _WIN32 */
-/* 16-bit windows stuff */
-
-#include <sys\types.h>
-#include <sys\stat.h>
-#include <dos.h>
-
-
-
-/* Getting cocky to support multiple file systems */
-typedef struct dirStruct_tag {
- struct _find_t file_data;
- char c_checkdrive;
-} dirStruct;
-
-typedef struct DIR_Struct {
- void * directoryPtr;
- dirStruct data;
-} DIR;
-
-#define _ST_FSTYPSZ 16
-typedef unsigned long mode_t;
-typedef long uid_t;
-typedef long gid_t;
-typedef long off_t;
-typedef unsigned long nlink_t;
-
-typedef struct timestruc {
- time_t tv_sec; /* seconds */
- long tv_nsec; /* and nanoseconds */
-} timestruc_t;
-
-struct dirent { /* data from readdir() */
- ino_t d_ino; /* inode number of entry */
- off_t d_off; /* offset of disk direntory entry */
- unsigned short d_reclen; /* length of this record */
-#ifdef XP_WIN32
- char d_name[_MAX_FNAME]; /* name of file */
-#else
- char d_name[20]; /* name of file */
-#endif
-};
-
-#define S_ISDIR(s) ((s) & _S_IFDIR)
-
-#endif /* 16-bit windows */
-
-#define CONST const
-
-#endif /* _WINDOWS */
-
-#endif /* WINFILE_H */
diff --git a/dbm/macbuild/DBM.Prefix b/dbm/macbuild/DBM.Prefix
deleted file mode 100644
index bace25e50..000000000
--- a/dbm/macbuild/DBM.Prefix
+++ /dev/null
@@ -1,33 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * The contents of this file are subject to the Netscape Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/NPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1998 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- */
-
-//
-// DBM.Prefix
-//
-// Global prefix file for the non-debug DBM project.
-//
-//
-
-
-#include "MacPrefix.h"
-#include "DBMConfig.h"
-
diff --git a/dbm/macbuild/DBM.mcp b/dbm/macbuild/DBM.mcp
deleted file mode 100644
index 8efed3102..000000000
--- a/dbm/macbuild/DBM.mcp
+++ /dev/null
Binary files differ
diff --git a/dbm/macbuild/DBMConfig.h b/dbm/macbuild/DBMConfig.h
deleted file mode 100644
index 6493d254f..000000000
--- a/dbm/macbuild/DBMConfig.h
+++ /dev/null
@@ -1,23 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * The contents of this file are subject to the Netscape Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/NPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1998 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- */
-
-/* Nothing to do here. If you need DBM-specific defines, put them here */
diff --git a/dbm/macbuild/DBMDebug.Prefix b/dbm/macbuild/DBMDebug.Prefix
deleted file mode 100644
index 7d40bdad3..000000000
--- a/dbm/macbuild/DBMDebug.Prefix
+++ /dev/null
@@ -1,32 +0,0 @@
-/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * The contents of this file are subject to the Netscape Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/NPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1998 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- */
-
-//
-// DBMDebug.Prefix
-//
-// Global prefix file for the debug DBM project.
-//
-//
-
-#include "MacPrefix_debug.h"
-#include "DBMConfig.h"
-
diff --git a/dbm/macbuild/macstubs.c b/dbm/macbuild/macstubs.c
deleted file mode 100644
index bbfe69a54..000000000
--- a/dbm/macbuild/macstubs.c
+++ /dev/null
@@ -1,8 +0,0 @@
-
-// Hack to define a never-called routine from libdbm
-#include "mcom_db.h"
-
-int mkstemp(const char* /*path*/)
-{
- return -1;
-}
diff --git a/dbm/makefile.win b/dbm/makefile.win
deleted file mode 100644
index 27470574e..000000000
--- a/dbm/makefile.win
+++ /dev/null
@@ -1,38 +0,0 @@
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-
-DEPTH=..
-
-#//------------------------------------------------------------------------
-#//
-#// Specify any "command" targets. (ie. DIRS, INSTALL_FILES, ...)
-#// (these must come before the common makefiles are included)
-#//
-#// DIRS - There are subdirectories to process
-#//
-#//------------------------------------------------------------------------
-DIRS = include src
-
-#//------------------------------------------------------------------------
-#//
-#// Include the common makefile rules
-#//
-#//------------------------------------------------------------------------
-include <$(DEPTH)\config\rules.mak>
-
diff --git a/dbm/src/.cvsignore b/dbm/src/.cvsignore
deleted file mode 100644
index f3c7a7c5d..000000000
--- a/dbm/src/.cvsignore
+++ /dev/null
@@ -1 +0,0 @@
-Makefile
diff --git a/dbm/src/Makefile.in b/dbm/src/Makefile.in
deleted file mode 100644
index ef54dd675..000000000
--- a/dbm/src/Makefile.in
+++ /dev/null
@@ -1,70 +0,0 @@
-#
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-
-DEPTH = ../..
-topsrcdir = @top_srcdir@
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-LIBRARY_NAME = mozdbm_s
-LIB_IS_C_ONLY = 1
-
-CSRCS = \
- db.c \
- h_bigkey.c \
- h_func.c \
- h_log2.c \
- h_page.c \
- hash.c \
- hash_buf.c \
- hsearch.c \
- mktemp.c \
- ndbm.c \
- strerror.c \
- nsres.c \
- $(NULL)
-
-ifeq (,$(filter -DHAVE_MEMMOVE=1,$(DEFS)))
-CSRC += memmove.c
-endif
-
-ifeq (,$(filter -DHAVE_SNPRINTF=1,$(DEFS)))
-CSRC += snprintf.c
-endif
-
-LOCAL_INCLUDES = -I$(srcdir)/../include
-
-override NO_SHARED_LIB=1
-override NO_STATIC_LIB=
-
-include $(topsrcdir)/config/rules.mk
-
-DEFINES += -DMEMMOVE -D__DBINTERFACE_PRIVATE $(SECURITY_FLAG)
-ifeq ($(OS_ARCH), Linux)
-DEFINES += -D_BSD_SOURCE
-endif
-
-ifeq ($(OS_ARCH),AIX)
-OS_LIBS += -lc_r
-endif
-
diff --git a/dbm/src/Makefile.win b/dbm/src/Makefile.win
deleted file mode 100644
index 1d49e5f91..000000000
--- a/dbm/src/Makefile.win
+++ /dev/null
@@ -1,96 +0,0 @@
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-
-
-#//------------------------------------------------------------------------
-#//
-#// Makefile to build the cert library
-#//
-#//------------------------------------------------------------------------
-
-!if "$(MOZ_BITS)" == "16"
-!ifndef MOZ_DEBUG
-OPTIMIZER=-Os -UDEBUG -DNDEBUG
-!endif
-!endif
-
-#//------------------------------------------------------------------------
-#//
-#// Specify the depth of the current directory relative to the
-#// root of NS
-#//
-#//------------------------------------------------------------------------
-DEPTH= ..\..
-
-!ifndef MAKE_OBJ_TYPE
-MAKE_OBJ_TYPE=EXE
-!endif
-
-#//------------------------------------------------------------------------
-#//
-#// Define any Public Make Variables here: (ie. PDFFILE, MAPFILE, ...)
-#//
-#//------------------------------------------------------------------------
-LIBNAME=dbm$(MOZ_BITS)
-PDBFILE=$(LIBNAME).pdb
-
-#//------------------------------------------------------------------------
-#//
-#// Define the files necessary to build the target (ie. OBJS)
-#//
-#//------------------------------------------------------------------------
-OBJS= \
- .\$(OBJDIR)\db.obj \
- .\$(OBJDIR)\h_bigkey.obj \
- .\$(OBJDIR)\h_func.obj \
- .\$(OBJDIR)\h_log2.obj \
- .\$(OBJDIR)\h_page.obj \
- .\$(OBJDIR)\hash.obj \
- .\$(OBJDIR)\hash_buf.obj \
- .\$(OBJDIR)\hsearch.obj \
- .\$(OBJDIR)\memmove.obj \
- .\$(OBJDIR)\mktemp.obj \
- .\$(OBJDIR)\ndbm.obj \
- .\$(OBJDIR)\snprintf.obj \
- .\$(OBJDIR)\strerror.obj \
- .\$(OBJDIR)\nsres.obj \
- $(NULL)
-
-#//------------------------------------------------------------------------
-#//
-#// Define any Public Targets here (ie. PROGRAM, LIBRARY, DLL, ...)
-#// (these must be defined before the common makefiles are included)
-#//
-#//------------------------------------------------------------------------
-LIBRARY = .\$(OBJDIR)\$(LIBNAME).lib
-LINCS = -I..\include
-
-#//------------------------------------------------------------------------
-#//
-#// Include the common makefile rules
-#//
-#//------------------------------------------------------------------------
-include <$(DEPTH)/config/rules.mak>
-
-CFLAGS = $(CFLAGS) -DMOZILLA_CLIENT
-
-install:: $(LIBRARY)
- $(MAKE_INSTALL) $(LIBRARY) $(DIST)\lib
-
-
diff --git a/dbm/src/db.c b/dbm/src/db.c
deleted file mode 100644
index 2c6edec2a..000000000
--- a/dbm/src/db.c
+++ /dev/null
@@ -1,146 +0,0 @@
-/*-
- * Copyright (c) 1991, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)db.c 8.4 (Berkeley) 2/21/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#ifndef __DBINTERFACE_PRIVATE
-#define __DBINTERFACE_PRIVATE
-#endif
-#ifdef macintosh
-#include <unix.h>
-#else
-#include <sys/types.h>
-#endif
-
-#include <errno.h>
-#ifndef macintosh
-#include <fcntl.h>
-#endif
-#include <stddef.h>
-#include <stdio.h>
-
-#include "mcom_db.h"
-
-/* a global flag that locks closed all databases */
-int all_databases_locked_closed = 0;
-
-/* set or unset a global lock flag to disable the
- * opening of any DBM file
- */
-void
-dbSetOrClearDBLock(DBLockFlagEnum type)
-{
- if(type == LockOutDatabase)
- all_databases_locked_closed = 1;
- else
- all_databases_locked_closed = 0;
-}
-
-#if defined(__WATCOMC__) || defined(__WATCOM_CPLUSPLUS__)
-DB *
-#else
-PR_IMPLEMENT(DB *)
-#endif
-dbopen(const char *fname, int flags,int mode, DBTYPE type, const void *openinfo)
-{
-
- /* lock out all file databases. Let in-memory databases through
- */
- if(all_databases_locked_closed && fname)
- {
- errno = EINVAL;
- return(NULL);
- }
-
-#define DB_FLAGS (DB_LOCK | DB_SHMEM | DB_TXN)
-
-
-#if 0 /* most systems dont have EXLOCK and SHLOCK */
-#define USE_OPEN_FLAGS \
- (O_CREAT | O_EXCL | O_EXLOCK | O_NONBLOCK | O_RDONLY | \
- O_RDWR | O_SHLOCK | O_TRUNC)
-#else
-#define USE_OPEN_FLAGS \
- (O_CREAT | O_EXCL | O_RDONLY | \
- O_RDWR | O_TRUNC)
-#endif
-
- if ((flags & ~(USE_OPEN_FLAGS | DB_FLAGS)) == 0)
- switch (type) {
-/* we don't need btree and recno right now */
-#if 0
- case DB_BTREE:
- return (__bt_open(fname, flags & USE_OPEN_FLAGS,
- mode, openinfo, flags & DB_FLAGS));
- case DB_RECNO:
- return (__rec_open(fname, flags & USE_OPEN_FLAGS,
- mode, openinfo, flags & DB_FLAGS));
-#endif
-
- case DB_HASH:
- return (__hash_open(fname, flags & USE_OPEN_FLAGS,
- mode, (const HASHINFO *)openinfo, flags & DB_FLAGS));
- default:
- break;
- }
- errno = EINVAL;
- return (NULL);
-}
-
-static int
-__dberr()
-{
- return (RET_ERROR);
-}
-
-/*
- * __DBPANIC -- Stop.
- *
- * Parameters:
- * dbp: pointer to the DB structure.
- */
-void
-__dbpanic(DB *dbp)
-{
- /* The only thing that can succeed is a close. */
- dbp->del = (int (*)(const struct __db *, const DBT *, uint))__dberr;
- dbp->fd = (int (*)(const struct __db *))__dberr;
- dbp->get = (int (*)(const struct __db *, const DBT *, DBT *, uint))__dberr;
- dbp->put = (int (*)(const struct __db *, DBT *, const DBT *, uint))__dberr;
- dbp->seq = (int (*)(const struct __db *, DBT *, DBT *, uint))__dberr;
- dbp->sync = (int (*)(const struct __db *, uint))__dberr;
-}
diff --git a/dbm/src/h_bigkey.c b/dbm/src/h_bigkey.c
deleted file mode 100644
index fe5d8f800..000000000
--- a/dbm/src/h_bigkey.c
+++ /dev/null
@@ -1,677 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hash_bigkey.c 8.3 (Berkeley) 5/31/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-/*
- * PACKAGE: hash
- * DESCRIPTION:
- * Big key/data handling for the hashing package.
- *
- * ROUTINES:
- * External
- * __big_keydata
- * __big_split
- * __big_insert
- * __big_return
- * __big_delete
- * __find_last_page
- * Internal
- * collect_key
- * collect_data
- */
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2_VACPP)
-#include <sys/param.h>
-#endif
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#ifdef DEBUG
-#include <assert.h>
-#endif
-
-#include "mcom_db.h"
-#include "hash.h"
-#include "page.h"
-/* #include "extern.h" */
-
-static int collect_key __P((HTAB *, BUFHEAD *, int, DBT *, int));
-static int collect_data __P((HTAB *, BUFHEAD *, int, int));
-
-/*
- * Big_insert
- *
- * You need to do an insert and the key/data pair is too big
- *
- * Returns:
- * 0 ==> OK
- *-1 ==> ERROR
- */
-extern int
-__big_insert(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT *val)
-{
- register uint16 *p;
- uint key_size, n, val_size;
- uint16 space, move_bytes, off;
- char *cp, *key_data, *val_data;
-
- cp = bufp->page; /* Character pointer of p. */
- p = (uint16 *)cp;
-
- key_data = (char *)key->data;
- key_size = key->size;
- val_data = (char *)val->data;
- val_size = val->size;
-
- /* First move the Key */
- for (space = FREESPACE(p) - BIGOVERHEAD; key_size;
- space = FREESPACE(p) - BIGOVERHEAD) {
- move_bytes = PR_MIN(space, key_size);
- off = OFFSET(p) - move_bytes;
- memmove(cp + off, key_data, move_bytes);
- key_size -= move_bytes;
- key_data += move_bytes;
- n = p[0];
- p[++n] = off;
- p[0] = ++n;
- FREESPACE(p) = off - PAGE_META(n);
- OFFSET(p) = off;
- p[n] = PARTIAL_KEY;
- bufp = __add_ovflpage(hashp, bufp);
- if (!bufp)
- return (-1);
- n = p[0];
- if (!key_size) {
- if (FREESPACE(p)) {
- move_bytes = PR_MIN(FREESPACE(p), val_size);
- off = OFFSET(p) - move_bytes;
- p[n] = off;
- memmove(cp + off, val_data, move_bytes);
- val_data += move_bytes;
- val_size -= move_bytes;
- p[n - 2] = FULL_KEY_DATA;
- FREESPACE(p) = FREESPACE(p) - move_bytes;
- OFFSET(p) = off;
- } else
- p[n - 2] = FULL_KEY;
- }
- p = (uint16 *)bufp->page;
- cp = bufp->page;
- bufp->flags |= BUF_MOD;
- }
-
- /* Now move the data */
- for (space = FREESPACE(p) - BIGOVERHEAD; val_size;
- space = FREESPACE(p) - BIGOVERHEAD) {
- move_bytes = PR_MIN(space, val_size);
- /*
- * Here's the hack to make sure that if the data ends on the
- * same page as the key ends, FREESPACE is at least one.
- */
- if (space == val_size && val_size == val->size)
- move_bytes--;
- off = OFFSET(p) - move_bytes;
- memmove(cp + off, val_data, move_bytes);
- val_size -= move_bytes;
- val_data += move_bytes;
- n = p[0];
- p[++n] = off;
- p[0] = ++n;
- FREESPACE(p) = off - PAGE_META(n);
- OFFSET(p) = off;
- if (val_size) {
- p[n] = FULL_KEY;
- bufp = __add_ovflpage(hashp, bufp);
- if (!bufp)
- return (-1);
- cp = bufp->page;
- p = (uint16 *)cp;
- } else
- p[n] = FULL_KEY_DATA;
- bufp->flags |= BUF_MOD;
- }
- return (0);
-}
-
-/*
- * Called when bufp's page contains a partial key (index should be 1)
- *
- * All pages in the big key/data pair except bufp are freed. We cannot
- * free bufp because the page pointing to it is lost and we can't get rid
- * of its pointer.
- *
- * Returns:
- * 0 => OK
- *-1 => ERROR
- */
-extern int
-__big_delete(HTAB *hashp, BUFHEAD *bufp)
-{
- register BUFHEAD *last_bfp, *rbufp;
- uint16 *bp, pageno;
- int key_done, n;
-
- rbufp = bufp;
- last_bfp = NULL;
- bp = (uint16 *)bufp->page;
- pageno = 0;
- key_done = 0;
-
- while (!key_done || (bp[2] != FULL_KEY_DATA)) {
- if (bp[2] == FULL_KEY || bp[2] == FULL_KEY_DATA)
- key_done = 1;
-
- /*
- * If there is freespace left on a FULL_KEY_DATA page, then
- * the data is short and fits entirely on this page, and this
- * is the last page.
- */
- if (bp[2] == FULL_KEY_DATA && FREESPACE(bp))
- break;
- pageno = bp[bp[0] - 1];
- rbufp->flags |= BUF_MOD;
- rbufp = __get_buf(hashp, pageno, rbufp, 0);
- if (last_bfp)
- __free_ovflpage(hashp, last_bfp);
- last_bfp = rbufp;
- if (!rbufp)
- return (-1); /* Error. */
- bp = (uint16 *)rbufp->page;
- }
-
- /*
- * If we get here then rbufp points to the last page of the big
- * key/data pair. Bufp points to the first one -- it should now be
- * empty pointing to the next page after this pair. Can't free it
- * because we don't have the page pointing to it.
- */
-
- /* This is information from the last page of the pair. */
- n = bp[0];
- pageno = bp[n - 1];
-
- /* Now, bp is the first page of the pair. */
- bp = (uint16 *)bufp->page;
- if (n > 2) {
- /* There is an overflow page. */
- bp[1] = pageno;
- bp[2] = OVFLPAGE;
- bufp->ovfl = rbufp->ovfl;
- } else
- /* This is the last page. */
- bufp->ovfl = NULL;
- n -= 2;
- bp[0] = n;
- FREESPACE(bp) = hashp->BSIZE - PAGE_META(n);
- OFFSET(bp) = hashp->BSIZE - 1;
-
- bufp->flags |= BUF_MOD;
- if (rbufp)
- __free_ovflpage(hashp, rbufp);
- if (last_bfp != rbufp)
- __free_ovflpage(hashp, last_bfp);
-
- hashp->NKEYS--;
- return (0);
-}
-/*
- * Returns:
- * 0 = key not found
- * -1 = get next overflow page
- * -2 means key not found and this is big key/data
- * -3 error
- */
-extern int
-__find_bigpair(HTAB *hashp, BUFHEAD *bufp, int ndx, char *key, int size)
-{
- register uint16 *bp;
- register char *p;
- int ksize;
- uint16 bytes;
- char *kkey;
-
- bp = (uint16 *)bufp->page;
- p = bufp->page;
- ksize = size;
- kkey = key;
-
- for (bytes = hashp->BSIZE - bp[ndx];
- bytes <= size && bp[ndx + 1] == PARTIAL_KEY;
- bytes = hashp->BSIZE - bp[ndx]) {
- if (memcmp(p + bp[ndx], kkey, bytes))
- return (-2);
- kkey += bytes;
- ksize -= bytes;
- bufp = __get_buf(hashp, bp[ndx + 2], bufp, 0);
- if (!bufp)
- return (-3);
- p = bufp->page;
- bp = (uint16 *)p;
- ndx = 1;
- }
-
- if (bytes != ksize || memcmp(p + bp[ndx], kkey, bytes)) {
-#ifdef HASH_STATISTICS
- ++hash_collisions;
-#endif
- return (-2);
- } else
- return (ndx);
-}
-
-/*
- * Given the buffer pointer of the first overflow page of a big pair,
- * find the end of the big pair
- *
- * This will set bpp to the buffer header of the last page of the big pair.
- * It will return the pageno of the overflow page following the last page
- * of the pair; 0 if there isn't any (i.e. big pair is the last key in the
- * bucket)
- */
-extern uint16
-__find_last_page(HTAB *hashp, BUFHEAD **bpp)
-{
- BUFHEAD *bufp;
- uint16 *bp, pageno;
- uint n;
-
- bufp = *bpp;
- bp = (uint16 *)bufp->page;
- for (;;) {
- n = bp[0];
-
- /*
- * This is the last page if: the tag is FULL_KEY_DATA and
- * either only 2 entries OVFLPAGE marker is explicit there
- * is freespace on the page.
- */
- if (bp[2] == FULL_KEY_DATA &&
- ((n == 2) || (bp[n] == OVFLPAGE) || (FREESPACE(bp))))
- break;
-
- /* LJM bound the size of n to reasonable limits
- */
- if(n > hashp->BSIZE/sizeof(uint16))
- return(0);
-
- pageno = bp[n - 1];
- bufp = __get_buf(hashp, pageno, bufp, 0);
- if (!bufp)
- return (0); /* Need to indicate an error! */
- bp = (uint16 *)bufp->page;
- }
-
- *bpp = bufp;
- if (bp[0] > 2)
- return (bp[3]);
- else
- return (0);
-}
-
-/*
- * Return the data for the key/data pair that begins on this page at this
- * index (index should always be 1).
- */
-extern int
-__big_return(
- HTAB *hashp,
- BUFHEAD *bufp,
- int ndx,
- DBT *val,
- int set_current)
-{
- BUFHEAD *save_p;
- uint16 *bp, len, off, save_addr;
- char *tp;
-
- bp = (uint16 *)bufp->page;
- while (bp[ndx + 1] == PARTIAL_KEY) {
- bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!bufp)
- return (-1);
- bp = (uint16 *)bufp->page;
- ndx = 1;
- }
-
- if (bp[ndx + 1] == FULL_KEY) {
- bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!bufp)
- return (-1);
- bp = (uint16 *)bufp->page;
- save_p = bufp;
- save_addr = save_p->addr;
- off = bp[1];
- len = 0;
- } else
- if (!FREESPACE(bp)) {
- /*
- * This is a hack. We can't distinguish between
- * FULL_KEY_DATA that contains complete data or
- * incomplete data, so we require that if the data
- * is complete, there is at least 1 byte of free
- * space left.
- */
- off = bp[bp[0]];
- len = bp[1] - off;
- save_p = bufp;
- save_addr = bufp->addr;
- bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!bufp)
- return (-1);
- bp = (uint16 *)bufp->page;
- } else {
- /* The data is all on one page. */
- tp = (char *)bp;
- off = bp[bp[0]];
- val->data = (uint8 *)tp + off;
- val->size = bp[1] - off;
- if (set_current) {
- if (bp[0] == 2) { /* No more buckets in
- * chain */
- hashp->cpage = NULL;
- hashp->cbucket++;
- hashp->cndx = 1;
- } else {
- hashp->cpage = __get_buf(hashp,
- bp[bp[0] - 1], bufp, 0);
- if (!hashp->cpage)
- return (-1);
- hashp->cndx = 1;
- if (!((uint16 *)
- hashp->cpage->page)[0]) {
- hashp->cbucket++;
- hashp->cpage = NULL;
- }
- }
- }
- return (0);
- }
-
- val->size = collect_data(hashp, bufp, (int)len, set_current);
- if ((val->size + 1) == 0) /* unsigned ints are not really negative */
- return (-1);
- if (save_p->addr != save_addr) {
- /* We are pretty short on buffers. */
- errno = EINVAL; /* OUT OF BUFFERS */
- return (-1);
- }
- memmove(hashp->tmp_buf, (save_p->page) + off, len);
- val->data = (uint8 *)hashp->tmp_buf;
- return (0);
-}
-/*
- * Count how big the total datasize is by recursing through the pages. Then
- * allocate a buffer and copy the data as you recurse up.
- */
-static int
-collect_data(
- HTAB *hashp,
- BUFHEAD *bufp,
- int len, int set)
-{
- register uint16 *bp;
- register char *p;
- BUFHEAD *xbp;
- uint16 save_addr;
- int mylen, totlen;
-
- p = bufp->page;
- bp = (uint16 *)p;
- mylen = hashp->BSIZE - bp[1];
-
- /* if mylen ever goes negative it means that the
- * page is screwed up.
- */
- if(mylen < 0)
- return (-1);
-
- save_addr = bufp->addr;
-
- if (bp[2] == FULL_KEY_DATA) { /* End of Data */
- totlen = len + mylen;
- if (hashp->tmp_buf)
- free(hashp->tmp_buf);
- if ((hashp->tmp_buf = (char *)malloc((size_t)totlen)) == NULL)
- return (-1);
- if (set) {
- hashp->cndx = 1;
- if (bp[0] == 2) { /* No more buckets in chain */
- hashp->cpage = NULL;
- hashp->cbucket++;
- } else {
- hashp->cpage =
- __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!hashp->cpage)
- return (-1);
- else if (!((uint16 *)hashp->cpage->page)[0]) {
- hashp->cbucket++;
- hashp->cpage = NULL;
- }
- }
- }
- } else {
- xbp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!xbp || ((totlen =
- collect_data(hashp, xbp, len + mylen, set)) < 1))
- return (-1);
- }
- if (bufp->addr != save_addr) {
- errno = EINVAL; /* Out of buffers. */
- return (-1);
- }
- memmove(&hashp->tmp_buf[len], (bufp->page) + bp[1], (size_t)mylen);
- return (totlen);
-}
-
-/*
- * Fill in the key and data for this big pair.
- */
-extern int
-__big_keydata(
- HTAB *hashp,
- BUFHEAD *bufp,
- DBT *key, DBT *val,
- int set)
-{
- key->size = collect_key(hashp, bufp, 0, val, set);
- if ((key->size + 1) == 0) /* same compile warning about comparing signed and unsigned */
- return (-1);
- key->data = (uint8 *)hashp->tmp_key;
- return (0);
-}
-
-/*
- * Count how big the total key size is by recursing through the pages. Then
- * collect the data, allocate a buffer and copy the key as you recurse up.
- */
-static int
-collect_key(
- HTAB *hashp,
- BUFHEAD *bufp,
- int len,
- DBT *val,
- int set)
-{
- BUFHEAD *xbp;
- char *p;
- int mylen, totlen;
- uint16 *bp, save_addr;
-
- p = bufp->page;
- bp = (uint16 *)p;
- mylen = hashp->BSIZE - bp[1];
-
- save_addr = bufp->addr;
- totlen = len + mylen;
- if (bp[2] == FULL_KEY || bp[2] == FULL_KEY_DATA) { /* End of Key. */
- if (hashp->tmp_key != NULL)
- free(hashp->tmp_key);
- if ((hashp->tmp_key = (char *)malloc((size_t)totlen)) == NULL)
- return (-1);
- if (__big_return(hashp, bufp, 1, val, set))
- return (-1);
- } else {
- xbp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!xbp || ((totlen =
- collect_key(hashp, xbp, totlen, val, set)) < 1))
- return (-1);
- }
- if (bufp->addr != save_addr) {
- errno = EINVAL; /* MIS -- OUT OF BUFFERS */
- return (-1);
- }
- memmove(&hashp->tmp_key[len], (bufp->page) + bp[1], (size_t)mylen);
- return (totlen);
-}
-
-/*
- * Returns:
- * 0 => OK
- * -1 => error
- */
-extern int
-__big_split(
- HTAB *hashp,
- BUFHEAD *op, /* Pointer to where to put keys that go in old bucket */
- BUFHEAD *np, /* Pointer to new bucket page */
- /* Pointer to first page containing the big key/data */
- BUFHEAD *big_keyp,
- uint32 addr, /* Address of big_keyp */
- uint32 obucket,/* Old Bucket */
- SPLIT_RETURN *ret)
-{
- register BUFHEAD *tmpp;
- register uint16 *tp;
- BUFHEAD *bp;
- DBT key, val;
- uint32 change;
- uint16 free_space, n, off;
-
- bp = big_keyp;
-
- /* Now figure out where the big key/data goes */
- if (__big_keydata(hashp, big_keyp, &key, &val, 0))
- return (-1);
- change = (__call_hash(hashp,(char*) key.data, key.size) != obucket);
-
- if ((ret->next_addr = __find_last_page(hashp, &big_keyp))) {
- if (!(ret->nextp =
- __get_buf(hashp, ret->next_addr, big_keyp, 0)))
- return (-1);;
- } else
- ret->nextp = NULL;
-
- /* Now make one of np/op point to the big key/data pair */
-#ifdef DEBUG
- assert(np->ovfl == NULL);
-#endif
- if (change)
- tmpp = np;
- else
- tmpp = op;
-
- tmpp->flags |= BUF_MOD;
-#ifdef DEBUG1
- (void)fprintf(stderr,
- "BIG_SPLIT: %d->ovfl was %d is now %d\n", tmpp->addr,
- (tmpp->ovfl ? tmpp->ovfl->addr : 0), (bp ? bp->addr : 0));
-#endif
- tmpp->ovfl = bp; /* one of op/np point to big_keyp */
- tp = (uint16 *)tmpp->page;
-
-
-#if 0 /* this get's tripped on database corrupted error */
- assert(FREESPACE(tp) >= OVFLSIZE);
-#endif
- if(FREESPACE(tp) < OVFLSIZE)
- return(DATABASE_CORRUPTED_ERROR);
-
- n = tp[0];
- off = OFFSET(tp);
- free_space = FREESPACE(tp);
- tp[++n] = (uint16)addr;
- tp[++n] = OVFLPAGE;
- tp[0] = n;
- OFFSET(tp) = off;
- FREESPACE(tp) = free_space - OVFLSIZE;
-
- /*
- * Finally, set the new and old return values. BIG_KEYP contains a
- * pointer to the last page of the big key_data pair. Make sure that
- * big_keyp has no following page (2 elements) or create an empty
- * following page.
- */
-
- ret->newp = np;
- ret->oldp = op;
-
- tp = (uint16 *)big_keyp->page;
- big_keyp->flags |= BUF_MOD;
- if (tp[0] > 2) {
- /*
- * There may be either one or two offsets on this page. If
- * there is one, then the overflow page is linked on normally
- * and tp[4] is OVFLPAGE. If there are two, tp[4] contains
- * the second offset and needs to get stuffed in after the
- * next overflow page is added.
- */
- n = tp[4];
- free_space = FREESPACE(tp);
- off = OFFSET(tp);
- tp[0] -= 2;
- FREESPACE(tp) = free_space + OVFLSIZE;
- OFFSET(tp) = off;
- tmpp = __add_ovflpage(hashp, big_keyp);
- if (!tmpp)
- return (-1);
- tp[4] = n;
- } else
- tmpp = big_keyp;
-
- if (change)
- ret->newp = tmpp;
- else
- ret->oldp = tmpp;
- return (0);
-}
diff --git a/dbm/src/h_func.c b/dbm/src/h_func.c
deleted file mode 100644
index 5819efe23..000000000
--- a/dbm/src/h_func.c
+++ /dev/null
@@ -1,211 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hash_func.c 8.2 (Berkeley) 2/21/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#ifndef macintosh
-#include <sys/types.h>
-#endif
-#include "mcom_db.h"
-#include "hash.h"
-#include "page.h"
-/* #include "extern.h" */
-
-#if 0
-static uint32 hash1 __P((const void *, size_t));
-static uint32 hash2 __P((const void *, size_t));
-static uint32 hash3 __P((const void *, size_t));
-#endif
-static uint32 hash4 __P((const void *, size_t));
-
-/* Global default hash function */
-uint32 (*__default_hash) __P((const void *, size_t)) = hash4;
-
-/*
- * HASH FUNCTIONS
- *
- * Assume that we've already split the bucket to which this key hashes,
- * calculate that bucket, and check that in fact we did already split it.
- *
- * This came from ejb's hsearch.
- */
-
-#define PRIME1 37
-#define PRIME2 1048583
-
-#if 0
-static uint32
-hash1(const void *keyarg, register size_t len)
-{
- register const uint8 *key;
- register uint32 h;
-
- /* Convert string to integer */
- for (key = (const uint8 *)keyarg, h = 0; len--;)
- h = h * PRIME1 ^ (*key++ - ' ');
- h %= PRIME2;
- return (h);
-}
-
-/*
- * Phong's linear congruential hash
- */
-#define dcharhash(h, c) ((h) = 0x63c63cd9*(h) + 0x9c39c33d + (c))
-
-static uint32
-hash2(const void *keyarg, size_t len)
-{
- register const uint8 *e, *key;
- register uint32 h;
- register uint8 c;
-
- key = (const uint8 *)keyarg;
- e = key + len;
- for (h = 0; key != e;) {
- c = *key++;
- if (!c && key > e)
- break;
- dcharhash(h, c);
- }
- return (h);
-}
-
-/*
- * This is INCREDIBLY ugly, but fast. We break the string up into 8 byte
- * units. On the first time through the loop we get the "leftover bytes"
- * (strlen % 8). On every other iteration, we perform 8 HASHC's so we handle
- * all 8 bytes. Essentially, this saves us 7 cmp & branch instructions. If
- * this routine is heavily used enough, it's worth the ugly coding.
- *
- * OZ's original sdbm hash
- */
-static uint32
-hash3(const void *keyarg, register size_t len)
-{
- register const uint8 *key;
- register size_t loop;
- register uint32 h;
-
-#define HASHC h = *key++ + 65599 * h
-
- h = 0;
- key = (const uint8 *)keyarg;
- if (len > 0) {
- loop = (len + 8 - 1) >> 3;
-
- switch (len & (8 - 1)) {
- case 0:
- do {
- HASHC;
- /* FALLTHROUGH */
- case 7:
- HASHC;
- /* FALLTHROUGH */
- case 6:
- HASHC;
- /* FALLTHROUGH */
- case 5:
- HASHC;
- /* FALLTHROUGH */
- case 4:
- HASHC;
- /* FALLTHROUGH */
- case 3:
- HASHC;
- /* FALLTHROUGH */
- case 2:
- HASHC;
- /* FALLTHROUGH */
- case 1:
- HASHC;
- } while (--loop);
- }
- }
- return (h);
-}
-#endif /* 0 */
-
-/* Hash function from Chris Torek. */
-static uint32
-hash4(const void *keyarg, register size_t len)
-{
- register const uint8 *key;
- register size_t loop;
- register uint32 h;
-
-#define HASH4a h = (h << 5) - h + *key++;
-#define HASH4b h = (h << 5) + h + *key++;
-#define HASH4 HASH4b
-
- h = 0;
- key = (const uint8 *)keyarg;
- if (len > 0) {
- loop = (len + 8 - 1) >> 3;
-
- switch (len & (8 - 1)) {
- case 0:
- do {
- HASH4;
- /* FALLTHROUGH */
- case 7:
- HASH4;
- /* FALLTHROUGH */
- case 6:
- HASH4;
- /* FALLTHROUGH */
- case 5:
- HASH4;
- /* FALLTHROUGH */
- case 4:
- HASH4;
- /* FALLTHROUGH */
- case 3:
- HASH4;
- /* FALLTHROUGH */
- case 2:
- HASH4;
- /* FALLTHROUGH */
- case 1:
- HASH4;
- } while (--loop);
- }
- }
- return (h);
-}
diff --git a/dbm/src/h_log2.c b/dbm/src/h_log2.c
deleted file mode 100644
index 4d8b0a715..000000000
--- a/dbm/src/h_log2.c
+++ /dev/null
@@ -1,56 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hash_log2.c 8.2 (Berkeley) 5/31/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#include <stdio.h>
-#ifndef macintosh
-#include <sys/types.h>
-#endif
-#include "mcom_db.h"
-
-uint32 __log2(uint32 num)
-{
- register uint32 i, limit;
-
- limit = 1;
- for (i = 0; limit < num; limit = limit << 1, i++) {}
- return (i);
-}
diff --git a/dbm/src/h_page.c b/dbm/src/h_page.c
deleted file mode 100644
index aa82b4ad4..000000000
--- a/dbm/src/h_page.c
+++ /dev/null
@@ -1,1237 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(unix)
-#define MY_LSEEK lseek
-#else
-#define MY_LSEEK new_lseek
-extern long new_lseek(int fd, long pos, int start);
-#endif
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hash_page.c 8.7 (Berkeley) 8/16/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-/*
- * PACKAGE: hashing
- *
- * DESCRIPTION:
- * Page manipulation for hashing package.
- *
- * ROUTINES:
- *
- * External
- * __get_page
- * __add_ovflpage
- * Internal
- * overflow_page
- * open_temp
- */
-#ifndef macintosh
-#include <sys/types.h>
-#endif
-
-#include <errno.h>
-#ifndef macintosh
-#include <fcntl.h>
-#endif
-#include <signal.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2_VACPP)
-#include <unistd.h>
-#endif
-
-#include <assert.h>
-
-#include "mcom_db.h"
-#include "hash.h"
-#include "page.h"
-/* #include "extern.h" */
-
-static uint32 *fetch_bitmap __P((HTAB *, uint32));
-static uint32 first_free __P((uint32));
-static int open_temp __P((HTAB *));
-static uint16 overflow_page __P((HTAB *));
-static void squeeze_key __P((uint16 *, const DBT *, const DBT *));
-static int ugly_split
- __P((HTAB *, uint32, BUFHEAD *, BUFHEAD *, int, int));
-
-#define PAGE_INIT(P) { \
- ((uint16 *)(P))[0] = 0; \
- ((uint16 *)(P))[1] = hashp->BSIZE - 3 * sizeof(uint16); \
- ((uint16 *)(P))[2] = hashp->BSIZE; \
-}
-
-/* implement a new lseek using lseek that
- * writes zero's when extending a file
- * beyond the end.
- */
-long new_lseek(int fd, long offset, int origin)
-{
- long cur_pos=0;
- long end_pos=0;
- long seek_pos=0;
-
- if(origin == SEEK_CUR)
- {
- if(offset < 1)
- return(lseek(fd, offset, SEEK_CUR));
-
- cur_pos = lseek(fd, 0, SEEK_CUR);
-
- if(cur_pos < 0)
- return(cur_pos);
- }
-
- end_pos = lseek(fd, 0, SEEK_END);
- if(end_pos < 0)
- return(end_pos);
-
- if(origin == SEEK_SET)
- seek_pos = offset;
- else if(origin == SEEK_CUR)
- seek_pos = cur_pos + offset;
- else if(origin == SEEK_END)
- seek_pos = end_pos + offset;
- else
- {
- assert(0);
- return(-1);
- }
-
- /* the seek position desired is before the
- * end of the file. We don't need
- * to do anything special except the seek.
- */
- if(seek_pos <= end_pos)
- return(lseek(fd, seek_pos, SEEK_SET));
-
- /* the seek position is beyond the end of the
- * file. Write zero's to the end.
- *
- * we are already at the end of the file so
- * we just need to "write()" zeros for the
- * difference between seek_pos-end_pos and
- * then seek to the position to finish
- * the call
- */
- {
- char buffer[1024];
- long len = seek_pos-end_pos;
- memset(&buffer, 0, 1024);
- while(len > 0)
- {
- write(fd, (char*)&buffer, (size_t)(1024 > len ? len : 1024));
- len -= 1024;
- }
- return(lseek(fd, seek_pos, SEEK_SET));
- }
-
-}
-
-/*
- * This is called AFTER we have verified that there is room on the page for
- * the pair (PAIRFITS has returned true) so we go right ahead and start moving
- * stuff on.
- */
-static void
-putpair(char *p, const DBT *key, DBT * val)
-{
- register uint16 *bp, n, off;
-
- bp = (uint16 *)p;
-
- /* Enter the key first. */
- n = bp[0];
-
- off = OFFSET(bp) - key->size;
- memmove(p + off, key->data, key->size);
- bp[++n] = off;
-
- /* Now the data. */
- off -= val->size;
- memmove(p + off, val->data, val->size);
- bp[++n] = off;
-
- /* Adjust page info. */
- bp[0] = n;
- bp[n + 1] = off - ((n + 3) * sizeof(uint16));
- bp[n + 2] = off;
-}
-
-/*
- * Returns:
- * 0 OK
- * -1 error
- */
-extern int
-__delpair(HTAB *hashp, BUFHEAD *bufp, int ndx)
-{
- register uint16 *bp, newoff;
- register int n;
- uint16 pairlen;
-
- bp = (uint16 *)bufp->page;
- n = bp[0];
-
- if (bp[ndx + 1] < REAL_KEY)
- return (__big_delete(hashp, bufp));
- if (ndx != 1)
- newoff = bp[ndx - 1];
- else
- newoff = hashp->BSIZE;
- pairlen = newoff - bp[ndx + 1];
-
- if (ndx != (n - 1)) {
- /* Hard Case -- need to shuffle keys */
- register int i;
- register char *src = bufp->page + (int)OFFSET(bp);
- uint32 dst_offset = (uint32)OFFSET(bp) + (uint32)pairlen;
- register char *dst = bufp->page + dst_offset;
- uint32 length = bp[ndx + 1] - OFFSET(bp);
-
- /*
- * +-----------+XXX+---------+XXX+---------+---------> +infinity
- * | | | |
- * 0 src_offset dst_offset BSIZE
- *
- * Dst_offset is > src_offset, so if src_offset were bad, dst_offset
- * would be too, therefore we check only dst_offset.
- *
- * If dst_offset is >= BSIZE, either OFFSET(bp), or pairlen, or both
- * is corrupted.
- *
- * Once we know dst_offset is < BSIZE, we can subtract it from BSIZE
- * to get an upper bound on length.
- */
- if(dst_offset > (uint32)hashp->BSIZE)
- return(DATABASE_CORRUPTED_ERROR);
-
- if(length > (uint32)(hashp->BSIZE - dst_offset))
- return(DATABASE_CORRUPTED_ERROR);
-
- memmove(dst, src, length);
-
- /* Now adjust the pointers */
- for (i = ndx + 2; i <= n; i += 2) {
- if (bp[i + 1] == OVFLPAGE) {
- bp[i - 2] = bp[i];
- bp[i - 1] = bp[i + 1];
- } else {
- bp[i - 2] = bp[i] + pairlen;
- bp[i - 1] = bp[i + 1] + pairlen;
- }
- }
- }
- /* Finally adjust the page data */
- bp[n] = OFFSET(bp) + pairlen;
- bp[n - 1] = bp[n + 1] + pairlen + 2 * sizeof(uint16);
- bp[0] = n - 2;
- hashp->NKEYS--;
-
- bufp->flags |= BUF_MOD;
- return (0);
-}
-/*
- * Returns:
- * 0 ==> OK
- * -1 ==> Error
- */
-extern int
-__split_page(HTAB *hashp, uint32 obucket, uint32 nbucket)
-{
- register BUFHEAD *new_bufp, *old_bufp;
- register uint16 *ino;
- register uint16 *tmp_uint16_array;
- register char *np;
- DBT key, val;
- uint16 n, ndx;
- int retval;
- uint16 copyto, diff, moved;
- size_t off;
- char *op;
-
- copyto = (uint16)hashp->BSIZE;
- off = (uint16)hashp->BSIZE;
- old_bufp = __get_buf(hashp, obucket, NULL, 0);
- if (old_bufp == NULL)
- return (-1);
- new_bufp = __get_buf(hashp, nbucket, NULL, 0);
- if (new_bufp == NULL)
- return (-1);
-
- old_bufp->flags |= (BUF_MOD | BUF_PIN);
- new_bufp->flags |= (BUF_MOD | BUF_PIN);
-
- ino = (uint16 *)(op = old_bufp->page);
- np = new_bufp->page;
-
- moved = 0;
-
- for (n = 1, ndx = 1; n < ino[0]; n += 2) {
- if (ino[n + 1] < REAL_KEY) {
- retval = ugly_split(hashp, obucket, old_bufp, new_bufp,
- (int)copyto, (int)moved);
- old_bufp->flags &= ~BUF_PIN;
- new_bufp->flags &= ~BUF_PIN;
- return (retval);
-
- }
- key.data = (uint8 *)op + ino[n];
-
- /* check here for ino[n] being greater than
- * off. If it is then the database has
- * been corrupted.
- */
- if(ino[n] > off)
- return(DATABASE_CORRUPTED_ERROR);
-
- key.size = off - ino[n];
-
-#ifdef DEBUG
- /* make sure the size is positive */
- assert(((int)key.size) > -1);
-#endif
-
- if (__call_hash(hashp, (char *)key.data, key.size) == obucket) {
- /* Don't switch page */
- diff = copyto - off;
- if (diff) {
- copyto = ino[n + 1] + diff;
- memmove(op + copyto, op + ino[n + 1],
- off - ino[n + 1]);
- ino[ndx] = copyto + ino[n] - ino[n + 1];
- ino[ndx + 1] = copyto;
- } else
- copyto = ino[n + 1];
- ndx += 2;
- } else {
- /* Switch page */
- val.data = (uint8 *)op + ino[n + 1];
- val.size = ino[n] - ino[n + 1];
-
- /* if the pair doesn't fit something is horribly
- * wrong. LJM
- */
- tmp_uint16_array = (uint16*)np;
- if(!PAIRFITS(tmp_uint16_array, &key, &val))
- return(DATABASE_CORRUPTED_ERROR);
-
- putpair(np, &key, &val);
- moved += 2;
- }
-
- off = ino[n + 1];
- }
-
- /* Now clean up the page */
- ino[0] -= moved;
- FREESPACE(ino) = copyto - sizeof(uint16) * (ino[0] + 3);
- OFFSET(ino) = copyto;
-
-#ifdef DEBUG3
- (void)fprintf(stderr, "split %d/%d\n",
- ((uint16 *)np)[0] / 2,
- ((uint16 *)op)[0] / 2);
-#endif
- /* unpin both pages */
- old_bufp->flags &= ~BUF_PIN;
- new_bufp->flags &= ~BUF_PIN;
- return (0);
-}
-
-/*
- * Called when we encounter an overflow or big key/data page during split
- * handling. This is special cased since we have to begin checking whether
- * the key/data pairs fit on their respective pages and because we may need
- * overflow pages for both the old and new pages.
- *
- * The first page might be a page with regular key/data pairs in which case
- * we have a regular overflow condition and just need to go on to the next
- * page or it might be a big key/data pair in which case we need to fix the
- * big key/data pair.
- *
- * Returns:
- * 0 ==> success
- * -1 ==> failure
- */
-
-/* the maximum number of loops we will allow UGLY split to chew
- * on before we assume the database is corrupted and throw it
- * away.
- */
-#define MAX_UGLY_SPLIT_LOOPS 10000
-
-static int
-ugly_split(HTAB *hashp, uint32 obucket, BUFHEAD *old_bufp,
- BUFHEAD *new_bufp,/* Same as __split_page. */ int copyto, int moved)
- /* int copyto; First byte on page which contains key/data values. */
- /* int moved; Number of pairs moved to new page. */
-{
- register BUFHEAD *bufp; /* Buffer header for ino */
- register uint16 *ino; /* Page keys come off of */
- register uint16 *np; /* New page */
- register uint16 *op; /* Page keys go on to if they aren't moving */
- uint32 loop_detection=0;
-
- BUFHEAD *last_bfp; /* Last buf header OVFL needing to be freed */
- DBT key, val;
- SPLIT_RETURN ret;
- uint16 n, off, ov_addr, scopyto;
- char *cino; /* Character value of ino */
- int status;
-
- bufp = old_bufp;
- ino = (uint16 *)old_bufp->page;
- np = (uint16 *)new_bufp->page;
- op = (uint16 *)old_bufp->page;
- last_bfp = NULL;
- scopyto = (uint16)copyto; /* ANSI */
-
- n = ino[0] - 1;
- while (n < ino[0]) {
-
-
- /* this function goes nuts sometimes and never returns.
- * I havent found the problem yet but I need a solution
- * so if we loop too often we assume a database curruption error
- * :LJM
- */
- loop_detection++;
-
- if(loop_detection > MAX_UGLY_SPLIT_LOOPS)
- return DATABASE_CORRUPTED_ERROR;
-
- if (ino[2] < REAL_KEY && ino[2] != OVFLPAGE) {
- if ((status = __big_split(hashp, old_bufp,
- new_bufp, bufp, bufp->addr, obucket, &ret)))
- return (status);
- old_bufp = ret.oldp;
- if (!old_bufp)
- return (-1);
- op = (uint16 *)old_bufp->page;
- new_bufp = ret.newp;
- if (!new_bufp)
- return (-1);
- np = (uint16 *)new_bufp->page;
- bufp = ret.nextp;
- if (!bufp)
- return (0);
- cino = (char *)bufp->page;
- ino = (uint16 *)cino;
- last_bfp = ret.nextp;
- } else if (ino[n + 1] == OVFLPAGE) {
- ov_addr = ino[n];
- /*
- * Fix up the old page -- the extra 2 are the fields
- * which contained the overflow information.
- */
- ino[0] -= (moved + 2);
- FREESPACE(ino) =
- scopyto - sizeof(uint16) * (ino[0] + 3);
- OFFSET(ino) = scopyto;
-
- bufp = __get_buf(hashp, ov_addr, bufp, 0);
- if (!bufp)
- return (-1);
-
- ino = (uint16 *)bufp->page;
- n = 1;
- scopyto = hashp->BSIZE;
- moved = 0;
-
- if (last_bfp)
- __free_ovflpage(hashp, last_bfp);
- last_bfp = bufp;
- }
- /* Move regular sized pairs of there are any */
- off = hashp->BSIZE;
- for (n = 1; (n < ino[0]) && (ino[n + 1] >= REAL_KEY); n += 2) {
- cino = (char *)ino;
- key.data = (uint8 *)cino + ino[n];
- key.size = off - ino[n];
- val.data = (uint8 *)cino + ino[n + 1];
- val.size = ino[n] - ino[n + 1];
- off = ino[n + 1];
-
- if (__call_hash(hashp, (char*)key.data, key.size) == obucket) {
- /* Keep on old page */
- if (PAIRFITS(op, (&key), (&val)))
- putpair((char *)op, &key, &val);
- else {
- old_bufp =
- __add_ovflpage(hashp, old_bufp);
- if (!old_bufp)
- return (-1);
- op = (uint16 *)old_bufp->page;
- putpair((char *)op, &key, &val);
- }
- old_bufp->flags |= BUF_MOD;
- } else {
- /* Move to new page */
- if (PAIRFITS(np, (&key), (&val)))
- putpair((char *)np, &key, &val);
- else {
- new_bufp =
- __add_ovflpage(hashp, new_bufp);
- if (!new_bufp)
- return (-1);
- np = (uint16 *)new_bufp->page;
- putpair((char *)np, &key, &val);
- }
- new_bufp->flags |= BUF_MOD;
- }
- }
- }
- if (last_bfp)
- __free_ovflpage(hashp, last_bfp);
- return (0);
-}
-
-/*
- * Add the given pair to the page
- *
- * Returns:
- * 0 ==> OK
- * 1 ==> failure
- */
-extern int
-__addel(HTAB *hashp, BUFHEAD *bufp, const DBT *key, const DBT * val)
-{
- register uint16 *bp, *sop;
- int do_expand;
-
- bp = (uint16 *)bufp->page;
- do_expand = 0;
- while (bp[0] && (bp[2] < REAL_KEY || bp[bp[0]] < REAL_KEY))
- /* Exception case */
- if (bp[2] == FULL_KEY_DATA && bp[0] == 2)
- /* This is the last page of a big key/data pair
- and we need to add another page */
- break;
- else if (bp[2] < REAL_KEY && bp[bp[0]] != OVFLPAGE) {
- bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!bufp)
- {
-#ifdef DEBUG
- assert(0);
-#endif
- return (-1);
- }
- bp = (uint16 *)bufp->page;
- } else
- /* Try to squeeze key on this page */
- if (FREESPACE(bp) > PAIRSIZE(key, val)) {
- {
- squeeze_key(bp, key, val);
-
- /* LJM: I added this because I think it was
- * left out on accident.
- * if this isn't incremented nkeys will not
- * be the actual number of keys in the db.
- */
- hashp->NKEYS++;
- return (0);
- }
- } else {
- bufp = __get_buf(hashp, bp[bp[0] - 1], bufp, 0);
- if (!bufp)
- {
-#ifdef DEBUG
- assert(0);
-#endif
- return (-1);
- }
- bp = (uint16 *)bufp->page;
- }
-
- if (PAIRFITS(bp, key, val))
- putpair(bufp->page, key, (DBT *)val);
- else {
- do_expand = 1;
- bufp = __add_ovflpage(hashp, bufp);
- if (!bufp)
- {
-#ifdef DEBUG
- assert(0);
-#endif
- return (-1);
- }
- sop = (uint16 *)bufp->page;
-
- if (PAIRFITS(sop, key, val))
- putpair((char *)sop, key, (DBT *)val);
- else
- if (__big_insert(hashp, bufp, key, val))
- {
-#ifdef DEBUG
- assert(0);
-#endif
- return (-1);
- }
- }
- bufp->flags |= BUF_MOD;
- /*
- * If the average number of keys per bucket exceeds the fill factor,
- * expand the table.
- */
- hashp->NKEYS++;
- if (do_expand ||
- (hashp->NKEYS / (hashp->MAX_BUCKET + 1) > hashp->FFACTOR))
- return (__expand_table(hashp));
- return (0);
-}
-
-/*
- *
- * Returns:
- * pointer on success
- * NULL on error
- */
-extern BUFHEAD *
-__add_ovflpage(HTAB *hashp, BUFHEAD *bufp)
-{
- register uint16 *sp;
- uint16 ndx, ovfl_num;
-#ifdef DEBUG1
- int tmp1, tmp2;
-#endif
- sp = (uint16 *)bufp->page;
-
- /* Check if we are dynamically determining the fill factor */
- if (hashp->FFACTOR == DEF_FFACTOR) {
- hashp->FFACTOR = sp[0] >> 1;
- if (hashp->FFACTOR < MIN_FFACTOR)
- hashp->FFACTOR = MIN_FFACTOR;
- }
- bufp->flags |= BUF_MOD;
- ovfl_num = overflow_page(hashp);
-#ifdef DEBUG1
- tmp1 = bufp->addr;
- tmp2 = bufp->ovfl ? bufp->ovfl->addr : 0;
-#endif
- if (!ovfl_num || !(bufp->ovfl = __get_buf(hashp, ovfl_num, bufp, 1)))
- return (NULL);
- bufp->ovfl->flags |= BUF_MOD;
-#ifdef DEBUG1
- (void)fprintf(stderr, "ADDOVFLPAGE: %d->ovfl was %d is now %d\n",
- tmp1, tmp2, bufp->ovfl->addr);
-#endif
- ndx = sp[0];
- /*
- * Since a pair is allocated on a page only if there's room to add
- * an overflow page, we know that the OVFL information will fit on
- * the page.
- */
- sp[ndx + 4] = OFFSET(sp);
- sp[ndx + 3] = FREESPACE(sp) - OVFLSIZE;
- sp[ndx + 1] = ovfl_num;
- sp[ndx + 2] = OVFLPAGE;
- sp[0] = ndx + 2;
-#ifdef HASH_STATISTICS
- hash_overflows++;
-#endif
- return (bufp->ovfl);
-}
-
-/*
- * Returns:
- * 0 indicates SUCCESS
- * -1 indicates FAILURE
- */
-extern int
-__get_page(HTAB *hashp,
- char * p,
- uint32 bucket,
- int is_bucket,
- int is_disk,
- int is_bitmap)
-{
- register int fd, page;
- size_t size;
- int rsize;
- uint16 *bp;
-
- fd = hashp->fp;
- size = hashp->BSIZE;
-
- if ((fd == -1) || !is_disk) {
- PAGE_INIT(p);
- return (0);
- }
- if (is_bucket)
- page = BUCKET_TO_PAGE(bucket);
- else
- page = OADDR_TO_PAGE(bucket);
- if ((MY_LSEEK(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
- ((rsize = read(fd, p, size)) == -1))
- return (-1);
-
- bp = (uint16 *)p;
- if (!rsize)
- bp[0] = 0; /* We hit the EOF, so initialize a new page */
- else
- if ((unsigned)rsize != size) {
- errno = EFTYPE;
- return (-1);
- }
-
- if (!is_bitmap && !bp[0]) {
- PAGE_INIT(p);
- } else {
-
-#ifdef DEBUG
- if(BYTE_ORDER == LITTLE_ENDIAN)
- {
- int is_little_endian;
- is_little_endian = BYTE_ORDER;
- }
- else if(BYTE_ORDER == BIG_ENDIAN)
- {
- int is_big_endian;
- is_big_endian = BYTE_ORDER;
- }
- else
- {
- assert(0);
- }
-#endif
-
- if (hashp->LORDER != BYTE_ORDER) {
- register int i, max;
-
- if (is_bitmap) {
- max = hashp->BSIZE >> 2; /* divide by 4 */
- for (i = 0; i < max; i++)
- M_32_SWAP(((int *)p)[i]);
- } else {
- M_16_SWAP(bp[0]);
- max = bp[0] + 2;
-
- /* bound the size of max by
- * the maximum number of entries
- * in the array
- */
- if((unsigned)max > (size / sizeof(uint16)))
- return(DATABASE_CORRUPTED_ERROR);
-
- /* do the byte order swap
- */
- for (i = 1; i <= max; i++)
- M_16_SWAP(bp[i]);
- }
- }
-
- /* check the validity of the page here
- * (after doing byte order swaping if necessary)
- */
- if(!is_bitmap && bp[0] != 0)
- {
- uint16 num_keys = bp[0];
- uint16 offset;
- uint16 i;
-
- /* bp[0] is supposed to be the number of
- * entries currently in the page. If
- * bp[0] is too large (larger than the whole
- * page) then the page is corrupted
- */
- if(bp[0] > (size / sizeof(uint16)))
- return(DATABASE_CORRUPTED_ERROR);
-
- /* bound free space */
- if(FREESPACE(bp) > size)
- return(DATABASE_CORRUPTED_ERROR);
-
- /* check each key and data offset to make
- * sure they are all within bounds they
- * should all be less than the previous
- * offset as well.
- */
- offset = size;
- for(i=1 ; i <= num_keys; i+=2)
- {
- /* ignore overflow pages etc. */
- if(bp[i+1] >= REAL_KEY)
- {
-
- if(bp[i] > offset || bp[i+1] > bp[i])
- return(DATABASE_CORRUPTED_ERROR);
-
- offset = bp[i+1];
- }
- else
- {
- /* there are no other valid keys after
- * seeing a non REAL_KEY
- */
- break;
- }
- }
- }
- }
- return (0);
-}
-
-/*
- * Write page p to disk
- *
- * Returns:
- * 0 ==> OK
- * -1 ==>failure
- */
-extern int
-__put_page(HTAB *hashp, char *p, uint32 bucket, int is_bucket, int is_bitmap)
-{
- register int fd, page;
- size_t size;
- int wsize;
-
- size = hashp->BSIZE;
- if ((hashp->fp == -1) && open_temp(hashp))
- return (-1);
- fd = hashp->fp;
-
- if (hashp->LORDER != BYTE_ORDER) {
- register int i;
- register int max;
-
- if (is_bitmap) {
- max = hashp->BSIZE >> 2; /* divide by 4 */
- for (i = 0; i < max; i++)
- M_32_SWAP(((int *)p)[i]);
- } else {
- max = ((uint16 *)p)[0] + 2;
-
- /* bound the size of max by
- * the maximum number of entries
- * in the array
- */
- if((unsigned)max > (size / sizeof(uint16)))
- return(DATABASE_CORRUPTED_ERROR);
-
- for (i = 0; i <= max; i++)
- M_16_SWAP(((uint16 *)p)[i]);
-
- }
- }
-
- if (is_bucket)
- page = BUCKET_TO_PAGE(bucket);
- else
- page = OADDR_TO_PAGE(bucket);
- if ((MY_LSEEK(fd, (off_t)page << hashp->BSHIFT, SEEK_SET) == -1) ||
- ((wsize = write(fd, p, size)) == -1))
- /* Errno is set */
- return (-1);
- if ((unsigned)wsize != size) {
- errno = EFTYPE;
- return (-1);
- }
-
- /* put the page back the way it was so that it isn't byteswapped
- * if it remains in memory - LJM
- */
- if (hashp->LORDER != BYTE_ORDER) {
- register int i;
- register int max;
-
- if (is_bitmap) {
- max = hashp->BSIZE >> 2; /* divide by 4 */
- for (i = 0; i < max; i++)
- M_32_SWAP(((int *)p)[i]);
- } else {
- uint16 *bp = (uint16 *)p;
-
- M_16_SWAP(bp[0]);
- max = bp[0] + 2;
-
- /* no need to bound the size if max again
- * since it was done already above
- */
-
- /* do the byte order re-swap
- */
- for (i = 1; i <= max; i++)
- M_16_SWAP(bp[i]);
- }
- }
-
- return (0);
-}
-
-#define BYTE_MASK ((1 << INT_BYTE_SHIFT) -1)
-/*
- * Initialize a new bitmap page. Bitmap pages are left in memory
- * once they are read in.
- */
-extern int
-__ibitmap(HTAB *hashp, int pnum, int nbits, int ndx)
-{
- uint32 *ip;
- size_t clearbytes, clearints;
-
- if ((ip = (uint32 *)malloc((size_t)hashp->BSIZE)) == NULL)
- return (1);
- hashp->nmaps++;
- clearints = ((nbits - 1) >> INT_BYTE_SHIFT) + 1;
- clearbytes = clearints << INT_TO_BYTE;
- (void)memset((char *)ip, 0, clearbytes);
- (void)memset(((char *)ip) + clearbytes, 0xFF,
- hashp->BSIZE - clearbytes);
- ip[clearints - 1] = ALL_SET << (nbits & BYTE_MASK);
- SETBIT(ip, 0);
- hashp->BITMAPS[ndx] = (uint16)pnum;
- hashp->mapp[ndx] = ip;
- return (0);
-}
-
-static uint32
-first_free(uint32 map)
-{
- register uint32 i, mask;
-
- mask = 0x1;
- for (i = 0; i < BITS_PER_MAP; i++) {
- if (!(mask & map))
- return (i);
- mask = mask << 1;
- }
- return (i);
-}
-
-static uint16
-overflow_page(HTAB *hashp)
-{
- register uint32 *freep=NULL;
- register int max_free, offset, splitnum;
- uint16 addr;
- uint32 i;
- int bit, first_page, free_bit, free_page, in_use_bits, j;
-#ifdef DEBUG2
- int tmp1, tmp2;
-#endif
- splitnum = hashp->OVFL_POINT;
- max_free = hashp->SPARES[splitnum];
-
- free_page = (max_free - 1) >> (hashp->BSHIFT + BYTE_SHIFT);
- free_bit = (max_free - 1) & ((hashp->BSIZE << BYTE_SHIFT) - 1);
-
- /* Look through all the free maps to find the first free block */
- first_page = hashp->LAST_FREED >>(hashp->BSHIFT + BYTE_SHIFT);
- for ( i = first_page; i <= (unsigned)free_page; i++ ) {
- if (!(freep = (uint32 *)hashp->mapp[i]) &&
- !(freep = fetch_bitmap(hashp, i)))
- return (0);
- if (i == (unsigned)free_page)
- in_use_bits = free_bit;
- else
- in_use_bits = (hashp->BSIZE << BYTE_SHIFT) - 1;
-
- if (i == (unsigned)first_page) {
- bit = hashp->LAST_FREED &
- ((hashp->BSIZE << BYTE_SHIFT) - 1);
- j = bit / BITS_PER_MAP;
- bit = bit & ~(BITS_PER_MAP - 1);
- } else {
- bit = 0;
- j = 0;
- }
- for (; bit <= in_use_bits; j++, bit += BITS_PER_MAP)
- if (freep[j] != ALL_SET)
- goto found;
- }
-
- /* No Free Page Found */
- hashp->LAST_FREED = hashp->SPARES[splitnum];
- hashp->SPARES[splitnum]++;
- offset = hashp->SPARES[splitnum] -
- (splitnum ? hashp->SPARES[splitnum - 1] : 0);
-
-#define OVMSG "HASH: Out of overflow pages. Increase page size\n"
- if (offset > SPLITMASK) {
- if (++splitnum >= NCACHED) {
-#ifndef macintosh
- (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
-#endif
- return (0);
- }
- hashp->OVFL_POINT = splitnum;
- hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
- hashp->SPARES[splitnum-1]--;
- offset = 1;
- }
-
- /* Check if we need to allocate a new bitmap page */
- if (free_bit == (hashp->BSIZE << BYTE_SHIFT) - 1) {
- free_page++;
- if (free_page >= NCACHED) {
-#ifndef macintosh
- (void)write(STDERR_FILENO, OVMSG, sizeof(OVMSG) - 1);
-#endif
- return (0);
- }
- /*
- * This is tricky. The 1 indicates that you want the new page
- * allocated with 1 clear bit. Actually, you are going to
- * allocate 2 pages from this map. The first is going to be
- * the map page, the second is the overflow page we were
- * looking for. The init_bitmap routine automatically, sets
- * the first bit of itself to indicate that the bitmap itself
- * is in use. We would explicitly set the second bit, but
- * don't have to if we tell init_bitmap not to leave it clear
- * in the first place.
- */
- if (__ibitmap(hashp,
- (int)OADDR_OF(splitnum, offset), 1, free_page))
- return (0);
- hashp->SPARES[splitnum]++;
-#ifdef DEBUG2
- free_bit = 2;
-#endif
- offset++;
- if (offset > SPLITMASK) {
- if (++splitnum >= NCACHED) {
-#ifndef macintosh
- (void)write(STDERR_FILENO, OVMSG,
- sizeof(OVMSG) - 1);
-#endif
- return (0);
- }
- hashp->OVFL_POINT = splitnum;
- hashp->SPARES[splitnum] = hashp->SPARES[splitnum-1];
- hashp->SPARES[splitnum-1]--;
- offset = 0;
- }
- } else {
- /*
- * Free_bit addresses the last used bit. Bump it to address
- * the first available bit.
- */
- free_bit++;
- SETBIT(freep, free_bit);
- }
-
- /* Calculate address of the new overflow page */
- addr = OADDR_OF(splitnum, offset);
-#ifdef DEBUG2
- (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
- addr, free_bit, free_page);
-#endif
- return (addr);
-
-found:
- bit = bit + first_free(freep[j]);
- SETBIT(freep, bit);
-#ifdef DEBUG2
- tmp1 = bit;
- tmp2 = i;
-#endif
- /*
- * Bits are addressed starting with 0, but overflow pages are addressed
- * beginning at 1. Bit is a bit addressnumber, so we need to increment
- * it to convert it to a page number.
- */
- bit = 1 + bit + (i * (hashp->BSIZE << BYTE_SHIFT));
- if (bit >= hashp->LAST_FREED)
- hashp->LAST_FREED = bit - 1;
-
- /* Calculate the split number for this page */
- for (i = 0; (i < (unsigned)splitnum) && (bit > hashp->SPARES[i]); i++) {}
- offset = (i ? bit - hashp->SPARES[i - 1] : bit);
- if (offset >= SPLITMASK)
- return (0); /* Out of overflow pages */
- addr = OADDR_OF(i, offset);
-#ifdef DEBUG2
- (void)fprintf(stderr, "OVERFLOW_PAGE: ADDR: %d BIT: %d PAGE %d\n",
- addr, tmp1, tmp2);
-#endif
-
- /* Allocate and return the overflow page */
- return (addr);
-}
-
-/*
- * Mark this overflow page as free.
- */
-extern void
-__free_ovflpage(HTAB *hashp, BUFHEAD *obufp)
-{
- uint16 addr;
- uint32 *freep;
- uint32 bit_address, free_page, free_bit;
- uint16 ndx;
-
- if(!obufp || !obufp->addr)
- return;
-
- addr = obufp->addr;
-#ifdef DEBUG1
- (void)fprintf(stderr, "Freeing %d\n", addr);
-#endif
- ndx = (((uint16)addr) >> SPLITSHIFT);
- bit_address =
- (ndx ? hashp->SPARES[ndx - 1] : 0) + (addr & SPLITMASK) - 1;
- if (bit_address < (unsigned)hashp->LAST_FREED)
- hashp->LAST_FREED = bit_address;
- free_page = (bit_address >> (hashp->BSHIFT + BYTE_SHIFT));
- free_bit = bit_address & ((hashp->BSIZE << BYTE_SHIFT) - 1);
-
- if (!(freep = hashp->mapp[free_page]))
- freep = fetch_bitmap(hashp, free_page);
-
-#ifdef DEBUG
- /*
- * This had better never happen. It means we tried to read a bitmap
- * that has already had overflow pages allocated off it, and we
- * failed to read it from the file.
- */
- if (!freep)
- {
- assert(0);
- return;
- }
-#endif
- CLRBIT(freep, free_bit);
-#ifdef DEBUG2
- (void)fprintf(stderr, "FREE_OVFLPAGE: ADDR: %d BIT: %d PAGE %d\n",
- obufp->addr, free_bit, free_page);
-#endif
- __reclaim_buf(hashp, obufp);
-}
-
-/*
- * Returns:
- * 0 success
- * -1 failure
- */
-static int
-open_temp(HTAB *hashp)
-{
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2)
- sigset_t set, oset;
-#endif
- static char namestr[] = "_hashXXXXXX";
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2)
- /* Block signals; make sure file goes away at process exit. */
- (void)sigfillset(&set);
- (void)sigprocmask(SIG_BLOCK, &set, &oset);
-#endif
-
- if ((hashp->fp = mkstemp(namestr)) != -1) {
- (void)unlink(namestr);
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2)
- (void)fcntl(hashp->fp, F_SETFD, 1);
-#endif
- }
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2)
- (void)sigprocmask(SIG_SETMASK, &oset, (sigset_t *)NULL);
-#endif
- return (hashp->fp != -1 ? 0 : -1);
-}
-
-/*
- * We have to know that the key will fit, but the last entry on the page is
- * an overflow pair, so we need to shift things.
- */
-static void
-squeeze_key(uint16 *sp, const DBT * key, const DBT * val)
-{
- register char *p;
- uint16 free_space, n, off, pageno;
-
- p = (char *)sp;
- n = sp[0];
- free_space = FREESPACE(sp);
- off = OFFSET(sp);
-
- pageno = sp[n - 1];
- off -= key->size;
- sp[n - 1] = off;
- memmove(p + off, key->data, key->size);
- off -= val->size;
- sp[n] = off;
- memmove(p + off, val->data, val->size);
- sp[0] = n + 2;
- sp[n + 1] = pageno;
- sp[n + 2] = OVFLPAGE;
- FREESPACE(sp) = free_space - PAIRSIZE(key, val);
- OFFSET(sp) = off;
-}
-
-static uint32 *
-fetch_bitmap(HTAB *hashp, uint32 ndx)
-{
- if (ndx >= (unsigned)hashp->nmaps)
- return (NULL);
- if ((hashp->mapp[ndx] = (uint32 *)malloc((size_t)hashp->BSIZE)) == NULL)
- return (NULL);
- if (__get_page(hashp,
- (char *)hashp->mapp[ndx], hashp->BITMAPS[ndx], 0, 1, 1)) {
- free(hashp->mapp[ndx]);
- hashp->mapp[ndx] = NULL; /* NEW: 9-11-95 */
- return (NULL);
- }
- return (hashp->mapp[ndx]);
-}
-
-#ifdef DEBUG4
-int
-print_chain(int addr)
-{
- BUFHEAD *bufp;
- short *bp, oaddr;
-
- (void)fprintf(stderr, "%d ", addr);
- bufp = __get_buf(hashp, addr, NULL, 0);
- bp = (short *)bufp->page;
- while (bp[0] && ((bp[bp[0]] == OVFLPAGE) ||
- ((bp[0] > 2) && bp[2] < REAL_KEY))) {
- oaddr = bp[bp[0] - 1];
- (void)fprintf(stderr, "%d ", (int)oaddr);
- bufp = __get_buf(hashp, (int)oaddr, bufp, 0);
- bp = (short *)bufp->page;
- }
- (void)fprintf(stderr, "\n");
-}
-#endif
diff --git a/dbm/src/hash.c b/dbm/src/hash.c
deleted file mode 100644
index be08567fc..000000000
--- a/dbm/src/hash.c
+++ /dev/null
@@ -1,1188 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hash.c 8.9 (Berkeley) 6/16/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2_VACPP)
-#include <sys/param.h>
-#endif
-
-#if !defined(macintosh)
-#ifdef XP_OS2_EMX
-#include <sys/types.h>
-#include "xp_mcom.h" /* For strdup. */
-#endif
-#include <sys/stat.h>
-#endif
-
-#include <errno.h>
-#ifdef macintosh
-#include <unix.h>
-#else
-#include <fcntl.h>
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2_VACPP)
-#include <unistd.h>
-#endif
-
-#ifdef XP_OS2_VACPP
-#include "types.h"
-#define EPERM SOCEPERM
-#endif
-
-#ifdef DEBUG
-#include <assert.h>
-#endif
-
-#include "mcom_db.h"
-#include "hash.h"
-#include "page.h"
-
-/*
-#include "extern.h"
-*/
-static int alloc_segs __P((HTAB *, int));
-static int flush_meta __P((HTAB *));
-static int hash_access __P((HTAB *, ACTION, DBT *, DBT *));
-static int hash_close __P((DB *));
-static int hash_delete __P((const DB *, const DBT *, uint));
-static int hash_fd __P((const DB *));
-static int hash_get __P((const DB *, const DBT *, DBT *, uint));
-static int hash_put __P((const DB *, DBT *, const DBT *, uint));
-static void *hash_realloc __P((SEGMENT **, size_t, size_t));
-static int hash_seq __P((const DB *, DBT *, DBT *, uint));
-static int hash_sync __P((const DB *, uint));
-static int hdestroy __P((HTAB *));
-static HTAB *init_hash __P((HTAB *, const char *, HASHINFO *));
-static int init_htab __P((HTAB *, int));
-#if BYTE_ORDER == LITTLE_ENDIAN
-static void swap_header __P((HTAB *));
-static void swap_header_copy __P((HASHHDR *, HASHHDR *));
-#endif
-
-/* Fast arithmetic, relying on powers of 2, */
-#define MOD(x, y) ((x) & ((y) - 1))
-
-#define RETURN_ERROR(ERR, LOC) { save_errno = ERR; goto LOC; }
-
-/* Return values */
-#define SUCCESS (0)
-#define DBM_ERROR (-1)
-#define ABNORMAL (1)
-
-#ifdef HASH_STATISTICS
-int hash_accesses, hash_collisions, hash_expansions, hash_overflows;
-#endif
-
-/* A new Lou (montulli@mozilla.com) routine.
- *
- * The database is screwed. Delete it by
- * making it a zero length file
- *
- * This zero's hashp so that the
- * database can't be accessed any more
- */
-static void
-__remove_database(DB *dbp)
-{
- HTAB *hashp = (HTAB *)dbp->internal;
- if (!hashp)
- return;
-
- if(hashp->fp != NO_FILE)
- close(hashp->fp);
- if(hashp->filename)
- unlink(hashp->filename);
- dbp->internal = NULL; /* zero the internal stuff */
-
-}
-
-/************************** INTERFACE ROUTINES ***************************/
-/* OPEN/CLOSE */
-
-
-extern DB *
-__hash_open(const char *file, int flags, int mode, const HASHINFO *info, int dflags)
-{
- HTAB *hashp=NULL;
- struct stat statbuf;
- DB *dbp;
- int bpages, hdrsize, new_table, nsegs, save_errno;
-
- if ((flags & O_ACCMODE) == O_WRONLY) {
- errno = EINVAL;
- RETURN_ERROR(ENOMEM, error0);
- }
-
- /* zero the statbuffer so that
- * we can check it for a non-zero
- * date to see if stat succeeded
- */
- memset(&statbuf, 0, sizeof(struct stat));
-
- if (!(hashp = (HTAB *)calloc(1, sizeof(HTAB))))
- RETURN_ERROR(ENOMEM, error0);
- hashp->fp = NO_FILE;
- if(file)
- hashp->filename = strdup(file);
-
- /*
- * Even if user wants write only, we need to be able to read
- * the actual file, so we need to open it read/write. But, the
- * field in the hashp structure needs to be accurate so that
- * we can check accesses.
- */
- hashp->flags = flags;
-
- new_table = 0;
- if (!file || (flags & O_TRUNC) || (stat(file, &statbuf) && (errno == ENOENT)))
- {
- if (errno == ENOENT)
- errno = 0; /* Just in case someone looks at errno */
- new_table = 1;
- }
- else if(statbuf.st_mtime && statbuf.st_size == 0)
- {
- /* check for a zero length file and delete it
- * if it exists
- */
- new_table = 1;
- }
-
- if (file) {
-
-#if defined(_WIN32) || defined(_WINDOWS) || defined (macintosh) || defined(XP_OS2_VACPP)
- if ((hashp->fp = DBFILE_OPEN(file, flags | O_BINARY, mode)) == -1)
- RETURN_ERROR(errno, error0);
-#else
- if ((hashp->fp = open(file, flags, mode)) == -1)
- RETURN_ERROR(errno, error0);
- (void)fcntl(hashp->fp, F_SETFD, 1);
-/* We can't use fcntl because of NFS bugs. SIGH */
-#if 0
- {
- struct flock fl;
- memset(&fl, 0, sizeof(fl));
- fl.l_type = F_WRLCK;
- if (fcntl(hashp->fp, F_SETLK, &fl) < 0) {
-#ifdef DEBUG
- fprintf(stderr, "unable to open %s because it's locked (flags=0x%x)\n", file, flags);
-#endif
- RETURN_ERROR(EACCES, error1);
- }
- }
-#endif
-
-#endif
- }
- if (new_table) {
- if (!init_hash(hashp, file, (HASHINFO *)info))
- RETURN_ERROR(errno, error1);
- } else {
- /* Table already exists */
- if (info && info->hash)
- hashp->hash = info->hash;
- else
- hashp->hash = __default_hash;
-
- hdrsize = read(hashp->fp, (char *)&hashp->hdr, sizeof(HASHHDR));
-#if BYTE_ORDER == LITTLE_ENDIAN
- swap_header(hashp);
-#endif
- if (hdrsize == -1)
- RETURN_ERROR(errno, error1);
- if (hdrsize != sizeof(HASHHDR))
- RETURN_ERROR(EFTYPE, error1);
- /* Verify file type, versions and hash function */
- if (hashp->MAGIC != HASHMAGIC)
- RETURN_ERROR(EFTYPE, error1);
-#define OLDHASHVERSION 1
- if (hashp->VERSION != HASHVERSION &&
- hashp->VERSION != OLDHASHVERSION)
- RETURN_ERROR(EFTYPE, error1);
- if (hashp->hash(CHARKEY, sizeof(CHARKEY)) != (unsigned)hashp->H_CHARKEY)
- RETURN_ERROR(EFTYPE, error1);
- if (hashp->NKEYS < 0) {
- /*
- ** OOPS. Old bad database from previously busted
- ** code. Blow it away.
- */
- close(hashp->fp);
- if (remove(file) < 0) {
-#if defined(DEBUG) && defined(XP_UNIX)
- fprintf(stderr,
- "WARNING: You have an old bad cache.db file"
- " '%s', and I couldn't remove it!\n", file);
-#endif
- } else {
-#if defined(DEBUG) && defined(XP_UNIX)
- fprintf(stderr,
- "WARNING: I blew away your %s file because"
- " it was bad due to a recently fixed bug\n",
- file);
-#endif
- }
- RETURN_ERROR(ENOENT, error0);
- }
-
- /*
- * Figure out how many segments we need. Max_Bucket is the
- * maximum bucket number, so the number of buckets is
- * max_bucket + 1.
- */
- nsegs = (hashp->MAX_BUCKET + 1 + hashp->SGSIZE - 1) /
- hashp->SGSIZE;
- hashp->nsegs = 0;
- if (alloc_segs(hashp, nsegs))
- /*
- * If alloc_segs fails, table will have been destroyed
- * and errno will have been set.
- */
- RETURN_ERROR(ENOMEM, error0);
- /* Read in bitmaps */
- bpages = (hashp->SPARES[hashp->OVFL_POINT] +
- (hashp->BSIZE << BYTE_SHIFT) - 1) >>
- (hashp->BSHIFT + BYTE_SHIFT);
-
- hashp->nmaps = bpages;
- (void)memset(&hashp->mapp[0], 0, bpages * sizeof(uint32 *));
- }
-
- /* Initialize Buffer Manager */
- if (info && info->cachesize)
- __buf_init(hashp, (int32) info->cachesize);
- else
- __buf_init(hashp, DEF_BUFSIZE);
-
- hashp->new_file = new_table;
-#ifdef macintosh
- hashp->save_file = file && !(hashp->flags & O_RDONLY);
-#else
- hashp->save_file = file && (hashp->flags & O_RDWR);
-#endif
- hashp->cbucket = -1;
- if (!(dbp = (DB *)malloc(sizeof(DB)))) {
- save_errno = errno;
- hdestroy(hashp);
- errno = save_errno;
- RETURN_ERROR(ENOMEM, error0);
- }
- dbp->internal = hashp;
- dbp->close = hash_close;
- dbp->del = hash_delete;
- dbp->fd = hash_fd;
- dbp->get = hash_get;
- dbp->put = hash_put;
- dbp->seq = hash_seq;
- dbp->sync = hash_sync;
- dbp->type = DB_HASH;
-
-#if 0
-#if defined(DEBUG) && !defined(_WINDOWS)
-{
-extern int MKLib_trace_flag;
-
- if(MKLib_trace_flag)
- (void)fprintf(stderr,
-"%s\n%s%lx\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%d\n%s%x\n%s%x\n%s%d\n%s%d\n",
- "init_htab:",
- "TABLE POINTER ", (unsigned long) hashp,
- "BUCKET SIZE ", hashp->BSIZE,
- "BUCKET SHIFT ", hashp->BSHIFT,
- "DIRECTORY SIZE ", hashp->DSIZE,
- "SEGMENT SIZE ", hashp->SGSIZE,
- "SEGMENT SHIFT ", hashp->SSHIFT,
- "FILL FACTOR ", hashp->FFACTOR,
- "MAX BUCKET ", hashp->MAX_BUCKET,
- "OVFL POINT ", hashp->OVFL_POINT,
- "LAST FREED ", hashp->LAST_FREED,
- "HIGH MASK ", hashp->HIGH_MASK,
- "LOW MASK ", hashp->LOW_MASK,
- "NSEGS ", hashp->nsegs,
- "NKEYS ", hashp->NKEYS);
-}
-#endif
-#endif /* 0 */
-#ifdef HASH_STATISTICS
- hash_overflows = hash_accesses = hash_collisions = hash_expansions = 0;
-#endif
- return (dbp);
-
-error1:
- if (hashp != NULL)
- (void)close(hashp->fp);
-
-error0:
- free(hashp);
- errno = save_errno;
- return (NULL);
-}
-
-static int
-hash_close(DB *dbp)
-{
- HTAB *hashp;
- int retval;
-
- if (!dbp)
- return (DBM_ERROR);
-
- hashp = (HTAB *)dbp->internal;
- if(!hashp)
- return (DBM_ERROR);
-
- retval = hdestroy(hashp);
- free(dbp);
- return (retval);
-}
-
-static int hash_fd(const DB *dbp)
-{
- HTAB *hashp;
-
- if (!dbp)
- return (DBM_ERROR);
-
- hashp = (HTAB *)dbp->internal;
- if(!hashp)
- return (DBM_ERROR);
-
- if (hashp->fp == -1) {
- errno = ENOENT;
- return (-1);
- }
- return (hashp->fp);
-}
-
-/************************** LOCAL CREATION ROUTINES **********************/
-static HTAB *
-init_hash(HTAB *hashp, const char *file, HASHINFO *info)
-{
- struct stat statbuf;
- int nelem;
-
- nelem = 1;
- hashp->NKEYS = 0;
- hashp->LORDER = BYTE_ORDER;
- hashp->BSIZE = DEF_BUCKET_SIZE;
- hashp->BSHIFT = DEF_BUCKET_SHIFT;
- hashp->SGSIZE = DEF_SEGSIZE;
- hashp->SSHIFT = DEF_SEGSIZE_SHIFT;
- hashp->DSIZE = DEF_DIRSIZE;
- hashp->FFACTOR = DEF_FFACTOR;
- hashp->hash = __default_hash;
- memset(hashp->SPARES, 0, sizeof(hashp->SPARES));
- memset(hashp->BITMAPS, 0, sizeof (hashp->BITMAPS));
-
- /* Fix bucket size to be optimal for file system */
- if (file != NULL) {
- if (stat(file, &statbuf))
- return (NULL);
-
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(VMS) && !defined(XP_OS2)
-#ifdef __QNX__
- hashp->BSIZE = statbuf.st_size;
-#else
- hashp->BSIZE = statbuf.st_blksize;
-#endif
-
- /* new code added by Lou to reduce block
- * size down below MAX_BSIZE
- */
- if (hashp->BSIZE > MAX_BSIZE)
- hashp->BSIZE = MAX_BSIZE;
-#endif
- hashp->BSHIFT = __log2((uint32)hashp->BSIZE);
- }
-
- if (info) {
- if (info->bsize) {
- /* Round pagesize up to power of 2 */
- hashp->BSHIFT = __log2(info->bsize);
- hashp->BSIZE = 1 << hashp->BSHIFT;
- if (hashp->BSIZE > MAX_BSIZE) {
- errno = EINVAL;
- return (NULL);
- }
- }
- if (info->ffactor)
- hashp->FFACTOR = info->ffactor;
- if (info->hash)
- hashp->hash = info->hash;
- if (info->nelem)
- nelem = info->nelem;
- if (info->lorder) {
- if (info->lorder != BIG_ENDIAN &&
- info->lorder != LITTLE_ENDIAN) {
- errno = EINVAL;
- return (NULL);
- }
- hashp->LORDER = info->lorder;
- }
- }
- /* init_htab should destroy the table and set errno if it fails */
- if (init_htab(hashp, nelem))
- return (NULL);
- else
- return (hashp);
-}
-/*
- * This calls alloc_segs which may run out of memory. Alloc_segs will destroy
- * the table and set errno, so we just pass the error information along.
- *
- * Returns 0 on No Error
- */
-static int
-init_htab(HTAB *hashp, int nelem)
-{
- register int nbuckets, nsegs;
- int l2;
-
- /*
- * Divide number of elements by the fill factor and determine a
- * desired number of buckets. Allocate space for the next greater
- * power of two number of buckets.
- */
- nelem = (nelem - 1) / hashp->FFACTOR + 1;
-
- l2 = __log2((uint32)PR_MAX(nelem, 2));
- nbuckets = 1 << l2;
-
- hashp->SPARES[l2] = l2 + 1;
- hashp->SPARES[l2 + 1] = l2 + 1;
- hashp->OVFL_POINT = l2;
- hashp->LAST_FREED = 2;
-
- /* First bitmap page is at: splitpoint l2 page offset 1 */
- if (__ibitmap(hashp, (int)OADDR_OF(l2, 1), l2 + 1, 0))
- return (-1);
-
- hashp->MAX_BUCKET = hashp->LOW_MASK = nbuckets - 1;
- hashp->HIGH_MASK = (nbuckets << 1) - 1;
- hashp->HDRPAGES = ((PR_MAX(sizeof(HASHHDR), MINHDRSIZE) - 1) >>
- hashp->BSHIFT) + 1;
-
- nsegs = (nbuckets - 1) / hashp->SGSIZE + 1;
- nsegs = 1 << __log2((uint32)nsegs);
-
- if (nsegs > hashp->DSIZE)
- hashp->DSIZE = nsegs;
- return (alloc_segs(hashp, nsegs));
-}
-
-/********************** DESTROY/CLOSE ROUTINES ************************/
-
-/*
- * Flushes any changes to the file if necessary and destroys the hashp
- * structure, freeing all allocated space.
- */
-static int
-hdestroy(HTAB *hashp)
-{
- int i, save_errno;
-
- save_errno = 0;
-
-#ifdef HASH_STATISTICS
- (void)fprintf(stderr, "hdestroy: accesses %ld collisions %ld\n",
- hash_accesses, hash_collisions);
- (void)fprintf(stderr, "hdestroy: expansions %ld\n",
- hash_expansions);
- (void)fprintf(stderr, "hdestroy: overflows %ld\n",
- hash_overflows);
- (void)fprintf(stderr, "keys %ld maxp %d segmentcount %d\n",
- hashp->NKEYS, hashp->MAX_BUCKET, hashp->nsegs);
-
- for (i = 0; i < NCACHED; i++)
- (void)fprintf(stderr,
- "spares[%d] = %d\n", i, hashp->SPARES[i]);
-#endif
- /*
- * Call on buffer manager to free buffers, and if required,
- * write them to disk.
- */
- if (__buf_free(hashp, 1, hashp->save_file))
- save_errno = errno;
- if (hashp->dir) {
- free(*hashp->dir); /* Free initial segments */
- /* Free extra segments */
- while (hashp->exsegs--)
- free(hashp->dir[--hashp->nsegs]);
- free(hashp->dir);
- }
- if (flush_meta(hashp) && !save_errno)
- save_errno = errno;
- /* Free Bigmaps */
- for (i = 0; i < hashp->nmaps; i++)
- if (hashp->mapp[i])
- free(hashp->mapp[i]);
-
- if (hashp->fp != -1)
- (void)close(hashp->fp);
-
- if(hashp->filename)
- free(hashp->filename);
-
- free(hashp);
-
- if (save_errno) {
- errno = save_errno;
- return (DBM_ERROR);
- }
- return (SUCCESS);
-}
-/*
- * Write modified pages to disk
- *
- * Returns:
- * 0 == OK
- * -1 DBM_ERROR
- */
-static int
-hash_sync(const DB *dbp, uint flags)
-{
- HTAB *hashp;
-
- if (flags != 0) {
- errno = EINVAL;
- return (DBM_ERROR);
- }
-
- if (!dbp)
- return (DBM_ERROR);
-
- hashp = (HTAB *)dbp->internal;
- if(!hashp)
- return (DBM_ERROR);
-
- if (!hashp->save_file)
- return (0);
- if (__buf_free(hashp, 0, 1) || flush_meta(hashp))
- return (DBM_ERROR);
- hashp->new_file = 0;
- return (0);
-}
-
-/*
- * Returns:
- * 0 == OK
- * -1 indicates that errno should be set
- */
-static int
-flush_meta(HTAB *hashp)
-{
- HASHHDR *whdrp;
-#if BYTE_ORDER == LITTLE_ENDIAN
- HASHHDR whdr;
-#endif
- int fp, i, wsize;
-
- if (!hashp->save_file)
- return (0);
- hashp->MAGIC = HASHMAGIC;
- hashp->VERSION = HASHVERSION;
- hashp->H_CHARKEY = hashp->hash(CHARKEY, sizeof(CHARKEY));
-
- fp = hashp->fp;
- whdrp = &hashp->hdr;
-#if BYTE_ORDER == LITTLE_ENDIAN
- whdrp = &whdr;
- swap_header_copy(&hashp->hdr, whdrp);
-#endif
- if ((lseek(fp, (off_t)0, SEEK_SET) == -1) ||
- ((wsize = write(fp, (char*)whdrp, sizeof(HASHHDR))) == -1))
- return (-1);
- else
- if (wsize != sizeof(HASHHDR)) {
- errno = EFTYPE;
- hashp->dbmerrno = errno;
- return (-1);
- }
- for (i = 0; i < NCACHED; i++)
- if (hashp->mapp[i])
- if (__put_page(hashp, (char *)hashp->mapp[i],
- hashp->BITMAPS[i], 0, 1))
- return (-1);
- return (0);
-}
-
-/*******************************SEARCH ROUTINES *****************************/
-/*
- * All the access routines return
- *
- * Returns:
- * 0 on SUCCESS
- * 1 to indicate an external DBM_ERROR (i.e. key not found, etc)
- * -1 to indicate an internal DBM_ERROR (i.e. out of memory, etc)
- */
-static int
-hash_get(
- const DB *dbp,
- const DBT *key,
- DBT *data,
- uint flag)
-{
- HTAB *hashp;
- int rv;
-
- hashp = (HTAB *)dbp->internal;
- if (!hashp)
- return (DBM_ERROR);
-
- if (flag) {
- hashp->dbmerrno = errno = EINVAL;
- return (DBM_ERROR);
- }
-
- rv = hash_access(hashp, HASH_GET, (DBT *)key, data);
-
- if(rv == DATABASE_CORRUPTED_ERROR)
- {
-#if defined(unix) && defined(DEBUG)
- printf("\n\nDBM Database has been corrupted, tell Lou...\n\n");
-#endif
- __remove_database((DB *)dbp);
- }
-
- return(rv);
-}
-
-static int
-hash_put(
- const DB *dbp,
- DBT *key,
- const DBT *data,
- uint flag)
-{
- HTAB *hashp;
- int rv;
-
- hashp = (HTAB *)dbp->internal;
- if (!hashp)
- return (DBM_ERROR);
-
- if (flag && flag != R_NOOVERWRITE) {
- hashp->dbmerrno = errno = EINVAL;
- return (DBM_ERROR);
- }
- if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
- hashp->dbmerrno = errno = EPERM;
- return (DBM_ERROR);
- }
-
- rv = hash_access(hashp, flag == R_NOOVERWRITE ?
- HASH_PUTNEW : HASH_PUT, (DBT *)key, (DBT *)data);
-
- if(rv == DATABASE_CORRUPTED_ERROR)
- {
-#if defined(unix) && defined(DEBUG)
- printf("\n\nDBM Database has been corrupted, tell Lou...\n\n");
-#endif
- __remove_database((DB *)dbp);
- }
-
- return(rv);
-}
-
-static int
-hash_delete(
- const DB *dbp,
- const DBT *key,
- uint flag) /* Ignored */
-{
- HTAB *hashp;
- int rv;
-
- hashp = (HTAB *)dbp->internal;
- if (!hashp)
- return (DBM_ERROR);
-
- if (flag && flag != R_CURSOR) {
- hashp->dbmerrno = errno = EINVAL;
- return (DBM_ERROR);
- }
- if ((hashp->flags & O_ACCMODE) == O_RDONLY) {
- hashp->dbmerrno = errno = EPERM;
- return (DBM_ERROR);
- }
- rv = hash_access(hashp, HASH_DELETE, (DBT *)key, NULL);
-
- if(rv == DATABASE_CORRUPTED_ERROR)
- {
-#if defined(unix) && defined(DEBUG)
- printf("\n\nDBM Database has been corrupted, tell Lou...\n\n");
-#endif
- __remove_database((DB *)dbp);
- }
-
- return(rv);
-}
-
-#define MAX_OVERFLOW_HASH_ACCESS_LOOPS 2000
-/*
- * Assume that hashp has been set in wrapper routine.
- */
-static int
-hash_access(
- HTAB *hashp,
- ACTION action,
- DBT *key, DBT *val)
-{
- register BUFHEAD *rbufp;
- BUFHEAD *bufp, *save_bufp;
- register uint16 *bp;
- register long n, ndx, off;
- register size_t size;
- register char *kp;
- uint16 pageno;
- uint32 ovfl_loop_count=0;
- int32 last_overflow_page_no = -1;
-
-#ifdef HASH_STATISTICS
- hash_accesses++;
-#endif
-
- off = hashp->BSIZE;
- size = key->size;
- kp = (char *)key->data;
- rbufp = __get_buf(hashp, __call_hash(hashp, kp, size), NULL, 0);
- if (!rbufp)
- return (DATABASE_CORRUPTED_ERROR);
- save_bufp = rbufp;
-
- /* Pin the bucket chain */
- rbufp->flags |= BUF_PIN;
- for (bp = (uint16 *)rbufp->page, n = *bp++, ndx = 1; ndx < n;)
- {
-
- if (bp[1] >= REAL_KEY) {
- /* Real key/data pair */
- if (size == (unsigned)(off - *bp) &&
- memcmp(kp, rbufp->page + *bp, size) == 0)
- goto found;
- off = bp[1];
-#ifdef HASH_STATISTICS
- hash_collisions++;
-#endif
- bp += 2;
- ndx += 2;
- } else if (bp[1] == OVFLPAGE) {
-
- /* database corruption: overflow loop detection */
- if(last_overflow_page_no == (int32)*bp)
- return (DATABASE_CORRUPTED_ERROR);
-
- last_overflow_page_no = *bp;
-
- rbufp = __get_buf(hashp, *bp, rbufp, 0);
- if (!rbufp) {
- save_bufp->flags &= ~BUF_PIN;
- return (DBM_ERROR);
- }
-
- ovfl_loop_count++;
- if(ovfl_loop_count > MAX_OVERFLOW_HASH_ACCESS_LOOPS)
- return (DATABASE_CORRUPTED_ERROR);
-
- /* FOR LOOP INIT */
- bp = (uint16 *)rbufp->page;
- n = *bp++;
- ndx = 1;
- off = hashp->BSIZE;
- } else if (bp[1] < REAL_KEY) {
- if ((ndx =
- __find_bigpair(hashp, rbufp, ndx, kp, (int)size)) > 0)
- goto found;
- if (ndx == -2) {
- bufp = rbufp;
- if (!(pageno =
- __find_last_page(hashp, &bufp))) {
- ndx = 0;
- rbufp = bufp;
- break; /* FOR */
- }
- rbufp = __get_buf(hashp, pageno, bufp, 0);
- if (!rbufp) {
- save_bufp->flags &= ~BUF_PIN;
- return (DBM_ERROR);
- }
- /* FOR LOOP INIT */
- bp = (uint16 *)rbufp->page;
- n = *bp++;
- ndx = 1;
- off = hashp->BSIZE;
- } else {
- save_bufp->flags &= ~BUF_PIN;
- return (DBM_ERROR);
-
- }
- }
- }
-
- /* Not found */
- switch (action) {
- case HASH_PUT:
- case HASH_PUTNEW:
- if (__addel(hashp, rbufp, key, val)) {
- save_bufp->flags &= ~BUF_PIN;
- return (DBM_ERROR);
- } else {
- save_bufp->flags &= ~BUF_PIN;
- return (SUCCESS);
- }
- case HASH_GET:
- case HASH_DELETE:
- default:
- save_bufp->flags &= ~BUF_PIN;
- return (ABNORMAL);
- }
-
-found:
- switch (action) {
- case HASH_PUTNEW:
- save_bufp->flags &= ~BUF_PIN;
- return (ABNORMAL);
- case HASH_GET:
- bp = (uint16 *)rbufp->page;
- if (bp[ndx + 1] < REAL_KEY) {
- if (__big_return(hashp, rbufp, ndx, val, 0))
- return (DBM_ERROR);
- } else {
- val->data = (uint8 *)rbufp->page + (int)bp[ndx + 1];
- val->size = bp[ndx] - bp[ndx + 1];
- }
- break;
- case HASH_PUT:
- if ((__delpair(hashp, rbufp, ndx)) ||
- (__addel(hashp, rbufp, key, val))) {
- save_bufp->flags &= ~BUF_PIN;
- return (DBM_ERROR);
- }
- break;
- case HASH_DELETE:
- if (__delpair(hashp, rbufp, ndx))
- return (DBM_ERROR);
- break;
- default:
- abort();
- }
- save_bufp->flags &= ~BUF_PIN;
- return (SUCCESS);
-}
-
-static int
-hash_seq(
- const DB *dbp,
- DBT *key, DBT *data,
- uint flag)
-{
- register uint32 bucket;
- register BUFHEAD *bufp;
- HTAB *hashp;
- uint16 *bp, ndx;
-
- hashp = (HTAB *)dbp->internal;
- if (!hashp)
- return (DBM_ERROR);
-
- if (flag && flag != R_FIRST && flag != R_NEXT) {
- hashp->dbmerrno = errno = EINVAL;
- return (DBM_ERROR);
- }
-#ifdef HASH_STATISTICS
- hash_accesses++;
-#endif
- if ((hashp->cbucket < 0) || (flag == R_FIRST)) {
- hashp->cbucket = 0;
- hashp->cndx = 1;
- hashp->cpage = NULL;
- }
-
- for (bp = NULL; !bp || !bp[0]; ) {
- if (!(bufp = hashp->cpage)) {
- for (bucket = hashp->cbucket;
- bucket <= (unsigned)hashp->MAX_BUCKET;
- bucket++, hashp->cndx = 1) {
- bufp = __get_buf(hashp, bucket, NULL, 0);
- if (!bufp)
- return (DBM_ERROR);
- hashp->cpage = bufp;
- bp = (uint16 *)bufp->page;
- if (bp[0])
- break;
- }
- hashp->cbucket = bucket;
- if (hashp->cbucket > hashp->MAX_BUCKET) {
- hashp->cbucket = -1;
- return (ABNORMAL);
- }
- } else
- bp = (uint16 *)hashp->cpage->page;
-
-#ifdef DEBUG
- assert(bp);
- assert(bufp);
-#endif
- while (bp[hashp->cndx + 1] == OVFLPAGE) {
- bufp = hashp->cpage =
- __get_buf(hashp, bp[hashp->cndx], bufp, 0);
- if (!bufp)
- return (DBM_ERROR);
- bp = (uint16 *)(bufp->page);
- hashp->cndx = 1;
- }
- if (!bp[0]) {
- hashp->cpage = NULL;
- ++hashp->cbucket;
- }
- }
- ndx = hashp->cndx;
- if (bp[ndx + 1] < REAL_KEY) {
- if (__big_keydata(hashp, bufp, key, data, 1))
- return (DBM_ERROR);
- } else {
- key->data = (uint8 *)hashp->cpage->page + bp[ndx];
- key->size = (ndx > 1 ? bp[ndx - 1] : hashp->BSIZE) - bp[ndx];
- data->data = (uint8 *)hashp->cpage->page + bp[ndx + 1];
- data->size = bp[ndx] - bp[ndx + 1];
- ndx += 2;
- if (ndx > bp[0]) {
- hashp->cpage = NULL;
- hashp->cbucket++;
- hashp->cndx = 1;
- } else
- hashp->cndx = ndx;
- }
- return (SUCCESS);
-}
-
-/********************************* UTILITIES ************************/
-
-/*
- * Returns:
- * 0 ==> OK
- * -1 ==> Error
- */
-extern int
-__expand_table(HTAB *hashp)
-{
- uint32 old_bucket, new_bucket;
- int new_segnum, spare_ndx;
- size_t dirsize;
-
-#ifdef HASH_STATISTICS
- hash_expansions++;
-#endif
- new_bucket = ++hashp->MAX_BUCKET;
- old_bucket = (hashp->MAX_BUCKET & hashp->LOW_MASK);
-
- new_segnum = new_bucket >> hashp->SSHIFT;
-
- /* Check if we need a new segment */
- if (new_segnum >= hashp->nsegs) {
- /* Check if we need to expand directory */
- if (new_segnum >= hashp->DSIZE) {
- /* Reallocate directory */
- dirsize = hashp->DSIZE * sizeof(SEGMENT *);
- if (!hash_realloc(&hashp->dir, dirsize, dirsize << 1))
- return (-1);
- hashp->DSIZE = dirsize << 1;
- }
- if ((hashp->dir[new_segnum] =
- (SEGMENT)calloc((size_t)hashp->SGSIZE, sizeof(SEGMENT))) == NULL)
- return (-1);
- hashp->exsegs++;
- hashp->nsegs++;
- }
- /*
- * If the split point is increasing (MAX_BUCKET's log base 2
- * * increases), we need to copy the current contents of the spare
- * split bucket to the next bucket.
- */
- spare_ndx = __log2((uint32)(hashp->MAX_BUCKET + 1));
- if (spare_ndx > hashp->OVFL_POINT) {
- hashp->SPARES[spare_ndx] = hashp->SPARES[hashp->OVFL_POINT];
- hashp->OVFL_POINT = spare_ndx;
- }
-
- if (new_bucket > (unsigned)hashp->HIGH_MASK) {
- /* Starting a new doubling */
- hashp->LOW_MASK = hashp->HIGH_MASK;
- hashp->HIGH_MASK = new_bucket | hashp->LOW_MASK;
- }
- /* Relocate records to the new bucket */
- return (__split_page(hashp, old_bucket, new_bucket));
-}
-
-/*
- * If realloc guarantees that the pointer is not destroyed if the realloc
- * fails, then this routine can go away.
- */
-static void *
-hash_realloc(
- SEGMENT **p_ptr,
- size_t oldsize, size_t newsize)
-{
- register void *p;
-
- if ((p = malloc(newsize))) {
- memmove(p, *p_ptr, oldsize);
- memset((char *)p + oldsize, 0, newsize - oldsize);
- free(*p_ptr);
- *p_ptr = (SEGMENT *)p;
- }
- return (p);
-}
-
-extern uint32
-__call_hash(HTAB *hashp, char *k, size_t len)
-{
- uint32 n, bucket;
-
- n = hashp->hash(k, len);
- bucket = n & hashp->HIGH_MASK;
- if (bucket > (unsigned)hashp->MAX_BUCKET)
- bucket = bucket & hashp->LOW_MASK;
- return (bucket);
-}
-
-/*
- * Allocate segment table. On error, destroy the table and set errno.
- *
- * Returns 0 on success
- */
-static int
-alloc_segs(
- HTAB *hashp,
- int nsegs)
-{
- register int i;
- register SEGMENT store;
-
- int save_errno;
-
- if ((hashp->dir =
- (SEGMENT *)calloc((size_t)hashp->DSIZE, sizeof(SEGMENT *))) == NULL) {
- save_errno = errno;
- (void)hdestroy(hashp);
- errno = save_errno;
- return (-1);
- }
- /* Allocate segments */
- if ((store =
- (SEGMENT)calloc((size_t)nsegs << hashp->SSHIFT, sizeof(SEGMENT))) == NULL) {
- save_errno = errno;
- (void)hdestroy(hashp);
- errno = save_errno;
- return (-1);
- }
- for (i = 0; i < nsegs; i++, hashp->nsegs++)
- hashp->dir[i] = &store[i << hashp->SSHIFT];
- return (0);
-}
-
-#if BYTE_ORDER == LITTLE_ENDIAN
-/*
- * Hashp->hdr needs to be byteswapped.
- */
-static void
-swap_header_copy(
- HASHHDR *srcp, HASHHDR *destp)
-{
- int i;
-
- P_32_COPY(srcp->magic, destp->magic);
- P_32_COPY(srcp->version, destp->version);
- P_32_COPY(srcp->lorder, destp->lorder);
- P_32_COPY(srcp->bsize, destp->bsize);
- P_32_COPY(srcp->bshift, destp->bshift);
- P_32_COPY(srcp->dsize, destp->dsize);
- P_32_COPY(srcp->ssize, destp->ssize);
- P_32_COPY(srcp->sshift, destp->sshift);
- P_32_COPY(srcp->ovfl_point, destp->ovfl_point);
- P_32_COPY(srcp->last_freed, destp->last_freed);
- P_32_COPY(srcp->max_bucket, destp->max_bucket);
- P_32_COPY(srcp->high_mask, destp->high_mask);
- P_32_COPY(srcp->low_mask, destp->low_mask);
- P_32_COPY(srcp->ffactor, destp->ffactor);
- P_32_COPY(srcp->nkeys, destp->nkeys);
- P_32_COPY(srcp->hdrpages, destp->hdrpages);
- P_32_COPY(srcp->h_charkey, destp->h_charkey);
- for (i = 0; i < NCACHED; i++) {
- P_32_COPY(srcp->spares[i], destp->spares[i]);
- P_16_COPY(srcp->bitmaps[i], destp->bitmaps[i]);
- }
-}
-
-static void
-swap_header(HTAB *hashp)
-{
- HASHHDR *hdrp;
- int i;
-
- hdrp = &hashp->hdr;
-
- M_32_SWAP(hdrp->magic);
- M_32_SWAP(hdrp->version);
- M_32_SWAP(hdrp->lorder);
- M_32_SWAP(hdrp->bsize);
- M_32_SWAP(hdrp->bshift);
- M_32_SWAP(hdrp->dsize);
- M_32_SWAP(hdrp->ssize);
- M_32_SWAP(hdrp->sshift);
- M_32_SWAP(hdrp->ovfl_point);
- M_32_SWAP(hdrp->last_freed);
- M_32_SWAP(hdrp->max_bucket);
- M_32_SWAP(hdrp->high_mask);
- M_32_SWAP(hdrp->low_mask);
- M_32_SWAP(hdrp->ffactor);
- M_32_SWAP(hdrp->nkeys);
- M_32_SWAP(hdrp->hdrpages);
- M_32_SWAP(hdrp->h_charkey);
- for (i = 0; i < NCACHED; i++) {
- M_32_SWAP(hdrp->spares[i]);
- M_16_SWAP(hdrp->bitmaps[i]);
- }
-}
-#endif
diff --git a/dbm/src/hash_buf.c b/dbm/src/hash_buf.c
deleted file mode 100644
index 7bfe01a34..000000000
--- a/dbm/src/hash_buf.c
+++ /dev/null
@@ -1,408 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993, 1994
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hash_buf.c 8.5 (Berkeley) 7/15/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-/*
- * PACKAGE: hash
- *
- * DESCRIPTION:
- * Contains buffer management
- *
- * ROUTINES:
- * External
- * __buf_init
- * __get_buf
- * __buf_free
- * __reclaim_buf
- * Internal
- * newbuf
- */
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(macintosh) && !defined(XP_OS2_VACPP)
-#include <sys/param.h>
-#endif
-
-#include <errno.h>
-#include <stddef.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-#ifdef DEBUG
-#include <assert.h>
-#endif
-
-#include "mcom_db.h"
-#include "hash.h"
-#include "page.h"
-/* #include "extern.h" */
-
-static BUFHEAD *newbuf __P((HTAB *, uint32, BUFHEAD *));
-
-/* Unlink B from its place in the lru */
-#define BUF_REMOVE(B) { \
- (B)->prev->next = (B)->next; \
- (B)->next->prev = (B)->prev; \
-}
-
-/* Insert B after P */
-#define BUF_INSERT(B, P) { \
- (B)->next = (P)->next; \
- (B)->prev = (P); \
- (P)->next = (B); \
- (B)->next->prev = (B); \
-}
-
-#define MRU hashp->bufhead.next
-#define LRU hashp->bufhead.prev
-
-#define MRU_INSERT(B) BUF_INSERT((B), &hashp->bufhead)
-#define LRU_INSERT(B) BUF_INSERT((B), LRU)
-
-/*
- * We are looking for a buffer with address "addr". If prev_bp is NULL, then
- * address is a bucket index. If prev_bp is not NULL, then it points to the
- * page previous to an overflow page that we are trying to find.
- *
- * CAVEAT: The buffer header accessed via prev_bp's ovfl field may no longer
- * be valid. Therefore, you must always verify that its address matches the
- * address you are seeking.
- */
-extern BUFHEAD *
-__get_buf(HTAB *hashp, uint32 addr, BUFHEAD *prev_bp, int newpage)
-/* If prev_bp set, indicates a new overflow page. */
-{
- register BUFHEAD *bp;
- register uint32 is_disk_mask;
- register int is_disk, segment_ndx = 0;
- SEGMENT segp = 0;
-
- is_disk = 0;
- is_disk_mask = 0;
- if (prev_bp) {
- bp = prev_bp->ovfl;
- if (!bp || (bp->addr != addr))
- bp = NULL;
- if (!newpage)
- is_disk = BUF_DISK;
- } else {
- /* Grab buffer out of directory */
- segment_ndx = addr & (hashp->SGSIZE - 1);
-
- /* valid segment ensured by __call_hash() */
- segp = hashp->dir[addr >> hashp->SSHIFT];
-#ifdef DEBUG
- assert(segp != NULL);
-#endif
-
- bp = PTROF(segp[segment_ndx]);
-
- is_disk_mask = ISDISK(segp[segment_ndx]);
- is_disk = is_disk_mask || !hashp->new_file;
- }
-
- if (!bp) {
- bp = newbuf(hashp, addr, prev_bp);
- if (!bp)
- return(NULL);
- if(__get_page(hashp, bp->page, addr, !prev_bp, is_disk, 0))
- {
- /* free bp and its page */
- if(prev_bp)
- {
- /* if prev_bp is set then the new page that
- * failed is hooked onto prev_bp as an overflow page.
- * if we don't remove the pointer to the bad page
- * we may try and access it later and we will die
- * horribly because it will have already been
- * free'd and overwritten with bogus data.
- */
- prev_bp->ovfl = NULL;
- }
- BUF_REMOVE(bp);
- free(bp->page);
- free(bp);
- return (NULL);
- }
-
- if (!prev_bp)
- {
-#if 0
- /* 16 bit windows and mac can't handle the
- * oring of the is disk flag.
- */
- segp[segment_ndx] =
- (BUFHEAD *)((ptrdiff_t)bp | is_disk_mask);
-#else
- /* set the is_disk thing inside the structure
- */
- bp->is_disk = is_disk_mask;
- segp[segment_ndx] = bp;
-#endif
- }
- } else {
- BUF_REMOVE(bp);
- MRU_INSERT(bp);
- }
- return (bp);
-}
-
-/*
- * We need a buffer for this page. Either allocate one, or evict a resident
- * one (if we have as many buffers as we're allowed) and put this one in.
- *
- * If newbuf finds an error (returning NULL), it also sets errno.
- */
-static BUFHEAD *
-newbuf(HTAB *hashp, uint32 addr, BUFHEAD *prev_bp)
-{
- register BUFHEAD *bp; /* The buffer we're going to use */
- register BUFHEAD *xbp; /* Temp pointer */
- register BUFHEAD *next_xbp;
- SEGMENT segp;
- int segment_ndx;
- uint16 oaddr, *shortp;
-
- oaddr = 0;
- bp = LRU;
- /*
- * If LRU buffer is pinned, the buffer pool is too small. We need to
- * allocate more buffers.
- */
- if (hashp->nbufs || (bp->flags & BUF_PIN)) {
- /* Allocate a new one */
- if ((bp = (BUFHEAD *)malloc(sizeof(BUFHEAD))) == NULL)
- return (NULL);
-
- /* this memset is supposedly unnecessary but lets add
- * it anyways.
- */
- memset(bp, 0xff, sizeof(BUFHEAD));
-
- if ((bp->page = (char *)malloc((size_t)hashp->BSIZE)) == NULL) {
- free(bp);
- return (NULL);
- }
-
- /* this memset is supposedly unnecessary but lets add
- * it anyways.
- */
- memset(bp->page, 0xff, (size_t)hashp->BSIZE);
-
- if (hashp->nbufs)
- hashp->nbufs--;
- } else {
- /* Kick someone out */
- BUF_REMOVE(bp);
- /*
- * If this is an overflow page with addr 0, it's already been
- * flushed back in an overflow chain and initialized.
- */
- if ((bp->addr != 0) || (bp->flags & BUF_BUCKET)) {
- /*
- * Set oaddr before __put_page so that you get it
- * before bytes are swapped.
- */
- shortp = (uint16 *)bp->page;
- if (shortp[0])
- {
- if(shortp[0] > (hashp->BSIZE / sizeof(uint16)))
- {
- return(NULL);
- }
- oaddr = shortp[shortp[0] - 1];
- }
- if ((bp->flags & BUF_MOD) && __put_page(hashp, bp->page,
- bp->addr, (int)IS_BUCKET(bp->flags), 0))
- return (NULL);
- /*
- * Update the pointer to this page (i.e. invalidate it).
- *
- * If this is a new file (i.e. we created it at open
- * time), make sure that we mark pages which have been
- * written to disk so we retrieve them from disk later,
- * rather than allocating new pages.
- */
- if (IS_BUCKET(bp->flags)) {
- segment_ndx = bp->addr & (hashp->SGSIZE - 1);
- segp = hashp->dir[bp->addr >> hashp->SSHIFT];
-#ifdef DEBUG
- assert(segp != NULL);
-#endif
-
- if (hashp->new_file &&
- ((bp->flags & BUF_MOD) ||
- ISDISK(segp[segment_ndx])))
- segp[segment_ndx] = (BUFHEAD *)BUF_DISK;
- else
- segp[segment_ndx] = NULL;
- }
- /*
- * Since overflow pages can only be access by means of
- * their bucket, free overflow pages associated with
- * this bucket.
- */
- for (xbp = bp; xbp->ovfl;) {
- next_xbp = xbp->ovfl;
- xbp->ovfl = 0;
- xbp = next_xbp;
-
- /* Check that ovfl pointer is up date. */
- if (IS_BUCKET(xbp->flags) ||
- (oaddr != xbp->addr))
- break;
-
- shortp = (uint16 *)xbp->page;
- if (shortp[0])
- {
- /* LJM is the number of reported
- * pages way too much?
- */
- if(shortp[0] > hashp->BSIZE/sizeof(uint16))
- return NULL;
- /* set before __put_page */
- oaddr = shortp[shortp[0] - 1];
- }
- if ((xbp->flags & BUF_MOD) && __put_page(hashp,
- xbp->page, xbp->addr, 0, 0))
- return (NULL);
- xbp->addr = 0;
- xbp->flags = 0;
- BUF_REMOVE(xbp);
- LRU_INSERT(xbp);
- }
- }
- }
-
- /* Now assign this buffer */
- bp->addr = addr;
-#ifdef DEBUG1
- (void)fprintf(stderr, "NEWBUF1: %d->ovfl was %d is now %d\n",
- bp->addr, (bp->ovfl ? bp->ovfl->addr : 0), 0);
-#endif
- bp->ovfl = NULL;
- if (prev_bp) {
- /*
- * If prev_bp is set, this is an overflow page, hook it in to
- * the buffer overflow links.
- */
-#ifdef DEBUG1
- (void)fprintf(stderr, "NEWBUF2: %d->ovfl was %d is now %d\n",
- prev_bp->addr, (prev_bp->ovfl ? bp->ovfl->addr : 0),
- (bp ? bp->addr : 0));
-#endif
- prev_bp->ovfl = bp;
- bp->flags = 0;
- } else
- bp->flags = BUF_BUCKET;
- MRU_INSERT(bp);
- return (bp);
-}
-
-extern void __buf_init(HTAB *hashp, int32 nbytes)
-{
- BUFHEAD *bfp;
- int npages;
-
- bfp = &(hashp->bufhead);
- npages = (nbytes + hashp->BSIZE - 1) >> hashp->BSHIFT;
- npages = PR_MAX(npages, MIN_BUFFERS);
-
- hashp->nbufs = npages;
- bfp->next = bfp;
- bfp->prev = bfp;
- /*
- * This space is calloc'd so these are already null.
- *
- * bfp->ovfl = NULL;
- * bfp->flags = 0;
- * bfp->page = NULL;
- * bfp->addr = 0;
- */
-}
-
-extern int
-__buf_free(HTAB *hashp, int do_free, int to_disk)
-{
- BUFHEAD *bp;
- int status = -1;
-
- /* Need to make sure that buffer manager has been initialized */
- if (!LRU)
- return (0);
- for (bp = LRU; bp != &hashp->bufhead;) {
- /* Check that the buffer is valid */
- if (bp->addr || IS_BUCKET(bp->flags)) {
- if (to_disk && (bp->flags & BUF_MOD) &&
- (status = __put_page(hashp, bp->page,
- bp->addr, IS_BUCKET(bp->flags), 0))) {
-
- if (do_free) {
- if (bp->page)
- free(bp->page);
- BUF_REMOVE(bp);
- free(bp);
- }
-
- return (status);
- }
- }
- /* Check if we are freeing stuff */
- if (do_free) {
- if (bp->page)
- free(bp->page);
- BUF_REMOVE(bp);
- free(bp);
- bp = LRU;
- } else
- bp = bp->prev;
- }
- return (0);
-}
-
-extern void
-__reclaim_buf(HTAB *hashp, BUFHEAD *bp)
-{
- bp->ovfl = 0;
- bp->addr = 0;
- bp->flags = 0;
- BUF_REMOVE(bp);
- LRU_INSERT(bp);
-}
diff --git a/dbm/src/hsearch.c b/dbm/src/hsearch.c
deleted file mode 100644
index 4ae4cabe4..000000000
--- a/dbm/src/hsearch.c
+++ /dev/null
@@ -1,108 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)hsearch.c 8.4 (Berkeley) 7/21/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#ifndef macintosh
-#include <sys/types.h>
-
-#include <fcntl.h>
-#endif
-#include <string.h>
-
-#include "mcom_db.h"
-#include "hsearch.h"
-
-static DB *dbp = NULL;
-static ENTRY retval;
-
-extern int
-hcreate(uint nel)
-{
- HASHINFO info;
-
- info.nelem = nel;
- info.bsize = 256;
- info.ffactor = 8;
- info.cachesize = 0;
- info.hash = NULL;
- info.lorder = 0;
- dbp = (DB *)__hash_open(NULL, O_CREAT | O_RDWR, 0600, &info, 0);
- return ((int)dbp);
-}
-
-extern ENTRY *
-hsearch(ENTRY item, ACTION action)
-{
- DBT key, val;
- int status;
-
- if (!dbp)
- return (NULL);
- key.data = (uint8 *)item.key;
- key.size = strlen(item.key) + 1;
-
- if (action == ENTER) {
- val.data = (uint8 *)item.data;
- val.size = strlen(item.data) + 1;
- status = (dbp->put)(dbp, &key, &val, R_NOOVERWRITE);
- if (status)
- return (NULL);
- } else {
- /* FIND */
- status = (dbp->get)(dbp, &key, &val, 0);
- if (status)
- return (NULL);
- else
- item.data = (char *)val.data;
- }
- retval.key = item.key;
- retval.data = item.data;
- return (&retval);
-}
-
-extern void
-hdestroy()
-{
- if (dbp) {
- (void)(dbp->close)(dbp);
- dbp = NULL;
- }
-}
diff --git a/dbm/src/memmove.c b/dbm/src/memmove.c
deleted file mode 100644
index c4f9ff02e..000000000
--- a/dbm/src/memmove.c
+++ /dev/null
@@ -1,150 +0,0 @@
-#if defined(__sun) && !defined(__svr4__)
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Chris Torek.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)bcopy.c 8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#ifdef HAVE_SYS_CDEFS_H
-#include <sys/cdefs.h>
-#else
-#include "cdefs.h"
-#endif
-#include <string.h>
-
-/*
- * sizeof(word) MUST BE A POWER OF TWO
- * SO THAT wmask BELOW IS ALL ONES
- */
-typedef int word; /* "word" used for optimal copy speed */
-
-#define wsize sizeof(word)
-#define wmask (wsize - 1)
-
-/*
- * Copy a block of memory, handling overlap.
- * This is the routine that actually implements
- * (the portable versions of) bcopy, memcpy, and memmove.
- */
-#ifdef MEMCOPY
-void *
-memcpy(dst0, src0, length)
-#else
-#ifdef MEMMOVE
-void *
-memmove(dst0, src0, length)
-#else
-void
-bcopy(src0, dst0, length)
-#endif
-#endif
- void *dst0;
- const void *src0;
- register size_t length;
-{
- register char *dst = dst0;
- register const char *src = src0;
- register size_t t;
-
- if (length == 0 || dst == src) /* nothing to do */
- goto done;
-
- /*
- * Macros: loop-t-times; and loop-t-times, t>0
- */
-#define TLOOP(s) if (t) TLOOP1(s)
-#define TLOOP1(s) do { s; } while (--t)
-
- if ((unsigned long)dst < (unsigned long)src) {
- /*
- * Copy forward.
- */
- t = (int)src; /* only need low bits */
- if ((t | (int)dst) & wmask) {
- /*
- * Try to align operands. This cannot be done
- * unless the low bits match.
- */
- if ((t ^ (int)dst) & wmask || length < wsize)
- t = length;
- else
- t = wsize - (t & wmask);
- length -= t;
- TLOOP1(*dst++ = *src++);
- }
- /*
- * Copy whole words, then mop up any trailing bytes.
- */
- t = length / wsize;
- TLOOP(*(word *)dst = *(word *)src; src += wsize; dst += wsize);
- t = length & wmask;
- TLOOP(*dst++ = *src++);
- } else {
- /*
- * Copy backwards. Otherwise essentially the same.
- * Alignment works as before, except that it takes
- * (t&wmask) bytes to align, not wsize-(t&wmask).
- */
- src += length;
- dst += length;
- t = (int)src;
- if ((t | (int)dst) & wmask) {
- if ((t ^ (int)dst) & wmask || length <= wsize)
- t = length;
- else
- t &= wmask;
- length -= t;
- TLOOP1(*--dst = *--src);
- }
- t = length / wsize;
- TLOOP(src -= wsize; dst -= wsize; *(word *)dst = *(word *)src);
- t = length & wmask;
- TLOOP(*--dst = *--src);
- }
-done:
-#if defined(MEMCOPY) || defined(MEMMOVE)
- return (dst0);
-#else
- return;
-#endif
-}
-#endif /* no __sgi */
-
-/* Some compilers don't like an empty source file. */
-static int dummy = 0;
diff --git a/dbm/src/mktemp.c b/dbm/src/mktemp.c
deleted file mode 100644
index ab606e30f..000000000
--- a/dbm/src/mktemp.c
+++ /dev/null
@@ -1,151 +0,0 @@
-/*
- * Copyright (c) 1987, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)mktemp.c 8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#ifdef macintosh
-#include <unix.h>
-#else
-#include <sys/types.h>
-#include <sys/stat.h>
-#endif
-#include <fcntl.h>
-#include <errno.h>
-#include <stdio.h>
-#include <ctype.h>
-#include "mcom_db.h"
-
-#if !defined(_WINDOWS) && !defined(XP_OS2_VACPP)
-#include <unistd.h>
-#endif
-
-#ifdef XP_OS2_VACPP
-#define ENOTDIR EBADPOS
-#include <process.h>
-#include <dirent.h>
-#endif
-
-#ifdef _WINDOWS
-#include <process.h>
-#include "winfile.h"
-#endif
-
-static int _gettemp(char *path, register int *doopen);
-
-int
-mkstemp(path)
- char *path;
-{
- int fd;
-
- return (_gettemp(path, &fd) ? fd : -1);
-}
-
-char *
-mktemp(path)
- char *path;
-{
- return(_gettemp(path, (int *)NULL) ? path : (char *)NULL);
-}
-
-static int
-_gettemp(path, doopen)
- char *path;
- register int *doopen;
-{
-#if !defined(_WINDOWS) || defined(_WIN32)
- extern int errno;
-#endif
- register char *start, *trv;
- struct stat sbuf;
- unsigned int pid;
-
- pid = getpid();
- for (trv = path; *trv; ++trv); /* extra X's get set to 0's */
- while (*--trv == 'X') {
- *trv = (pid % 10) + '0';
- pid /= 10;
- }
-
- /*
- * check the target directory; if you have six X's and it
- * doesn't exist this runs for a *very* long time.
- */
- for (start = trv + 1;; --trv) {
- if (trv <= path)
- break;
- if (*trv == '/') {
- *trv = '\0';
- if (stat(path, &sbuf))
- return(0);
- if (!S_ISDIR(sbuf.st_mode)) {
- errno = ENOTDIR;
- return(0);
- }
- *trv = '/';
- break;
- }
- }
-
- for (;;) {
- if (doopen) {
- if ((*doopen =
- open(path, O_CREAT|O_EXCL|O_RDWR, 0600)) >= 0)
- return(1);
- if (errno != EEXIST)
- return(0);
- }
- else if (stat(path, &sbuf))
- return(errno == ENOENT ? 1 : 0);
-
- /* tricky little algorithm for backward compatibility */
- for (trv = start;;) {
- if (!*trv)
- return(0);
- if (*trv == 'z')
- *trv++ = 'a';
- else {
- if (isdigit(*trv))
- *trv = 'a';
- else
- ++*trv;
- break;
- }
- }
- }
- /*NOTREACHED*/
-}
diff --git a/dbm/src/ndbm.c b/dbm/src/ndbm.c
deleted file mode 100644
index ca008de0c..000000000
--- a/dbm/src/ndbm.c
+++ /dev/null
@@ -1,195 +0,0 @@
-/*-
- * Copyright (c) 1990, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * This code is derived from software contributed to Berkeley by
- * Margo Seltzer.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)ndbm.c 8.4 (Berkeley) 7/21/94";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-/*
- * This package provides a dbm compatible interface to the new hashing
- * package described in db(3).
- */
-#if !defined(_WIN32) && !defined(_WINDOWS) && !defined(XP_OS2_VACPP)
-#include <sys/param.h>
-#endif
-
-#if defined(__linux)
-#include <linux/limits.h>
-#endif
-
-#include <stdio.h>
-#include <string.h>
-
-#include "ndbm.h"
-#include "hash.h"
-
-/*
- * Returns:
- * *DBM on success
- * NULL on failure
- */
-extern DBM *
-dbm_open(const char *file, int flags, int mode)
-{
- HASHINFO info;
- char path[MAXPATHLEN];
-
- info.bsize = 4096;
- info.ffactor = 40;
- info.nelem = 1;
- info.cachesize = 0;
- info.hash = NULL;
- info.lorder = 0;
- (void)strcpy(path, file);
- (void)strcat(path, DBM_SUFFIX);
- return ((DBM *)__hash_open(path, flags, mode, &info, 0));
-}
-
-extern void
-dbm_close(DBM *db)
-{
- (void)(db->close)(db);
-}
-
-/*
- * Returns:
- * DATUM on success
- * NULL on failure
- */
-extern datum
-dbm_fetch(DBM *db, datum key)
-{
- datum retval;
- int status;
-
- status = (db->get)(db, (DBT *)&key, (DBT *)&retval, 0);
- if (status) {
- retval.dptr = NULL;
- retval.dsize = 0;
- }
- return (retval);
-}
-
-/*
- * Returns:
- * DATUM on success
- * NULL on failure
- */
-extern datum
-dbm_firstkey(DBM *db)
-{
- int status;
- datum retdata, retkey;
-
- status = (db->seq)(db, (DBT *)&retkey, (DBT *)&retdata, R_FIRST);
- if (status)
- retkey.dptr = NULL;
- return (retkey);
-}
-
-/*
- * Returns:
- * DATUM on success
- * NULL on failure
- */
-extern datum
-dbm_nextkey(DBM *db)
-{
- int status;
- datum retdata, retkey;
-
- status = (db->seq)(db, (DBT *)&retkey, (DBT *)&retdata, R_NEXT);
- if (status)
- retkey.dptr = NULL;
- return (retkey);
-}
-/*
- * Returns:
- * 0 on success
- * <0 failure
- */
-extern int
-dbm_delete(DBM *db, datum key)
-{
- int status;
-
- status = (db->del)(db, (DBT *)&key, 0);
- if (status)
- return (-1);
- else
- return (0);
-}
-
-/*
- * Returns:
- * 0 on success
- * <0 failure
- * 1 if DBM_INSERT and entry exists
- */
-extern int
-dbm_store(DBM *db, datum key, datum content, int flags)
-{
- return ((db->put)(db, (DBT *)&key, (DBT *)&content,
- (flags == DBM_INSERT) ? R_NOOVERWRITE : 0));
-}
-
-
-extern int
-dbm_error(DBM *db)
-{
- HTAB *hp;
-
- hp = (HTAB *)db->internal;
- return (hp->dbmerrno);
-}
-
-extern int
-dbm_clearerr(DBM *db)
-{
- HTAB *hp;
-
- hp = (HTAB *)db->internal;
- hp->dbmerrno = 0;
- return (0);
-}
-
-extern int
-dbm_dirfno(DBM *db)
-{
- return(((HTAB *)db->internal)->fp);
-}
diff --git a/dbm/src/nsres.c b/dbm/src/nsres.c
deleted file mode 100644
index 44b448cf7..000000000
--- a/dbm/src/nsres.c
+++ /dev/null
@@ -1,311 +0,0 @@
-#include "watcomfx.h"
-
-#include "nsres.h"
-
-#include <stdio.h>
-
-#if defined(BSDI)||defined(RHAPSODY)
-#include <stdlib.h>
-#else
-#include <malloc.h>
-#endif
-
-#include <string.h>
-
-struct RESDATABASE
-{
- DB *hdb;
- NSRESTHREADINFO *threadinfo;
- char * pbuf[MAXBUFNUM];
-} ;
-typedef struct RESDATABASE * RESHANDLE;
-
-typedef struct STRINGDATA
-{
- char *str;
- unsigned int charsetid;
-} STRINGDATA;
-
-
-typedef unsigned int CHARSETTYPE;
-#define RES_LOCK if (hres->threadinfo) hres->threadinfo->fn_lock(hres->threadinfo->lock);
-#define RES_UNLOCK if (hres->threadinfo) hres->threadinfo->fn_unlock(hres->threadinfo->lock);
-
-int GenKeyData(const char *library, int32 id, DBT *key);
-
-/*
- Right now, the page size used for resource is same as for Navigator cache
- database
- */
-HASHINFO res_hash_info = {
- 32*1024,
- 0,
- 0,
- 0,
- 0, /* 64 * 1024U */
- 0};
-
-int GenKeyData(const char *library, int32 id, DBT *key)
-{
- char idstr[10];
- static char * strdata = NULL;
- size_t len;
-
- if (strdata)
- free (strdata);
-
- if (id == 0)
- idstr[0] = '\0';
- else
- {
- sprintf(idstr, "%d", id);
- /* itoa(id, idstr, 10); */
- }
-
- if (library == NULL)
- len = strlen(idstr) + 1;
- else
- len = strlen(library) + strlen(idstr) + 1;
- strdata = (char *) malloc (len);
- strcpy(strdata, library);
- strcat(strdata, idstr);
-
- key->size = len;
- key->data = strdata;
-
- return 1;
-}
-
-NSRESHANDLE NSResCreateTable(const char *filename, NSRESTHREADINFO *threadinfo)
-{
- RESHANDLE hres;
- int flag;
-
- flag = O_RDWR | O_CREAT;
-
- hres = (RESHANDLE) malloc ( sizeof(struct RESDATABASE) );
- memset(hres, 0, sizeof(struct RESDATABASE));
-
- if (threadinfo && threadinfo->lock && threadinfo->fn_lock
- && threadinfo->fn_unlock)
- {
- hres->threadinfo = (NSRESTHREADINFO *) malloc( sizeof(NSRESTHREADINFO) );
- hres->threadinfo->lock = threadinfo->lock;
- hres->threadinfo->fn_lock = threadinfo->fn_lock;
- hres->threadinfo->fn_unlock = threadinfo->fn_unlock;
- }
-
-
- RES_LOCK
-
- hres->hdb = dbopen(filename, flag, 0644, DB_HASH, &res_hash_info);
-
- RES_UNLOCK
-
- if(!hres->hdb)
- return NULL;
-
- return (NSRESHANDLE) hres;
-}
-
-NSRESHANDLE NSResOpenTable(const char *filename, NSRESTHREADINFO *threadinfo)
-{
- RESHANDLE hres;
- int flag;
-
- flag = O_RDONLY; /* only open database for reading */
-
- hres = (RESHANDLE) malloc ( sizeof(struct RESDATABASE) );
- memset(hres, 0, sizeof(struct RESDATABASE));
-
- if (threadinfo && threadinfo->lock && threadinfo->fn_lock
- && threadinfo->fn_unlock)
- {
- hres->threadinfo = (NSRESTHREADINFO *) malloc( sizeof(NSRESTHREADINFO) );
- hres->threadinfo->lock = threadinfo->lock;
- hres->threadinfo->fn_lock = threadinfo->fn_lock;
- hres->threadinfo->fn_unlock = threadinfo->fn_unlock;
- }
-
-
- RES_LOCK
-
- hres->hdb = dbopen(filename, flag, 0644, DB_HASH, &res_hash_info);
-
- RES_UNLOCK
-
- if(!hres->hdb)
- return NULL;
-
- return (NSRESHANDLE) hres;
-}
-
-
-
-void NSResCloseTable(NSRESHANDLE handle)
-{
- RESHANDLE hres;
- int i;
-
- if (handle == NULL)
- return;
- hres = (RESHANDLE) handle;
-
- RES_LOCK
-
- (*hres->hdb->sync)(hres->hdb, 0);
- (*hres->hdb->close)(hres->hdb);
-
- RES_UNLOCK
-
- for (i = 0; i < MAXBUFNUM; i++)
- {
- if (hres->pbuf[i])
- free (hres->pbuf[i]);
- }
-
- if (hres->threadinfo)
- free (hres->threadinfo);
- free (hres);
-}
-
-
-char *NSResLoadString(NSRESHANDLE handle, const char * library, int32 id,
- unsigned int charsetid, char *retbuf)
-{
- int status;
- RESHANDLE hres;
- DBT key, data;
- if (handle == NULL)
- return NULL;
-
- hres = (RESHANDLE) handle;
- GenKeyData(library, id, &key);
-
- RES_LOCK
-
- status = (*hres->hdb->get)(hres->hdb, &key, &data, 0);
-
- RES_UNLOCK
-
- if (retbuf)
- {
- memcpy(retbuf, (char *)data.data + sizeof(CHARSETTYPE), data.size - sizeof(CHARSETTYPE));
- return retbuf;
- }
- else
- {
- static int WhichString = 0;
- static int bFirstTime = 1;
- char *szLoadedString;
- int i;
-
- RES_LOCK
-
- if (bFirstTime) {
- for (i = 0; i < MAXBUFNUM; i++)
- hres->pbuf[i] = (char *) malloc(MAXSTRINGLEN * sizeof(char));
- bFirstTime = 0;
- }
-
- szLoadedString = hres->pbuf[WhichString];
- WhichString++;
-
- /* reset to 0, if WhichString reaches to the end */
- if (WhichString == MAXBUFNUM)
- WhichString = 0;
-
- if (status == 0)
- memcpy(szLoadedString, (char *) data.data + sizeof(CHARSETTYPE),
- data.size - sizeof(CHARSETTYPE));
- else
- szLoadedString[0] = 0;
-
- RES_UNLOCK
-
- return szLoadedString;
- }
-}
-
-int32 NSResGetSize(NSRESHANDLE handle, const char *library, int32 id)
-{
- int status;
- RESHANDLE hres;
- DBT key, data;
- if (handle == NULL)
- return 0;
- hres = (RESHANDLE) handle;
- GenKeyData(library, id, &key);
-
- RES_LOCK
-
- status = (*hres->hdb->get)(hres->hdb, &key, &data, 0);
-
- RES_UNLOCK
-
- return data.size - sizeof(CHARSETTYPE);
-}
-
-int32 NSResLoadResource(NSRESHANDLE handle, const char *library, int32 id, char *retbuf)
-{
- int status;
- RESHANDLE hres;
- DBT key, data;
- if (handle == NULL)
- return 0;
- hres = (RESHANDLE) handle;
- GenKeyData(library, id, &key);
-
- RES_LOCK
-
- status = (*hres->hdb->get)(hres->hdb, &key, &data, 0);
-
- RES_UNLOCK
-
- if (retbuf)
- {
- memcpy(retbuf, (char *)data.data + sizeof(CHARSETTYPE), data.size - sizeof(CHARSETTYPE));
- return data.size;
- }
- else
- return 0;
-}
-
-int NSResAddString(NSRESHANDLE handle, const char *library, int32 id,
- const char *string, unsigned int charset)
-{
- int status;
- RESHANDLE hres;
- DBT key, data;
- char * recdata;
-
- if (handle == NULL)
- return 0;
- hres = (RESHANDLE) handle;
-
- GenKeyData(library, id, &key);
-
- data.size = sizeof(CHARSETTYPE) + (strlen(string) + 1) ;
-
- recdata = (char *) malloc(data.size) ;
-
- /* set charset to the first field of record data */
- *((CHARSETTYPE *)recdata) = (CHARSETTYPE)charset;
-
- /* set data field */
- memcpy(recdata+sizeof(CHARSETTYPE), string, strlen(string) + 1);
-
- data.data = recdata;
-
- RES_LOCK
-
- status = (*hres->hdb->put)(hres->hdb, &key, &data, 0);
-
-
- if (recdata)
- free(recdata);
-
- RES_UNLOCK
-
- return status;
-}
diff --git a/dbm/src/snprintf.c b/dbm/src/snprintf.c
deleted file mode 100644
index 7a6b2005c..000000000
--- a/dbm/src/snprintf.c
+++ /dev/null
@@ -1,75 +0,0 @@
-#ifndef HAVE_SNPRINTF
-
-#include "watcomfx.h"
-#include <sys/types.h>
-#include <stddef.h>
-#include <stdio.h>
-
-#if defined(_WINDOWS) || defined(SOLARIS) || defined(AIXV3) || defined(AIX) || defined(OSF1) || defined(NEC) || !defined(HAVE_SYS_CDEFS_H)
-#include "cdefs.h"
-#elif !defined(HPUX) && !defined(UNIXWARE) && !defined(SNI)
-#include <sys/cdefs.h>
-#endif
-
-#include "prtypes.h"
-
-#include <ncompat.h>
-
-/* The OS/2 VAC compiler doesn't appear to define __STDC__ and won't let us define it either */
-#if defined(__STDC__) || defined(XP_OS2_VACPP)
-#include <stdarg.h>
-#else
-#include <varargs.h>
-#endif
-
-int
-#if defined(__STDC__) || defined(XP_OS2_VACPP)
-snprintf(char *str, size_t n, const char *fmt, ...)
-#else
-snprintf(str, n, fmt, va_alist)
- char *str;
- size_t n;
- const char *fmt;
- va_dcl
-#endif
-{
- va_list ap;
-#ifdef VSPRINTF_CHARSTAR
- char *rp;
-#else
- int rval;
-#endif
-#if defined(__STDC__) || defined(XP_OS2_VACPP)
- va_start(ap, fmt);
-#else
- va_start(ap);
-#endif
-#ifdef VSPRINTF_CHARSTAR
- rp = vsprintf(str, fmt, ap);
- va_end(ap);
- return (strlen(rp));
-#else
- rval = vsprintf(str, fmt, ap);
- va_end(ap);
- return (rval);
-#endif
-}
-
-int
-vsnprintf(str, n, fmt, ap)
- char *str;
- size_t n;
- const char *fmt;
- va_list ap;
-{
-#ifdef VSPRINTF_CHARSTAR
- return (strlen(vsprintf(str, fmt, ap)));
-#else
- return (vsprintf(str, fmt, ap));
-#endif
-}
-
-#endif /* HAVE_SNPRINTF */
-
-/* Some compilers don't like an empty source file. */
-static int dummy = 0;
diff --git a/dbm/src/strerror.c b/dbm/src/strerror.c
deleted file mode 100644
index d1ae2666a..000000000
--- a/dbm/src/strerror.c
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 1988, 1993
- * The Regents of the University of California. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- * 1. Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- * 2. Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- * 3. All advertising materials mentioning features or use of this software
- * must display the following acknowledgement:
- * This product includes software developed by the University of
- * California, Berkeley and its contributors.
- * 4. Neither the name of the University nor the names of its contributors
- * may be used to endorse or promote products derived from this software
- * without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
- * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
- * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
- * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
- * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
- * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
- * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
- * SUCH DAMAGE.
- */
-
-#if defined(LIBC_SCCS) && !defined(lint)
-static char sccsid[] = "@(#)strerror.c 8.1 (Berkeley) 6/4/93";
-#endif /* LIBC_SCCS and not lint */
-
-#include "watcomfx.h"
-
-#include <string.h>
-
-#ifdef _DLL
-#define sys_nerr (*_sys_nerr_dll)
-#endif
-
-#ifndef HAVE_STRERROR
-#ifndef _AFXDLL
-char *
-strerror(num)
- int num;
-{
- extern int sys_nerr;
- extern char *sys_errlist[];
-#define UPREFIX "Unknown error: "
- static char ebuf[40] = UPREFIX; /* 64-bit number + slop */
- register unsigned int errnum;
- register char *p, *t;
- char tmp[40];
-
- errnum = num; /* convert to unsigned */
- if (errnum < sys_nerr)
- return(sys_errlist[errnum]);
-
- /* Do this by hand, so we don't include stdio(3). */
- t = tmp;
- do {
- *t++ = "0123456789"[errnum % 10];
- } while (errnum /= 10);
- for (p = ebuf + sizeof(UPREFIX) - 1;;) {
- *p++ = *--t;
- if (t <= tmp)
- break;
- }
- return(ebuf);
-}
-
-#endif
-#endif /* !HAVE_STRERROR */
diff --git a/dbm/tests/.cvsignore b/dbm/tests/.cvsignore
deleted file mode 100644
index a21fbfc35..000000000
--- a/dbm/tests/.cvsignore
+++ /dev/null
@@ -1,3 +0,0 @@
-Makefile
-lots
-test.db
diff --git a/dbm/tests/Makefile.in b/dbm/tests/Makefile.in
deleted file mode 100644
index 97d20213e..000000000
--- a/dbm/tests/Makefile.in
+++ /dev/null
@@ -1,46 +0,0 @@
-#
-# The contents of this file are subject to the Netscape Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/NPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is mozilla.org code.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1998 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-
-DEPTH = ../..
-topsrcdir = @top_srcdir@
-srcdir = @srcdir@
-VPATH = @srcdir@
-
-include $(DEPTH)/config/autoconf.mk
-
-MODULE = dbm
-PROGRAM = lots$(BIN_SUFFIX)
-
-CSRCS = lots.c
-
-EXTRA_DSO_LIBS = mozdbm_s
-
-ifeq ($(MOZ_OS2_TOOLS),VACPP)
-LIBS = $(DIST)/lib/libmozdbm_s.$(LIB_SUFFIX)
-else
-LIBS = $(EXTRA_DSO_LIBS)
-endif
-
-include $(topsrcdir)/config/rules.mk
-
-ifeq ($(OS_ARCH), Linux)
-DEFINES += -D_BSD_SOURCE
-endif
diff --git a/dbm/tests/lots.c b/dbm/tests/lots.c
deleted file mode 100644
index f8b3c3568..000000000
--- a/dbm/tests/lots.c
+++ /dev/null
@@ -1,623 +0,0 @@
-/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 2 -*-
- *
- * The contents of this file are subject to the Netscape Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/NPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is mozilla.org code.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1998 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- */
-
-/* use sequental numbers printed to strings
- * to store lots and lots of entries in the
- * database.
- *
- * Start with 100 entries, put them and then
- * read them out. Then delete the first
- * half and verify that all of the first half
- * is gone and then verify that the second
- * half is still there.
- * Then add the first half back and verify
- * again. Then delete the middle third
- * and verify again.
- * Then increase the size by 1000 and do
- * the whole add delete thing again.
- *
- * The data for each object is the number string translated
- * to hex and replicated a random number of times. The
- * number of times that the data is replicated is the first
- * int32 in the data.
- */
-
-#include <stdio.h>
-
-#include <stdlib.h>
-#ifdef STDC_HEADERS
-#include <stdarg.h>
-#else
-#include <varargs.h>
-#endif
-
-#ifdef HAVE_MEMORY_H
-#include <memory.h>
-#endif
-#include <string.h>
-#include <assert.h>
-#include "mcom_db.h"
-
-DB *database=0;
-int MsgPriority=5;
-
-#if defined(_WINDOWS) && !defined(WIN32)
-#define int32 long
-#define uint32 unsigned long
-#else
-#define int32 int
-#define uint32 unsigned int
-#endif
-
-typedef enum {
-USE_LARGE_KEY,
-USE_SMALL_KEY
-} key_type_enum;
-
-#define TraceMe(priority, msg) \
- do { \
- if(priority <= MsgPriority) \
- { \
- ReportStatus msg; \
- } \
- } while(0)
-
-int
-ReportStatus(char *string, ...)
-{
- va_list args;
-
-#ifdef STDC_HEADERS
- va_start(args, string);
-#else
- va_start(args);
-#endif
- vfprintf(stderr, string, args);
- va_end(args);
-
- fprintf (stderr, "\n");
-
- return(0);
-}
-
-int
-ReportError(char *string, ...)
-{
- va_list args;
-
-#ifdef STDC_HEADERS
- va_start(args, string);
-#else
- va_start(args);
-#endif
- fprintf (stderr, "\n ");
- vfprintf(stderr, string, args);
- fprintf (stderr, "\n");
- va_end(args);
-
- return(0);
-}
-
-DBT * MakeLargeKey(int32 num)
-{
- int32 low_bits;
- static DBT rv;
- static char *string_rv=0;
- int rep_char;
- int32 size;
-
- if(string_rv)
- free(string_rv);
-
- /* generate a really large text key derived from
- * an int32
- */
- low_bits = (num % 10000) + 1;
-
- /* get the repeat char from the low 26 */
- rep_char = (char) ((low_bits % 26) + 'a');
-
- /* malloc a string low_bits wide */
- size = low_bits*sizeof(char);
- string_rv = (char *)malloc((size_t)size);
-
- memset(string_rv, rep_char, (size_t)size);
-
- rv.data = string_rv;
- rv.size = size;
-
- return(&rv);
-}
-
-DBT * MakeSmallKey(int32 num)
-{
- static DBT rv;
- static char data_string[64];
-
- rv.data = data_string;
-
- sprintf(data_string, "%ld", (long)num);
- rv.size = strlen(data_string);
-
- return(&rv);
-
-}
-
-DBT * GenKey(int32 num, key_type_enum key_type)
-{
- DBT *key;
-
- switch(key_type)
- {
- case USE_LARGE_KEY:
- key = MakeLargeKey(num);
- break;
- case USE_SMALL_KEY:
- key = MakeSmallKey(num);
- break;
- default:
- abort();
- break;
- }
-
- return(key);
-}
-
-int
-SeqDatabase()
-{
- int status;
- DBT key, data;
-
- ReportStatus("SEQuencing through database...");
-
- /* seq throught the whole database */
- if(!(status = (*database->seq)(database, &key, &data, R_FIRST)))
- {
- while(!(status = (database->seq) (database, &key, &data, R_NEXT)));
- ; /* null body */
- }
-
- if(status < 0)
- ReportError("Error seq'ing database");
-
- return(status);
-}
-
-int
-VerifyData(DBT *data, int32 num, key_type_enum key_type)
-{
- int32 count, compare_num;
- uint32 size;
- int32 *int32_array;
-
- /* The first int32 is count
- * The other n entries should
- * all equal num
- */
- if(data->size < sizeof(int32))
- {
- ReportError("Data size corrupted");
- return -1;
- }
-
- memcpy(&count, data->data, sizeof(int32));
-
- size = sizeof(int32)*(count+1);
-
- if(size != data->size)
- {
- ReportError("Data size corrupted");
- return -1;
- }
-
- int32_array = (int32*)data->data;
-
- for(;count > 0; count--)
- {
- memcpy(&compare_num, &int32_array[count], sizeof(int32));
-
- if(compare_num != num)
- {
- ReportError("Data corrupted");
- return -1;
- }
- }
-
- return(0);
-}
-
-
-/* verify that a range of number strings exist
- * or don't exist. And that the data is valid
- */
-#define SHOULD_EXIST 1
-#define SHOULD_NOT_EXIST 0
-int
-VerifyRange(int32 low, int32 high, int32 should_exist, key_type_enum key_type)
-{
- DBT *key, data;
- int32 num;
- int status;
-
- TraceMe(1, ("Verifying: %ld to %ld, using %s keys",
- low, high, key_type == USE_SMALL_KEY ? "SMALL" : "LARGE"));
-
- for(num = low; num <= high; num++)
- {
-
- key = GenKey(num, key_type);
-
- status = (*database->get)(database, key, &data, 0);
-
- if(status == 0)
- {
- /* got the item */
- if(!should_exist)
- {
- ReportError("Item exists but shouldn't: %ld", num);
- }
- else
- {
- /* else verify the data */
- VerifyData(&data, num, key_type);
- }
- }
- else if(status > 0)
- {
- /* item not found */
- if(should_exist)
- {
- ReportError("Item not found but should be: %ld", num);
- }
- }
- else
- {
- /* database error */
- ReportError("Database error");
- return(-1);
- }
-
- }
-
- TraceMe(1, ("Correctly verified: %ld to %ld", low, high));
-
- return(0);
-
-}
-
-DBT *
-GenData(int32 num)
-{
- int32 n;
- static DBT *data=0;
- int32 *int32_array;
- int32 size;
-
- if(!data)
- {
- data = (DBT*)malloc(sizeof(DBT));
- data->size = 0;
- data->data = 0;
- }
- else if(data->data)
- {
- free(data->data);
- }
-
- n = rand();
-
- n = n % 512; /* bound to a 2K size */
-
-
- size = sizeof(int32)*(n+1);
- int32_array = (int32 *) malloc((size_t)size);
-
- memcpy(&int32_array[0], &n, sizeof(int32));
-
- for(; n > 0; n--)
- {
- memcpy(&int32_array[n], &num, sizeof(int32));
- }
-
- data->data = (void*)int32_array;
- data->size = size;
-
- return(data);
-}
-
-#define ADD_RANGE 1
-#define DELETE_RANGE 2
-
-int
-AddOrDelRange(int32 low, int32 high, int action, key_type_enum key_type)
-{
- DBT *key, *data;
-#if 0 /* only do this if your really analy checking the puts */
- DBT tmp_data;
-#endif
- int32 num;
- int status;
-
- if(action != ADD_RANGE && action != DELETE_RANGE)
- assert(0);
-
- if(action == ADD_RANGE)
- {
- TraceMe(1, ("Adding: %ld to %ld: %s keys", low, high,
- key_type == USE_SMALL_KEY ? "SMALL" : "LARGE"));
- }
- else
- {
- TraceMe(1, ("Deleting: %ld to %ld: %s keys", low, high,
- key_type == USE_SMALL_KEY ? "SMALL" : "LARGE"));
- }
-
- for(num = low; num <= high; num++)
- {
-
- key = GenKey(num, key_type);
-
- if(action == ADD_RANGE)
- {
- data = GenData(num);
- status = (*database->put)(database, key, data, 0);
- }
- else
- {
- status = (*database->del)(database, key, 0);
- }
-
- if(status < 0)
- {
- ReportError("Database error %s item: %ld",
- action == ADD_RANGE ? "ADDING" : "DELETING",
- num);
- }
- else if(status > 0)
- {
- ReportError("Could not %s item: %ld",
- action == ADD_RANGE ? "ADD" : "DELETE",
- num);
- }
- else if(action == ADD_RANGE)
- {
-#define SYNC_EVERY_TIME
-#ifdef SYNC_EVERY_TIME
- status = (*database->sync)(database, 0);
- if(status != 0)
- ReportError("Database error syncing after add");
-#endif
-
-#if 0 /* only do this if your really analy checking the puts */
-
- /* make sure we can still get it
- */
- status = (*database->get)(database, key, &tmp_data, 0);
-
- if(status != 0)
- {
- ReportError("Database error checking item just added: %d",
- num);
- }
- else
- {
- /* now verify that none of the ones we already
- * put in have disappeared
- */
- VerifyRange(low, num, SHOULD_EXIST, key_type);
- }
-#endif
-
- }
- }
-
-
- if(action == ADD_RANGE)
- {
- TraceMe(1, ("Successfully added: %ld to %ld", low, high));
- }
- else
- {
- TraceMe(1, ("Successfully deleted: %ld to %ld", low, high));
- }
-
- return(0);
-}
-
-int
-TestRange(int32 low, int32 range, key_type_enum key_type)
-{
- int status; int32 low_of_range1, high_of_range1; int32 low_of_range2, high_of_range2;
- int32 low_of_range3, high_of_range3;
-
- status = AddOrDelRange(low, low+range, ADD_RANGE, key_type);
- status = VerifyRange(low, low+range, SHOULD_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 1"));
-
- SeqDatabase();
-
- low_of_range1 = low;
- high_of_range1 = low+(range/2);
- low_of_range2 = high_of_range1+1;
- high_of_range2 = low+range;
- status = AddOrDelRange(low_of_range1, high_of_range1, DELETE_RANGE, key_type);
- status = VerifyRange(low_of_range1, high_of_range1, SHOULD_NOT_EXIST, key_type);
- status = VerifyRange(low_of_range2, low_of_range2, SHOULD_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 2"));
-
- SeqDatabase();
-
- status = AddOrDelRange(low_of_range1, high_of_range1, ADD_RANGE, key_type);
- /* the whole thing should exist now */
- status = VerifyRange(low, low+range, SHOULD_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 3"));
-
- SeqDatabase();
-
- status = AddOrDelRange(low_of_range2, high_of_range2, DELETE_RANGE, key_type);
- status = VerifyRange(low_of_range1, high_of_range1, SHOULD_EXIST, key_type);
- status = VerifyRange(low_of_range2, high_of_range2, SHOULD_NOT_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 4"));
-
- SeqDatabase();
-
- status = AddOrDelRange(low_of_range2, high_of_range2, ADD_RANGE, key_type);
- /* the whole thing should exist now */
- status = VerifyRange(low, low+range, SHOULD_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 5"));
-
- SeqDatabase();
-
- low_of_range1 = low;
- high_of_range1 = low+(range/3);
- low_of_range2 = high_of_range1+1;
- high_of_range2 = high_of_range1+(range/3);
- low_of_range3 = high_of_range2+1;
- high_of_range3 = low+range;
- /* delete range 2 */
- status = AddOrDelRange(low_of_range2, high_of_range2, DELETE_RANGE, key_type);
- status = VerifyRange(low_of_range1, high_of_range1, SHOULD_EXIST, key_type);
- status = VerifyRange(low_of_range2, low_of_range2, SHOULD_NOT_EXIST, key_type);
- status = VerifyRange(low_of_range3, low_of_range2, SHOULD_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 6"));
-
- SeqDatabase();
-
- status = AddOrDelRange(low_of_range2, high_of_range2, ADD_RANGE, key_type);
- /* the whole thing should exist now */
- status = VerifyRange(low, low+range, SHOULD_EXIST, key_type);
-
- TraceMe(1, ("Finished with sub test 7"));
-
- return(0);
-}
-
-#define START_RANGE 109876
-int
-main(int argc, char **argv)
-{
- int32 i, j=0;
- int quick_exit = 0;
- int large_keys = 0;
- HASHINFO hash_info = {
- 16*1024,
- 0,
- 0,
- 0,
- 0,
- 0};
-
-
- if(argc > 1)
- {
- while(argc > 1)
- {
- if(!strcmp(argv[argc-1], "-quick"))
- quick_exit = 1;
- else if(!strcmp(argv[argc-1], "-large"))
- {
- large_keys = 1;
- }
- argc--;
- }
- }
-
- database = dbopen("test.db", O_RDWR | O_CREAT, 0644, DB_HASH, &hash_info);
-
- if(!database)
- {
- ReportError("Could not open database");
-#ifdef unix
- perror("");
-#endif
- exit(1);
- }
-
- if(quick_exit)
- {
- if(large_keys)
- TestRange(START_RANGE, 200, USE_LARGE_KEY);
- else
- TestRange(START_RANGE, 200, USE_SMALL_KEY);
-
- (*database->sync)(database, 0);
- (*database->close)(database);
- exit(0);
- }
-
- for(i=100; i < 10000000; i+=200)
- {
- if(1 || j)
- {
- TestRange(START_RANGE, i, USE_LARGE_KEY);
- j = 0;
- }
- else
- {
- TestRange(START_RANGE, i, USE_SMALL_KEY);
- j = 1;
- }
-
- if(1 == rand() % 3)
- {
- (*database->sync)(database, 0);
- }
-
- if(1 == rand() % 3)
- {
- /* close and reopen */
- (*database->close)(database);
- database = dbopen("test.db", O_RDWR | O_CREAT, 0644, DB_HASH, 0);
- if(!database)
- {
- ReportError("Could not reopen database");
-#ifdef unix
- perror("");
-#endif
- exit(1);
- }
- }
- else
- {
- /* reopen database without closeing the other */
- database = dbopen("test.db", O_RDWR | O_CREAT, 0644, DB_HASH, 0);
- if(!database)
- {
- ReportError("Could not reopen database "
- "after not closing the other");
-#ifdef unix
- perror("");
-#endif
- exit(1);
- }
- }
- }
-
- return(0);
-}
diff --git a/security/coreconf/tree.mk b/security/coreconf/tree.mk
deleted file mode 100644
index 0517a6df3..000000000
--- a/security/coreconf/tree.mk
+++ /dev/null
@@ -1,114 +0,0 @@
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-
-#######################################################################
-# Master "Core Components" file system "release" prefixes #
-#######################################################################
-
-# RELEASE_TREE = $(CORE_DEPTH)/../coredist
-
-
-ifndef RELEASE_TREE
- ifdef BUILD_SHIP
- ifdef USE_SHIPS
- RELEASE_TREE = $(BUILD_SHIP)
- else
- RELEASE_TREE = /m/dist
- endif
- else
- RELEASE_TREE = /m/dist
- endif
- ifeq ($(OS_TARGET), WINNT)
- ifdef BUILD_SHIP
- ifdef USE_SHIPS
- RELEASE_TREE = $(NTBUILD_SHIP)
- else
- RELEASE_TREE = //helium/dist
- endif
- else
- RELEASE_TREE = //helium/dist
- endif
- endif
-
- ifeq ($(OS_TARGET), WIN95)
- ifdef BUILD_SHIP
- ifdef USE_SHIPS
- RELEASE_TREE = $(NTBUILD_SHIP)
- else
- RELEASE_TREE = //helium/dist
- endif
- else
- RELEASE_TREE = //helium/dist
- endif
- endif
- ifeq ($(OS_TARGET), WIN16)
- ifdef BUILD_SHIP
- ifdef USE_SHIPS
- RELEASE_TREE = $(NTBUILD_SHIP)
- else
- RELEASE_TREE = //helium/dist
- endif
- else
- RELEASE_TREE = //helium/dist
- endif
- endif
-endif
-
-#
-# NOTE: export control policy enforced for XP and MD files
-# released to the binary release tree
-#
-
-ifeq ($(POLICY), domestic)
- RELEASE_XP_DIR = domestic
- RELEASE_MD_DIR = domestic/$(PLATFORM)
-else
- ifeq ($(POLICY), export)
- RELEASE_XP_DIR = export
- RELEASE_MD_DIR = export/$(PLATFORM)
- else
- ifeq ($(POLICY), france)
- RELEASE_XP_DIR = france
- RELEASE_MD_DIR = france/$(PLATFORM)
- else
- RELEASE_XP_DIR =
- RELEASE_MD_DIR = $(PLATFORM)
- endif
- endif
-endif
-
-
-REPORTER_TREE = $(subst \,\\,$(RELEASE_TREE))
-
-IMPORT_XP_DIR =
-IMPORT_MD_DIR = $(PLATFORM)
diff --git a/security/nss/cmd/bltest/Makefile b/security/nss/cmd/bltest/Makefile
deleted file mode 100644
index c99a3c017..000000000
--- a/security/nss/cmd/bltest/Makefile
+++ /dev/null
@@ -1,82 +0,0 @@
-#! gmake
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-
-#######################################################################
-# (1) Include initial platform-independent assignments (MANDATORY). #
-#######################################################################
-
-include manifest.mn
-#MKPROG = purify -cache-dir=/u/mcgreer/pcache -best-effort \
-# -always-use-cache-dir $(CC)
-
-#######################################################################
-# (2) Include "global" configuration information. (OPTIONAL) #
-#######################################################################
-
-include $(CORE_DEPTH)/coreconf/config.mk
-
-#######################################################################
-# (3) Include "component" configuration information. (OPTIONAL) #
-#######################################################################
-
-
-
-#######################################################################
-# (4) Include "local" platform-dependent assignments (OPTIONAL). #
-#######################################################################
-
-include ../platlibs.mk
-
-#EXTRA_SHARED_LIBS += \
-# -L/usr/lib \
-# -lposix4 \
-# $(NULL)
-
-#######################################################################
-# (5) Execute "global" rules. (OPTIONAL) #
-#######################################################################
-
-include $(CORE_DEPTH)/coreconf/rules.mk
-
-#######################################################################
-# (6) Execute "component" rules. (OPTIONAL) #
-#######################################################################
-
-
-
-#######################################################################
-# (7) Execute "local" rules. (OPTIONAL). #
-#######################################################################
-
-include ../platrules.mk
diff --git a/security/nss/cmd/bltest/blapitest.c b/security/nss/cmd/bltest/blapitest.c
deleted file mode 100644
index c5f770e4a..000000000
--- a/security/nss/cmd/bltest/blapitest.c
+++ /dev/null
@@ -1,1798 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#include <stdio.h>
-#include <stdlib.h>
-
-#include "blapi.h"
-#include "prmem.h"
-#include "prprf.h"
-#include "prtime.h"
-#include "prsystem.h"
-#include "plstr.h"
-#include "nssb64.h"
-#include "secutil.h"
-#include "plgetopt.h"
-#include "softoken.h"
-
-char *progName;
-char *testdir = ".";
-
-#define CHECKERROR(rv, ln) \
- if (rv) { \
- char *errtxt = NULL; \
- if (PR_GetError() != 0) { \
- errtxt = PORT_Alloc(PR_GetErrorTextLength()); \
- PR_GetErrorText(errtxt); \
- } \
- PR_fprintf(PR_STDERR, "%s: ERR (%s) at line %d.\n", progName, \
- (errtxt) ? "" : errtxt, ln); \
- exit(-1); \
- }
-
-static void Usage()
-{
-#define PRINTUSAGE(subject, option, predicate) \
- fprintf(stderr, "%10s %s\t%s\n", subject, option, predicate);
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "[-DEHSV] -m", "List available cipher modes.");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-E -m mode ", "Encrypt a buffer.");
- PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]");
- PRINTUSAGE("", "", "[-b bufsize] [-g keysize] [-erw]");
- PRINTUSAGE("", "", "[-p repetitions]");
- PRINTUSAGE("", "-m", "cipher mode to use.");
- PRINTUSAGE("", "-i", "file which contains input buffer.");
- PRINTUSAGE("", "-o", "file for output buffer.");
- PRINTUSAGE("", "-k", "file which contains key.");
- PRINTUSAGE("", "-v", "file which contains initialization vector.");
- PRINTUSAGE("", "-b", "size of input buffer.");
- PRINTUSAGE("", "-g", "key size (in bytes).");
- PRINTUSAGE("", "-p", "do performance test.");
- PRINTUSAGE("(rsa)", "-e", "rsa public exponent.");
- PRINTUSAGE("(rc5)", "-r", "number of rounds.");
- PRINTUSAGE("(rc5)", "-w", "wordsize (32 or 64).");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-D -m mode", "Decrypt a buffer.");
- PRINTUSAGE("", "", "[-i plaintext] [-o ciphertext] [-k key] [-v iv]");
- PRINTUSAGE("", "", "[-p repetitions]");
- PRINTUSAGE("", "-m", "cipher mode to use.");
- PRINTUSAGE("", "-i", "file which contains input buffer.");
- PRINTUSAGE("", "-o", "file for output buffer.");
- PRINTUSAGE("", "-k", "file which contains key.");
- PRINTUSAGE("", "-v", "file which contains initialization vector.");
- PRINTUSAGE("", "-p", "do performance test.");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-H -m mode", "Hash a buffer.");
- PRINTUSAGE("", "", "[-i plaintext] [-o hash]");
- PRINTUSAGE("", "", "[-b bufsize]");
- PRINTUSAGE("", "", "[-p repetitions]");
- PRINTUSAGE("", "-m", "cipher mode to use.");
- PRINTUSAGE("", "-i", "file which contains input buffer.");
- PRINTUSAGE("", "-o", "file for hash.");
- PRINTUSAGE("", "-b", "size of input buffer.");
- PRINTUSAGE("", "-p", "do performance test.");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-S -m mode", "Sign a buffer.");
- PRINTUSAGE("", "", "[-i plaintext] [-o signature] [-k key]");
- PRINTUSAGE("", "", "[-b bufsize]");
- PRINTUSAGE("", "", "[-p repetitions]");
- PRINTUSAGE("", "-m", "cipher mode to use.");
- PRINTUSAGE("", "-i", "file which contains input buffer.");
- PRINTUSAGE("", "-o", "file for signature.");
- PRINTUSAGE("", "-k", "file which contains key.");
- PRINTUSAGE("", "-p", "do performance test.");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-V -m mode", "Verify a signed buffer.");
- PRINTUSAGE("", "", "[-i plaintext] [-s signature] [-k key]");
- PRINTUSAGE("", "", "[-p repetitions]");
- PRINTUSAGE("", "-m", "cipher mode to use.");
- PRINTUSAGE("", "-i", "file which contains input buffer.");
- PRINTUSAGE("", "-s", "file which contains signature of input buffer.");
- PRINTUSAGE("", "-k", "file which contains key.");
- PRINTUSAGE("", "-p", "do performance test.");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-F", "Run the FIPS self-test.");
- fprintf(stderr, "\n");
- PRINTUSAGE(progName, "-T [mode1 mode2 ...]", "Run the BLAPI self-test.");
- fprintf(stderr, "\n");
- exit(1);
-}
-
-/* Helper functions for ascii<-->binary conversion/reading/writing */
-
-static PRInt32
-get_binary(void *arg, const unsigned char *ibuf, PRInt32 size)
-{
- SECItem *binary = arg;
- SECItem *tmp;
- int index;
- if (binary->data == NULL) {
- tmp = SECITEM_AllocItem(NULL, NULL, size);
- binary->data = tmp->data;
- binary->len = tmp->len;
- index = 0;
- } else {
- SECITEM_ReallocItem(NULL, binary, binary->len, binary->len + size);
- index = binary->len;
- }
- PORT_Memcpy(&binary->data[index], ibuf, size);
- return binary->len;
-}
-
-static PRInt32
-get_ascii(void *arg, const char *ibuf, PRInt32 size)
-{
- SECItem *ascii = arg;
- SECItem *tmp;
- int index;
- if (ascii->data == NULL) {
- tmp = SECITEM_AllocItem(NULL, NULL, size);
- ascii->data = tmp->data;
- ascii->len = tmp->len;
- index = 0;
- } else {
- SECITEM_ReallocItem(NULL, ascii, ascii->len, ascii->len + size);
- index = ascii->len;
- }
- PORT_Memcpy(&ascii->data[index], ibuf, size);
- return ascii->len;
-}
-
-static SECStatus
-atob(SECItem *ascii, SECItem *binary)
-{
- SECStatus status;
- NSSBase64Decoder *cx;
- int len;
- binary->data = NULL;
- binary->len = 0;
- len = (strcmp(&ascii->data[ascii->len-2],"\r\n"))?ascii->len:ascii->len-2;
- cx = NSSBase64Decoder_Create(get_binary, binary);
- status = NSSBase64Decoder_Update(cx, (const char *)ascii->data, len);
- status = NSSBase64Decoder_Destroy(cx, PR_FALSE);
- return status;
-}
-
-static PRInt32
-output_ascii(void *arg, const char *obuf, PRInt32 size)
-{
- PRFileDesc *outfile = arg;
- PRInt32 nb = PR_Write(outfile, obuf, size);
- if (nb != size) {
- PORT_SetError(SEC_ERROR_IO);
- return -1;
- }
- return nb;
-}
-
-static SECStatus
-btoa(SECItem *binary, SECItem *ascii)
-{
- SECStatus status;
- NSSBase64Encoder *cx;
- ascii->data = NULL;
- ascii->len = 0;
- cx = NSSBase64Encoder_Create(get_ascii, ascii);
- status = NSSBase64Encoder_Update(cx, binary->data, binary->len);
- status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
- return status;
-}
-
-static SECStatus
-btoa_file(SECItem *binary, PRFileDesc *outfile)
-{
- SECStatus status;
- NSSBase64Encoder *cx;
- SECItem ascii;
- ascii.data = NULL;
- ascii.len = 0;
- if (binary->len == 0)
- return SECSuccess;
- cx = NSSBase64Encoder_Create(output_ascii, outfile);
- status = NSSBase64Encoder_Update(cx, binary->data, binary->len);
- status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
- status = PR_Write(outfile, "\r\n", 2);
- return status;
-}
-
-static SECStatus
-get_and_write_random_bytes(SECItem *item, PRInt32 numbytes, char *filename)
-{
- SECStatus rv;
- PRFileDesc *file;
- item->len = numbytes;
- item->data = (unsigned char *)PORT_ZAlloc(numbytes);
- RNG_GenerateGlobalRandomBytes(item->data + 1, numbytes - 1);
- file = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 00660);
- rv = btoa_file(item, file);
- CHECKERROR((rv < 0), __LINE__);
- return (rv < 0);
-}
-
-static RSAPrivateKey *
-rsakey_from_filedata(SECItem *filedata)
-{
- PRArenaPool *arena;
- RSAPrivateKey *key;
- unsigned char *buf = filedata->data;
- int fpos = 0;
- int i;
- SECItem *item;
- /* Allocate space for key structure. */
- arena = PORT_NewArena(2048);
- key = (RSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(RSAPrivateKey));
- key->arena = arena;
- item = &key->version;
- for (i=0; i<9; i++) {
- item->len = (buf[fpos++] & 0xff) << 24;
- item->len |= (buf[fpos++] & 0xff) << 16;
- item->len |= (buf[fpos++] & 0xff) << 8;
- item->len |= (buf[fpos++] & 0xff);
- if (item->len > 0) {
- item->data = PORT_ArenaAlloc(arena, item->len);
- PORT_Memcpy(item->data, &buf[fpos], item->len);
- } else {
- item->data = NULL;
- }
- fpos += item->len;
- item++;
- }
- return key;
-}
-
-static void
-rsakey_to_file(RSAPrivateKey *key, char *filename)
-{
- PRFileDesc *file;
- SECItem *item;
- unsigned char len[4];
- int i;
- SECStatus status;
- NSSBase64Encoder *cx;
- SECItem ascii;
- ascii.data = NULL;
- ascii.len = 0;
- file = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 00660);
- cx = NSSBase64Encoder_Create(output_ascii, file);
- item = &key->version;
- for (i=0; i<9; i++) {
- len[0] = (item->len >> 24) & 0xff;
- len[1] = (item->len >> 16) & 0xff;
- len[2] = (item->len >> 8) & 0xff;
- len[3] = (item->len & 0xff);
- status = NSSBase64Encoder_Update(cx, len, 4);
- status = NSSBase64Encoder_Update(cx, item->data, item->len);
- item++;
- }
- status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
- status = PR_Write(file, "\r\n", 2);
- PR_Close(file);
-}
-
-static PQGParams *
-pqg_from_filedata(SECItem *filedata)
-{
- PRArenaPool *arena;
- PQGParams *pqg;
- unsigned char *buf = filedata->data;
- int fpos = 0;
- int i;
- SECItem *item;
- /* Allocate space for key structure. */
- arena = PORT_NewArena(2048);
- pqg = (PQGParams *)PORT_ArenaZAlloc(arena, sizeof(PQGParams));
- pqg->arena = arena;
- item = &pqg->prime;
- for (i=0; i<3; i++) {
- item->len = (buf[fpos++] & 0xff) << 24;
- item->len |= (buf[fpos++] & 0xff) << 16;
- item->len |= (buf[fpos++] & 0xff) << 8;
- item->len |= (buf[fpos++] & 0xff);
- if (item->len > 0) {
- item->data = PORT_ArenaAlloc(arena, item->len);
- PORT_Memcpy(item->data, &buf[fpos], item->len);
- } else {
- item->data = NULL;
- }
- fpos += item->len;
- item++;
- }
- return pqg;
-}
-
-static DSAPrivateKey *
-dsakey_from_filedata(SECItem *filedata)
-{
- PRArenaPool *arena;
- DSAPrivateKey *key;
- unsigned char *buf = filedata->data;
- int fpos = 0;
- int i;
- SECItem *item;
- /* Allocate space for key structure. */
- arena = PORT_NewArena(2048);
- key = (DSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DSAPrivateKey));
- key->params.arena = arena;
- item = &key->params.prime;
- for (i=0; i<5; i++) {
- item->len = (buf[fpos++] & 0xff) << 24;
- item->len |= (buf[fpos++] & 0xff) << 16;
- item->len |= (buf[fpos++] & 0xff) << 8;
- item->len |= (buf[fpos++] & 0xff);
- if (item->len > 0) {
- item->data = PORT_ArenaAlloc(arena, item->len);
- PORT_Memcpy(item->data, &buf[fpos], item->len);
- } else {
- item->data = NULL;
- }
- fpos += item->len;
- item++;
- }
- return key;
-}
-
-static void
-pqg_to_file(PQGParams *params, char *filename)
-{
- PRFileDesc *file;
- SECItem *item;
- unsigned char len[4];
- int i;
- SECStatus status;
- NSSBase64Encoder *cx;
- SECItem ascii;
- ascii.data = NULL;
- ascii.len = 0;
- file = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 00660);
- cx = NSSBase64Encoder_Create(output_ascii, file);
- item = &params->prime;
- for (i=0; i<3; i++) {
- len[0] = (item->len >> 24) & 0xff;
- len[1] = (item->len >> 16) & 0xff;
- len[2] = (item->len >> 8) & 0xff;
- len[3] = (item->len & 0xff);
- status = NSSBase64Encoder_Update(cx, len, 4);
- status = NSSBase64Encoder_Update(cx, item->data, item->len);
- item++;
- }
- status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
- status = PR_Write(file, "\r\n", 2);
-}
-
-static void
-dsakey_to_file(DSAPrivateKey *key, char *filename)
-{
- PRFileDesc *file;
- SECItem *item;
- unsigned char len[4];
- int i;
- SECStatus status;
- NSSBase64Encoder *cx;
- SECItem ascii;
- ascii.data = NULL;
- ascii.len = 0;
- file = PR_Open(filename, PR_WRONLY|PR_CREATE_FILE, 00660);
- cx = NSSBase64Encoder_Create(output_ascii, file);
- item = &key->params.prime;
- for (i=0; i<5; i++) {
- len[0] = (item->len >> 24) & 0xff;
- len[1] = (item->len >> 16) & 0xff;
- len[2] = (item->len >> 8) & 0xff;
- len[3] = (item->len & 0xff);
- status = NSSBase64Encoder_Update(cx, len, 4);
- status = NSSBase64Encoder_Update(cx, item->data, item->len);
- item++;
- }
- status = NSSBase64Encoder_Destroy(cx, PR_FALSE);
- status = PR_Write(file, "\r\n", 2);
-}
-
-static void
-dump_pqg(PQGParams *pqg)
-{
- SECU_PrintInteger(stdout, &pqg->prime, "PRIME:", 0);
- SECU_PrintInteger(stdout, &pqg->subPrime, "SUBPRIME:", 0);
- SECU_PrintInteger(stdout, &pqg->base, "BASE:", 0);
-}
-
-static void
-dump_dsakey(DSAPrivateKey *key)
-{
- dump_pqg(&key->params);
- SECU_PrintInteger(stdout, &key->publicValue, "PUBLIC VALUE:", 0);
- SECU_PrintInteger(stdout, &key->privateValue, "PRIVATE VALUE:", 0);
-}
-
-/* Multi-purpose crypto information */
-typedef struct
-{
- PRBool encrypt;
- PRBool decrypt;
- PRBool sign;
- PRBool verify;
- PRBool hash;
- SECItem seed;
- SECItem pqg;
- SECItem key;
- SECItem iv;
- SECItem in;
- SECItem out;
- SECItem sigseed;
- PRInt32 keysize;
- PRInt32 bufsize;
- PRBool useseed;
- PRBool usesigseed;
- PRBool performance;
- PRBool multihash;
- PQGParams *params; /* DSA only */
- unsigned int rounds; /* RC5 only */
- unsigned int wordsize; /* RC5 only */
- unsigned int rsapubexp; /* RSA only */
- unsigned int repetitions; /* performance tests only */
-} blapitestInfo;
-
-/* Macros for performance timing. */
-#define TIMESTART() \
- if (info->performance) \
- time1 = PR_IntervalNow();
-
-#define TIMEFINISH(mode, nb) \
- if (info->performance) { \
- time2 = (PRIntervalTime)(PR_IntervalNow() - time1); \
- time1 = PR_IntervalToMilliseconds(time2); \
- printf("%s,%d,%.3f\n", mode, nb, ((float)(time1))/info->repetitions); \
- }
-
-SECStatus
-fillitem(SECItem *item, int numbytes, char *filename)
-{
- if (item->len == 0)
- return get_and_write_random_bytes(item, numbytes, filename);
- return SECSuccess;
-}
-
-/************************
-** DES
-************************/
-
-/* encrypt/decrypt for all DES */
-static SECStatus
-des_common(DESContext *descx, blapitestInfo *info)
-{
- PRInt32 maxsize;
- SECStatus rv;
- PRIntervalTime time1, time2;
- int i, numiter;
- numiter = info->repetitions;
- maxsize = info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(maxsize);
- if (info->encrypt) {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = DES_Encrypt(descx, info->out.data, &info->out.len, maxsize,
- info->in.data, info->in.len);
- TIMEFINISH("DES ENCRYPT", maxsize);
- if (rv) {
- fprintf(stderr, "%s: Failed to encrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = DES_Decrypt(descx, info->out.data, &info->out.len, maxsize,
- info->in.data, info->in.len);
- TIMEFINISH("DES DECRYPT", maxsize);
- if (rv) {
- fprintf(stderr, "%s: Failed to decrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- }
- return rv;
-}
-
-/* DES codebook mode */
-static SECStatus
-des_ecb_test(blapitestInfo *info)
-{
- SECStatus rv;
- DESContext *descx;
- PRIntervalTime time1, time2;
- int i, numiter = info->repetitions;
- fillitem(&info->key, DES_KEY_LENGTH, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- descx = DES_CreateContext(info->key.data, NULL, NSS_DES, info->encrypt);
- DES_DestroyContext(descx, PR_TRUE);
- }
- descx = DES_CreateContext(info->key.data, NULL, NSS_DES, info->encrypt);
- TIMEFINISH("DES ECB CONTEXT CREATE", info->key.len);
- if (!descx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- rv = des_common(descx, info);
- CHECKERROR(rv, __LINE__);
- DES_DestroyContext(descx, PR_TRUE);
- return rv;
-}
-
-/* DES chaining mode */
-static SECStatus
-des_cbc_test(blapitestInfo *info)
-{
- SECStatus rv;
- DESContext *descx;
- PRIntervalTime time1, time2;
- int i, numiter = info->repetitions;
- fillitem(&info->key, DES_KEY_LENGTH, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- fillitem(&info->iv, DES_KEY_LENGTH, "tmp.iv");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- descx = DES_CreateContext(info->key.data, info->iv.data, NSS_DES_CBC,
- info->encrypt);
- DES_DestroyContext(descx, PR_TRUE);
- }
- descx = DES_CreateContext(info->key.data, info->iv.data, NSS_DES_CBC,
- info->encrypt);
- TIMEFINISH("DES CBC CONTEXT CREATE", info->key.len);
- if (!descx) {
- PR_fprintf(PR_STDERR,
- "%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- if (info->performance) {
- /* In chaining mode, repeated iterations of the encryption
- * function using the same context will alter the final output.
- * So, once the performance test is done, reset the context
- * and perform a single iteration to obtain the correct result.
- */
- int tmp = info->repetitions;
- rv = des_common(descx, info);
- DES_DestroyContext(descx, PR_TRUE);
- descx = DES_CreateContext(info->key.data, info->iv.data, NSS_DES_CBC,
- info->encrypt);
- info->performance = PR_FALSE;
- info->repetitions = 1;
- rv = des_common(descx, info);
- info->performance = PR_TRUE;
- info->repetitions = tmp;
- } else {
- rv = des_common(descx, info);
- }
- CHECKERROR(rv, __LINE__);
- DES_DestroyContext(descx, PR_TRUE);
- return rv;
-}
-
-/* 3-key Triple-DES codebook mode */
-static SECStatus
-des_ede_ecb_test(blapitestInfo *info)
-{
- SECStatus rv;
- DESContext *descx;
- PRIntervalTime time1, time2;
- int i, numiter = info->repetitions;
- fillitem(&info->key, 3*DES_KEY_LENGTH, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- descx = DES_CreateContext(info->key.data, NULL, NSS_DES_EDE3,
- info->encrypt);
- DES_DestroyContext(descx, PR_TRUE);
- }
- descx = DES_CreateContext(info->key.data, NULL, NSS_DES_EDE3,
- info->encrypt);
- TIMEFINISH("3DES ECB CONTEXT CREATE", info->key.len);
- if (!descx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- rv = des_common(descx, info);
- CHECKERROR(rv, __LINE__);
- DES_DestroyContext(descx, PR_TRUE);
- return rv;
-}
-
-/* 3-key Triple-DES chaining mode */
-static SECStatus
-des_ede_cbc_test(blapitestInfo *info)
-{
- SECStatus rv;
- DESContext *descx;
- PRIntervalTime time1, time2;
- int i, numiter = info->repetitions;
- fillitem(&info->key, 3*DES_KEY_LENGTH, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- fillitem(&info->iv, DES_KEY_LENGTH, "tmp.iv");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- descx = DES_CreateContext(info->key.data, info->iv.data,
- NSS_DES_EDE3_CBC, info->encrypt);
- DES_DestroyContext(descx, PR_TRUE);
- }
- descx = DES_CreateContext(info->key.data, info->iv.data, NSS_DES_EDE3_CBC,
- info->encrypt);
- TIMEFINISH("3DES CBC CONTEXT CREATE", info->key.len);
- if (!descx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- if (info->performance) {
- /* In chaining mode, repeated iterations of the encryption
- * function using the same context will alter the final output.
- * So, once the performance test is done, reset the context
- * and perform a single iteration to obtain the correct result.
- */
- int tmp = info->repetitions;
- rv = des_common(descx, info);
- DES_DestroyContext(descx, PR_TRUE);
- descx = DES_CreateContext(info->key.data, info->iv.data,
- NSS_DES_EDE3_CBC, info->encrypt);
- info->performance = PR_FALSE;
- info->repetitions = 1;
- rv = des_common(descx, info);
- info->performance = PR_TRUE;
- info->repetitions = tmp;
- } else {
- rv = des_common(descx, info);
- }
- CHECKERROR(rv, __LINE__);
- DES_DestroyContext(descx, PR_TRUE);
- return rv;
-}
-
-/************************
-** RC2
-************************/
-
-/* RC2 ECB */
-static SECStatus
-rc2_ecb_test(blapitestInfo *info)
-{
- SECStatus rv;
- RC2Context *rc2cx;
- PRIntervalTime time1, time2;
- int i, numiter = info->repetitions;
- fillitem(&info->key, info->keysize, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- rc2cx = RC2_CreateContext(info->key.data, info->key.len, NULL,
- NSS_RC2, info->key.len);
- RC2_DestroyContext(rc2cx, PR_TRUE);
- }
- rc2cx = RC2_CreateContext(info->key.data, info->key.len, NULL,
- NSS_RC2, info->key.len);
- TIMEFINISH("RC2 ECB CONTEXT CREATE", info->key.len);
- if (!rc2cx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- info->out.len = 2*info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->encrypt) {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC2_Encrypt(rc2cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC2 ECB ENCRYPT", info->in.len);
- CHECKERROR(rv, __LINE__);
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC2_Decrypt(rc2cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC2 ECB DECRYPT", info->in.len);
- CHECKERROR(rv, __LINE__);
- }
- RC2_DestroyContext(rc2cx, PR_TRUE);
- return rv;
-}
-
-/* RC2 CBC */
-static SECStatus
-rc2_cbc_test(blapitestInfo *info)
-{
- SECStatus rv;
- RC2Context *rc2cx;
- PRIntervalTime time1, time2;
- int i, numiter = info->repetitions;
- fillitem(&info->key, info->keysize, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- fillitem(&info->iv, info->bufsize, "tmp.iv");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- rc2cx = RC2_CreateContext(info->key.data, info->key.len, info->iv.data,
- NSS_RC2_CBC, info->key.len);
- RC2_DestroyContext(rc2cx, PR_TRUE);
- }
- rc2cx = RC2_CreateContext(info->key.data, info->key.len, info->iv.data,
- NSS_RC2_CBC, info->key.len);
- TIMEFINISH("RC2 CBC CONTEXT CREATE", info->key.len);
- if (!rc2cx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- info->out.len = 2*info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->encrypt) {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC2_Encrypt(rc2cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC2 CBC ENCRYPT", info->in.len);
- if (info->performance) {
- /* reset the context */
- RC2_DestroyContext(rc2cx, PR_TRUE);
- rc2cx = RC2_CreateContext(info->key.data, info->key.len,
- info->iv.data, NSS_RC2_CBC, info->key.len);
- rv = RC2_Encrypt(rc2cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- }
- CHECKERROR(rv, __LINE__);
- if (rv) {
- fprintf(stderr, "%s: Failed to encrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC2_Decrypt(rc2cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC2 CBC DECRYPT", info->in.len);
- if (info->performance) {
- /* reset the context */
- RC2_DestroyContext(rc2cx, PR_TRUE);
- rc2cx = RC2_CreateContext(info->key.data, info->key.len,
- info->iv.data, NSS_RC2_CBC, info->key.len);
- rv = RC2_Decrypt(rc2cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- }
- if (rv) {
- fprintf(stderr, "%s: Failed to decrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- }
- RC2_DestroyContext(rc2cx, PR_TRUE);
- return rv;
-}
-
-/************************
-** RC4
-************************/
-
-static SECStatus
-rc4_test(blapitestInfo *info)
-{
- SECStatus rv;
- RC4Context *rc4cx;
- PRIntervalTime time1, time2;
- int i, numiter;
- numiter = info->repetitions;
- fillitem(&info->key, info->keysize, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- rc4cx = RC4_CreateContext(info->key.data, info->key.len);
- RC4_DestroyContext(rc4cx, PR_TRUE);
- }
- rc4cx = RC4_CreateContext(info->key.data, info->key.len);
- TIMEFINISH("RC4 CONTEXT CREATE", info->key.len);
- if (!rc4cx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- info->out.len = 2*info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->encrypt) {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC4_Encrypt(rc4cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC4 ENCRYPT", info->in.len);
- if (info->performance) {
- /* reset the context */
- RC4_DestroyContext(rc4cx, PR_TRUE);
- rc4cx = RC4_CreateContext(info->key.data, info->key.len);
- rv = RC4_Encrypt(rc4cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- }
- if (rv) {
- fprintf(stderr, "%s: Failed to encrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC4_Decrypt(rc4cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC4 DECRYPT", info->in.len);
- if (info->performance) {
- /* reset the context */
- RC4_DestroyContext(rc4cx, PR_TRUE);
- rc4cx = RC4_CreateContext(info->key.data, info->key.len);
- rv = RC4_Decrypt(rc4cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- }
- if (rv) {
- fprintf(stderr, "%s: Failed to decrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- }
- RC4_DestroyContext(rc4cx, PR_TRUE);
- return rv;
-}
-
-/************************
-** RC5
-************************/
-
-/* RC5 ECB */
-static SECStatus
-rc5_ecb_test(blapitestInfo *info)
-{
- SECStatus rv;
- RC5Context *rc5cx;
- PRIntervalTime time1, time2;
- int i, numiter;
- numiter = info->repetitions;
- fillitem(&info->key, info->keysize, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- rc5cx = RC5_CreateContext(&info->key, info->rounds, info->wordsize,
- NULL, NSS_RC5);
- RC5_DestroyContext(rc5cx, PR_TRUE);
- }
- rc5cx = RC5_CreateContext(&info->key, info->rounds, info->wordsize,
- NULL, NSS_RC5);
- TIMEFINISH("RC5 ECB CONTEXT CREATE", info->key.len);
- if (!rc5cx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- info->out.len = 2*info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->encrypt) {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC5_Encrypt(rc5cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC5 ECB ENCRYPT", info->in.len);
- if (rv) {
- fprintf(stderr, "%s: Failed to encrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC5_Decrypt(rc5cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC5 ECB ENCRYPT", info->in.len);
- if (rv) {
- fprintf(stderr, "%s: Failed to decrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- }
- RC5_DestroyContext(rc5cx, PR_TRUE);
- return rv;
-}
-
-/* RC5 CBC */
-static SECStatus
-rc5_cbc_test(blapitestInfo *info)
-{
- SECStatus rv;
- RC5Context *rc5cx;
- PRIntervalTime time1, time2;
- int i, numiter;
- numiter = info->repetitions;
- fillitem(&info->key, info->keysize, "tmp.key");
- fillitem(&info->in, info->bufsize, "tmp.pt");
- fillitem(&info->iv, info->bufsize, "tmp.iv");
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- rc5cx = RC5_CreateContext(&info->key, info->rounds, info->wordsize,
- info->iv.data, NSS_RC5_CBC);
- RC5_DestroyContext(rc5cx, PR_TRUE);
- }
- rc5cx = RC5_CreateContext(&info->key, info->rounds, info->wordsize,
- info->iv.data, NSS_RC5_CBC);
- TIMEFINISH("RC5 CBC CONTEXT CREATE", info->key.len);
- if (!rc5cx) {
- fprintf(stderr,"%s: Failed to create encryption context!\n", progName);
- return SECFailure;
- }
- info->out.len = 2*info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->encrypt) {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC5_Encrypt(rc5cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC5 CBC ENCRYPT", info->in.len);
- if (info->performance) {
- /* reset the context */
- RC5_DestroyContext(rc5cx, PR_TRUE);
- rc5cx = RC5_CreateContext(&info->key, info->rounds, info->wordsize,
- info->iv.data, NSS_RC5_CBC);
- rv = RC5_Encrypt(rc5cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- }
- if (rv) {
- fprintf(stderr, "%s: Failed to encrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = RC5_Decrypt(rc5cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- TIMEFINISH("RC5 CBC DECRYPT", info->in.len);
- if (info->performance) {
- /* reset the context */
- RC5_DestroyContext(rc5cx, PR_TRUE);
- rc5cx = RC5_CreateContext(&info->key, info->rounds, info->wordsize,
- info->iv.data, NSS_RC5_CBC);
- rv = RC5_Decrypt(rc5cx, info->out.data, &info->out.len,
- info->out.len, info->in.data, info->in.len);
- }
- if (rv) {
- fprintf(stderr, "%s: Failed to decrypt!\n", progName);
- CHECKERROR(rv, __LINE__);
- }
- }
- RC5_DestroyContext(rc5cx, PR_TRUE);
- return rv;
-}
-
-static SECStatus
-rsa_test(blapitestInfo *info)
-{
- RSAPrivateKey *key;
- SECItem expitem;
- SECStatus rv;
- PRIntervalTime time1, time2;
- int i, j, numiter;
- unsigned int modLen;
- numiter = info->repetitions;
- fillitem(&info->in, info->bufsize, "tmp.pt");
- if (info->key.len > 0) {
- key = rsakey_from_filedata(&info->key);
- } else {
- expitem.len = 4;
- expitem.data = (unsigned char *)PORT_ZAlloc(4);
- expitem.data[0] = (info->rsapubexp >> 24) & 0xff;
- expitem.data[1] = (info->rsapubexp >> 16) & 0xff;
- expitem.data[2] = (info->rsapubexp >> 8) & 0xff;
- expitem.data[3] = (info->rsapubexp & 0xff);
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- key = RSA_NewKey(info->keysize*8, &expitem);
- PORT_FreeArena(key->arena, PR_TRUE);
- }
- key = RSA_NewKey(info->keysize*8, &expitem);
- TIMEFINISH("RSA KEY GEN", info->keysize);
- rsakey_to_file(key, "tmp.key");
- }
- if (key->modulus.data[0] == 0) {
- /* integer value of input must be less than modulus */
- if (info->in.data[0] >= key->modulus.data[1])
- return SECFailure;
- } else {
- if (info->in.data[0] >= key->modulus.data[0])
- return SECFailure;
- }
- modLen = key->modulus.len - !key->modulus.data[0];
- if (info->in.len % modLen != 0) {
- fprintf(stderr, "Input buffer must be a multiple of modulus length!\n");
- return SECFailure;
- }
- info->out.len = info->in.len;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->encrypt) {
- RSAPublicKey pubkey;
- SECITEM_CopyItem(key->arena, &pubkey.modulus, &key->modulus);
- SECITEM_CopyItem(key->arena, &pubkey.publicExponent,
- &key->publicExponent);
- TIMESTART();
- for (i=0; i<numiter; i++) {
- for (j=0; j<info->in.len; j+=pubkey.modulus.len) {
- rv = RSA_PublicKeyOp(&pubkey, &info->out.data[j],
- &info->in.data[j]);
- }
- }
- TIMEFINISH("RSA ENCRYPT", info->in.len);
- CHECKERROR(rv, __LINE__);
- } else {
- TIMESTART();
- for (i=info->repetitions; i>0; i--) {
- for (j=0; j<info->in.len; j+=key->modulus.len) {
- rv = RSA_PrivateKeyOp(key, &info->out.data[j],
- &info->in.data[j]);
- }
- }
- TIMEFINISH("RSA DECRYPT", info->in.len);
- CHECKERROR(rv, __LINE__);
- }
- PORT_FreeArena(key->arena, PR_TRUE);
- return SECSuccess;
-}
-
-static SECStatus
-pqg_test(blapitestInfo *info)
-{
- SECStatus rv = SECSuccess;
- PQGVerify *verify;
- PRIntervalTime time1, time2;
- int i, numiter;
- numiter = info->repetitions;
- if (info->pqg.len > 0) {
- info->params = pqg_from_filedata(&info->pqg);
- } else {
- TIMESTART();
- for (i=0; i<numiter-1; i++) {
- rv = PQG_ParamGen(info->keysize, &info->params, &verify);
- PORT_FreeArena(info->params->arena, PR_TRUE);
- }
- rv = PQG_ParamGen(info->keysize, &info->params, &verify);
- TIMEFINISH("PQG PARAM GEN", info->keysize);
- pqg_to_file(info->params, "tmp.pqg");
- }
- CHECKERROR(rv, __LINE__);
- return rv;
-}
-
-static SECStatus
-dsa_test(blapitestInfo *info)
-{
- DSAPrivateKey *key;
- SECStatus rv = SECSuccess;
- PRIntervalTime time1, time2;
- int i, numiter;
- numiter = info->repetitions;
- fillitem(&info->in, info->bufsize, "tmp.pt");
- if (info->key.len > 0) {
- key = dsakey_from_filedata(&info->key);
- } else {
- pqg_test(info);
- if (info->useseed) {
- if (info->seed.len == 0)
- get_and_write_random_bytes(&info->seed, DSA_SUBPRIME_LEN,
- "tmp.seed");
- rv = DSA_NewKeyFromSeed(info->params, info->seed.data, &key);
- } else {
- rv = DSA_NewKey(info->params, &key);
- }
- CHECKERROR(rv, __LINE__);
- dsakey_to_file(key, "tmp.key");
- }
- if (info->sign) {
- info->out.len = 48;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- if (info->usesigseed) {
- if (info->sigseed.len == 0)
- get_and_write_random_bytes(&info->sigseed, DSA_SUBPRIME_LEN,
- "tmp.sigseed");
- TIMESTART();
- rv = DSA_SignDigestWithSeed(key, &info->out, &info->in,
- info->sigseed.data);
- TIMEFINISH("DSA SIGN", info->in.len);
- } else {
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = DSA_SignDigest(key, &info->out, &info->in);
- TIMEFINISH("DSA SIGN", info->in.len);
- }
- CHECKERROR(rv, __LINE__);
- } else {
- DSAPublicKey pubkey;
- PRArenaPool *arena;
- arena = key->params.arena;
- SECITEM_CopyItem(arena, &pubkey.params.prime, &key->params.prime);
- SECITEM_CopyItem(arena, &pubkey.params.subPrime, &key->params.subPrime);
- SECITEM_CopyItem(arena, &pubkey.params.base, &key->params.base);
- SECITEM_CopyItem(arena, &pubkey.publicValue, &key->publicValue);
- TIMESTART();
- for (i=0; i<numiter; i++)
- rv = DSA_VerifyDigest(&pubkey, &info->out, &info->in);
- TIMEFINISH("DSA VERIFY", info->in.len);
- if (rv == SECSuccess) {
- PR_fprintf(PR_STDOUT, "Signature verified.\n");
- } else {
- PR_fprintf(PR_STDOUT, "Signature failed verification!\n");
- CHECKERROR(rv, __LINE__);
- }
- }
- PORT_FreeArena(key->params.arena, PR_TRUE);
- return SECSuccess;
-}
-
-static SECStatus
-md5_multi_test(blapitestInfo *info)
-{
- SECStatus rv = SECSuccess;
- MD5Context *md5cx;
- unsigned int len;
- MD5Context *foomd5cx;
- unsigned char *foomd5;
- int i;
- if (info->in.len == 0) {
- rv = get_and_write_random_bytes(&info->in, info->bufsize, "tmp.pt");
- CHECKERROR(rv, __LINE__);
- }
- md5cx = MD5_NewContext();
- if (!md5cx) {
- PR_fprintf(PR_STDERR,
- "%s: Failed to create hash context!\n", progName);
- return SECFailure;
- }
- info->out.len = MD5_LENGTH;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- MD5_Begin(md5cx);
- for (i=0; i<info->bufsize/8; i++) {
- MD5_Update(md5cx, &info->in.data[i*8], 8);
- len = MD5_FlattenSize(md5cx);
- foomd5 = PORT_Alloc(len);
- MD5_Flatten(md5cx, foomd5);
- foomd5cx = MD5_Resurrect(foomd5, NULL);
- rv = PORT_Memcmp(foomd5cx, md5cx, len);
- if (rv != SECSuccess)
- PR_fprintf(PR_STDERR, "%s: MD5_Resurrect failed!\n", progName);
- MD5_DestroyContext(foomd5cx, PR_TRUE);
- PORT_Free(foomd5);
- }
- MD5_End(md5cx, info->out.data, &len, MD5_LENGTH);
- if (len != MD5_LENGTH)
- PR_fprintf(PR_STDERR, "%s: Bad hash size %d.\n", progName, len);
- MD5_DestroyContext(md5cx, PR_TRUE);
- return rv;
-}
-
-static SECStatus
-md5_test(blapitestInfo *info)
-{
- SECStatus rv = SECSuccess;
- PRIntervalTime time1, time2;
- int i;
- if (!info->hash) return SECFailure;
- if (info->multihash) return md5_multi_test(info);
- if (info->in.len == 0) {
- rv = get_and_write_random_bytes(&info->in, info->bufsize, "tmp.pt");
- CHECKERROR(rv, __LINE__);
- }
- info->out.len = MD5_LENGTH;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- TIMESTART();
- for (i=info->repetitions; i>0; i--) {
- MD5_HashBuf(info->out.data, info->in.data, info->in.len);
- }
- TIMEFINISH("MD5 HASH", info->in.len);
- return rv;
-}
-
-static SECStatus
-md2_multi_test(blapitestInfo *info)
-{
- SECStatus rv = SECSuccess;
- MD2Context *md2cx;
- unsigned int len;
- MD2Context *foomd2cx;
- unsigned char *foomd2;
- int i;
- if (!info->hash) return SECFailure;
- if (info->in.len == 0) {
- rv = get_and_write_random_bytes(&info->in, info->bufsize, "tmp.pt");
- CHECKERROR(rv, __LINE__);
- }
- md2cx = MD2_NewContext();
- if (!md2cx) {
- PR_fprintf(PR_STDERR,
- "%s: Failed to create hash context!\n", progName);
- return SECFailure;
- }
- info->out.len = MD2_LENGTH;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- MD2_Begin(md2cx);
- for (i=0; i<info->bufsize/8; i++) {
- MD2_Update(md2cx, &info->in.data[i*8], 8);
- len = MD2_FlattenSize(md2cx);
- foomd2 = PORT_Alloc(len);
- MD2_Flatten(md2cx, foomd2);
- foomd2cx = MD2_Resurrect(foomd2, NULL);
- rv = PORT_Memcmp(foomd2cx, md2cx, len);
- if (rv != SECSuccess)
- PR_fprintf(PR_STDERR, "%s: MD2_Resurrect failed!\n", progName);
- MD2_DestroyContext(foomd2cx, PR_TRUE);
- PORT_Free(foomd2);
- }
- MD2_End(md2cx, info->out.data, &len, MD2_LENGTH);
- if (len != MD2_LENGTH)
- PR_fprintf(PR_STDERR, "%s: Bad hash size %d.\n", progName, len);
- MD2_DestroyContext(md2cx, PR_TRUE);
- return rv;
-}
-
-static SECStatus
-md2_test(blapitestInfo *info)
-{
- unsigned int len;
- MD2Context *cx = MD2_NewContext();
- SECStatus rv = SECSuccess;
- PRIntervalTime time1, time2;
- int i;
- if (!info->hash) return SECFailure;
- if (info->multihash) return md2_multi_test(info);
- if (info->in.len == 0) {
- rv = get_and_write_random_bytes(&info->in, info->bufsize, "tmp.pt");
- CHECKERROR(rv, __LINE__);
- }
- info->out.len = 16;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- info->in.data[info->in.len] = '\0';
- TIMESTART();
- for (i=0; i<info->repetitions; i++) {
- MD2_Begin(cx);
- MD2_Update(cx, info->in.data, info->in.len);
- MD2_End(cx, info->out.data, &len, 16);
- }
- TIMEFINISH("MD2 HASH", info->in.len);
- MD2_DestroyContext(cx, PR_TRUE);
- return rv;
-}
-
-static SECStatus
-sha1_multi_test(blapitestInfo *info)
-{
- SECStatus rv = SECSuccess;
- SHA1Context *sha1cx;
- unsigned int len;
- SHA1Context *foosha1cx;
- unsigned char *foosha1;
- int i;
- if (info->in.len == 0) {
- rv = get_and_write_random_bytes(&info->in, info->bufsize, "tmp.pt");
- CHECKERROR(rv, __LINE__);
- }
- sha1cx = SHA1_NewContext();
- if (!sha1cx) {
- PR_fprintf(PR_STDERR,
- "%s: Failed to create hash context!\n", progName);
- return SECFailure;
- }
- info->out.len = SHA1_LENGTH;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- SHA1_Begin(sha1cx);
- for (i=0; i<info->bufsize/8; i++) {
- SHA1_Update(sha1cx, &info->in.data[i*8], 8);
- len = SHA1_FlattenSize(sha1cx);
- foosha1 = PORT_Alloc(len);
- SHA1_Flatten(sha1cx, foosha1);
- foosha1cx = SHA1_Resurrect(foosha1, NULL);
- rv = PORT_Memcmp(foosha1cx, sha1cx, len);
- if (rv != SECSuccess)
- PR_fprintf(PR_STDERR, "%s: SHA1_Resurrect failed!\n", progName);
- SHA1_DestroyContext(foosha1cx, PR_TRUE);
- PORT_Free(foosha1);
- }
- SHA1_End(sha1cx, info->out.data, &len, SHA1_LENGTH);
- if (len != SHA1_LENGTH)
- PR_fprintf(PR_STDERR, "%s: Bad hash size %d.\n", progName, len);
- SHA1_DestroyContext(sha1cx, PR_TRUE);
- return rv;
-}
-
-static SECStatus
-sha1_test(blapitestInfo *info)
-{
- unsigned int len;
- SHA1Context *cx = SHA1_NewContext();
- SECStatus rv = SECSuccess;
- PRIntervalTime time1, time2;
- int i;
- if (!info->hash) return SECFailure;
- if (info->multihash) return sha1_multi_test(info);
- if (info->in.len == 0) {
- rv = get_and_write_random_bytes(&info->in, info->bufsize, "tmp.pt");
- CHECKERROR(rv, __LINE__);
- }
- info->out.len = SHA1_LENGTH;
- info->out.data = (unsigned char *)PORT_ZAlloc(info->out.len);
- info->in.data[info->in.len] = '\0';
- TIMESTART();
- for (i=info->repetitions; i>0; i--) {
- SHA1_Begin(cx);
- SHA1_Update(cx, info->in.data, info->in.len);
- SHA1_End(cx, info->out.data, &len, SHA1_LENGTH);
- }
- TIMEFINISH("SHA1 HASH", info->in.len);
- SHA1_DestroyContext(cx, PR_TRUE);
- return rv;
-}
-
-typedef SECStatus (* blapitestCryptoFn)(blapitestInfo *);
-
-static blapitestCryptoFn crypto_fns[] =
-{
- des_ecb_test,
- des_cbc_test,
- des_ede_ecb_test,
- des_ede_cbc_test,
- rc2_ecb_test,
- rc2_cbc_test,
- rc4_test,
- rc5_ecb_test,
- rc5_cbc_test,
- rsa_test,
- NULL,
- pqg_test,
- dsa_test,
- NULL,
- md5_test,
- md2_test,
- sha1_test,
- NULL
-};
-
-static char *mode_strings[] =
-{
- "des_ecb",
- "des_cbc",
- "des3_ecb",
- "des3_cbc",
- "rc2_ecb",
- "rc2_cbc",
- "rc4",
- "rc5_ecb",
- "rc5_cbc",
- "rsa",
- "#endencrypt",
- "pqg",
- "dsa",
- "#endsign",
- "md5",
- "md2",
- "sha1",
- "#endhash"
-};
-
-static void
-printmodes(blapitestInfo *info)
-{
- int i = 0;
- char *mode = mode_strings[0];
- PR_fprintf(PR_STDERR, "Available modes: (specify with -m)\n", progName);
- while (mode[0] != '#') {
- if (info->encrypt || info->decrypt)
- fprintf(stderr, "%s\n", mode);
- mode = mode_strings[++i];
- }
- mode = mode_strings[++i];
- while (mode[0] != '#') {
- if (info->sign || info->verify)
- fprintf(stderr, "%s\n", mode);
- mode = mode_strings[++i];
- }
- mode = mode_strings[++i];
- while (mode[0] != '#') {
- if (info->hash)
- fprintf(stderr, "%s\n", mode);
- mode = mode_strings[++i];
- }
-}
-
-static blapitestCryptoFn
-get_test_mode(const char *modestring)
-{
- int i;
- int nummodes = sizeof(mode_strings) / sizeof(char *);
- for (i=0; i<nummodes; i++)
- if (PL_strcmp(modestring, mode_strings[i]) == 0)
- return crypto_fns[i];
- PR_fprintf(PR_STDERR, "%s: invalid mode: %s\n", progName, modestring);
- return NULL;
-}
-
-static void
-get_params(blapitestInfo *info, char *mode, int num)
-{
- SECItem *item;
- /* XXX
- * this should use NSPR, but the string functions (strchr and atoi)
- * barf when the commented code below is used.
- PRFileDesc *file;
- */
- FILE *file;
- char filename[32];
- char *mark, *param, *val;
- int index = 0;
- int len;
- sprintf(filename, "%s/tests/%s/params%d", testdir, mode, num);
- /*
- file = PR_Open(filename, PR_RDONLY, 00440);
- if (file)
- SECU_FileToItem(item, file);
- else
- return;
- param = (char *)item->data;
- */
- file = fopen(filename, "r");
- if (!file) return;
- param = malloc(100);
- len = fread(param, 1, 100, file);
- while (index < len) {
- mark = PL_strchr(param, '=');
- *mark = '\0';
- val = mark + 1;
- mark = PL_strchr(val, '\n');
- *mark = '\0';
- if (PL_strcmp(param, "rounds") == 0) {
- info->rounds = atoi(val);
- } else if (PL_strcmp(param, "wordsize") == 0) {
- info->wordsize = atoi(val);
- }
- index += PL_strlen(param) + PL_strlen(val) + 2;
- param = mark + 1;
- }
-}
-
-static SECStatus
-get_ascii_file_data(SECItem *item, char *mode, char *type, int num)
-{
- char filename[32];
- PRFileDesc *file;
- SECStatus rv;
- sprintf(filename, "%s/tests/%s/%s%d", testdir, mode, type, num);
- file = PR_Open(filename, PR_RDONLY, 00440);
- if (file) {
- rv = SECU_FileToItem(item, file);
- } else {
- /* Not a failure if "mode" does not need "type". */
- return SECSuccess;
- }
- if ((PL_strcmp(mode, "rsa") == 0 || PL_strcmp(mode, "dsa") == 0) &&
- PL_strcmp(type, "key") == 0)
- atob(SECITEM_DupItem(item), item);
- /* remove a trailing newline, else byte count will be wrong */
- if (item->data[item->len-1] == '\n')
- item->len--;
- PR_Close(file);
- return rv;
-}
-
-static SECStatus
-blapi_selftest(char **modesToTest, int numModesToTest)
-{
- blapitestCryptoFn cryptofn;
- blapitestInfo info;
- SECItem output, asciiOut, item, inpCopy;
- SECStatus rv;
- char filename[32];
- PRFileDesc *file;
- char *mode;
- int i, j, nummodes;
-
- PORT_Memset(&info, 0, sizeof(info));
- info.repetitions = 1;
- info.useseed = PR_TRUE;
- info.usesigseed = PR_TRUE;
- if (modesToTest) {
- /* user gave a list of modes to test */
- nummodes = numModesToTest;
- } else {
- /* test all modes */
- nummodes = sizeof(mode_strings) / sizeof(char *);
- }
- for (i=0; i<nummodes; i++) {
- if (modesToTest) {
- mode = modesToTest[i];
- } else {
- mode = mode_strings[i];
- }
- /* skip pqg - nothing to do for self-test. */
- if (PL_strcmp(mode, "pqg") == 0)
- continue;
- cryptofn = get_test_mode(mode);
- if (mode[0] == '#') continue;
- /* get the number of tests in the directory */
- sprintf(filename, "%s/tests/%s/%s", testdir, mode, "numtests");
- file = PR_Open(filename, PR_RDONLY, 00440);
- if (!file) {
- fprintf(stderr, "File %s does not exist.\n", filename);
- return SECFailure;
- }
- rv = SECU_FileToItem(&item, file);
- PR_Close(file);
- /* loop over the tests in the directory */
- for (j=0; j<(int)(item.data[0] - '0'); j++) {
- rv = get_ascii_file_data(&info.key, mode, "key", j);
- rv = get_ascii_file_data(&info.iv, mode, "iv", j);
- rv = get_ascii_file_data(&info.in, mode, "plaintext", j);
- rv = get_ascii_file_data(&info.seed, mode, "keyseed", j);
- rv = get_ascii_file_data(&info.sigseed, mode, "sigseed", j);
- SECITEM_CopyItem(NULL, &inpCopy, &info.in);
- get_params(&info, mode, j);
- sprintf(filename, "%s/tests/%s/%s%d", testdir, mode,
- "ciphertext", j);
- file = PR_Open(filename, PR_RDONLY, 00440);
- rv = SECU_FileToItem(&asciiOut, file);
- PR_Close(file);
- rv = atob(&asciiOut, &output);
- info.encrypt = info.hash = info.sign = PR_TRUE;
- (*cryptofn)(&info);
- if (SECITEM_CompareItem(&output, &info.out) != 0) {
- printf("encrypt self-test for %s failed!\n", mode);
- } else {
- printf("encrypt self-test for %s passed.\n", mode);
- }
- info.encrypt = info.hash = info.sign = PR_FALSE;
- info.decrypt = info.verify = PR_TRUE;
- if (PL_strcmp(mode, "dsa") == 0) {
- rv = (*cryptofn)(&info);
- if (rv == SECSuccess) {
- printf("signature self-test for %s passed.\n", mode);
- } else {
- printf("signature self-test for %s failed!\n", mode);
- }
- } else {
- SECITEM_ZfreeItem(&info.in, PR_FALSE);
- SECITEM_ZfreeItem(&info.out, PR_FALSE);
- SECITEM_CopyItem(NULL, &info.in, &output);
- info.out.len = 0;
- rv = (*cryptofn)(&info);
- if (rv == SECSuccess) {
- if (SECITEM_CompareItem(&inpCopy, &info.out) != 0) {
- printf("decrypt self-test for %s failed!\n", mode);
- } else {
- printf("decrypt self-test for %s passed.\n", mode);
- }
- }
- }
- }
- }
- return SECSuccess;
-}
-
-static SECStatus
-get_file_data(char *filename, SECItem *item, PRBool b64)
-{
- SECStatus rv = SECSuccess;
- PRFileDesc *file = PR_Open(filename, PR_RDONLY, 006600);
- if (file) {
- SECItem asciiItem;
- rv = SECU_FileToItem(&asciiItem, file);
- CHECKERROR(rv, __LINE__);
- if (b64) {
- rv = atob(&asciiItem, item);
- } else {
- SECITEM_CopyItem(NULL, item, &asciiItem);
- if (item->data[item->len-1] == '\n')
- item->len--;
- }
- CHECKERROR(rv, __LINE__);
- PR_Close(file);
- }
- return rv;
-}
-
-SECStatus
-dump_file(char *mode, char *filename)
-{
- SECItem item;
- if (PL_strcmp(mode, "rsa") == 0) {
- } else if (PL_strcmp(mode, "pqg") == 0) {
- PQGParams *pqg;
- get_file_data(filename, &item, PR_TRUE);
- pqg = pqg_from_filedata(&item);
- dump_pqg(pqg);
- } else if (PL_strcmp(mode, "dsa") == 0) {
- DSAPrivateKey *key;
- get_file_data(filename, &item, PR_TRUE);
- key = dsakey_from_filedata(&item);
- dump_dsakey(key);
- }
- return SECFailure;
-}
-
-int main(int argc, char **argv)
-{
- char *infile, *outfile, *keyfile, *ivfile, *sigfile, *seedfile,
- *sigseedfile, *pqgfile;
- PRBool b64 = PR_TRUE;
- blapitestInfo info;
- blapitestCryptoFn cryptofn = NULL;
- PLOptState *optstate;
- PLOptStatus status;
- PRBool dofips = PR_FALSE;
- PRBool doselftest = PR_FALSE;
- PRBool zerobuffer = PR_FALSE;
- char *dumpfile = NULL;
- char *mode = NULL;
- char *modesToTest[20];
- int numModesToTest = 0;
- SECStatus rv;
-
- PORT_Memset(&info, 0, sizeof(info));
- info.bufsize = 8;
- info.keysize = DES_KEY_LENGTH;
- info.rsapubexp = 17;
- info.rounds = 10;
- info.wordsize = 4;
- infile=outfile=keyfile=pqgfile=ivfile=sigfile=seedfile=sigseedfile=NULL;
- info.repetitions = 1;
- progName = strrchr(argv[0], '/');
- progName = progName ? progName+1 : argv[0];
- optstate = PL_CreateOptState(argc, argv,
- "DEFHP:STVab:d:ce:g:j:i:o:p:k:m:t:qr:s:v:w:xyz:");
- while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
- switch (optstate->option) {
- case 'D': info.decrypt = PR_TRUE; break;
- case 'E': info.encrypt = PR_TRUE; break;
- case 'F': dofips = PR_TRUE; break;
- case 'H': info.hash = PR_TRUE; break;
- case 'P': dumpfile = PL_strdup(optstate->value); break;
- case 'S': info.sign = PR_TRUE; break;
- case 'T': doselftest = PR_TRUE; break;
- case 'V': info.verify = PR_TRUE; break;
- case 'a': b64 = PR_FALSE; break;
- case 'b': info.bufsize = PORT_Atoi(optstate->value); break;
- case 'c': info.multihash = PR_TRUE; break;
- case 'd': testdir = PL_strdup(optstate->value); break;
- case 'e': info.rsapubexp = PORT_Atoi(optstate->value); break;
- case 'g': info.keysize = PORT_Atoi(optstate->value); break;
- case 'i': infile = PL_strdup(optstate->value); break;
- case 'j': pqgfile = PL_strdup(optstate->value); break;
- case 'k': keyfile = PL_strdup(optstate->value); break;
- case 'm': cryptofn = get_test_mode(optstate->value);
- mode = PL_strdup(optstate->value);
- break;
- case 'o': outfile = PL_strdup(optstate->value); break;
- case 'p': info.performance = PR_TRUE;
- info.repetitions = PORT_Atoi(optstate->value);
- break;
- case 'q': zerobuffer = PR_TRUE; break;
- case 'r': info.rounds = PORT_Atoi(optstate->value); break;
- case 's': sigfile = PL_strdup(optstate->value); break;
- case 't': sigseedfile = PL_strdup(optstate->value); break;
- case 'v': ivfile = PL_strdup(optstate->value); break;
- case 'w': info.wordsize = PORT_Atoi(optstate->value); break;
- case 'x': info.useseed = PR_TRUE; break;
- case 'y': info.usesigseed = PR_TRUE; break;
- case 'z': seedfile = PL_strdup(optstate->value); break;
- case '\0': if (optstate->value[0] != '-')
- modesToTest[numModesToTest++] =
- PL_strdup(optstate->value);
- break;
- default: break;
- }
- }
-
- if (dumpfile)
- return dump_file(mode, dumpfile);
-
- if (doselftest) {
- if (numModesToTest > 0) {
- return blapi_selftest(modesToTest, numModesToTest);
- } else {
- return blapi_selftest(NULL, 0);
- }
- }
-
- if (dofips) {
- CK_RV foo = pk11_fipsPowerUpSelfTest();
- PR_fprintf(PR_STDOUT, "CK_RV: %d.\n", foo);
- return 0;
- }
-
- if (!info.encrypt && !info.decrypt && !info.hash &&
- !info.sign && !info.verify)
- Usage();
-
- if (!cryptofn) {
- printmodes(&info);
- return -1;
- }
-
- if (info.decrypt && !infile)
- Usage();
-
- if (info.performance) {
- char buf[256];
- PRStatus stat;
- stat = PR_GetSystemInfo(PR_SI_HOSTNAME, buf, sizeof(buf));
- printf("HOST: %s\n", buf);
- stat = PR_GetSystemInfo(PR_SI_SYSNAME, buf, sizeof(buf));
- printf("SYSTEM: %s\n", buf);
- stat = PR_GetSystemInfo(PR_SI_RELEASE, buf, sizeof(buf));
- printf("RELEASE: %s\n", buf);
- stat = PR_GetSystemInfo(PR_SI_ARCHITECTURE, buf, sizeof(buf));
- printf("ARCH: %s\n", buf);
- }
-
- RNG_RNGInit();
-
- if (keyfile) {
- /* RSA and DSA keys are always b64 encoded. */
- if (b64 || PL_strcmp(mode,"rsa")==0 || PL_strcmp(mode,"dsa")==0)
- get_file_data(keyfile, &info.key, PR_TRUE);
- else
- get_file_data(keyfile, &info.key, b64);
- }
- if (ivfile)
- get_file_data(ivfile, &info.iv, b64);
- if (infile)
- get_file_data(infile, &info.in, b64);
- if (sigfile)
- get_file_data(sigfile, &info.out, PR_TRUE);
- if (seedfile) {
- get_file_data(seedfile, &info.seed, b64);
- info.useseed = PR_TRUE;
- }
- if (sigseedfile) {
- get_file_data(sigseedfile, &info.sigseed, b64);
- info.usesigseed = PR_TRUE;
- }
- if (pqgfile)
- get_file_data(pqgfile, &info.pqg, PR_TRUE);
-
- if (zerobuffer) {
- PRFileDesc *ifile;
- info.in.len = info.bufsize;
- info.in.data = PORT_ZAlloc(info.in.len);
- ifile = PR_Open("tmp.pt", PR_WRONLY|PR_CREATE_FILE, 00660);
- rv = btoa_file(&info.in, ifile);
- CHECKERROR((rv < 0), __LINE__);
- PR_Close(ifile);
- }
-
- rv = (*cryptofn)(&info);
- CHECKERROR(rv, __LINE__);
-
- if (!sigfile && info.out.len > 0) {
- PRFileDesc *ofile;
- if (!outfile)
- ofile = PR_Open("tmp.out", PR_WRONLY|PR_CREATE_FILE, 00660);
- else
- ofile = PR_Open(outfile, PR_WRONLY|PR_CREATE_FILE, 00660);
- rv = btoa_file(&info.out, ofile);
- PR_Close(ofile);
- CHECKERROR((rv < 0), __LINE__);
- }
-
- RNG_RNGShutdown();
-
- return SECSuccess;
-}
diff --git a/security/nss/cmd/bltest/manifest.mn b/security/nss/cmd/bltest/manifest.mn
deleted file mode 100644
index ad31bb961..000000000
--- a/security/nss/cmd/bltest/manifest.mn
+++ /dev/null
@@ -1,50 +0,0 @@
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-CORE_DEPTH = ../../..
-
-MODULE = security
-
-REQUIRES = seccmd dbm
-
-PROGRAM = bltest
-
-EXPORTS = \
- $(NULL)
-
-PRIVATE_EXPORTS = \
- $(NULL)
-
-CSRCS = \
- blapitest.c \
- $(NULL)
-
diff --git a/security/nss/cmd/bltest/tests/README b/security/nss/cmd/bltest/tests/README
deleted file mode 100644
index 998639aee..000000000
--- a/security/nss/cmd/bltest/tests/README
+++ /dev/null
@@ -1,26 +0,0 @@
-This directory contains a set of tests for each cipher supported by BLAPI. Each subdirectory contains known plaintext and ciphertext pairs (and keys and/or iv's if needed). The tests can be run as a full set with:
-bltest -T
-or as subsets, for example:
-bltest -T des_ecb rc2 rsa
-
-In each subdirectory, the plaintext, key, and iv are ascii, and treated as such. The ciphertext is base64-encoded to avoid the hassle of binary files.
-
-To add a test, incremement the value in the numtests file. Create a plaintext, key, and iv file, such that the name of the file is incrememted one from the last set of tests. For example, if you are adding the second test, put your data in files named plaintext1, key1, and iv1 (ignoring key and iv if they are not needed, of course). Make sure your key and iv are the correct number of bytes for your cipher (a trailing \n is okay, but any other trailing bytes will be used!). Once you have your input data, create output data by running bltest on a trusted implementation. For example, for a new DES ECB test, run
-bltest -E -m des_ecb -i plaintext1 -k key1 -o ciphertext1 -a
-in the tests/des_ecb directory. Then run
-bltest -T des_ecb
-from the cmd/bltest directory in the tree of the implementation you want to test.
-
-Note that the -a option above is important, it tells bltest to expect the input to be straight ASCII, and not base64 encoded binary!
-
-Special cases:
-
-RC5:
-RC5 can take additional parameters, the number of rounds to perform and the wordsize to use. The number of rounds is between is between 0 and 255, and the wordsize is either is either 16, 32, or 64 bits (at this time only 32-bit is supported). These parameters are specified in a paramsN file, where N is an index as above. The format of the file is "rounds=R\nwordsize=W\n".
-
-public key modes (RSA and DSA):
-Asymmetric key ciphers use keys with special properties, so creating a key file with "Mozilla!" in it will not get you very far! To create a public key, run bltest with the plaintext you want to encrypt, using a trusted implementation. bltest will generate a key and store it in "tmp.key", rename that file to keyN. For example:
-bltest -E -m rsa -i plaintext0 -o ciphertext0 -e 65537 -g 32 -a
-mv tmp.key key0
-
-[note: specifying a keysize (-g) when using RSA is important!] \ No newline at end of file
diff --git a/security/nss/cmd/bltest/tests/des3_cbc/ciphertext0 b/security/nss/cmd/bltest/tests/des3_cbc/ciphertext0
deleted file mode 100644
index b5b78e440..000000000
--- a/security/nss/cmd/bltest/tests/des3_cbc/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-KV3MDNGKWOc=
diff --git a/security/nss/cmd/bltest/tests/des3_cbc/iv0 b/security/nss/cmd/bltest/tests/des3_cbc/iv0
deleted file mode 100644
index 97b5955f7..000000000
--- a/security/nss/cmd/bltest/tests/des3_cbc/iv0
+++ /dev/null
@@ -1 +0,0 @@
-12345678
diff --git a/security/nss/cmd/bltest/tests/des3_cbc/key0 b/security/nss/cmd/bltest/tests/des3_cbc/key0
deleted file mode 100644
index 588efd111..000000000
--- a/security/nss/cmd/bltest/tests/des3_cbc/key0
+++ /dev/null
@@ -1 +0,0 @@
-abcdefghijklmnopqrstuvwx
diff --git a/security/nss/cmd/bltest/tests/des3_cbc/numtests b/security/nss/cmd/bltest/tests/des3_cbc/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/des3_cbc/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/des3_cbc/plaintext0 b/security/nss/cmd/bltest/tests/des3_cbc/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/des3_cbc/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/des3_ecb/ciphertext0 b/security/nss/cmd/bltest/tests/des3_ecb/ciphertext0
deleted file mode 100644
index 7bdcde21d..000000000
--- a/security/nss/cmd/bltest/tests/des3_ecb/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-RgckVNh4QcM=
diff --git a/security/nss/cmd/bltest/tests/des3_ecb/key0 b/security/nss/cmd/bltest/tests/des3_ecb/key0
deleted file mode 100644
index 588efd111..000000000
--- a/security/nss/cmd/bltest/tests/des3_ecb/key0
+++ /dev/null
@@ -1 +0,0 @@
-abcdefghijklmnopqrstuvwx
diff --git a/security/nss/cmd/bltest/tests/des3_ecb/numtests b/security/nss/cmd/bltest/tests/des3_ecb/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/des3_ecb/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/des3_ecb/plaintext0 b/security/nss/cmd/bltest/tests/des3_ecb/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/des3_ecb/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/des_cbc/ciphertext0 b/security/nss/cmd/bltest/tests/des_cbc/ciphertext0
deleted file mode 100644
index 56acfeeaf..000000000
--- a/security/nss/cmd/bltest/tests/des_cbc/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-Perdg9FMYQ4=
diff --git a/security/nss/cmd/bltest/tests/des_cbc/iv0 b/security/nss/cmd/bltest/tests/des_cbc/iv0
deleted file mode 100644
index 97b5955f7..000000000
--- a/security/nss/cmd/bltest/tests/des_cbc/iv0
+++ /dev/null
@@ -1 +0,0 @@
-12345678
diff --git a/security/nss/cmd/bltest/tests/des_cbc/key0 b/security/nss/cmd/bltest/tests/des_cbc/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/des_cbc/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/des_cbc/numtests b/security/nss/cmd/bltest/tests/des_cbc/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/des_cbc/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/des_cbc/plaintext0 b/security/nss/cmd/bltest/tests/des_cbc/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/des_cbc/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/des_ecb/ciphertext0 b/security/nss/cmd/bltest/tests/des_ecb/ciphertext0
deleted file mode 100644
index 86ed115a1..000000000
--- a/security/nss/cmd/bltest/tests/des_ecb/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-3bNoWzzNiFc=
diff --git a/security/nss/cmd/bltest/tests/des_ecb/key0 b/security/nss/cmd/bltest/tests/des_ecb/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/des_ecb/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/des_ecb/numtests b/security/nss/cmd/bltest/tests/des_ecb/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/des_ecb/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/des_ecb/plaintext0 b/security/nss/cmd/bltest/tests/des_ecb/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/des_ecb/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/dsa/ciphertext0 b/security/nss/cmd/bltest/tests/dsa/ciphertext0
deleted file mode 100644
index 784581fae..000000000
--- a/security/nss/cmd/bltest/tests/dsa/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-gG8blX+paEQhO6vfYbOJTk8VnulxdWZwl4q2LG+QZuxFMOmuKedJ0g==
diff --git a/security/nss/cmd/bltest/tests/dsa/key0 b/security/nss/cmd/bltest/tests/dsa/key0
deleted file mode 100644
index ce4aab925..000000000
--- a/security/nss/cmd/bltest/tests/dsa/key0
+++ /dev/null
@@ -1,6 +0,0 @@
-AAAAQPMqxsvVL4Wyzr79fr0/61V0IbRwQ+KdFgP1rdaCzTmh+zMXOL47dBC5sL2v
-0df+bpOitrFZeiLchi6Mc+wpjREAAAAUmMYJXJpQuVvoX782XJeR1RiGRo0AAABA
-gwPAlkPOf8Mm/ZhKhzxu/IJv5QPsFmV6cZsASJmYlgty3gIheyB+V/H0rTmSgTTu
-jgqFjPhwEkCDVKV8ciuQ/QAAAEEAqfgFS3p3KP86A9LIzJBVTIwsV7xB6dp1J6w5
-070lCOfMWQYFR2jx8SxDWsar9SfNTNx4TKJPHLpd278pJ4J2tAAAABQyMC1ieXRl
-IHNlZWQgZm9yIGtleQ==
diff --git a/security/nss/cmd/bltest/tests/dsa/keyseed0 b/security/nss/cmd/bltest/tests/dsa/keyseed0
deleted file mode 100644
index c90af8bb7..000000000
--- a/security/nss/cmd/bltest/tests/dsa/keyseed0
+++ /dev/null
@@ -1 +0,0 @@
-20-byte seed for key
diff --git a/security/nss/cmd/bltest/tests/dsa/numtests b/security/nss/cmd/bltest/tests/dsa/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/dsa/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/dsa/plaintext0 b/security/nss/cmd/bltest/tests/dsa/plaintext0
deleted file mode 100644
index 8b561c5b7..000000000
--- a/security/nss/cmd/bltest/tests/dsa/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Buffer to sign w/DSA
diff --git a/security/nss/cmd/bltest/tests/dsa/pqg0 b/security/nss/cmd/bltest/tests/dsa/pqg0
deleted file mode 100644
index a6459738f..000000000
--- a/security/nss/cmd/bltest/tests/dsa/pqg0
+++ /dev/null
@@ -1,4 +0,0 @@
-AAAAQPMqxsvVL4Wyzr79fr0/61V0IbRwQ+KdFgP1rdaCzTmh+zMXOL47dBC5sL2v
-0df+bpOitrFZeiLchi6Mc+wpjREAAAAUmMYJXJpQuVvoX782XJeR1RiGRo0AAABA
-gwPAlkPOf8Mm/ZhKhzxu/IJv5QPsFmV6cZsASJmYlgty3gIheyB+V/H0rTmSgTTu
-jgqFjPhwEkCDVKV8ciuQ/Q==
diff --git a/security/nss/cmd/bltest/tests/dsa/sigseed0 b/security/nss/cmd/bltest/tests/dsa/sigseed0
deleted file mode 100644
index 45f7e2421..000000000
--- a/security/nss/cmd/bltest/tests/dsa/sigseed0
+++ /dev/null
@@ -1 +0,0 @@
-20-byte seed for sig
diff --git a/security/nss/cmd/bltest/tests/md2/ciphertext0 b/security/nss/cmd/bltest/tests/md2/ciphertext0
deleted file mode 100644
index 0b7bc262f..000000000
--- a/security/nss/cmd/bltest/tests/md2/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-CS/UNcrWhB5Knt7Gf8Tz3Q==
diff --git a/security/nss/cmd/bltest/tests/md2/numtests b/security/nss/cmd/bltest/tests/md2/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/md2/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/md2/plaintext0 b/security/nss/cmd/bltest/tests/md2/plaintext0
deleted file mode 100644
index dce2994ba..000000000
--- a/security/nss/cmd/bltest/tests/md2/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-16-bytes to MD2.
diff --git a/security/nss/cmd/bltest/tests/md5/ciphertext0 b/security/nss/cmd/bltest/tests/md5/ciphertext0
deleted file mode 100644
index 7bb485d01..000000000
--- a/security/nss/cmd/bltest/tests/md5/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-XN8lnQuWAiMqmSGfvd8Hdw==
diff --git a/security/nss/cmd/bltest/tests/md5/numtests b/security/nss/cmd/bltest/tests/md5/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/md5/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/md5/plaintext0 b/security/nss/cmd/bltest/tests/md5/plaintext0
deleted file mode 100644
index 5ae3875e2..000000000
--- a/security/nss/cmd/bltest/tests/md5/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-63-byte input to MD5 can be a bit tricky, but no problems here.
diff --git a/security/nss/cmd/bltest/tests/rc2_cbc/ciphertext0 b/security/nss/cmd/bltest/tests/rc2_cbc/ciphertext0
deleted file mode 100644
index 91ddac381..000000000
--- a/security/nss/cmd/bltest/tests/rc2_cbc/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-3ki6eVsWpY8=
diff --git a/security/nss/cmd/bltest/tests/rc2_cbc/iv0 b/security/nss/cmd/bltest/tests/rc2_cbc/iv0
deleted file mode 100644
index 97b5955f7..000000000
--- a/security/nss/cmd/bltest/tests/rc2_cbc/iv0
+++ /dev/null
@@ -1 +0,0 @@
-12345678
diff --git a/security/nss/cmd/bltest/tests/rc2_cbc/key0 b/security/nss/cmd/bltest/tests/rc2_cbc/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/rc2_cbc/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/rc2_cbc/numtests b/security/nss/cmd/bltest/tests/rc2_cbc/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/rc2_cbc/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/rc2_cbc/plaintext0 b/security/nss/cmd/bltest/tests/rc2_cbc/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/rc2_cbc/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/rc2_ecb/ciphertext0 b/security/nss/cmd/bltest/tests/rc2_ecb/ciphertext0
deleted file mode 100644
index c569f4dbd..000000000
--- a/security/nss/cmd/bltest/tests/rc2_ecb/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-WT+tc4fANhQ=
diff --git a/security/nss/cmd/bltest/tests/rc2_ecb/key0 b/security/nss/cmd/bltest/tests/rc2_ecb/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/rc2_ecb/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/rc2_ecb/numtests b/security/nss/cmd/bltest/tests/rc2_ecb/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/rc2_ecb/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/rc2_ecb/plaintext0 b/security/nss/cmd/bltest/tests/rc2_ecb/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/rc2_ecb/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/rc4/ciphertext0 b/security/nss/cmd/bltest/tests/rc4/ciphertext0
deleted file mode 100644
index e0c2147dc..000000000
--- a/security/nss/cmd/bltest/tests/rc4/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-34sTZJtr20k=
diff --git a/security/nss/cmd/bltest/tests/rc4/key0 b/security/nss/cmd/bltest/tests/rc4/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/rc4/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/rc4/numtests b/security/nss/cmd/bltest/tests/rc4/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/rc4/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/rc4/plaintext0 b/security/nss/cmd/bltest/tests/rc4/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/rc4/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/rc5_cbc/ciphertext0 b/security/nss/cmd/bltest/tests/rc5_cbc/ciphertext0
deleted file mode 100644
index 2c5ae7e44..000000000
--- a/security/nss/cmd/bltest/tests/rc5_cbc/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-qsv4Fn2J6d0=
diff --git a/security/nss/cmd/bltest/tests/rc5_cbc/iv0 b/security/nss/cmd/bltest/tests/rc5_cbc/iv0
deleted file mode 100644
index 97b5955f7..000000000
--- a/security/nss/cmd/bltest/tests/rc5_cbc/iv0
+++ /dev/null
@@ -1 +0,0 @@
-12345678
diff --git a/security/nss/cmd/bltest/tests/rc5_cbc/key0 b/security/nss/cmd/bltest/tests/rc5_cbc/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/rc5_cbc/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/rc5_cbc/numtests b/security/nss/cmd/bltest/tests/rc5_cbc/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/rc5_cbc/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/rc5_cbc/params0 b/security/nss/cmd/bltest/tests/rc5_cbc/params0
deleted file mode 100644
index d68e0362d..000000000
--- a/security/nss/cmd/bltest/tests/rc5_cbc/params0
+++ /dev/null
@@ -1,2 +0,0 @@
-rounds=10
-wordsize=4
diff --git a/security/nss/cmd/bltest/tests/rc5_cbc/plaintext0 b/security/nss/cmd/bltest/tests/rc5_cbc/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/rc5_cbc/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/rc5_ecb/ciphertext0 b/security/nss/cmd/bltest/tests/rc5_ecb/ciphertext0
deleted file mode 100644
index 67c88bc8a..000000000
--- a/security/nss/cmd/bltest/tests/rc5_ecb/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-4ZKK/1v5Ohc=
diff --git a/security/nss/cmd/bltest/tests/rc5_ecb/key0 b/security/nss/cmd/bltest/tests/rc5_ecb/key0
deleted file mode 100644
index 65513c116..000000000
--- a/security/nss/cmd/bltest/tests/rc5_ecb/key0
+++ /dev/null
@@ -1 +0,0 @@
-zyxwvuts
diff --git a/security/nss/cmd/bltest/tests/rc5_ecb/numtests b/security/nss/cmd/bltest/tests/rc5_ecb/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/rc5_ecb/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/rc5_ecb/params0 b/security/nss/cmd/bltest/tests/rc5_ecb/params0
deleted file mode 100644
index d68e0362d..000000000
--- a/security/nss/cmd/bltest/tests/rc5_ecb/params0
+++ /dev/null
@@ -1,2 +0,0 @@
-rounds=10
-wordsize=4
diff --git a/security/nss/cmd/bltest/tests/rc5_ecb/plaintext0 b/security/nss/cmd/bltest/tests/rc5_ecb/plaintext0
deleted file mode 100644
index 5513e438c..000000000
--- a/security/nss/cmd/bltest/tests/rc5_ecb/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-Mozilla!
diff --git a/security/nss/cmd/bltest/tests/rsa/ciphertext0 b/security/nss/cmd/bltest/tests/rsa/ciphertext0
deleted file mode 100644
index e6357efd7..000000000
--- a/security/nss/cmd/bltest/tests/rsa/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-qPVrXv0y3SC5rY44bIi6GE4Aec8uDpHH7/cCg0FU5as=
diff --git a/security/nss/cmd/bltest/tests/rsa/key0 b/security/nss/cmd/bltest/tests/rsa/key0
deleted file mode 100644
index 1352fe986..000000000
--- a/security/nss/cmd/bltest/tests/rsa/key0
+++ /dev/null
@@ -1,4 +0,0 @@
-AAAAAAAAACC5lyu2K2ro8YGnvOCKaL1sFX1HEIblIVbuMXsa8oeFSwAAAAERAAAA
-IBXVjKwFG6LvPG4WOIjBBzmxGNpkQwDs3W5qZcXVzqahAAAAEOEOH/WnhZCJyM39
-oNfhf18AAAAQ0xvmxqXXs3L62xxogUl9lQAAABAaeiHgqkvy4wiQtG1Gkv/tAAAA
-EMaw2TNu6SFdKFXAYluQdjEAAAAQi0u+IlgKCt/hatGAsTrfzQ==
diff --git a/security/nss/cmd/bltest/tests/rsa/numtests b/security/nss/cmd/bltest/tests/rsa/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/rsa/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/rsa/plaintext0 b/security/nss/cmd/bltest/tests/rsa/plaintext0
deleted file mode 100644
index d915bc88c..000000000
--- a/security/nss/cmd/bltest/tests/rsa/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-512bitsforRSAPublicKeyEncryption
diff --git a/security/nss/cmd/bltest/tests/sha1/ciphertext0 b/security/nss/cmd/bltest/tests/sha1/ciphertext0
deleted file mode 100644
index a33d020cd..000000000
--- a/security/nss/cmd/bltest/tests/sha1/ciphertext0
+++ /dev/null
@@ -1 +0,0 @@
-cDSMAygXMPIJZC5bntZ4ZhecQ9g=
diff --git a/security/nss/cmd/bltest/tests/sha1/numtests b/security/nss/cmd/bltest/tests/sha1/numtests
deleted file mode 100644
index d00491fd7..000000000
--- a/security/nss/cmd/bltest/tests/sha1/numtests
+++ /dev/null
@@ -1 +0,0 @@
-1
diff --git a/security/nss/cmd/bltest/tests/sha1/plaintext0 b/security/nss/cmd/bltest/tests/sha1/plaintext0
deleted file mode 100644
index 863e79c65..000000000
--- a/security/nss/cmd/bltest/tests/sha1/plaintext0
+++ /dev/null
@@ -1 +0,0 @@
-A cage went in search of a bird.
diff --git a/security/nss/cmd/modutil/Makefile b/security/nss/cmd/modutil/Makefile
deleted file mode 100644
index 5f4321fec..000000000
--- a/security/nss/cmd/modutil/Makefile
+++ /dev/null
@@ -1,85 +0,0 @@
-#! gmake
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-
-#######################################################################
-# (1) Include initial platform-independent assignments (MANDATORY). #
-#######################################################################
-
-include manifest.mn
-
-#######################################################################
-# (2) Include "global" configuration information. (OPTIONAL) #
-#######################################################################
-
-include $(CORE_DEPTH)/coreconf/config.mk
-
-#######################################################################
-# (3) Include "component" configuration information. (OPTIONAL) #
-#######################################################################
-
-#######################################################################
-# (4) Include "local" platform-dependent assignments (OPTIONAL). #
-#######################################################################
-include ../platlibs.mk
-
-#######################################################################
-# (5) Execute "global" rules. (OPTIONAL) #
-#######################################################################
-
-include $(CORE_DEPTH)/coreconf/rules.mk
-
-#######################################################################
-# (6) Execute "component" rules. (OPTIONAL) #
-#######################################################################
-
-
-
-#######################################################################
-# (7) Execute "local" rules. (OPTIONAL). #
-#######################################################################
-
-
-include ../platrules.mk
-
-ifeq ($(OS_ARCH), WINNT)
-installparse.c: installparse.y
- yacc -d installparse.y
- mv ytab.c installparse.c
- mv ytab.h installparse.h
-else
-installparse.c: installparse.y
- yacc -d installparse.y
- mv y.tab.c installparse.c
- mv y.tab.h installparse.h
-endif
diff --git a/security/nss/cmd/modutil/installparse.c b/security/nss/cmd/modutil/installparse.c
deleted file mode 100644
index 5afa19ba6..000000000
--- a/security/nss/cmd/modutil/installparse.c
+++ /dev/null
@@ -1,745 +0,0 @@
-
-# line 37 "installparse.y"
-
-#define yyparse Pk11Install_yyparse
-#define yylex Pk11Install_yylex
-#define yyerror Pk11Install_yyerror
-#define yychar Pk11Install_yychar
-#define yyval Pk11Install_yyval
-#define yylval Pk11Install_yylval
-#define yydebug Pk11Install_yydebug
-#define yynerrs Pk11Install_yynerrs
-#define yyerrflag Pk11Install_yyerrflag
-#define yyss Pk11Install_yyss
-#define yyssp Pk11Install_yyssp
-#define yyvs Pk11Install_yyvs
-#define yyvsp Pk11Install_yyvsp
-#define yylhs Pk11Install_yylhs
-#define yylen Pk11Install_yylen
-#define yydefred Pk11Install_yydefred
-#define yydgoto Pk11Install_yydgoto
-#define yysindex Pk11Install_yysindex
-#define yyrindex Pk11Install_yyrindex
-#define yygindex Pk11Install_yygindex
-#define yytable Pk11Install_yytable
-#define yycheck Pk11Install_yycheck
-#define yyname Pk11Install_yyname
-#define yyrule Pk11Install_yyrule
-
-/* C Stuff */
-#include "install-ds.h"
-#include <prprf.h>
-
-#define YYSTYPE Pk11Install_Pointer
-extern char *Pk11Install_yytext;
-char *Pk11Install_yyerrstr=NULL;
-
-# define OPENBRACE 257
-# define CLOSEBRACE 258
-# define STRING 259
-
-#ifdef __STDC__
-#include <stdlib.h>
-#include <string.h>
-#else
-#include <malloc.h>
-#include <memory.h>
-#endif
-
-#include <values.h>
-
-#ifdef __cplusplus
-
-#ifndef yyerror
- void yyerror(const char *);
-#endif
-
-#ifndef yylex
-#ifdef __EXTERN_C__
- extern "C" { int yylex(void); }
-#else
- int yylex(void);
-#endif
-#endif
- int yyparse(void);
-
-#endif
-#define yyclearin yychar = -1
-#define yyerrok yyerrflag = 0
-extern int yychar;
-extern int yyerrflag;
-#ifndef YYSTYPE
-#define YYSTYPE int
-#endif
-YYSTYPE yylval;
-YYSTYPE yyval;
-typedef int yytabelem;
-#ifndef YYMAXDEPTH
-#define YYMAXDEPTH 150
-#endif
-#if YYMAXDEPTH > 0
-int yy_yys[YYMAXDEPTH], *yys = yy_yys;
-YYSTYPE yy_yyv[YYMAXDEPTH], *yyv = yy_yyv;
-#else /* user does initial allocation */
-int *yys;
-YYSTYPE *yyv;
-#endif
-static int yymaxdepth = YYMAXDEPTH;
-# define YYERRCODE 256
-
-# line 117 "installparse.y"
-
-/*----------------------- Program Section --------------------------------*/
-
-/*************************************************************************/
-void
-Pk11Install_yyerror(char *message)
-{
- char *tmp;
- if(Pk11Install_yyerrstr) {
- tmp=PR_smprintf("%sline %d: %s\n", Pk11Install_yyerrstr,
- Pk11Install_yylinenum, message);
- PR_smprintf_free(Pk11Install_yyerrstr);
- } else {
- tmp = PR_smprintf("line %d: %s\n", Pk11Install_yylinenum, message);
- }
- Pk11Install_yyerrstr=tmp;
-}
-static const yytabelem yyexca[] ={
--1, 1,
- 0, -1,
- -2, 0,
--1, 5,
- 257, 7,
- -2, 5,
- };
-# define YYNPROD 8
-# define YYLAST 13
-static const yytabelem yyact[]={
-
- 5, 10, 8, 2, 6, 4, 3, 7, 1, 0,
- 0, 0, 9 };
-static const yytabelem yypact[]={
-
- -259,-10000000,-10000000, -259,-10000000,-10000000, -255,-10000000, -259, -257,
--10000000 };
-static const yytabelem yypgo[]={
-
- 0, 8, 3, 6, 5, 4 };
-static const yytabelem yyr1[]={
-
- 0, 1, 2, 2, 3, 3, 4, 5 };
-static const yytabelem yyr2[]={
-
- 0, 3, 5, 1, 3, 3, 9, 3 };
-static const yytabelem yychk[]={
-
--10000000, -1, -2, -3, -4, 259, -5, -2, 257, -2,
- 258 };
-static const yytabelem yydef[]={
-
- 3, -2, 1, 3, 4, -2, 0, 2, 3, 0,
- 6 };
-typedef struct
-#ifdef __cplusplus
- yytoktype
-#endif
-{ char *t_name; int t_val; } yytoktype;
-#ifndef YYDEBUG
-# define YYDEBUG 0 /* don't allow debugging */
-#endif
-
-#if YYDEBUG
-
-yytoktype yytoks[] =
-{
- "OPENBRACE", 257,
- "CLOSEBRACE", 258,
- "STRING", 259,
- "-unknown-", -1 /* ends search */
-};
-
-char * yyreds[] =
-{
- "-no such reduction-",
- "toplist : valuelist",
- "valuelist : value valuelist",
- "valuelist : /* empty */",
- "value : key_value_pair",
- "value : STRING",
- "key_value_pair : key OPENBRACE valuelist CLOSEBRACE",
- "key : STRING",
-};
-#endif /* YYDEBUG */
-# line 1 "/usr/ccs/bin/yaccpar"
-/*
- * Copyright (c) 1993 by Sun Microsystems, Inc.
- */
-
-#pragma ident "@(#)yaccpar 6.14 97/01/16 SMI"
-
-/*
-** Skeleton parser driver for yacc output
-*/
-
-/*
-** yacc user known macros and defines
-*/
-#define YYERROR goto yyerrlab
-#define YYACCEPT return(0)
-#define YYABORT return(1)
-#define YYBACKUP( newtoken, newvalue )\
-{\
- if ( yychar >= 0 || ( yyr2[ yytmp ] >> 1 ) != 1 )\
- {\
- yyerror( "syntax error - cannot backup" );\
- goto yyerrlab;\
- }\
- yychar = newtoken;\
- yystate = *yyps;\
- yylval = newvalue;\
- goto yynewstate;\
-}
-#define YYRECOVERING() (!!yyerrflag)
-#define YYNEW(type) malloc(sizeof(type) * yynewmax)
-#define YYCOPY(to, from, type) \
- (type *) memcpy(to, (char *) from, yymaxdepth * sizeof (type))
-#define YYENLARGE( from, type) \
- (type *) realloc((char *) from, yynewmax * sizeof(type))
-#ifndef YYDEBUG
-# define YYDEBUG 1 /* make debugging available */
-#endif
-
-/*
-** user known globals
-*/
-int yydebug; /* set to 1 to get debugging */
-
-/*
-** driver internal defines
-*/
-#define YYFLAG (-10000000)
-
-/*
-** global variables used by the parser
-*/
-YYSTYPE *yypv; /* top of value stack */
-int *yyps; /* top of state stack */
-
-int yystate; /* current state */
-int yytmp; /* extra var (lasts between blocks) */
-
-int yynerrs; /* number of errors */
-int yyerrflag; /* error recovery flag */
-int yychar; /* current input token number */
-
-
-
-#ifdef YYNMBCHARS
-#define YYLEX() yycvtok(yylex())
-/*
-** yycvtok - return a token if i is a wchar_t value that exceeds 255.
-** If i<255, i itself is the token. If i>255 but the neither
-** of the 30th or 31st bit is on, i is already a token.
-*/
-#if defined(__STDC__) || defined(__cplusplus)
-int yycvtok(int i)
-#else
-int yycvtok(i) int i;
-#endif
-{
- int first = 0;
- int last = YYNMBCHARS - 1;
- int mid;
- wchar_t j;
-
- if(i&0x60000000){/*Must convert to a token. */
- if( yymbchars[last].character < i ){
- return i;/*Giving up*/
- }
- while ((last>=first)&&(first>=0)) {/*Binary search loop*/
- mid = (first+last)/2;
- j = yymbchars[mid].character;
- if( j==i ){/*Found*/
- return yymbchars[mid].tvalue;
- }else if( j<i ){
- first = mid + 1;
- }else{
- last = mid -1;
- }
- }
- /*No entry in the table.*/
- return i;/* Giving up.*/
- }else{/* i is already a token. */
- return i;
- }
-}
-#else/*!YYNMBCHARS*/
-#define YYLEX() yylex()
-#endif/*!YYNMBCHARS*/
-
-/*
-** yyparse - return 0 if worked, 1 if syntax error not recovered from
-*/
-#if defined(__STDC__) || defined(__cplusplus)
-int yyparse(void)
-#else
-int yyparse()
-#endif
-{
- register YYSTYPE *yypvt = 0; /* top of value stack for $vars */
-
-#if defined(__cplusplus) || defined(lint)
-/*
- hacks to please C++ and lint - goto's inside
- switch should never be executed
-*/
- static int __yaccpar_lint_hack__ = 0;
- switch (__yaccpar_lint_hack__)
- {
- case 1: goto yyerrlab;
- case 2: goto yynewstate;
- }
-#endif
-
- /*
- ** Initialize externals - yyparse may be called more than once
- */
- yypv = &yyv[-1];
- yyps = &yys[-1];
- yystate = 0;
- yytmp = 0;
- yynerrs = 0;
- yyerrflag = 0;
- yychar = -1;
-
-#if YYMAXDEPTH <= 0
- if (yymaxdepth <= 0)
- {
- if ((yymaxdepth = YYEXPAND(0)) <= 0)
- {
- yyerror("yacc initialization error");
- YYABORT;
- }
- }
-#endif
-
- {
- register YYSTYPE *yy_pv; /* top of value stack */
- register int *yy_ps; /* top of state stack */
- register int yy_state; /* current state */
- register int yy_n; /* internal state number info */
- goto yystack; /* moved from 6 lines above to here to please C++ */
-
- /*
- ** get globals into registers.
- ** branch to here only if YYBACKUP was called.
- */
- yynewstate:
- yy_pv = yypv;
- yy_ps = yyps;
- yy_state = yystate;
- goto yy_newstate;
-
- /*
- ** get globals into registers.
- ** either we just started, or we just finished a reduction
- */
- yystack:
- yy_pv = yypv;
- yy_ps = yyps;
- yy_state = yystate;
-
- /*
- ** top of for (;;) loop while no reductions done
- */
- yy_stack:
- /*
- ** put a state and value onto the stacks
- */
-#if YYDEBUG
- /*
- ** if debugging, look up token value in list of value vs.
- ** name pairs. 0 and negative (-1) are special values.
- ** Note: linear search is used since time is not a real
- ** consideration while debugging.
- */
- if ( yydebug )
- {
- register int yy_i;
-
- printf( "State %d, token ", yy_state );
- if ( yychar == 0 )
- printf( "end-of-file\n" );
- else if ( yychar < 0 )
- printf( "-none-\n" );
- else
- {
- for ( yy_i = 0; yytoks[yy_i].t_val >= 0;
- yy_i++ )
- {
- if ( yytoks[yy_i].t_val == yychar )
- break;
- }
- printf( "%s\n", yytoks[yy_i].t_name );
- }
- }
-#endif /* YYDEBUG */
- if ( ++yy_ps >= &yys[ yymaxdepth ] ) /* room on stack? */
- {
- /*
- ** reallocate and recover. Note that pointers
- ** have to be reset, or bad things will happen
- */
- int yyps_index = (yy_ps - yys);
- int yypv_index = (yy_pv - yyv);
- int yypvt_index = (yypvt - yyv);
- int yynewmax;
-#ifdef YYEXPAND
- yynewmax = YYEXPAND(yymaxdepth);
-#else
- yynewmax = 2 * yymaxdepth; /* double table size */
- if (yymaxdepth == YYMAXDEPTH) /* first time growth */
- {
- char *newyys = (char *)YYNEW(int);
- char *newyyv = (char *)YYNEW(YYSTYPE);
- if (newyys != 0 && newyyv != 0)
- {
- yys = YYCOPY(newyys, yys, int);
- yyv = YYCOPY(newyyv, yyv, YYSTYPE);
- }
- else
- yynewmax = 0; /* failed */
- }
- else /* not first time */
- {
- yys = YYENLARGE(yys, int);
- yyv = YYENLARGE(yyv, YYSTYPE);
- if (yys == 0 || yyv == 0)
- yynewmax = 0; /* failed */
- }
-#endif
- if (yynewmax <= yymaxdepth) /* tables not expanded */
- {
- yyerror( "yacc stack overflow" );
- YYABORT;
- }
- yymaxdepth = yynewmax;
-
- yy_ps = yys + yyps_index;
- yy_pv = yyv + yypv_index;
- yypvt = yyv + yypvt_index;
- }
- *yy_ps = yy_state;
- *++yy_pv = yyval;
-
- /*
- ** we have a new state - find out what to do
- */
- yy_newstate:
- if ( ( yy_n = yypact[ yy_state ] ) <= YYFLAG )
- goto yydefault; /* simple state */
-#if YYDEBUG
- /*
- ** if debugging, need to mark whether new token grabbed
- */
- yytmp = yychar < 0;
-#endif
- if ( ( yychar < 0 ) && ( ( yychar = YYLEX() ) < 0 ) )
- yychar = 0; /* reached EOF */
-#if YYDEBUG
- if ( yydebug && yytmp )
- {
- register int yy_i;
-
- printf( "Received token " );
- if ( yychar == 0 )
- printf( "end-of-file\n" );
- else if ( yychar < 0 )
- printf( "-none-\n" );
- else
- {
- for ( yy_i = 0; yytoks[yy_i].t_val >= 0;
- yy_i++ )
- {
- if ( yytoks[yy_i].t_val == yychar )
- break;
- }
- printf( "%s\n", yytoks[yy_i].t_name );
- }
- }
-#endif /* YYDEBUG */
- if ( ( ( yy_n += yychar ) < 0 ) || ( yy_n >= YYLAST ) )
- goto yydefault;
- if ( yychk[ yy_n = yyact[ yy_n ] ] == yychar ) /*valid shift*/
- {
- yychar = -1;
- yyval = yylval;
- yy_state = yy_n;
- if ( yyerrflag > 0 )
- yyerrflag--;
- goto yy_stack;
- }
-
- yydefault:
- if ( ( yy_n = yydef[ yy_state ] ) == -2 )
- {
-#if YYDEBUG
- yytmp = yychar < 0;
-#endif
- if ( ( yychar < 0 ) && ( ( yychar = YYLEX() ) < 0 ) )
- yychar = 0; /* reached EOF */
-#if YYDEBUG
- if ( yydebug && yytmp )
- {
- register int yy_i;
-
- printf( "Received token " );
- if ( yychar == 0 )
- printf( "end-of-file\n" );
- else if ( yychar < 0 )
- printf( "-none-\n" );
- else
- {
- for ( yy_i = 0;
- yytoks[yy_i].t_val >= 0;
- yy_i++ )
- {
- if ( yytoks[yy_i].t_val
- == yychar )
- {
- break;
- }
- }
- printf( "%s\n", yytoks[yy_i].t_name );
- }
- }
-#endif /* YYDEBUG */
- /*
- ** look through exception table
- */
- {
- register const int *yyxi = yyexca;
-
- while ( ( *yyxi != -1 ) ||
- ( yyxi[1] != yy_state ) )
- {
- yyxi += 2;
- }
- while ( ( *(yyxi += 2) >= 0 ) &&
- ( *yyxi != yychar ) )
- ;
- if ( ( yy_n = yyxi[1] ) < 0 )
- YYACCEPT;
- }
- }
-
- /*
- ** check for syntax error
- */
- if ( yy_n == 0 ) /* have an error */
- {
- /* no worry about speed here! */
- switch ( yyerrflag )
- {
- case 0: /* new error */
- yyerror( "syntax error" );
- goto skip_init;
- yyerrlab:
- /*
- ** get globals into registers.
- ** we have a user generated syntax type error
- */
- yy_pv = yypv;
- yy_ps = yyps;
- yy_state = yystate;
- skip_init:
- yynerrs++;
- /* FALLTHRU */
- case 1:
- case 2: /* incompletely recovered error */
- /* try again... */
- yyerrflag = 3;
- /*
- ** find state where "error" is a legal
- ** shift action
- */
- while ( yy_ps >= yys )
- {
- yy_n = yypact[ *yy_ps ] + YYERRCODE;
- if ( yy_n >= 0 && yy_n < YYLAST &&
- yychk[yyact[yy_n]] == YYERRCODE) {
- /*
- ** simulate shift of "error"
- */
- yy_state = yyact[ yy_n ];
- goto yy_stack;
- }
- /*
- ** current state has no shift on
- ** "error", pop stack
- */
-#if YYDEBUG
-# define _POP_ "Error recovery pops state %d, uncovers state %d\n"
- if ( yydebug )
- printf( _POP_, *yy_ps,
- yy_ps[-1] );
-# undef _POP_
-#endif
- yy_ps--;
- yy_pv--;
- }
- /*
- ** there is no state on stack with "error" as
- ** a valid shift. give up.
- */
- YYABORT;
- case 3: /* no shift yet; eat a token */
-#if YYDEBUG
- /*
- ** if debugging, look up token in list of
- ** pairs. 0 and negative shouldn't occur,
- ** but since timing doesn't matter when
- ** debugging, it doesn't hurt to leave the
- ** tests here.
- */
- if ( yydebug )
- {
- register int yy_i;
-
- printf( "Error recovery discards " );
- if ( yychar == 0 )
- printf( "token end-of-file\n" );
- else if ( yychar < 0 )
- printf( "token -none-\n" );
- else
- {
- for ( yy_i = 0;
- yytoks[yy_i].t_val >= 0;
- yy_i++ )
- {
- if ( yytoks[yy_i].t_val
- == yychar )
- {
- break;
- }
- }
- printf( "token %s\n",
- yytoks[yy_i].t_name );
- }
- }
-#endif /* YYDEBUG */
- if ( yychar == 0 ) /* reached EOF. quit */
- YYABORT;
- yychar = -1;
- goto yy_newstate;
- }
- }/* end if ( yy_n == 0 ) */
- /*
- ** reduction by production yy_n
- ** put stack tops, etc. so things right after switch
- */
-#if YYDEBUG
- /*
- ** if debugging, print the string that is the user's
- ** specification of the reduction which is just about
- ** to be done.
- */
- if ( yydebug )
- printf( "Reduce by (%d) \"%s\"\n",
- yy_n, yyreds[ yy_n ] );
-#endif
- yytmp = yy_n; /* value to switch over */
- yypvt = yy_pv; /* $vars top of value stack */
- /*
- ** Look in goto table for next state
- ** Sorry about using yy_state here as temporary
- ** register variable, but why not, if it works...
- ** If yyr2[ yy_n ] doesn't have the low order bit
- ** set, then there is no action to be done for
- ** this reduction. So, no saving & unsaving of
- ** registers done. The only difference between the
- ** code just after the if and the body of the if is
- ** the goto yy_stack in the body. This way the test
- ** can be made before the choice of what to do is needed.
- */
- {
- /* length of production doubled with extra bit */
- register int yy_len = yyr2[ yy_n ];
-
- if ( !( yy_len & 01 ) )
- {
- yy_len >>= 1;
- yyval = ( yy_pv -= yy_len )[1]; /* $$ = $1 */
- yy_state = yypgo[ yy_n = yyr1[ yy_n ] ] +
- *( yy_ps -= yy_len ) + 1;
- if ( yy_state >= YYLAST ||
- yychk[ yy_state =
- yyact[ yy_state ] ] != -yy_n )
- {
- yy_state = yyact[ yypgo[ yy_n ] ];
- }
- goto yy_stack;
- }
- yy_len >>= 1;
- yyval = ( yy_pv -= yy_len )[1]; /* $$ = $1 */
- yy_state = yypgo[ yy_n = yyr1[ yy_n ] ] +
- *( yy_ps -= yy_len ) + 1;
- if ( yy_state >= YYLAST ||
- yychk[ yy_state = yyact[ yy_state ] ] != -yy_n )
- {
- yy_state = yyact[ yypgo[ yy_n ] ];
- }
- }
- /* save until reenter driver code */
- yystate = yy_state;
- yyps = yy_ps;
- yypv = yy_pv;
- }
- /*
- ** code supplied by user is placed in this switch
- */
- switch( yytmp )
- {
-
-case 1:
-# line 84 "installparse.y"
-{
- Pk11Install_valueList = yypvt[-0].list;
-} break;
-case 2:
-# line 89 "installparse.y"
-{
- Pk11Install_ValueList_AddItem(yypvt[-0].list,yypvt[-1].value);
- yyval.list = yypvt[-0].list;
-} break;
-case 3:
-# line 94 "installparse.y"
-{
- yyval.list = Pk11Install_ValueList_new();
-} break;
-case 4:
-# line 99 "installparse.y"
-{
- yyval.value= Pk11Install_Value_new(PAIR_VALUE,yypvt[-0]);
-} break;
-case 5:
-# line 103 "installparse.y"
-{
- yyval.value= Pk11Install_Value_new(STRING_VALUE, yypvt[-0]);
-} break;
-case 6:
-# line 108 "installparse.y"
-{
- yyval.pair = Pk11Install_Pair_new(yypvt[-3].string,yypvt[-1].list);
-} break;
-case 7:
-# line 113 "installparse.y"
-{
- yyval.string = yypvt[-0].string;
-} break;
-# line 531 "/usr/ccs/bin/yaccpar"
- }
- goto yystack; /* reset registers in driver code */
-}
-
diff --git a/security/nss/cmd/modutil/installparse.h b/security/nss/cmd/modutil/installparse.h
deleted file mode 100644
index f57ad8f55..000000000
--- a/security/nss/cmd/modutil/installparse.h
+++ /dev/null
@@ -1,3 +0,0 @@
-# define OPENBRACE 257
-# define CLOSEBRACE 258
-# define STRING 259
diff --git a/security/nss/cmd/modutil/rules.mk b/security/nss/cmd/modutil/rules.mk
deleted file mode 100644
index c22175ffd..000000000
--- a/security/nss/cmd/modutil/rules.mk
+++ /dev/null
@@ -1,46 +0,0 @@
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-
-generate: installparse.c installparse.l
-
-installparse.c:
- yacc -p Pk11Install_yy -d installparse.y
- mv y.tab.c installparse.c
- mv y.tab.h installparse.h
-
-installparse.l:
- lex -olex.Pk11Install_yy.c -PPk11Install_yy installparse.l
- @echo
- @echo "**YOU MUST COMMENT OUT UNISTD.H FROM lex.Pk11Install_yy.cpp**"
-
-install.c: install-ds.h install.h
diff --git a/security/nss/cmd/strsclnt/strsclnt.c b/security/nss/cmd/strsclnt/strsclnt.c
deleted file mode 100644
index 059a0696e..000000000
--- a/security/nss/cmd/strsclnt/strsclnt.c
+++ /dev/null
@@ -1,1108 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-#include <stdio.h>
-#include <string.h>
-
-#include "secutil.h"
-
-#if defined(XP_UNIX)
-#include <unistd.h>
-#endif
-#include <stdlib.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdarg.h>
-
-#include "plgetopt.h"
-
-#include "nspr.h"
-#include "prio.h"
-#include "prnetdb.h"
-#include "prerror.h"
-
-#include "pk11func.h"
-#include "secitem.h"
-#include "sslproto.h"
-#include "nss.h"
-#include "ssl.h"
-
-#ifndef PORT_Sprintf
-#define PORT_Sprintf sprintf
-#endif
-
-#ifndef PORT_Strstr
-#define PORT_Strstr strstr
-#endif
-
-#ifndef PORT_Malloc
-#define PORT_Malloc PR_Malloc
-#endif
-
-#define RD_BUF_SIZE (60 * 1024)
-
-int cipherSuites[] = {
- SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA,
- SSL_FORTEZZA_DMS_WITH_RC4_128_SHA,
- SSL_RSA_WITH_RC4_128_MD5,
- SSL_RSA_WITH_3DES_EDE_CBC_SHA,
- SSL_RSA_WITH_DES_CBC_SHA,
- SSL_RSA_EXPORT_WITH_RC4_40_MD5,
- SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5,
- SSL_FORTEZZA_DMS_WITH_NULL_SHA,
- SSL_RSA_WITH_NULL_MD5,
- 0
-};
-
-/* Include these cipher suite arrays to re-use tstclnt's
- * cipher selection code.
- */
-
-int ssl2CipherSuites[] = {
- SSL_EN_RC4_128_WITH_MD5, /* A */
- SSL_EN_RC4_128_EXPORT40_WITH_MD5, /* B */
- SSL_EN_RC2_128_CBC_WITH_MD5, /* C */
- SSL_EN_RC2_128_CBC_EXPORT40_WITH_MD5, /* D */
- SSL_EN_DES_64_CBC_WITH_MD5, /* E */
- SSL_EN_DES_192_EDE3_CBC_WITH_MD5, /* F */
- 0
-};
-
-int ssl3CipherSuites[] = {
- SSL_FORTEZZA_DMS_WITH_FORTEZZA_CBC_SHA, /* a */
- SSL_FORTEZZA_DMS_WITH_RC4_128_SHA, /* b */
- SSL_RSA_WITH_RC4_128_MD5, /* c */
- SSL_RSA_WITH_3DES_EDE_CBC_SHA, /* d */
- SSL_RSA_WITH_DES_CBC_SHA, /* e */
- SSL_RSA_EXPORT_WITH_RC4_40_MD5, /* f */
- SSL_RSA_EXPORT_WITH_RC2_CBC_40_MD5, /* g */
- SSL_FORTEZZA_DMS_WITH_NULL_SHA, /* h */
- SSL_RSA_WITH_NULL_MD5, /* i */
- SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA, /* j */
- SSL_RSA_FIPS_WITH_DES_CBC_SHA, /* k */
- 0
-};
-
-/* This global string is so that client main can see
- * which ciphers to use.
- */
-
-char *cipherString;
-
-int MakeCertOK;
-
-void
-disableSSL2Ciphers(void)
-{
- int i;
-
- /* disable all the SSL2 cipher suites */
- for (i = 0; ssl2CipherSuites[i] != 0; ++i) {
- SSL_EnableCipher(ssl2CipherSuites[i], SSL_NOT_ALLOWED);
- }
-}
-
-void
-disableSSL3Ciphers(void)
-{
- int i;
-
- /* disable all the SSL3 cipher suites */
- for (i = 0; ssl3CipherSuites[i] != 0; ++i) {
- SSL_EnableCipher(ssl3CipherSuites[i], SSL_NOT_ALLOWED);
- }
-}
-
-char * ownPasswd( PK11SlotInfo *slot, PRBool retry, void *arg)
-{
- char *passwd = NULL;
-
- if ( (!retry) && arg ) {
- passwd = PL_strdup((char *)arg);
- }
-
- return passwd;
-}
-
-int stopping;
-int verbose;
-SECItem bigBuf;
-
-#define PRINTF if (verbose) printf
-#define FPRINTF if (verbose) fprintf
-
-static void
-Usage(const char *progName)
-{
- fprintf(stderr,
- "Usage: %s [-n rsa_nickname] [-p port] [-d dbdir] [-c connections]\n"
- " [-v] [-f fortezza_nickname] [-2 filename]\n"
- " [-w dbpasswd] [-C cipher(s)] hostname\n",
- progName);
- exit(1);
-}
-
-static void
-networkStart(void)
-{
-#if defined(XP_WIN) && !defined(NSPR20)
-
- WORD wVersionRequested;
- WSADATA wsaData;
- int err;
- wVersionRequested = MAKEWORD(1, 1);
-
- err = WSAStartup(wVersionRequested, &wsaData);
-
- if (err != 0) {
- /* Tell the user that we couldn't find a useable winsock.dll. */
- fputs("WSAStartup failed!\n", stderr);
- exit(1);
- }
-
-/* Confirm that the Windows Sockets DLL supports 1.1.*/
-/* Note that if the DLL supports versions greater */
-/* than 1.1 in addition to 1.1, it will still return */
-/* 1.1 in wVersion since that is the version we */
-/* requested. */
-
- if ( LOBYTE( wsaData.wVersion ) != 1 ||
- HIBYTE( wsaData.wVersion ) != 1 ) {
- /* Tell the user that we couldn't find a useable winsock.dll. */
- fputs("wrong winsock version\n", stderr);
- WSACleanup();
- exit(1);
- }
- /* The Windows Sockets DLL is acceptable. Proceed. */
-
-#endif
-}
-
-static void
-networkEnd(void)
-{
-#if defined(XP_WIN) && !defined(NSPR20)
- WSACleanup();
-#endif
-}
-
-static void
-errWarn(char * funcString)
-{
- PRErrorCode perr = PR_GetError();
- const char * errString = SECU_Strerror(perr);
-
- fprintf(stderr, "exit after %s with error %d:\n%s\n",
- funcString, perr, errString);
-}
-
-static void
-errExit(char * funcString)
-{
-#if defined (XP_WIN) && !defined(NSPR20)
- int err;
- LPVOID lpMsgBuf;
-
- err = WSAGetLastError();
-
- FormatMessage(
- FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
- NULL,
- err,
- MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
- (LPTSTR) &lpMsgBuf,
- 0,
- NULL
- );
-
- /* Display the string. */
- /*MessageBox( NULL, lpMsgBuf, "GetLastError", MB_OK|MB_ICONINFORMATION ); */
- fprintf(stderr, "%s\n", lpMsgBuf);
-
- /* Free the buffer. */
- LocalFree( lpMsgBuf );
-#endif
-
- errWarn(funcString);
- exit(1);
-}
-
-/* This invokes the "default" AuthCert handler in libssl.
-** The only reason to use this one is that it prints out info as it goes.
-*/
-static int
-mySSLAuthCertificate(void *arg, PRFileDesc *fd, PRBool checkSig,
- PRBool isServer)
-{
- SECStatus rv;
- CERTCertificate * peerCert;
-
- peerCert = SSL_PeerCertificate(fd);
-
- PRINTF("Subject: %s\nIssuer : %s\n",
- peerCert->subjectName, peerCert->issuerName);
- /* invoke the "default" AuthCert handler. */
- rv = SSL_AuthCertificate(arg, fd, checkSig, isServer);
-
- if (rv == SECSuccess) {
- fputs("-- SSL3: Server Certificate Validated.\n", stderr);
- }
- /* error, if any, will be displayed by the Bad Cert Handler. */
- return rv;
-}
-
-static int /* should be SECStatus but public prototype says int. */
-myBadCertHandler( void *arg, PRFileDesc *fd)
-{
- int err = PR_GetError();
- fprintf(stderr, "-- SSL: Server Certificate Invalid, err %d.\n%s\n",
- err, SECU_Strerror(err));
- return (MakeCertOK ? SECSuccess : SECFailure);
-}
-
-/* statistics from ssl3_SendClientHello (sch) */
-extern long ssl3_sch_sid_cache_hits;
-extern long ssl3_sch_sid_cache_misses;
-extern long ssl3_sch_sid_cache_not_ok;
-
-/* statistics from ssl3_HandleServerHello (hsh) */
-extern long ssl3_hsh_sid_cache_hits;
-extern long ssl3_hsh_sid_cache_misses;
-extern long ssl3_hsh_sid_cache_not_ok;
-
-/* statistics from ssl3_HandleClientHello (hch) */
-extern long ssl3_hch_sid_cache_hits;
-extern long ssl3_hch_sid_cache_misses;
-extern long ssl3_hch_sid_cache_not_ok;
-
-void
-printSecurityInfo(PRFileDesc *fd)
-{
- char * cp; /* bulk cipher name */
- char * ip; /* cert issuer DN */
- char * sp; /* cert subject DN */
- int op; /* High, Low, Off */
- int kp0; /* total key bits */
- int kp1; /* secret key bits */
- int result;
-
- static int only_once;
-
- if (! only_once++ && fd) {
- result = SSL_SecurityStatus(fd, &op, &cp, &kp0, &kp1, &ip, &sp);
- if (result != SECSuccess)
- return;
-#if 0
- PRINTF("bulk cipher %s, %d secret key bits, %d key bits, status: %d\n"
- "subject DN: %s\n"
- "issuer DN: %s\n", cp, kp1, kp0, op, sp, ip);
-#else
- PRINTF("bulk cipher %s, %d secret key bits, %d key bits, status: %d\n",
- cp, kp1, kp0, op, sp, ip);
-#endif
- PR_Free(cp);
- PR_Free(ip);
- PR_Free(sp);
- }
-
- PRINTF("%ld cache hits; %ld cache misses, %ld cache not reusable\n",
- ssl3_hsh_sid_cache_hits,
- ssl3_hsh_sid_cache_misses,
- ssl3_hsh_sid_cache_not_ok);
-
-}
-
-/**************************************************************************
-** Begin thread management routines and data.
-**************************************************************************/
-
-#define MAX_THREADS 32
-
-typedef int startFn(void *a, void *b, int c);
-
-PRLock * threadLock;
-PRCondVar * threadStartQ;
-PRCondVar * threadEndQ;
-
-int numUsed;
-int numRunning;
-
-typedef enum { rs_idle = 0, rs_running = 1, rs_zombie = 2 } runState;
-
-typedef struct perThreadStr {
- void * a;
- void * b;
- int c;
- int rv;
- startFn * startFunc;
- PRThread * prThread;
- PRBool inUse;
- runState running;
-} perThread;
-
-perThread threads[MAX_THREADS];
-
-void
-thread_wrapper(void * arg)
-{
- perThread * slot = (perThread *)arg;
-
- /* wait for parent to finish launching us before proceeding. */
- PR_Lock(threadLock);
- PR_Unlock(threadLock);
-
- slot->rv = (* slot->startFunc)(slot->a, slot->b, slot->c);
-
- /* Handle cleanup of thread here. */
- PRINTF("Thread in slot %d returned %d\n", slot - threads, slot->rv);
-
- PR_Lock(threadLock);
- slot->running = rs_idle;
- --numRunning;
-
- /* notify the thread launcher. */
- PR_NotifyCondVar(threadStartQ);
-
- PR_Unlock(threadLock);
-}
-
-SECStatus
-launch_thread(
- startFn * startFunc,
- void * a,
- void * b,
- int c)
-{
- perThread * slot;
- int i;
-
- if (!threadStartQ) {
- threadLock = PR_NewLock();
- threadStartQ = PR_NewCondVar(threadLock);
- threadEndQ = PR_NewCondVar(threadLock);
- }
- PR_Lock(threadLock);
- while (numRunning >= MAX_THREADS) {
- PR_WaitCondVar(threadStartQ, PR_INTERVAL_NO_TIMEOUT);
- }
- for (i = 0; i < numUsed; ++i) {
- slot = threads + i;
- if (slot->running == rs_idle)
- break;
- }
- if (i >= numUsed) {
- if (i >= MAX_THREADS) {
- /* something's really wrong here. */
- PORT_Assert(i < MAX_THREADS);
- PR_Unlock(threadLock);
- return SECFailure;
- }
- ++numUsed;
- PORT_Assert(numUsed == i + 1);
- slot = threads + i;
- }
-
- slot->a = a;
- slot->b = b;
- slot->c = c;
-
- slot->startFunc = startFunc;
-
- slot->prThread = PR_CreateThread(PR_USER_THREAD,
- thread_wrapper, slot,
- PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD,
- PR_UNJOINABLE_THREAD, 0);
- if (slot->prThread == NULL) {
- PR_Unlock(threadLock);
- printf("Failed to launch thread!\n");
- return SECFailure;
- }
-
- slot->inUse = 1;
- slot->running = 1;
- ++numRunning;
- PR_Unlock(threadLock);
- PRINTF("Launched thread in slot %d \n", i);
-
- return SECSuccess;
-}
-
-/* Wait until num_running == 0 */
-int
-reap_threads(void)
-{
- perThread * slot;
- int i;
-
- if (!threadLock)
- return 0;
- PR_Lock(threadLock);
- while (numRunning > 0) {
- PR_WaitCondVar(threadStartQ, PR_INTERVAL_NO_TIMEOUT);
- }
-
- /* Safety Sam sez: make sure count is right. */
- for (i = 0; i < numUsed; ++i) {
- slot = threads + i;
- if (slot->running != rs_idle) {
- FPRINTF(stderr, "Thread in slot %d is in state %d!\n",
- i, slot->running);
- }
- }
- PR_Unlock(threadLock);
- return 0;
-}
-
-void
-destroy_thread_data(void)
-{
- PORT_Memset(threads, 0, sizeof threads);
-
- if (threadEndQ) {
- PR_DestroyCondVar(threadEndQ);
- threadEndQ = NULL;
- }
- if (threadStartQ) {
- PR_DestroyCondVar(threadStartQ);
- threadStartQ = NULL;
- }
- if (threadLock) {
- PR_DestroyLock(threadLock);
- threadLock = NULL;
- }
-}
-
-/**************************************************************************
-** End thread management routines.
-**************************************************************************/
-
-PRBool useModelSocket = PR_TRUE;
-
-static const char stopCmd[] = { "GET /stop " };
-static const char outHeader[] = {
- "HTTP/1.0 200 OK\r\n"
- "Server: Netscape-Enterprise/2.0a\r\n"
- "Date: Tue, 26 Aug 1997 22:10:05 GMT\r\n"
- "Content-type: text/plain\r\n"
- "\r\n"
-};
-
-struct lockedVarsStr {
- PRLock * lock;
- int count;
- int waiters;
- PRCondVar * condVar;
-};
-
-typedef struct lockedVarsStr lockedVars;
-
-void
-lockedVars_Init( lockedVars * lv)
-{
- lv->count = 0;
- lv->waiters = 0;
- lv->lock = PR_NewLock();
- lv->condVar = PR_NewCondVar(lv->lock);
-}
-
-void
-lockedVars_Destroy( lockedVars * lv)
-{
- PR_DestroyCondVar(lv->condVar);
- lv->condVar = NULL;
-
- PR_DestroyLock(lv->lock);
- lv->lock = NULL;
-}
-
-void
-lockedVars_WaitForDone(lockedVars * lv)
-{
- PR_Lock(lv->lock);
- while (lv->count > 0) {
- PR_WaitCondVar(lv->condVar, PR_INTERVAL_NO_TIMEOUT);
- }
- PR_Unlock(lv->lock);
-}
-
-int /* returns count */
-lockedVars_AddToCount(lockedVars * lv, int addend)
-{
- int rv;
-
- PR_Lock(lv->lock);
- rv = lv->count += addend;
- if (rv <= 0) {
- PR_NotifyCondVar(lv->condVar);
- }
- PR_Unlock(lv->lock);
- return rv;
-}
-
-int
-do_writes(
- void * a,
- void * b,
- int c)
-{
- PRFileDesc * ssl_sock = (PRFileDesc *)a;
- lockedVars * lv = (lockedVars *)b;
- int sent = 0;
- int count = 0;
-
- while (sent < bigBuf.len) {
-
- count = PR_Write(ssl_sock, bigBuf.data + sent, bigBuf.len - sent);
- if (count < 0) {
- errWarn("PR_Write bigBuf");
- break;
- }
- FPRINTF(stderr, "PR_Write wrote %d bytes from bigBuf\n", count );
- sent += count;
- }
- if (count >= 0) { /* last write didn't fail. */
- PR_Shutdown(ssl_sock, PR_SHUTDOWN_SEND);
- }
-
- /* notify the reader that we're done. */
- lockedVars_AddToCount(lv, -1);
- return (sent < bigBuf.len) ? SECFailure : SECSuccess;
-}
-
-int
-handle_fdx_connection( PRFileDesc * ssl_sock, int connection)
-{
- SECStatus result;
- int firstTime = 1;
- int countRead = 0;
- lockedVars lv;
- char *buf;
-
-
- lockedVars_Init(&lv);
- lockedVars_AddToCount(&lv, 1);
-
- /* Attempt to launch the writer thread. */
- result = launch_thread(do_writes, ssl_sock, &lv, connection);
-
- if (result != SECSuccess)
- goto cleanup;
-
- buf = PR_Malloc(RD_BUF_SIZE);
-
- if (buf) {
- do {
- /* do reads here. */
- PRInt32 count;
-
- count = PR_Read(ssl_sock, buf, RD_BUF_SIZE);
- if (count < 0) {
- errWarn("PR_Read");
- break;
- }
- countRead += count;
- FPRINTF(stderr, "connection %d read %d bytes (%d total).\n",
- connection, count, countRead );
- if (firstTime) {
- firstTime = 0;
- printSecurityInfo(ssl_sock);
- }
- } while (lockedVars_AddToCount(&lv, 0) > 0);
- PR_Free(buf);
- buf = 0;
- }
-
- /* Wait for writer to finish */
- lockedVars_WaitForDone(&lv);
- lockedVars_Destroy(&lv);
-
- FPRINTF(stderr,
- "connection %d read %d bytes total. -----------------------------\n",
- connection, countRead);
-
-cleanup:
- /* Caller closes the socket. */
-
- return SECSuccess;
-}
-
-const char request[] = {"GET /abc HTTP/1.0\r\n\r\n" };
-
-SECStatus
-handle_connection( PRFileDesc *ssl_sock, int connection)
-{
- int countRead = 0;
- PRInt32 rv;
- char *buf;
-
- buf = PR_Malloc(RD_BUF_SIZE);
- if (!buf)
- return SECFailure;
-
- /* compose the http request here. */
-
- rv = PR_Write(ssl_sock, request, strlen(request));
- if (rv <= 0) {
- errWarn("PR_Write");
- PR_Free(buf);
- buf = 0;
- return SECFailure;
- }
- printSecurityInfo(ssl_sock);
-
- /* read until EOF */
- while (1) {
- rv = PR_Read(ssl_sock, buf, RD_BUF_SIZE);
- if (rv == 0) {
- break; /* EOF */
- }
- if (rv < 0) {
- errWarn("PR_Read");
- break;
- }
-
- countRead += rv;
- FPRINTF(stderr, "connection %d read %d bytes (%d total).\n",
- connection, rv, countRead );
- }
- PR_Free(buf);
- buf = 0;
-
- /* Caller closes the socket. */
-
- FPRINTF(stderr,
- "connection %d read %d bytes total. -----------------------------\n",
- connection, countRead);
-
- return SECSuccess; /* success */
-}
-
-/* one copy of this function is launched in a separate thread for each
-** connection to be made.
-*/
-int
-do_connects(
- void * a,
- void * b,
- int connection)
-{
- PRNetAddr * addr = (PRNetAddr *) a;
- PRFileDesc * model_sock = (PRFileDesc *) b;
- PRFileDesc * ssl_sock;
- PRFileDesc * tcp_sock;
- PRStatus prStatus;
- SECStatus result;
- int rv = SECSuccess;
- PRSocketOptionData opt;
-
-retry:
-
- tcp_sock = PR_NewTCPSocket();
- if (tcp_sock == NULL) {
- errExit("PR_NewTCPSocket");
- }
-
- opt.option = PR_SockOpt_Nonblocking;
- opt.value.non_blocking = PR_FALSE;
- prStatus = PR_SetSocketOption(tcp_sock, &opt);
- if (prStatus != PR_SUCCESS) {
- PR_Close(tcp_sock);
- return SECSuccess;
- }
-
- prStatus = PR_Connect(tcp_sock, addr, PR_INTERVAL_NO_TIMEOUT);
- if (prStatus != PR_SUCCESS) {
- PRErrorCode err = PR_GetError();
- if (err == PR_CONNECT_REFUSED_ERROR) {
- PR_Close(tcp_sock);
- PR_Sleep(PR_MillisecondsToInterval(10));
- goto retry;
- }
- errWarn("PR_Connect");
- goto done;
- }
-
- ssl_sock = SSL_ImportFD(model_sock, tcp_sock);
- /* XXX if this import fails, close tcp_sock and return. */
- if (!ssl_sock) {
- PR_Close(tcp_sock);
- return SECSuccess;
- }
-
- rv = SSL_ResetHandshake(ssl_sock, /* asServer */ 0);
- if (rv != SECSuccess) {
- errWarn("SSL_ResetHandshake");
- goto done;
- }
-
- if (bigBuf.data != NULL) {
- result = handle_fdx_connection( ssl_sock, connection);
- } else {
- result = handle_connection( ssl_sock, connection);
- }
-
-done:
- PR_Close(ssl_sock);
- return SECSuccess;
-}
-
-/* Returns IP address for hostname as PRUint32 in Host Byte Order.
-** Since the value returned is an integer (not a string of bytes),
-** it is inherently in Host Byte Order.
-*/
-PRUint32
-getIPAddress(const char * hostName)
-{
- const unsigned char *p;
- PRStatus prStatus;
- PRUint32 rv;
- PRHostEnt prHostEnt;
- char scratch[PR_NETDB_BUF_SIZE];
-
- prStatus = PR_GetHostByName(hostName, scratch, sizeof scratch, &prHostEnt);
- if (prStatus != PR_SUCCESS)
- errExit("PR_GetHostByName");
-
-#undef h_addr
-#define h_addr h_addr_list[0] /* address, for backward compatibility */
-
- p = (const unsigned char *)(prHostEnt.h_addr); /* in Network Byte order */
- FPRINTF(stderr, "%s -> %d.%d.%d.%d\n", hostName, p[0], p[1], p[2], p[3]);
- rv = (p[0] << 24) | (p[1] << 16) | (p[2] << 8) | p[3];
- return rv;
-}
-
-void
-client_main(
- unsigned short port,
- int connections,
- SECKEYPrivateKey ** privKey,
- CERTCertificate ** cert,
- const char * hostName,
- char * nickName)
-{
- PRFileDesc *model_sock = NULL;
- int i;
- int rv;
- SECStatus secStatus;
- PRUint32 ipAddress; /* in host byte order */
- PRNetAddr addr;
-
- networkStart();
-
- /* Assemble NetAddr struct for connections. */
- ipAddress = getIPAddress(hostName);
-
- addr.inet.family = PR_AF_INET;
- addr.inet.port = PR_htons(port);
- addr.inet.ip = PR_htonl(ipAddress);
-
- /* all suites except RSA_NULL_MD5 are enabled by Domestic Policy */
- NSS_SetDomesticPolicy();
-
-/* all the SSL2 and SSL3 cipher suites are enabled by default. */
- if (cipherString) {
- int ndx;
-
- /* disable all the ciphers, then enable the ones we want. */
- disableSSL2Ciphers();
- disableSSL3Ciphers();
-
- while (0 != (ndx = *cipherString++)) {
- int *cptr;
- int cipher;
-
- if (! isalpha(ndx))
- Usage("strsclnt");
- cptr = islower(ndx) ? ssl3CipherSuites : ssl2CipherSuites;
- for (ndx &= 0x1f; (cipher = *cptr++) != 0 && --ndx > 0; )
- /* do nothing */;
- if (cipher) {
- SSL_EnableCipher(cipher, SSL_ALLOWED);
- }
- }
- }
-
- /* configure model SSL socket. */
-
- model_sock = PR_NewTCPSocket();
- if (model_sock == NULL) {
- errExit("PR_NewTCPSocket on model socket");
- }
-
- model_sock = SSL_ImportFD(NULL, model_sock);
- if (model_sock == NULL) {
- errExit("SSL_ImportFD");
- }
-
- /* do SSL configuration. */
-
- rv = SSL_Enable(model_sock, SSL_SECURITY, 1);
- if (rv < 0) {
- errExit("SSL_Enable SSL_SECURITY");
- }
-
- if (bigBuf.data) { /* doing FDX */
- rv = SSL_Enable(model_sock, SSL_ENABLE_FDX, 1);
- if (rv < 0) {
- errExit("SSL_Enable SSL_ENABLE_FDX");
- }
- }
-
- SSL_SetURL(model_sock, hostName);
-
- SSL_AuthCertificateHook(model_sock, mySSLAuthCertificate,
- (void *)CERT_GetDefaultCertDB());
-
- SSL_BadCertHook(model_sock, myBadCertHandler, NULL);
-
- SSL_GetClientAuthDataHook(model_sock, NSS_GetClientAuthData, nickName);
-
- /* I'm not going to set the HandshakeCallback function. */
-
- /* end of ssl configuration. */
-
- rv = launch_thread(do_connects, &addr, model_sock, 1);
-
- if (connections > 1) {
- /* wait for the first connection to terminate, then launch the rest. */
- reap_threads();
- /* Start up the connections */
- for (i = 2; i <= connections; ++i) {
-
- rv = launch_thread(do_connects, &addr, model_sock, i);
-
- }
- }
-
- reap_threads();
- destroy_thread_data();
-
- PR_Close(model_sock);
-
- networkEnd();
-}
-
-SECStatus
-readBigFile(const char * fileName)
-{
- PRFileInfo info;
- PRStatus status;
- SECStatus rv = SECFailure;
- int count;
- int hdrLen;
- PRFileDesc *local_file_fd = NULL;
-
- status = PR_GetFileInfo(fileName, &info);
-
- if (status == PR_SUCCESS &&
- info.type == PR_FILE_FILE &&
- info.size > 0 &&
- NULL != (local_file_fd = PR_Open(fileName, PR_RDONLY, 0))) {
-
- hdrLen = PORT_Strlen(outHeader);
- bigBuf.len = hdrLen + info.size;
- bigBuf.data = PORT_Malloc(bigBuf.len + 4095);
- if (!bigBuf.data) {
- errWarn("PORT_Malloc");
- goto done;
- }
-
- PORT_Memcpy(bigBuf.data, outHeader, hdrLen);
-
- count = PR_Read(local_file_fd, bigBuf.data + hdrLen, info.size);
- if (count != info.size) {
- errWarn("PR_Read local file");
- goto done;
- }
- rv = SECSuccess;
-done:
- PR_Close(local_file_fd);
- }
- return rv;
-}
-
-int
-main(int argc, char **argv)
-{
- char * dir = ".";
- char * fNickName = NULL;
- char * fileName = NULL;
- char * hostName = NULL;
- char * nickName = NULL;
- char * progName = NULL;
- char * tmp = NULL;
- CERTCertificate * cert [kt_kea_size] = { NULL };
- SECKEYPrivateKey * privKey[kt_kea_size] = { NULL };
- int optchar;
- int connections = 1;
- unsigned short port = 443;
- SECStatus rv;
- PRBool useCommandLinePasswd = PR_FALSE;
- char * passwd = NULL;
- PLOptState *optstate;
- PLOptStatus status;
-
- /* Call the NSPR initialization routines */
- PR_Init( PR_SYSTEM_THREAD, PR_PRIORITY_NORMAL, 1);
-
- tmp = strrchr(argv[0], '/');
- tmp = tmp ? tmp + 1 : argv[0];
- progName = strrchr(tmp, '\\');
- progName = progName ? progName + 1 : tmp;
-
-
- optstate = PL_CreateOptState(argc, argv, "2:C:c:d:f:n:op:vw:");
- while ((status = PL_GetNextOpt(optstate)) == PL_OPT_OK) {
- switch(optstate->option) {
-
- case '2':
- fileName = optstate->value;
- break;
- case 'C':
- cipherString = optstate->value;
- break;
-
- case 'c':
- connections = PORT_Atoi(optstate->value);
- break;
-
- case 'd':
- dir = optstate->value;
- break;
-
- case 'f':
- fNickName = optstate->value;
- break;
-
- case 'n':
- nickName = optstate->value;
- break;
- case 'o':
- MakeCertOK = 1;
- break;
-
- case 'p':
- port = PORT_Atoi(optstate->value);
- break;
-
- case 'v':
- verbose++;
- break;
- case 'w':
- passwd = optstate->value;
- useCommandLinePasswd = PR_TRUE;
- break;
- case '\0':
- hostName = PL_strdup(optstate->value);
- break;
- default:
- case '?':
- Usage(progName);
- break;
-
- }
- }
- if (!hostName || status == PL_OPT_BAD)
- Usage(progName);
-
- if (port == 0)
- Usage(progName);
-
- if (fileName)
- readBigFile(fileName);
-
- /* set our password function */
- if ( useCommandLinePasswd ) {
- PK11_SetPasswordFunc(ownPasswd);
- } else {
- PK11_SetPasswordFunc(SECU_GetModulePassword);
- }
-
- /* Call the libsec initialization routines */
- rv = NSS_Init(dir);
- if (rv != SECSuccess) {
- fputs("NSS_Init failed.\n", stderr);
- exit(1);
- }
-
- if (nickName) {
-
- if (useCommandLinePasswd) {
- cert[kt_rsa] = PK11_FindCertFromNickname(nickName, passwd);
- } else {
- cert[kt_rsa] = PK11_FindCertFromNickname(nickName, NULL);
- }
- if (cert[kt_rsa] == NULL) {
- fprintf(stderr, "Can't find certificate %s\n", nickName);
- exit(1);
- }
-
- if (useCommandLinePasswd) {
- privKey[kt_rsa] = PK11_FindKeyByAnyCert(cert[kt_rsa], passwd);
- } else {
- privKey[kt_rsa] = PK11_FindKeyByAnyCert(cert[kt_rsa], NULL);
- }
-
- if (privKey[kt_rsa] == NULL) {
- fprintf(stderr, "Can't find Private Key for cert %s\n", nickName);
- exit(1);
- }
-
- }
- if (fNickName) {
- cert[kt_fortezza] = PK11_FindCertFromNickname(fNickName, NULL);
- if (cert[kt_fortezza] == NULL) {
- fprintf(stderr, "Can't find certificate %s\n", fNickName);
- exit(1);
- }
-
- privKey[kt_fortezza] = PK11_FindKeyByAnyCert(cert[kt_fortezza], NULL);
- if (privKey[kt_fortezza] == NULL) {
- fprintf(stderr, "Can't find Private Key for cert %s\n", fNickName);
- exit(1);
- }
- }
-
- client_main(port, connections, privKey, cert, hostName, nickName);
-
- /* some final stats. */
- printf("%ld cache hits; %ld cache misses, %ld cache not reusable\n",
- ssl3_hsh_sid_cache_hits,
- ssl3_hsh_sid_cache_misses,
- ssl3_hsh_sid_cache_not_ok);
-
- NSS_Shutdown();
- PR_Cleanup();
- return 0;
-}
-
diff --git a/security/nss/lib/ckfw/dbm/Makefile b/security/nss/lib/ckfw/dbm/Makefile
deleted file mode 100644
index 03e1fb4c6..000000000
--- a/security/nss/lib/ckfw/dbm/Makefile
+++ /dev/null
@@ -1,38 +0,0 @@
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-MAKEFILE_CVS_ID = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"
-
-include manifest.mn
-include config.mk
-include $(CORE_DEPTH)/coreconf/config.mk
-include $(CORE_DEPTH)/coreconf/rules.mk
diff --git a/security/nss/lib/ckfw/dbm/anchor.c b/security/nss/lib/ckfw/dbm/anchor.c
deleted file mode 100644
index 588fd00e0..000000000
--- a/security/nss/lib/ckfw/dbm/anchor.c
+++ /dev/null
@@ -1,50 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-/*
- * dbm/anchor.c
- *
- * This file "anchors" the actual cryptoki entry points in this module's
- * shared library, which is required for dynamic loading. See the
- * comments in nssck.api for more information.
- */
-
-#include "ckdbm.h"
-
-#define MODULE_NAME dbm
-#define INSTANCE_NAME (NSSCKMDInstance *)&nss_dbm_mdInstance
-#include "nssck.api"
diff --git a/security/nss/lib/ckfw/dbm/ckdbm.h b/security/nss/lib/ckfw/dbm/ckdbm.h
deleted file mode 100644
index 7bab87ec7..000000000
--- a/security/nss/lib/ckfw/dbm/ckdbm.h
+++ /dev/null
@@ -1,281 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CKDBM_CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#ifndef CKDBM_H
-#define CKDBM_H
-
-#include "nssckmdt.h"
-#include "nssckfw.h"
-
-/*
- * I'm including this for access to the arena functions.
- * Looks like we should publish that API.
- */
-#ifndef BASE_H
-#include "base.h"
-#endif /* BASE_H */
-
-/*
- * This is where the Netscape extensions live, at least for now.
- */
-#ifndef CKT_H
-#include "ckt.h"
-#endif /* CKT_H */
-
-#include "mcom_db.h"
-
-NSS_EXTERN_DATA NSSCKMDInstance nss_dbm_mdInstance;
-
-typedef struct nss_dbm_db_struct nss_dbm_db_t;
-struct nss_dbm_db_struct {
- DB *db;
- NSSCKFWMutex *crustylock;
-};
-
-typedef struct nss_dbm_dbt_struct nss_dbm_dbt_t;
-struct nss_dbm_dbt_struct {
- DBT dbt;
- nss_dbm_db_t *my_db;
-};
-
-typedef struct nss_dbm_instance_struct nss_dbm_instance_t;
-struct nss_dbm_instance_struct {
- NSSArena *arena;
- CK_ULONG nSlots;
- char **filenames;
- int *flags; /* e.g. O_RDONLY, O_RDWR */
-};
-
-typedef struct nss_dbm_slot_struct nss_dbm_slot_t;
-struct nss_dbm_slot_struct {
- nss_dbm_instance_t *instance;
- char *filename;
- int flags;
- nss_dbm_db_t *token_db;
-};
-
-typedef struct nss_dbm_token_struct nss_dbm_token_t;
-struct nss_dbm_token_struct {
- NSSArena *arena;
- nss_dbm_slot_t *slot;
- nss_dbm_db_t *session_db;
- NSSUTF8 *label;
-};
-
-struct nss_dbm_dbt_node {
- struct nss_dbm_dbt_node *next;
- nss_dbm_dbt_t *dbt;
-};
-
-typedef struct nss_dbm_session_struct nss_dbm_session_t;
-struct nss_dbm_session_struct {
- NSSArena *arena;
- nss_dbm_token_t *token;
- CK_ULONG deviceError;
- struct nss_dbm_dbt_node *session_objects;
- NSSCKFWMutex *list_lock;
-};
-
-typedef struct nss_dbm_object_struct nss_dbm_object_t;
-struct nss_dbm_object_struct {
- NSSArena *arena; /* token or session */
- nss_dbm_dbt_t *handle;
-};
-
-typedef struct nss_dbm_find_struct nss_dbm_find_t;
-struct nss_dbm_find_struct {
- NSSArena *arena;
- struct nss_dbm_dbt_node *found;
- NSSCKFWMutex *list_lock;
-};
-
-NSS_EXTERN NSSCKMDSlot *
-nss_dbm_mdSlot_factory
-(
- nss_dbm_instance_t *instance,
- char *filename,
- int flags,
- CK_RV *pError
-);
-
-NSS_EXTERN NSSCKMDToken *
-nss_dbm_mdToken_factory
-(
- nss_dbm_slot_t *slot,
- CK_RV *pError
-);
-
-NSS_EXTERN NSSCKMDSession *
-nss_dbm_mdSession_factory
-(
- nss_dbm_token_t *token,
- NSSCKFWSession *fwSession,
- NSSCKFWInstance *fwInstance,
- CK_BBOOL rw,
- CK_RV *pError
-);
-
-NSS_EXTERN NSSCKMDObject *
-nss_dbm_mdObject_factory
-(
- nss_dbm_object_t *object,
- CK_RV *pError
-);
-
-NSS_EXTERN NSSCKMDFindObjects *
-nss_dbm_mdFindObjects_factory
-(
- nss_dbm_find_t *find,
- CK_RV *pError
-);
-
-NSS_EXTERN nss_dbm_db_t *
-nss_dbm_db_open
-(
- NSSArena *arena,
- NSSCKFWInstance *fwInstance,
- char *filename,
- int flags,
- CK_RV *pError
-);
-
-NSS_EXTERN void
-nss_dbm_db_close
-(
- nss_dbm_db_t *db
-);
-
-NSS_EXTERN CK_VERSION
-nss_dbm_db_get_format_version
-(
- nss_dbm_db_t *db
-);
-
-NSS_EXTERN CK_RV
-nss_dbm_db_set_label
-(
- nss_dbm_db_t *db,
- NSSUTF8 *label
-);
-
-NSS_EXTERN NSSUTF8 *
-nss_dbm_db_get_label
-(
- nss_dbm_db_t *db,
- NSSArena *arena,
- CK_RV *pError
-);
-
-NSS_EXTERN CK_RV
-nss_dbm_db_delete_object
-(
- nss_dbm_dbt_t *dbt
-);
-
-NSS_EXTERN nss_dbm_dbt_t *
-nss_dbm_db_create_object
-(
- NSSArena *arena,
- nss_dbm_db_t *db,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- CK_RV *pError,
- CK_ULONG *pdbrv
-);
-
-NSS_EXTERN CK_RV
-nss_dbm_db_find_objects
-(
- nss_dbm_find_t *find,
- nss_dbm_db_t *db,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- CK_ULONG *pdbrv
-);
-
-NSS_EXTERN CK_BBOOL
-nss_dbm_db_object_still_exists
-(
- nss_dbm_dbt_t *dbt
-);
-
-NSS_EXTERN CK_ULONG
-nss_dbm_db_get_object_attribute_count
-(
- nss_dbm_dbt_t *dbt,
- CK_RV *pError,
- CK_ULONG *pdbrv
-);
-
-NSS_EXTERN CK_RV
-nss_dbm_db_get_object_attribute_types
-(
- nss_dbm_dbt_t *dbt,
- CK_ATTRIBUTE_TYPE_PTR typeArray,
- CK_ULONG ulCount,
- CK_ULONG *pdbrv
-);
-
-NSS_EXTERN CK_ULONG
-nss_dbm_db_get_object_attribute_size
-(
- nss_dbm_dbt_t *dbt,
- CK_ATTRIBUTE_TYPE type,
- CK_RV *pError,
- CK_ULONG *pdbrv
-);
-
-NSS_EXTERN NSSItem *
-nss_dbm_db_get_object_attribute
-(
- nss_dbm_dbt_t *dbt,
- NSSArena *arena,
- CK_ATTRIBUTE_TYPE type,
- CK_RV *pError,
- CK_ULONG *pdbrv
-);
-
-NSS_EXTERN CK_RV
-nss_dbm_db_set_object_attribute
-(
- nss_dbm_dbt_t *dbt,
- CK_ATTRIBUTE_TYPE type,
- NSSItem *value,
- CK_ULONG *pdbrv
-);
-
-#endif /* CKDBM_H */
diff --git a/security/nss/lib/ckfw/dbm/config.mk b/security/nss/lib/ckfw/dbm/config.mk
deleted file mode 100644
index 80b3135f4..000000000
--- a/security/nss/lib/ckfw/dbm/config.mk
+++ /dev/null
@@ -1,37 +0,0 @@
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-CONFIG_CVS_ID = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"
-
-ifdef BUILD_IDG
-DEFINES += -DNSSDEBUG
-endif
diff --git a/security/nss/lib/ckfw/dbm/db.c b/security/nss/lib/ckfw/dbm/db.c
deleted file mode 100644
index 307c7f21d..000000000
--- a/security/nss/lib/ckfw/dbm/db.c
+++ /dev/null
@@ -1,1065 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-#define PREFIX_METADATA "0000"
-#define PREFIX_OBJECT "0001"
-#define PREFIX_INDEX "0002"
-
-static CK_VERSION nss_dbm_db_format_version = { 1, 0 };
-struct handle {
- char prefix[4];
- CK_ULONG id;
-};
-
-NSS_IMPLEMENT nss_dbm_db_t *
-nss_dbm_db_open
-(
- NSSArena *arena,
- NSSCKFWInstance *fwInstance,
- char *filename,
- int flags,
- CK_RV *pError
-)
-{
- nss_dbm_db_t *rv;
- CK_VERSION db_version;
-
- rv = nss_ZNEW(arena, nss_dbm_db_t);
- if( (nss_dbm_db_t *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (nss_dbm_db_t *)NULL;
- }
-
- rv->db = dbopen(filename, flags, 0600, DB_HASH, (const void *)NULL);
- if( (DB *)NULL == rv->db ) {
- *pError = CKR_TOKEN_NOT_PRESENT;
- return (nss_dbm_db_t *)NULL;
- }
-
- rv->crustylock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError);
- if( (NSSCKFWMutex *)NULL == rv->crustylock ) {
- return (nss_dbm_db_t *)NULL;
- }
-
- db_version = nss_dbm_db_get_format_version(rv);
- if( db_version.major != nss_dbm_db_format_version.major ) {
- nss_dbm_db_close(rv);
- *pError = CKR_TOKEN_NOT_RECOGNIZED;
- return (nss_dbm_db_t *)NULL;
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT void
-nss_dbm_db_close
-(
- nss_dbm_db_t *db
-)
-{
- if( (NSSCKFWMutex *)NULL != db->crustylock ) {
- (void)NSSCKFWMutex_Destroy(db->crustylock);
- }
-
- if( (DB *)NULL != db->db ) {
- (void)db->db->close(db->db);
- }
-
- nss_ZFreeIf(db);
-}
-
-NSS_IMPLEMENT CK_VERSION
-nss_dbm_db_get_format_version
-(
- nss_dbm_db_t *db
-)
-{
- CK_VERSION rv;
- DBT k, v;
- int dbrv;
- char buffer[64];
-
- rv.major = rv.minor = 0;
-
- k.data = PREFIX_METADATA "FormatVersion";
- k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL);
- (void)memset(&v, 0, sizeof(v));
-
- /* Locked region */
- {
- if( CKR_OK != NSSCKFWMutex_Lock(db->crustylock) ) {
- return rv;
- }
-
- dbrv = db->db->get(db->db, &k, &v, 0);
- if( dbrv == 0 ) {
- CK_ULONG major = 0, minor = 0;
- (void)PR_sscanf(v.data, "%ld.%ld", &major, &minor);
- rv.major = major;
- rv.minor = minor;
- } else if( dbrv > 0 ) {
- (void)PR_snprintf(buffer, sizeof(buffer), "%ld.%ld", nss_dbm_db_format_version.major,
- nss_dbm_db_format_version.minor);
- v.data = buffer;
- v.size = nssUTF8_Size((NSSUTF8 *)v.data, (PRStatus *)NULL);
- dbrv = db->db->put(db->db, &k, &v, 0);
- (void)db->db->sync(db->db, 0);
- rv = nss_dbm_db_format_version;
- } else {
- /* No error return.. */
- ;
- }
-
- (void)NSSCKFWMutex_Unlock(db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_RV
-nss_dbm_db_set_label
-(
- nss_dbm_db_t *db,
- NSSUTF8 *label
-)
-{
- CK_RV rv;
- DBT k, v;
- int dbrv;
-
- k.data = PREFIX_METADATA "Label";
- k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL);
- v.data = label;
- v.size = nssUTF8_Size((NSSUTF8 *)v.data, (PRStatus *)NULL);
-
- /* Locked region */
- {
- if( CKR_OK != NSSCKFWMutex_Lock(db->crustylock) ) {
- return rv;
- }
-
- dbrv = db->db->put(db->db, &k, &v, 0);
- if( 0 != dbrv ) {
- rv = CKR_DEVICE_ERROR;
- }
-
- dbrv = db->db->sync(db->db, 0);
- if( 0 != dbrv ) {
- rv = CKR_DEVICE_ERROR;
- }
-
- (void)NSSCKFWMutex_Unlock(db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT NSSUTF8 *
-nss_dbm_db_get_label
-(
- nss_dbm_db_t *db,
- NSSArena *arena,
- CK_RV *pError
-)
-{
- NSSUTF8 *rv = (NSSUTF8 *)NULL;
- DBT k, v;
- int dbrv;
-
- k.data = PREFIX_METADATA "Label";
- k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL);
-
- /* Locked region */
- {
- if( CKR_OK != NSSCKFWMutex_Lock(db->crustylock) ) {
- return rv;
- }
-
- dbrv = db->db->get(db->db, &k, &v, 0);
- if( 0 == dbrv ) {
- rv = nssUTF8_Duplicate((NSSUTF8 *)v.data, arena);
- if( (NSSUTF8 *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- }
- } else if( dbrv > 0 ) {
- /* Just return null */
- ;
- } else {
- *pError = CKR_DEVICE_ERROR;
- ;
- }
-
-
- (void)NSSCKFWMutex_Unlock(db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_RV
-nss_dbm_db_delete_object
-(
- nss_dbm_dbt_t *dbt
-)
-{
- CK_RV rv;
- int dbrv;
-
- /* Locked region */
- {
- rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != rv ) {
- return rv;
- }
-
- dbrv = dbt->my_db->db->del(dbt->my_db->db, &dbt->dbt, 0);
- if( 0 != dbrv ) {
- rv = CKR_DEVICE_ERROR;
- goto done;
- }
-
- dbrv = dbt->my_db->db->sync(dbt->my_db->db, 0);
- if( 0 != dbrv ) {
- rv = CKR_DEVICE_ERROR;
- goto done;
- }
-
- done:
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
- }
-
- return rv;
-}
-
-static CK_ULONG
-nss_dbm_db_new_handle
-(
- nss_dbm_db_t *db,
- DBT *dbt, /* pre-allocated */
- CK_RV *pError
-)
-{
- CK_ULONG rv;
- DBT k, v;
- CK_ULONG align = 0, id, myid;
- struct handle *hp;
-
- if( sizeof(struct handle) != dbt->size ) {
- return EINVAL;
- }
-
- /* Locked region */
- {
- *pError = NSSCKFWMutex_Lock(db->crustylock);
- if( CKR_OK != *pError ) {
- return EINVAL;
- }
-
- k.data = PREFIX_METADATA "LastID";
- k.size = nssUTF8_Size((NSSUTF8 *)k.data, (PRStatus *)NULL);
- (void)memset(&v, 0, sizeof(v));
-
- rv = db->db->get(db->db, &k, &v, 0);
- if( 0 == rv ) {
- (void)memcpy(&align, v.data, sizeof(CK_ULONG));
- id = ntohl(align);
- } else if( rv > 0 ) {
- id = 0;
- } else {
- goto done;
- }
-
- myid = id;
- id++;
- align = htonl(id);
- v.data = &align;
- v.size = sizeof(CK_ULONG);
-
- rv = db->db->put(db->db, &k, &v, 0);
- if( 0 != rv ) {
- goto done;
- }
-
- rv = db->db->sync(db->db, 0);
- if( 0 != rv ) {
- goto done;
- }
-
- done:
- (void)NSSCKFWMutex_Unlock(db->crustylock);
- }
-
- if( 0 != rv ) {
- return rv;
- }
-
- hp = (struct handle *)dbt->data;
- (void)memcpy(&hp->prefix[0], PREFIX_OBJECT, 4);
- hp->id = myid;
-
- return 0;
-}
-
-/*
- * This attribute-type-dependent swapping should probably
- * be in the Framework, because it'll be a concern of just
- * about every Module. Of course any Framework implementation
- * will have to be augmentable or overridable by a Module.
- */
-
-enum swap_type { type_byte, type_short, type_long, type_opaque };
-
-static enum swap_type
-nss_dbm_db_swap_type
-(
- CK_ATTRIBUTE_TYPE type
-)
-{
- switch( type ) {
- case CKA_CLASS: return type_long;
- case CKA_TOKEN: return type_byte;
- case CKA_PRIVATE: return type_byte;
- case CKA_LABEL: return type_opaque;
- case CKA_APPLICATION: return type_opaque;
- case CKA_VALUE: return type_opaque;
- case CKA_CERTIFICATE_TYPE: return type_long;
- case CKA_ISSUER: return type_opaque;
- case CKA_SERIAL_NUMBER: return type_opaque;
- case CKA_KEY_TYPE: return type_long;
- case CKA_SUBJECT: return type_opaque;
- case CKA_ID: return type_opaque;
- case CKA_SENSITIVE: return type_byte;
- case CKA_ENCRYPT: return type_byte;
- case CKA_DECRYPT: return type_byte;
- case CKA_WRAP: return type_byte;
- case CKA_UNWRAP: return type_byte;
- case CKA_SIGN: return type_byte;
- case CKA_SIGN_RECOVER: return type_byte;
- case CKA_VERIFY: return type_byte;
- case CKA_VERIFY_RECOVER: return type_byte;
- case CKA_DERIVE: return type_byte;
- case CKA_START_DATE: return type_opaque;
- case CKA_END_DATE: return type_opaque;
- case CKA_MODULUS: return type_opaque;
- case CKA_MODULUS_BITS: return type_long;
- case CKA_PUBLIC_EXPONENT: return type_opaque;
- case CKA_PRIVATE_EXPONENT: return type_opaque;
- case CKA_PRIME_1: return type_opaque;
- case CKA_PRIME_2: return type_opaque;
- case CKA_EXPONENT_1: return type_opaque;
- case CKA_EXPONENT_2: return type_opaque;
- case CKA_COEFFICIENT: return type_opaque;
- case CKA_PRIME: return type_opaque;
- case CKA_SUBPRIME: return type_opaque;
- case CKA_BASE: return type_opaque;
- case CKA_VALUE_BITS: return type_long;
- case CKA_VALUE_LEN: return type_long;
- case CKA_EXTRACTABLE: return type_byte;
- case CKA_LOCAL: return type_byte;
- case CKA_NEVER_EXTRACTABLE: return type_byte;
- case CKA_ALWAYS_SENSITIVE: return type_byte;
- case CKA_MODIFIABLE: return type_byte;
- case CKA_NETSCAPE_URL: return type_opaque;
- case CKA_NETSCAPE_EMAIL: return type_opaque;
- case CKA_NETSCAPE_SMIME_INFO: return type_opaque;
- case CKA_NETSCAPE_SMIME_TIMESTAMP: return type_opaque;
- case CKA_NETSCAPE_PKCS8_SALT: return type_opaque;
- case CKA_NETSCAPE_PASSWORD_CHECK: return type_opaque;
- case CKA_NETSCAPE_EXPIRES: return type_opaque;
- case CKA_TRUST_DIGITAL_SIGNATURE: return type_long;
- case CKA_TRUST_NON_REPUDIATION: return type_long;
- case CKA_TRUST_KEY_ENCIPHERMENT: return type_long;
- case CKA_TRUST_DATA_ENCIPHERMENT: return type_long;
- case CKA_TRUST_KEY_AGREEMENT: return type_long;
- case CKA_TRUST_KEY_CERT_SIGN: return type_long;
- case CKA_TRUST_CRL_SIGN: return type_long;
- case CKA_TRUST_SERVER_AUTH: return type_long;
- case CKA_TRUST_CLIENT_AUTH: return type_long;
- case CKA_TRUST_CODE_SIGNING: return type_long;
- case CKA_TRUST_EMAIL_PROTECTION: return type_long;
- case CKA_TRUST_IPSEC_END_SYSTEM: return type_long;
- case CKA_TRUST_IPSEC_TUNNEL: return type_long;
- case CKA_TRUST_IPSEC_USER: return type_long;
- case CKA_TRUST_TIME_STAMPING: return type_long;
- case CKA_NETSCAPE_DB: return type_opaque;
- case CKA_NETSCAPE_TRUST: return type_opaque;
- default: return type_opaque;
- }
-}
-
-static void
-nss_dbm_db_swap_copy
-(
- CK_ATTRIBUTE_TYPE type,
- void *dest,
- void *src,
- CK_ULONG len
-)
-{
- switch( nss_dbm_db_swap_type(type) ) {
- case type_byte:
- case type_opaque:
- (void)memcpy(dest, src, len);
- break;
- case type_short:
- {
- CK_USHORT s, d;
- (void)memcpy(&s, src, sizeof(CK_USHORT));
- d = htons(s);
- (void)memcpy(dest, &d, sizeof(CK_USHORT));
- break;
- }
- case type_long:
- {
- CK_ULONG s, d;
- (void)memcpy(&s, src, sizeof(CK_ULONG));
- d = htonl(s);
- (void)memcpy(dest, &d, sizeof(CK_ULONG));
- break;
- }
- }
-}
-
-static CK_RV
-nss_dbm_db_wrap_object
-(
- NSSArena *arena,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- DBT *object
-)
-{
- CK_ULONG object_size;
- CK_ULONG i;
- CK_ULONG *pulData;
- char *pcData;
- CK_ULONG offset;
-
- object_size = (1 + ulAttributeCount*3) * sizeof(CK_ULONG);
- offset = object_size;
- for( i = 0; i < ulAttributeCount; i++ ) {
- object_size += pTemplate[i].ulValueLen;
- }
-
- object->size = object_size;
- object->data = nss_ZAlloc(arena, object_size);
- if( (void *)NULL == object->data ) {
- return CKR_HOST_MEMORY;
- }
-
- pulData = (CK_ULONG *)object->data;
- pcData = (char *)object->data;
-
- pulData[0] = htonl(ulAttributeCount);
- for( i = 0; i < ulAttributeCount; i++ ) {
- CK_ULONG len = pTemplate[i].ulValueLen;
- pulData[1 + i*3] = htonl(pTemplate[i].type);
- pulData[2 + i*3] = htonl(len);
- pulData[3 + i*3] = htonl(offset);
- nss_dbm_db_swap_copy(pTemplate[i].type, &pcData[offset], pTemplate[i].pValue, len);
- offset += len;
- }
-
- return CKR_OK;
-}
-
-static CK_RV
-nss_dbm_db_unwrap_object
-(
- NSSArena *arena,
- DBT *object,
- CK_ATTRIBUTE_PTR *ppTemplate,
- CK_ULONG *pulAttributeCount
-)
-{
- CK_ULONG *pulData;
- char *pcData;
- CK_ULONG n, i;
- CK_ATTRIBUTE_PTR pTemplate;
-
- pulData = (CK_ULONG *)object->data;
- pcData = (char *)object->data;
-
- n = ntohl(pulData[0]);
- *pulAttributeCount = n;
- pTemplate = nss_ZNEWARRAY(arena, CK_ATTRIBUTE, n);
- if( (CK_ATTRIBUTE_PTR)NULL == pTemplate ) {
- return CKR_HOST_MEMORY;
- }
-
- for( i = 0; i < n; i++ ) {
- CK_ULONG len;
- CK_ULONG offset;
- void *p;
-
- pTemplate[i].type = ntohl(pulData[1 + i*3]);
- len = ntohl(pulData[2 + i*3]);
- offset = ntohl(pulData[3 + i*3]);
-
- p = nss_ZAlloc(arena, len);
- if( (void *)NULL == p ) {
- return CKR_HOST_MEMORY;
- }
-
- nss_dbm_db_swap_copy(pTemplate[i].type, p, &pcData[offset], len);
- pTemplate[i].ulValueLen = len;
- pTemplate[i].pValue = p;
- }
-
- *ppTemplate = pTemplate;
- return CKR_OK;
-}
-
-
-NSS_IMPLEMENT nss_dbm_dbt_t *
-nss_dbm_db_create_object
-(
- NSSArena *arena,
- nss_dbm_db_t *db,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- CK_RV *pError,
- CK_ULONG *pdbrv
-)
-{
- NSSArena *tmparena = (NSSArena *)NULL;
- nss_dbm_dbt_t *rv = (nss_dbm_dbt_t *)NULL;
- DBT object;
-
- rv = nss_ZNEW(arena, nss_dbm_dbt_t);
- if( (nss_dbm_dbt_t *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (nss_dbm_dbt_t *)NULL;
- }
-
- rv->my_db = db;
- rv->dbt.size = sizeof(struct handle);
- rv->dbt.data = nss_ZAlloc(arena, rv->dbt.size);
- if( (void *)NULL == rv->dbt.data ) {
- *pError = CKR_HOST_MEMORY;
- return (nss_dbm_dbt_t *)NULL;
- }
-
- *pdbrv = nss_dbm_db_new_handle(db, &rv->dbt, pError);
- if( 0 != *pdbrv ) {
- return (nss_dbm_dbt_t *)NULL;
- }
-
- tmparena = NSSArena_Create();
- if( (NSSArena *)NULL == tmparena ) {
- *pError = CKR_HOST_MEMORY;
- return (nss_dbm_dbt_t *)NULL;
- }
-
- *pError = nss_dbm_db_wrap_object(tmparena, pTemplate, ulAttributeCount, &object);
- if( CKR_OK != *pError ) {
- return (nss_dbm_dbt_t *)NULL;
- }
-
- /* Locked region */
- {
- *pError = NSSCKFWMutex_Lock(db->crustylock);
- if( CKR_OK != *pError ) {
- goto loser;
- }
-
- *pdbrv = db->db->put(db->db, &rv->dbt, &object, 0);
- if( 0 != *pdbrv ) {
- *pError = CKR_DEVICE_ERROR;
- }
-
- (void)db->db->sync(db->db, 0);
-
- (void)NSSCKFWMutex_Unlock(db->crustylock);
- }
-
- loser:
- if( (NSSArena *)NULL != tmparena ) {
- (void)NSSArena_Destroy(tmparena);
- }
-
- return rv;
-}
-
-
-NSS_IMPLEMENT CK_RV
-nss_dbm_db_find_objects
-(
- nss_dbm_find_t *find,
- nss_dbm_db_t *db,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- CK_ULONG *pdbrv
-)
-{
- CK_RV rv = CKR_OK;
-
- if( (nss_dbm_db_t *)NULL != db ) {
- DBT k, v;
-
- rv = NSSCKFWMutex_Lock(db->crustylock);
- if( CKR_OK != rv ) {
- return rv;
- }
-
- *pdbrv = db->db->seq(db->db, &k, &v, R_FIRST);
- while( 0 == *pdbrv ) {
- CK_ULONG i, j;
- NSSArena *tmparena = (NSSArena *)NULL;
- CK_ULONG ulac;
- CK_ATTRIBUTE_PTR pt;
-
- if( (k.size < 4) || (0 != memcmp(k.data, PREFIX_OBJECT, 4)) ) {
- goto nomatch;
- }
-
- tmparena = NSSArena_Create();
-
- rv = nss_dbm_db_unwrap_object(tmparena, &v, &pt, &ulac);
- if( CKR_OK != rv ) {
- goto loser;
- }
-
- for( i = 0; i < ulAttributeCount; i++ ) {
- for( j = 0; j < ulac; j++ ) {
- if( pTemplate[i].type == pt[j].type ) {
- if( pTemplate[i].ulValueLen != pt[j].ulValueLen ) {
- goto nomatch;
- }
- if( 0 != memcmp(pTemplate[i].pValue, pt[j].pValue, pt[j].ulValueLen) ) {
- goto nomatch;
- }
- break;
- }
- }
- if( j == ulac ) {
- goto nomatch;
- }
- }
-
- /* entire template matches */
- {
- struct nss_dbm_dbt_node *node;
-
- node = nss_ZNEW(find->arena, struct nss_dbm_dbt_node);
- if( (struct nss_dbm_dbt_node *)NULL == node ) {
- rv = CKR_HOST_MEMORY;
- goto loser;
- }
-
- node->dbt = nss_ZNEW(find->arena, nss_dbm_dbt_t);
- if( (nss_dbm_dbt_t *)NULL == node->dbt ) {
- rv = CKR_HOST_MEMORY;
- goto loser;
- }
-
- node->dbt->dbt.size = k.size;
- node->dbt->dbt.data = nss_ZAlloc(find->arena, k.size);
- if( (void *)NULL == node->dbt->dbt.data ) {
- rv = CKR_HOST_MEMORY;
- goto loser;
- }
-
- (void)memcpy(node->dbt->dbt.data, k.data, k.size);
-
- node->dbt->my_db = db;
-
- node->next = find->found;
- find->found = node;
- }
-
- nomatch:
- if( (NSSArena *)NULL != tmparena ) {
- (void)NSSArena_Destroy(tmparena);
- }
- *pdbrv = db->db->seq(db->db, &k, &v, R_NEXT);
- }
-
- if( *pdbrv < 0 ) {
- rv = CKR_DEVICE_ERROR;
- goto loser;
- }
-
- rv = CKR_OK;
-
- loser:
- (void)NSSCKFWMutex_Unlock(db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_BBOOL
-nss_dbm_db_object_still_exists
-(
- nss_dbm_dbt_t *dbt
-)
-{
- CK_BBOOL rv;
- CK_RV ckrv;
- int dbrv;
- DBT object;
-
- ckrv = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != ckrv ) {
- return CK_FALSE;
- }
-
- dbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 == dbrv ) {
- rv = CK_TRUE;
- } else {
- rv = CK_FALSE;
- }
-
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_ULONG
-nss_dbm_db_get_object_attribute_count
-(
- nss_dbm_dbt_t *dbt,
- CK_RV *pError,
- CK_ULONG *pdbrv
-)
-{
- CK_ULONG rv = 0;
- DBT object;
- CK_ULONG *pulData;
-
- /* Locked region */
- {
- *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != *pError ) {
- return rv;
- }
-
- *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 == *pdbrv ) {
- ;
- } else if( *pdbrv > 0 ) {
- *pError = CKR_OBJECT_HANDLE_INVALID;
- goto done;
- } else {
- *pError = CKR_DEVICE_ERROR;
- goto done;
- }
-
- pulData = (CK_ULONG *)object.data;
- rv = ntohl(pulData[0]);
-
- done:
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_RV
-nss_dbm_db_get_object_attribute_types
-(
- nss_dbm_dbt_t *dbt,
- CK_ATTRIBUTE_TYPE_PTR typeArray,
- CK_ULONG ulCount,
- CK_ULONG *pdbrv
-)
-{
- CK_RV rv = CKR_OK;
- DBT object;
- CK_ULONG *pulData;
- CK_ULONG n, i;
-
- /* Locked region */
- {
- rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != rv ) {
- return rv;
- }
-
- *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 == *pdbrv ) {
- ;
- } else if( *pdbrv > 0 ) {
- rv = CKR_OBJECT_HANDLE_INVALID;
- goto done;
- } else {
- rv = CKR_DEVICE_ERROR;
- goto done;
- }
-
- pulData = (CK_ULONG *)object.data;
- n = ntohl(pulData[0]);
-
- if( ulCount < n ) {
- rv = CKR_BUFFER_TOO_SMALL;
- goto done;
- }
-
- for( i = 0; i < n; i++ ) {
- typeArray[i] = ntohl(pulData[1 + i*3]);
- }
-
- done:
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_ULONG
-nss_dbm_db_get_object_attribute_size
-(
- nss_dbm_dbt_t *dbt,
- CK_ATTRIBUTE_TYPE type,
- CK_RV *pError,
- CK_ULONG *pdbrv
-)
-{
- CK_ULONG rv = 0;
- DBT object;
- CK_ULONG *pulData;
- CK_ULONG n, i;
-
- /* Locked region */
- {
- *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != *pError ) {
- return rv;
- }
-
- *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 == *pdbrv ) {
- ;
- } else if( *pdbrv > 0 ) {
- *pError = CKR_OBJECT_HANDLE_INVALID;
- goto done;
- } else {
- *pError = CKR_DEVICE_ERROR;
- goto done;
- }
-
- pulData = (CK_ULONG *)object.data;
- n = ntohl(pulData[0]);
-
- for( i = 0; i < n; i++ ) {
- if( type == ntohl(pulData[1 + i*3]) ) {
- rv = ntohl(pulData[2 + i*3]);
- }
- }
-
- if( i == n ) {
- *pError = CKR_ATTRIBUTE_TYPE_INVALID;
- goto done;
- }
-
- done:
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT NSSItem *
-nss_dbm_db_get_object_attribute
-(
- nss_dbm_dbt_t *dbt,
- NSSArena *arena,
- CK_ATTRIBUTE_TYPE type,
- CK_RV *pError,
- CK_ULONG *pdbrv
-)
-{
- NSSItem *rv = (NSSItem *)NULL;
- DBT object;
- CK_ULONG i;
- NSSArena *tmp = NSSArena_Create();
- CK_ATTRIBUTE_PTR pTemplate;
- CK_ULONG ulAttributeCount;
-
- /* Locked region */
- {
- *pError = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != *pError ) {
- goto loser;
- }
-
- *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 == *pdbrv ) {
- ;
- } else if( *pdbrv > 0 ) {
- *pError = CKR_OBJECT_HANDLE_INVALID;
- goto done;
- } else {
- *pError = CKR_DEVICE_ERROR;
- goto done;
- }
-
- *pError = nss_dbm_db_unwrap_object(tmp, &object, &pTemplate, &ulAttributeCount);
- if( CKR_OK != *pError ) {
- goto done;
- }
-
- for( i = 0; i < ulAttributeCount; i++ ) {
- if( type == pTemplate[i].type ) {
- rv = nss_ZNEW(arena, NSSItem);
- if( (NSSItem *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- goto done;
- }
- rv->size = pTemplate[i].ulValueLen;
- rv->data = nss_ZAlloc(arena, rv->size);
- if( (void *)NULL == rv->data ) {
- *pError = CKR_HOST_MEMORY;
- goto done;
- }
- (void)memcpy(rv->data, pTemplate[i].pValue, rv->size);
- break;
- }
- }
- if( ulAttributeCount == i ) {
- *pError = CKR_ATTRIBUTE_TYPE_INVALID;
- goto done;
- }
-
- done:
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
- }
-
- loser:
- if( (NSSArena *)NULL != tmp ) {
- NSSArena_Destroy(tmp);
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT CK_RV
-nss_dbm_db_set_object_attribute
-(
- nss_dbm_dbt_t *dbt,
- CK_ATTRIBUTE_TYPE type,
- NSSItem *value,
- CK_ULONG *pdbrv
-)
-{
- CK_RV rv = CKR_OK;
- DBT object;
- CK_ULONG i;
- NSSArena *tmp = NSSArena_Create();
- CK_ATTRIBUTE_PTR pTemplate;
- CK_ULONG ulAttributeCount;
-
- /* Locked region */
- {
- rv = NSSCKFWMutex_Lock(dbt->my_db->crustylock);
- if( CKR_OK != rv ) {
- goto loser;
- }
-
- *pdbrv = dbt->my_db->db->get(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 == *pdbrv ) {
- ;
- } else if( *pdbrv > 0 ) {
- rv = CKR_OBJECT_HANDLE_INVALID;
- goto done;
- } else {
- rv = CKR_DEVICE_ERROR;
- goto done;
- }
-
- rv = nss_dbm_db_unwrap_object(tmp, &object, &pTemplate, &ulAttributeCount);
- if( CKR_OK != rv ) {
- goto done;
- }
-
- for( i = 0; i < ulAttributeCount; i++ ) {
- if( type == pTemplate[i].type ) {
- /* Replacing an existing attribute */
- pTemplate[i].ulValueLen = value->size;
- pTemplate[i].pValue = value->data;
- break;
- }
- }
-
- if( i == ulAttributeCount ) {
- /* Adding a new attribute */
- CK_ATTRIBUTE_PTR npt = nss_ZNEWARRAY(tmp, CK_ATTRIBUTE, ulAttributeCount+1);
- if( (CK_ATTRIBUTE_PTR)NULL == npt ) {
- rv = CKR_DEVICE_ERROR;
- goto done;
- }
-
- for( i = 0; i < ulAttributeCount; i++ ) {
- npt[i] = pTemplate[i];
- }
-
- npt[ulAttributeCount].type = type;
- npt[ulAttributeCount].ulValueLen = value->size;
- npt[ulAttributeCount].pValue = value->data;
-
- pTemplate = npt;
- ulAttributeCount++;
- }
-
- rv = nss_dbm_db_wrap_object(tmp, pTemplate, ulAttributeCount, &object);
- if( CKR_OK != rv ) {
- goto done;
- }
-
- *pdbrv = dbt->my_db->db->put(dbt->my_db->db, &dbt->dbt, &object, 0);
- if( 0 != *pdbrv ) {
- rv = CKR_DEVICE_ERROR;
- goto done;
- }
-
- (void)dbt->my_db->db->sync(dbt->my_db->db, 0);
-
- done:
- (void)NSSCKFWMutex_Unlock(dbt->my_db->crustylock);
- }
-
- loser:
- if( (NSSArena *)NULL != tmp ) {
- NSSArena_Destroy(tmp);
- }
-
- return rv;
-}
diff --git a/security/nss/lib/ckfw/dbm/find.c b/security/nss/lib/ckfw/dbm/find.c
deleted file mode 100644
index 81fe5d8fb..000000000
--- a/security/nss/lib/ckfw/dbm/find.c
+++ /dev/null
@@ -1,166 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-static void
-nss_dbm_mdFindObjects_Final
-(
- NSSCKMDFindObjects *mdFindObjects,
- NSSCKFWFindObjects *fwFindObjects,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_find_t *find = (nss_dbm_find_t *)mdFindObjects->etc;
-
- /* Locks might have system resources associated */
- (void)NSSCKFWMutex_Destroy(find->list_lock);
- (void)NSSArena_Destroy(find->arena);
-}
-
-
-static NSSCKMDObject *
-nss_dbm_mdFindObjects_Next
-(
- NSSCKMDFindObjects *mdFindObjects,
- NSSCKFWFindObjects *fwFindObjects,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- NSSArena *arena,
- CK_RV *pError
-)
-{
- nss_dbm_find_t *find = (nss_dbm_find_t *)mdFindObjects->etc;
- struct nss_dbm_dbt_node *node;
- nss_dbm_object_t *object;
- NSSCKMDObject *rv;
-
- while(1) {
- /* Lock */
- {
- *pError = NSSCKFWMutex_Lock(find->list_lock);
- if( CKR_OK != *pError ) {
- return (NSSCKMDObject *)NULL;
- }
-
- node = find->found;
- if( (struct nss_dbm_dbt_node *)NULL != node ) {
- find->found = node->next;
- }
-
- *pError = NSSCKFWMutex_Unlock(find->list_lock);
- if( CKR_OK != *pError ) {
- /* screwed now */
- return (NSSCKMDObject *)NULL;
- }
- }
-
- if( (struct nss_dbm_dbt_node *)NULL == node ) {
- break;
- }
-
- if( nss_dbm_db_object_still_exists(node->dbt) ) {
- break;
- }
- }
-
- if( (struct nss_dbm_dbt_node *)NULL == node ) {
- *pError = CKR_OK;
- return (NSSCKMDObject *)NULL;
- }
-
- object = nss_ZNEW(arena, nss_dbm_object_t);
- if( (nss_dbm_object_t *)NULL == object ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDObject *)NULL;
- }
-
- object->arena = arena;
- object->handle = nss_ZNEW(arena, nss_dbm_dbt_t);
- if( (nss_dbm_dbt_t *)NULL == object->handle ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDObject *)NULL;
- }
-
- object->handle->my_db = node->dbt->my_db;
- object->handle->dbt.size = node->dbt->dbt.size;
- object->handle->dbt.data = nss_ZAlloc(arena, node->dbt->dbt.size);
- if( (void *)NULL == object->handle->dbt.data ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDObject *)NULL;
- }
-
- (void)memcpy(object->handle->dbt.data, node->dbt->dbt.data, node->dbt->dbt.size);
-
- rv = nss_dbm_mdObject_factory(object, pError);
- if( (NSSCKMDObject *)NULL == rv ) {
- return (NSSCKMDObject *)NULL;
- }
-
- return rv;
-}
-
-NSS_IMPLEMENT NSSCKMDFindObjects *
-nss_dbm_mdFindObjects_factory
-(
- nss_dbm_find_t *find,
- CK_RV *pError
-)
-{
- NSSCKMDFindObjects *rv;
-
- rv = nss_ZNEW(find->arena, NSSCKMDFindObjects);
- if( (NSSCKMDFindObjects *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDFindObjects *)NULL;
- }
-
- rv->etc = (void *)find;
- rv->Final = nss_dbm_mdFindObjects_Final;
- rv->Next = nss_dbm_mdFindObjects_Next;
-
- return rv;
-}
diff --git a/security/nss/lib/ckfw/dbm/instance.c b/security/nss/lib/ckfw/dbm/instance.c
deleted file mode 100644
index 70681803f..000000000
--- a/security/nss/lib/ckfw/dbm/instance.c
+++ /dev/null
@@ -1,196 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-static CK_RV
-nss_dbm_mdInstance_Initialize
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- NSSUTF8 *configurationData
-)
-{
- CK_RV rv = CKR_OK;
- NSSArena *arena;
- nss_dbm_instance_t *instance;
-
- arena = NSSCKFWInstance_GetArena(fwInstance, &rv);
- if( ((NSSArena *)NULL == arena) && (CKR_OK != rv) ) {
- return rv;
- }
-
- instance = nss_ZNEW(arena, nss_dbm_instance_t);
- if( (nss_dbm_instance_t *)NULL == instance ) {
- return CKR_HOST_MEMORY;
- }
-
- instance->arena = arena;
-
- /*
- * This should parse the configuration data for information on
- * number and locations of databases, modes (e.g. readonly), etc.
- * But for now, we'll have one slot with a creatable read-write
- * database called "cert8.db."
- */
-
- instance->nSlots = 1;
- instance->filenames = nss_ZNEWARRAY(arena, char *, instance->nSlots);
- if( (char **)NULL == instance->filenames ) {
- return CKR_HOST_MEMORY;
- }
-
- instance->flags = nss_ZNEWARRAY(arena, int, instance->nSlots);
- if( (int *)NULL == instance->flags ) {
- return CKR_HOST_MEMORY;
- }
-
- instance->filenames[0] = "cert8.db";
- instance->flags[0] = O_RDWR|O_CREAT;
-
- mdInstance->etc = (void *)instance;
- return CKR_OK;
-}
-
-/* nss_dbm_mdInstance_Finalize is not required */
-
-static CK_ULONG
-nss_dbm_mdInstance_GetNSlots
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc;
- return instance->nSlots;
-}
-
-static CK_VERSION
-nss_dbm_mdInstance_GetCryptokiVersion
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- static CK_VERSION rv = { 2, 1 };
- return rv;
-}
-
-static NSSUTF8 *
-nss_dbm_mdInstance_GetManufacturerID
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- return "Netscape Communications Corp.";
-}
-
-static NSSUTF8 *
-nss_dbm_mdInstance_GetLibraryDescription
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- return "Berkeley Database Module";
-}
-
-static CK_VERSION
-nss_dbm_mdInstance_GetLibraryVersion
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- static CK_VERSION rv = { 1, 0 }; /* My own version number */
- return rv;
-}
-
-static CK_BBOOL
-nss_dbm_mdInstance_ModuleHandlesSessionObjects
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- return CK_TRUE;
-}
-
-static CK_RV
-nss_dbm_mdInstance_GetSlots
-(
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- NSSCKMDSlot *slots[]
-)
-{
- nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc;
- CK_ULONG i;
- CK_RV rv = CKR_OK;
-
- for( i = 0; i < instance->nSlots; i++ ) {
- slots[i] = nss_dbm_mdSlot_factory(instance, instance->filenames[i],
- instance->flags[i], &rv);
- if( (NSSCKMDSlot *)NULL == slots[i] ) {
- return rv;
- }
- }
-
- return rv;
-}
-
-/* nss_dbm_mdInstance_WaitForSlotEvent is not relevant */
-
-NSS_IMPLEMENT_DATA NSSCKMDInstance
-nss_dbm_mdInstance = {
- NULL, /* etc; filled in later */
- nss_dbm_mdInstance_Initialize,
- NULL, /* nss_dbm_mdInstance_Finalize */
- nss_dbm_mdInstance_GetNSlots,
- nss_dbm_mdInstance_GetCryptokiVersion,
- nss_dbm_mdInstance_GetManufacturerID,
- nss_dbm_mdInstance_GetLibraryDescription,
- nss_dbm_mdInstance_GetLibraryVersion,
- nss_dbm_mdInstance_ModuleHandlesSessionObjects,
- nss_dbm_mdInstance_GetSlots,
- NULL, /* nss_dbm_mdInstance_WaitForSlotEvent */
- NULL /* terminator */
-};
diff --git a/security/nss/lib/ckfw/dbm/manifest.mn b/security/nss/lib/ckfw/dbm/manifest.mn
deleted file mode 100644
index 193e46bef..000000000
--- a/security/nss/lib/ckfw/dbm/manifest.mn
+++ /dev/null
@@ -1,54 +0,0 @@
-#
-# The contents of this file are subject to the Mozilla Public
-# License Version 1.1 (the "License"); you may not use this file
-# except in compliance with the License. You may obtain a copy of
-# the License at http://www.mozilla.org/MPL/
-#
-# Software distributed under the License is distributed on an "AS
-# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
-# implied. See the License for the specific language governing
-# rights and limitations under the License.
-#
-# The Original Code is the Netscape security libraries.
-#
-# The Initial Developer of the Original Code is Netscape
-# Communications Corporation. Portions created by Netscape are
-# Copyright (C) 1994-2000 Netscape Communications Corporation. All
-# Rights Reserved.
-#
-# Contributor(s):
-#
-# Alternatively, the contents of this file may be used under the
-# terms of the GNU General Public License Version 2 or later (the
-# "GPL"), in which case the provisions of the GPL are applicable
-# instead of those above. If you wish to allow use of your
-# version of this file only under the terms of the GPL and not to
-# allow others to use your version of this file under the MPL,
-# indicate your decision by deleting the provisions above and
-# replace them with the notice and other provisions required by
-# the GPL. If you do not delete the provisions above, a recipient
-# may use your version of this file under either the MPL or the
-# GPL.
-#
-MANIFEST_CVS_ID = "@(#) $RCSfile$ $Revision$ $Date$ $Name$"
-
-CORE_DEPTH = ../../../..
-
-MODULE = security
-
-CSRCS = \
- anchor.c \
- instance.c \
- slot.c \
- token.c \
- session.c \
- object.c \
- find.c \
- db.c \
- $(NULL)
-
-REQUIRES = security dbm nspr
-
-LIBRARY_NAME = nssckdbm
-
-EXTRA_SHARED_LIBS = -L$(DIST)/lib -lnssckfw -lnssb -ldbm -lnspr4 -lplc4 -lplds4
diff --git a/security/nss/lib/ckfw/dbm/object.c b/security/nss/lib/ckfw/dbm/object.c
deleted file mode 100644
index 2bd7578fd..000000000
--- a/security/nss/lib/ckfw/dbm/object.c
+++ /dev/null
@@ -1,204 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-static void
-nss_dbm_mdObject_Finalize
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- ;
-}
-
-static CK_RV
-nss_dbm_mdObject_Destroy
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc;
- return nss_dbm_db_delete_object(object->handle);
-}
-
-static CK_ULONG
-nss_dbm_mdObject_GetAttributeCount
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc;
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- return nss_dbm_db_get_object_attribute_count(object->handle, pError,
- &session->deviceError);
-}
-
-static CK_RV
-nss_dbm_mdObject_GetAttributeTypes
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_ATTRIBUTE_TYPE_PTR typeArray,
- CK_ULONG ulCount
-)
-{
- nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc;
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- return nss_dbm_db_get_object_attribute_types(object->handle, typeArray,
- ulCount, &session->deviceError);
-}
-
-static CK_ULONG
-nss_dbm_mdObject_GetAttributeSize
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_ATTRIBUTE_TYPE attribute,
- CK_RV *pError
-)
-{
- nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc;
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- return nss_dbm_db_get_object_attribute_size(object->handle, attribute, pError,
- &session->deviceError);
-}
-
-static NSSItem *
-nss_dbm_mdObject_GetAttribute
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_ATTRIBUTE_TYPE attribute,
- CK_RV *pError
-)
-{
- nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc;
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- return nss_dbm_db_get_object_attribute(object->handle, object->arena, attribute,
- pError, &session->deviceError);
-}
-
-static CK_RV
-nss_dbm_mdObject_SetAttribute
-(
- NSSCKMDObject *mdObject,
- NSSCKFWObject *fwObject,
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_ATTRIBUTE_TYPE attribute,
- NSSItem *value
-)
-{
- nss_dbm_object_t *object = (nss_dbm_object_t *)mdObject->etc;
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- return nss_dbm_db_set_object_attribute(object->handle, attribute, value,
- &session->deviceError);
-}
-
-NSS_IMPLEMENT NSSCKMDObject *
-nss_dbm_mdObject_factory
-(
- nss_dbm_object_t *object,
- CK_RV *pError
-)
-{
- NSSCKMDObject *rv;
-
- rv = nss_ZNEW(object->arena, NSSCKMDObject);
- if( (NSSCKMDObject *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDObject *)NULL;
- }
-
- rv->etc = (void *)object;
- rv->Finalize = nss_dbm_mdObject_Finalize;
- rv->Destroy = nss_dbm_mdObject_Destroy;
- /* IsTokenObject can be deferred */
- rv->GetAttributeCount = nss_dbm_mdObject_GetAttributeCount;
- rv->GetAttributeTypes = nss_dbm_mdObject_GetAttributeTypes;
- rv->GetAttributeSize = nss_dbm_mdObject_GetAttributeSize;
- rv->GetAttribute = nss_dbm_mdObject_GetAttribute;
- rv->SetAttribute = nss_dbm_mdObject_SetAttribute;
- /* GetObjectSize can be deferred */
-
- return rv;
-}
diff --git a/security/nss/lib/ckfw/dbm/session.c b/security/nss/lib/ckfw/dbm/session.c
deleted file mode 100644
index c0969d948..000000000
--- a/security/nss/lib/ckfw/dbm/session.c
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-static void
-nss_dbm_mdSession_Close
-(
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
-
- struct nss_dbm_dbt_node *w;
-
- /* Lock */
- {
- if( CKR_OK != NSSCKFWMutex_Lock(session->list_lock) ) {
- return;
- }
-
- w = session->session_objects;
- session->session_objects = (struct nss_dbm_dbt_node *)NULL; /* sanity */
-
- (void)NSSCKFWMutex_Unlock(session->list_lock);
- }
-
- for( ; (struct nss_dbm_dbt_node *)NULL != w; w = w->next ) {
- (void)nss_dbm_db_delete_object(w->dbt);
- }
-}
-
-static CK_ULONG
-nss_dbm_mdSession_GetDeviceError
-(
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- return session->deviceError;
-}
-
-/* Login isn't needed */
-/* Logout isn't needed */
-/* InitPIN is irrelevant */
-/* SetPIN is irrelevant */
-/* GetOperationStateLen is irrelevant */
-/* GetOperationState is irrelevant */
-/* SetOperationState is irrelevant */
-
-static NSSCKMDObject *
-nss_dbm_mdSession_CreateObject
-(
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- NSSArena *handyArenaPointer,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- CK_RV *pError
-)
-{
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
- CK_ULONG i;
- CK_BBOOL isToken = CK_FALSE; /* defaults to false */
- NSSCKMDObject *rv;
- struct nss_dbm_dbt_node *node = (struct nss_dbm_dbt_node *)NULL;
- nss_dbm_object_t *object;
- nss_dbm_db_t *which_db;
-
- /* This framework should really pass this to me */
- for( i = 0; i < ulAttributeCount; i++ ) {
- if( CKA_TOKEN == pTemplate[i].type ) {
- isToken = *(CK_BBOOL *)pTemplate[i].pValue;
- break;
- }
- }
-
- object = nss_ZNEW(handyArenaPointer, nss_dbm_object_t);
- if( (nss_dbm_object_t *)NULL == object ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDObject *)NULL;
- }
-
- object->arena = handyArenaPointer;
- which_db = isToken ? token->slot->token_db : token->session_db;
-
- /* Do this before the actual database call; it's easier to recover from */
- rv = nss_dbm_mdObject_factory(object, pError);
- if( (NSSCKMDObject *)NULL == rv ) {
- return (NSSCKMDObject *)NULL;
- }
-
- if( CK_FALSE == isToken ) {
- node = nss_ZNEW(session->arena, struct nss_dbm_dbt_node);
- if( (struct nss_dbm_dbt_node *)NULL == node ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDObject *)NULL;
- }
- }
-
- object->handle = nss_dbm_db_create_object(handyArenaPointer, which_db,
- pTemplate, ulAttributeCount,
- pError, &session->deviceError);
- if( (nss_dbm_dbt_t *)NULL == object->handle ) {
- return (NSSCKMDObject *)NULL;
- }
-
- if( CK_FALSE == isToken ) {
- node->dbt = object->handle;
- /* Lock */
- {
- *pError = NSSCKFWMutex_Lock(session->list_lock);
- if( CKR_OK != *pError ) {
- (void)nss_dbm_db_delete_object(object->handle);
- return (NSSCKMDObject *)NULL;
- }
-
- node->next = session->session_objects;
- session->session_objects = node;
-
- *pError = NSSCKFWMutex_Unlock(session->list_lock);
- }
- }
-
- return rv;
-}
-
-/* CopyObject isn't needed; the framework will use CreateObject */
-
-static NSSCKMDFindObjects *
-nss_dbm_mdSession_FindObjectsInit
-(
- NSSCKMDSession *mdSession,
- NSSCKFWSession *fwSession,
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_ATTRIBUTE_PTR pTemplate,
- CK_ULONG ulAttributeCount,
- CK_RV *pError
-)
-{
- nss_dbm_session_t *session = (nss_dbm_session_t *)mdSession->etc;
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
- NSSArena *arena;
- nss_dbm_find_t *find;
- NSSCKMDFindObjects *rv;
-
- arena = NSSArena_Create();
- if( (NSSArena *)NULL == arena ) {
- *pError = CKR_HOST_MEMORY;
- goto loser;
- }
-
- find = nss_ZNEW(arena, nss_dbm_find_t);
- if( (nss_dbm_find_t *)NULL == find ) {
- *pError = CKR_HOST_MEMORY;
- goto loser;
- }
-
- find->arena = arena;
- find->list_lock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError);
- if( (NSSCKFWMutex *)NULL == find->list_lock ) {
- goto loser;
- }
-
- *pError = nss_dbm_db_find_objects(find, token->slot->token_db, pTemplate,
- ulAttributeCount, &session->deviceError);
- if( CKR_OK != *pError ) {
- goto loser;
- }
-
- *pError = nss_dbm_db_find_objects(find, token->session_db, pTemplate,
- ulAttributeCount, &session->deviceError);
- if( CKR_OK != *pError ) {
- goto loser;
- }
-
- rv = nss_dbm_mdFindObjects_factory(find, pError);
- if( (NSSCKMDFindObjects *)NULL == rv ) {
- goto loser;
- }
-
- return rv;
-
- loser:
- if( (NSSArena *)NULL != arena ) {
- (void)NSSArena_Destroy(arena);
- }
-
- return (NSSCKMDFindObjects *)NULL;
-}
-
-/* SeedRandom is irrelevant */
-/* GetRandom is irrelevant */
-
-NSS_IMPLEMENT NSSCKMDSession *
-nss_dbm_mdSession_factory
-(
- nss_dbm_token_t *token,
- NSSCKFWSession *fwSession,
- NSSCKFWInstance *fwInstance,
- CK_BBOOL rw,
- CK_RV *pError
-)
-{
- NSSArena *arena;
- nss_dbm_session_t *session;
- NSSCKMDSession *rv;
-
- arena = NSSCKFWSession_GetArena(fwSession, pError);
-
- session = nss_ZNEW(arena, nss_dbm_session_t);
- if( (nss_dbm_session_t *)NULL == session ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDSession *)NULL;
- }
-
- rv = nss_ZNEW(arena, NSSCKMDSession);
- if( (NSSCKMDSession *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDSession *)NULL;
- }
-
- session->arena = arena;
- session->token = token;
- session->list_lock = NSSCKFWInstance_CreateMutex(fwInstance, arena, pError);
- if( (NSSCKFWMutex *)NULL == session->list_lock ) {
- return (NSSCKMDSession *)NULL;
- }
-
- rv->etc = (void *)session;
- rv->Close = nss_dbm_mdSession_Close;
- rv->GetDeviceError = nss_dbm_mdSession_GetDeviceError;
- /* Login isn't needed */
- /* Logout isn't needed */
- /* InitPIN is irrelevant */
- /* SetPIN is irrelevant */
- /* GetOperationStateLen is irrelevant */
- /* GetOperationState is irrelevant */
- /* SetOperationState is irrelevant */
- rv->CreateObject = nss_dbm_mdSession_CreateObject;
- /* CopyObject isn't needed; the framework will use CreateObject */
- rv->FindObjectsInit = nss_dbm_mdSession_FindObjectsInit;
- rv->null = NULL;
-
- return rv;
-}
diff --git a/security/nss/lib/ckfw/dbm/slot.c b/security/nss/lib/ckfw/dbm/slot.c
deleted file mode 100644
index 40898897a..000000000
--- a/security/nss/lib/ckfw/dbm/slot.c
+++ /dev/null
@@ -1,214 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-static CK_RV
-nss_dbm_mdSlot_Initialize
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc;
- nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc;
- CK_RV rv = CKR_OK;
-
- slot->token_db = nss_dbm_db_open(instance->arena, fwInstance, slot->filename,
- slot->flags, &rv);
- if( (nss_dbm_db_t *)NULL == slot->token_db ) {
- if( CKR_TOKEN_NOT_PRESENT == rv ) {
- /* This is not an error-- just means "the token isn't there" */
- rv = CKR_OK;
- }
- }
-
- return rv;
-}
-
-static void
-nss_dbm_mdSlot_Destroy
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc;
-
- if( (nss_dbm_db_t *)NULL != slot->token_db ) {
- nss_dbm_db_close(slot->token_db);
- slot->token_db = (nss_dbm_db_t *)NULL;
- }
-}
-
-static NSSUTF8 *
-nss_dbm_mdSlot_GetSlotDescription
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- return "Database";
-}
-
-static NSSUTF8 *
-nss_dbm_mdSlot_GetManufacturerID
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- return "Berkeley";
-}
-
-static CK_BBOOL
-nss_dbm_mdSlot_GetTokenPresent
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc;
-
- if( (nss_dbm_db_t *)NULL == slot->token_db ) {
- return CK_FALSE;
- } else {
- return CK_TRUE;
- }
-}
-
-static CK_BBOOL
-nss_dbm_mdSlot_GetRemovableDevice
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- /*
- * Well, this supports "tokens" (databases) that aren't there, so in
- * that sense they're removable. It'd be nice to handle databases
- * that suddenly disappear (NFS-mounted home directories and network
- * errors, for instance) but that's a harder problem. We'll say
- * we support removable devices, badly.
- */
-
- return CK_TRUE;
-}
-
-/* nss_dbm_mdSlot_GetHardwareSlot defaults to CK_FALSE */
-/*
- * nss_dbm_mdSlot_GetHardwareVersion
- * nss_dbm_mdSlot_GetFirmwareVersion
- *
- * These are kinda fuzzy concepts here. I suppose we could return the
- * Berkeley DB version for one of them, if we had an actual number we
- * were confident in. But mcom's "dbm" has been hacked enough that I
- * don't really know from what "real" version it stems..
- */
-
-static NSSCKMDToken *
-nss_dbm_mdSlot_GetToken
-(
- NSSCKMDSlot *mdSlot,
- NSSCKFWSlot *fwSlot,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- nss_dbm_slot_t *slot = (nss_dbm_slot_t *)mdSlot->etc;
- return nss_dbm_mdToken_factory(slot, pError);
-}
-
-NSS_IMPLEMENT NSSCKMDSlot *
-nss_dbm_mdSlot_factory
-(
- nss_dbm_instance_t *instance,
- char *filename,
- int flags,
- CK_RV *pError
-)
-{
- nss_dbm_slot_t *slot;
- NSSCKMDSlot *rv;
-
- slot = nss_ZNEW(instance->arena, nss_dbm_slot_t);
- if( (nss_dbm_slot_t *)NULL == slot ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDSlot *)NULL;
- }
-
- slot->instance = instance;
- slot->filename = filename;
- slot->flags = flags;
- slot->token_db = (nss_dbm_db_t *)NULL;
-
- rv = nss_ZNEW(instance->arena, NSSCKMDSlot);
- if( (NSSCKMDSlot *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDSlot *)NULL;
- }
-
- rv->etc = (void *)slot;
- rv->Initialize = nss_dbm_mdSlot_Initialize;
- rv->Destroy = nss_dbm_mdSlot_Destroy;
- rv->GetSlotDescription = nss_dbm_mdSlot_GetSlotDescription;
- rv->GetManufacturerID = nss_dbm_mdSlot_GetManufacturerID;
- rv->GetTokenPresent = nss_dbm_mdSlot_GetTokenPresent;
- rv->GetRemovableDevice = nss_dbm_mdSlot_GetRemovableDevice;
- /* GetHardwareSlot */
- /* GetHardwareVersion */
- /* GetFirmwareVersion */
- rv->GetToken = nss_dbm_mdSlot_GetToken;
- rv->null = (void *)NULL;
-
- return rv;
-}
diff --git a/security/nss/lib/ckfw/dbm/token.c b/security/nss/lib/ckfw/dbm/token.c
deleted file mode 100644
index 7c7fbf9e5..000000000
--- a/security/nss/lib/ckfw/dbm/token.c
+++ /dev/null
@@ -1,315 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-#ifdef DEBUG
-static const char CVS_ID[] = "@(#) $RCSfile$ $Revision$ $Date$ $Name$";
-#endif /* DEBUG */
-
-#include "ckdbm.h"
-
-static CK_RV
-nss_dbm_mdToken_Setup
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
- CK_RV rv = CKR_OK;
-
- token->arena = NSSCKFWToken_GetArena(fwToken, &rv);
- token->session_db = nss_dbm_db_open(token->arena, fwInstance, (char *)NULL,
- O_RDWR|O_CREAT, &rv);
- if( (nss_dbm_db_t *)NULL == token->session_db ) {
- return rv;
- }
-
- /* Add a label record if there isn't one? */
-
- return CKR_OK;
-}
-
-static void
-nss_dbm_mdToken_Invalidate
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
-
- if( (nss_dbm_db_t *)NULL != token->session_db ) {
- nss_dbm_db_close(token->session_db);
- token->session_db = (nss_dbm_db_t *)NULL;
- }
-}
-
-static CK_RV
-nss_dbm_mdToken_InitToken
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- NSSItem *pin,
- NSSUTF8 *label
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
- nss_dbm_instance_t *instance = (nss_dbm_instance_t *)mdInstance->etc;
- CK_RV rv;
-
- /* Wipe the session object data */
-
- if( (nss_dbm_db_t *)NULL != token->session_db ) {
- nss_dbm_db_close(token->session_db);
- }
-
- token->session_db = nss_dbm_db_open(token->arena, fwInstance, (char *)NULL,
- O_RDWR|O_CREAT, &rv);
- if( (nss_dbm_db_t *)NULL == token->session_db ) {
- return rv;
- }
-
- /* Wipe the token object data */
-
- if( token->slot->flags & O_RDWR ) {
- if( (nss_dbm_db_t *)NULL != token->slot->token_db ) {
- nss_dbm_db_close(token->slot->token_db);
- }
-
- token->slot->token_db = nss_dbm_db_open(instance->arena, fwInstance,
- token->slot->filename,
- token->slot->flags | O_CREAT | O_TRUNC,
- &rv);
- if( (nss_dbm_db_t *)NULL == token->slot->token_db ) {
- return rv;
- }
-
- /* PIN is irrelevant */
-
- rv = nss_dbm_db_set_label(token->slot->token_db, label);
- if( CKR_OK != rv ) {
- return rv;
- }
- }
-
- return CKR_OK;
-}
-
-static NSSUTF8 *
-nss_dbm_mdToken_GetLabel
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
-
- if( (NSSUTF8 *)NULL == token->label ) {
- token->label = nss_dbm_db_get_label(token->slot->token_db, token->arena, pError);
- }
-
- /* If no label has been set, return *something* */
- if( (NSSUTF8 *)NULL == token->label ) {
- return token->slot->filename;
- }
-
- return token->label;
-}
-
-static NSSUTF8 *
-nss_dbm_mdToken_GetManufacturerID
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- return "mozilla.org NSS";
-}
-
-static NSSUTF8 *
-nss_dbm_mdToken_GetModel
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- CK_RV *pError
-)
-{
- return "dbm";
-}
-
-/* GetSerialNumber is irrelevant */
-/* GetHasRNG defaults to CK_FALSE */
-
-static CK_BBOOL
-nss_dbm_mdToken_GetIsWriteProtected
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
-
- if( token->slot->flags & O_RDWR ) {
- return CK_FALSE;
- } else {
- return CK_TRUE;
- }
-}
-
-/* GetLoginRequired defaults to CK_FALSE */
-/* GetUserPinInitialized defaults to CK_FALSE */
-/* GetRestoreKeyNotNeeded is irrelevant */
-/* GetHasClockOnToken defaults to CK_FALSE */
-/* GetHasProtectedAuthenticationPath defaults to CK_FALSE */
-/* GetSupportsDualCryptoOperations is irrelevant */
-
-static CK_ULONG
-nss_dbm_mdToken_effectively_infinite
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- return CK_EFFECTIVELY_INFINITE;
-}
-
-static CK_VERSION
-nss_dbm_mdToken_GetHardwareVersion
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
- return nss_dbm_db_get_format_version(token->slot->token_db);
-}
-
-/* GetFirmwareVersion is irrelevant */
-/* GetUTCTime is irrelevant */
-
-static NSSCKMDSession *
-nss_dbm_mdToken_OpenSession
-(
- NSSCKMDToken *mdToken,
- NSSCKFWToken *fwToken,
- NSSCKMDInstance *mdInstance,
- NSSCKFWInstance *fwInstance,
- NSSCKFWSession *fwSession,
- CK_BBOOL rw,
- CK_RV *pError
-)
-{
- nss_dbm_token_t *token = (nss_dbm_token_t *)mdToken->etc;
- return nss_dbm_mdSession_factory(token, fwSession, fwInstance, rw, pError);
-}
-
-/* GetMechanismCount defaults to zero */
-/* GetMechanismTypes is irrelevant */
-/* GetMechanism is irrelevant */
-
-NSS_IMPLEMENT NSSCKMDToken *
-nss_dbm_mdToken_factory
-(
- nss_dbm_slot_t *slot,
- CK_RV *pError
-)
-{
- nss_dbm_token_t *token;
- NSSCKMDToken *rv;
-
- token = nss_ZNEW(slot->instance->arena, nss_dbm_token_t);
- if( (nss_dbm_token_t *)NULL == token ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDToken *)NULL;
- }
-
- rv = nss_ZNEW(slot->instance->arena, NSSCKMDToken);
- if( (NSSCKMDToken *)NULL == rv ) {
- *pError = CKR_HOST_MEMORY;
- return (NSSCKMDToken *)NULL;
- }
-
- token->slot = slot;
-
- rv->etc = (void *)token;
- rv->Setup = nss_dbm_mdToken_Setup;
- rv->Invalidate = nss_dbm_mdToken_Invalidate;
- rv->InitToken = nss_dbm_mdToken_InitToken;
- rv->GetLabel = nss_dbm_mdToken_GetLabel;
- rv->GetManufacturerID = nss_dbm_mdToken_GetManufacturerID;
- rv->GetModel = nss_dbm_mdToken_GetModel;
- /* GetSerialNumber is irrelevant */
- /* GetHasRNG defaults to CK_FALSE */
- rv->GetIsWriteProtected = nss_dbm_mdToken_GetIsWriteProtected;
- /* GetLoginRequired defaults to CK_FALSE */
- /* GetUserPinInitialized defaults to CK_FALSE */
- /* GetRestoreKeyNotNeeded is irrelevant */
- /* GetHasClockOnToken defaults to CK_FALSE */
- /* GetHasProtectedAuthenticationPath defaults to CK_FALSE */
- /* GetSupportsDualCryptoOperations is irrelevant */
- rv->GetMaxSessionCount = nss_dbm_mdToken_effectively_infinite;
- rv->GetMaxRwSessionCount = nss_dbm_mdToken_effectively_infinite;
- /* GetMaxPinLen is irrelevant */
- /* GetMinPinLen is irrelevant */
- /* GetTotalPublicMemory defaults to CK_UNAVAILABLE_INFORMATION */
- /* GetFreePublicMemory defaults to CK_UNAVAILABLE_INFORMATION */
- /* GetTotalPrivateMemory defaults to CK_UNAVAILABLE_INFORMATION */
- /* GetFreePrivateMemory defaults to CK_UNAVAILABLE_INFORMATION */
- rv->GetHardwareVersion = nss_dbm_mdToken_GetHardwareVersion;
- /* GetFirmwareVersion is irrelevant */
- /* GetUTCTime is irrelevant */
- rv->OpenSession = nss_dbm_mdToken_OpenSession;
- rv->null = NULL;
-
- return rv;
-}
diff --git a/security/nss/lib/fortcrypt/genci.h b/security/nss/lib/fortcrypt/genci.h
deleted file mode 100644
index 7868e1853..000000000
--- a/security/nss/lib/fortcrypt/genci.h
+++ /dev/null
@@ -1,145 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-/*
- * the following header file switches between MACI and CI based on
- * compile options. That lest the rest of the source code operate
- * without change, even if it only suports CI_ calls, not MACI_ calls
- */
-#ifndef _GENCI_H_
-#define _GENCI_H_ 1
-#include "seccomon.h"
-
-#if defined (XP_UNIX) || defined (XP_WIN32)
-
-/*
- * On unix, NT, and Windows '95 we use full maci
- */
-#include "maci.h"
-
-#define MACI_SEL(x)
-
-/*
- * for sec-for.c
- */
-#define CI_Initialize MACI_Initialize
-#define CI_Terminate() { HSESSION hs;\
- MACI_GetSessionID(&hs);\
- MACI_Terminate(hs); }
-
-#else
-
-/*
- * On Mac we use the original CI_LIB
- */
-#include "cryptint.h"
-
-/*
- * MACI specific values not defined for CI lib
- */
-#define MACI_SESSION_EXCEEDED (-53)
-
-#ifndef HSESSION_DEFINE
-typedef unsigned int HSESSION;
-#define HSESSION_DEFINE
-#endif
-
-/*
- * Map MACI_ calls to CI_ calls. NOTE: this assumes the proper CI_Select
- * calls are issued in the CI_ case
- */
-#define MACI_ChangePIN(s,pin,old,new) CI_ChangePIN(pin,old,new)
-#define MACI_CheckPIN(s,type,pin) CI_CheckPIN(type,pin)
-#define MACI_Close(s,flag,socket) CI_Close(flag,socket)
-#define MACI_Decrypt(s,size,in,out) CI_Decrypt(size,in,out)
-#define MACI_DeleteCertificate(s,cert) CI_DeleteCertificate(cert)
-#define MACI_DeleteKey(s,index) CI_DeleteKey(index)
-#define MACI_Encrypt(s,size,in,out) CI_Encrypt(size,in,out)
-#define MACI_ExtractX(s,cert,type,pass,ySize,y,x,Ra,pgSize,qSize,p,q,g) \
- CI_ExtractX(cert,type,pass,ySize,y,x,Ra,pgSize,qSize,p,q,g)
-#define MACI_FirmwareUpdate(s,flags,Cksum,len,size,data) \
- CI_FirmwareUpdate(flags,Cksum,len,size,data)
-#define MACI_GenerateIV(s,iv) CI_GenerateIV(iv)
-#define MACI_GenerateMEK(s,index,res) CI_GenerateMEK(index,res)
-#define MACI_GenerateRa(s,Ra) CI_GenerateRa(Ra)
-#define MACI_GenerateRandom(s,ran) CI_GenerateRandom(ran)
-#define MACI_GenerateTEK(s,flag,index,Ra,Rb,size,Y) \
- CI_GenerateTEK(flag,index,Ra,Rb,size,Y)
-#define MACI_GenerateX(s,cert,type,pgSize,qSize,p,q,g,ySize,y) \
- CI_GenerateX(cert,type,pgSize,qSize,p,q,g,ySize,y)
-#define MACI_GetCertificate(s,cert,val) CI_GetCertificate(cert,val)
-#define MACI_GetConfiguration(s,config) CI_GetConfiguration(config)
-#define MACI_GetHash(s,size,data,val) CI_GetHash(size,data,val)
-#define MACI_GetPersonalityList(s,cnt,list) CI_GetPersonalityList(cnt,list)
-#define MACI_GetSessionID(s) CI_OK
-#define MACI_GetState(s,state) CI_GetState(state)
-#define MACI_GetStatus(s,status) CI_GetStatus(status)
-#define MACI_GetTime(s,time) CI_GetTime(time)
-#define MACI_Hash(s,size,data) CI_Hash(size,data)
-#define MACI_Initialize(count) CI_Initialize(count)
-#define MACI_InitializeHash(s) CI_InitializeHash()
-#define MACI_InstallX(s,cert,type,pass,ySize,y,x,Ra,pgSize,qSize,p,q,g) \
- CI_InstallX(cert,type,pass,ySize,y,x,Ra,pgSize,qSize,p,q,g)
-#define MACI_LoadCertificate(s,cert,label,data,res) \
- CI_LoadCertificate(cert,label,data,res)
-#define MACI_LoadDSAParameters(s,pgSize,qSize,p,q,g) \
- CI_LoadDSAParameters(pgSize,qSize,p,q,g)
-#define MACI_LoadInitValues(s,seed,Ks) CI_LoadInitValues(seed,Ks)
-#define MACI_LoadIV(s,iv) CI_LoadIV(iv)
-#define MACI_LoadX(s,cert,type,pgSize,qSize,p,q,g,x,ySize,y) \
- CI_LoadX(cert,type,pgSize,qSize,p,q,g,x,ySize,y)
-#define MACI_Lock(s,flags) CI_Lock(flags)
-#define MACI_Open(s,flags,index) CI_Open(flags,index)
-#define MACI_RelayX(s,oPass,oSize,oY,oRa,oX,nPass,nSize,nY,nRa,nX) \
- CI_RelayX(oPass,oSize,oY,oRa,oX,nPass,nSize,nY,nRa,nX)
-#define MACI_Reset(s) CI_Reset()
-#define MACI_Restore(s,type,data) CI_Restore(type,data)
-#define MACI_Save(s,type,data) CI_Save(type,data)
-#define MACI_Select(s,socket) CI_Select(socket)
-#define MACI_SetConfiguration(s,typ,sz,d) CI_SetConfiguration(typ,sz,d)
-#define MACI_SetKey(s,key) CI_SetKey(key)
-#define MACI_SetMode(s,type,mode) CI_SetMode(type,mode)
-#define MACI_SetPersonality(s,index) CI_SetPersonality(index)
-#define MACI_SetTime(s,time) CI_SetTime(time)
-#define MACI_Sign(s,hash,sig) CI_Sign(hash,sig)
-#define MACI_Terminate(s) CI_Terminate()
-#define MACI_TimeStamp(s,val,sig,time) CI_TimeStamp(val,sig,time)
-#define MACI_Unlock(s) CI_Unlock()
-#define MACI_UnwrapKey(s,targ,wrap,key) CI_UnwrapKey(targ,wrap,key)
-#define MACI_VerifySignature(s,h,siz,y,sig) CI_VerifySignature(h,siz,y,sig)
-#define MACI_VerifyTimeStamp(s,hash,sig,tim) CI_VerityTimeStap(hash,sig,tim)
-#define MACI_WrapKey(s,src,wrap,key) CI_WrapKey(src,wrap,key)
-#define MACI_Zeroize(s) CI_Zeroize()
-
-#define MACI_SEL(x) CI_Select(x)
-#endif /* ! XP_UNIX */
-#endif /* _GENCI_H_ */
diff --git a/security/nss/lib/jar/jarevil.c b/security/nss/lib/jar/jarevil.c
deleted file mode 100644
index feecd43b0..000000000
--- a/security/nss/lib/jar/jarevil.c
+++ /dev/null
@@ -1,571 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-/*
- * JAREVIL
- *
- * Wrappers to callback in the mozilla thread
- *
- * Certificate code is unsafe when called outside the
- * mozilla thread. These functions push an event on the
- * queue to cause the cert function to run in that thread.
- *
- */
-
-#include "jar.h"
-#include "jarint.h"
-
-#include "jarevil.h"
-
-/* from libevent.h */
-#ifdef MOZILLA_CLIENT
-typedef void (*ETVoidPtrFunc) (void * data);
-extern void ET_moz_CallFunction (ETVoidPtrFunc fn, void *data);
-
-extern void *mozilla_event_queue;
-#endif
-
-
-/* Special macros facilitate running on Win 16 */
-#if defined(XP_PC) && !defined(_WIN32) /* then we are win 16 */
-
- /*
- * Allocate the data passed to the callback functions from the heap...
- *
- * This inter-thread structure cannot reside on a thread stack since the
- * thread's stack is swapped away with the thread under Win16...
- */
-
- #define ALLOC_OR_DEFINE(type, pointer_var_name, out_of_memory_return_value) \
- type * pointer_var_name = PORT_ZAlloc (sizeof(type)); \
- do { \
- if (!pointer_var_name) \
- return (out_of_memory_return_value); \
- } while (0) /* and now a semicolon can follow :-) */
-
- #define FREE_IF_ALLOC_IS_USED(pointer_var_name) PORT_Free(pointer_var_name)
-
-#else /* not win 16... so we can alloc via auto variables */
-
- #define ALLOC_OR_DEFINE(type, pointer_var_name, out_of_memory_return_value) \
- type actual_structure_allocated_in_macro; \
- type * pointer_var_name = &actual_structure_allocated_in_macro; \
- PORT_Memset (pointer_var_name, 0, sizeof (*pointer_var_name)); \
- ((void) 0) /* and now a semicolon can follow */
-
- #define FREE_IF_ALLOC_IS_USED(pointer_var_name) ((void) 0)
-
-#endif /* not Win 16 */
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_encode
- *
- * Call SEC_PKCS7Encode inside
- * the mozilla thread
- *
- */
-
-struct EVIL_encode
- {
- int error;
- SECStatus status;
- SEC_PKCS7ContentInfo *cinfo;
- SEC_PKCS7EncoderOutputCallback outputfn;
- void *outputarg;
- PK11SymKey *bulkkey;
- SECKEYGetPasswordKey pwfn;
- void *pwfnarg;
- };
-
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_encode_fn (void *data)
- {
- SECStatus status;
- struct EVIL_encode *encode_data = (struct EVIL_encode *)data;
-
- PORT_SetError (encode_data->error);
-
- status = SEC_PKCS7Encode (encode_data->cinfo, encode_data->outputfn,
- encode_data->outputarg, encode_data->bulkkey,
- encode_data->pwfn, encode_data->pwfnarg);
-
- encode_data->status = status;
- encode_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-SECStatus jar_moz_encode
- (
- SEC_PKCS7ContentInfo *cinfo,
- SEC_PKCS7EncoderOutputCallback outputfn,
- void *outputarg,
- PK11SymKey *bulkkey,
- SECKEYGetPasswordKey pwfn,
- void *pwfnarg
- )
- {
- SECStatus ret;
- ALLOC_OR_DEFINE(struct EVIL_encode, encode_data, SECFailure);
-
- encode_data->error = PORT_GetError();
- encode_data->cinfo = cinfo;
- encode_data->outputfn = outputfn;
- encode_data->outputarg = outputarg;
- encode_data->bulkkey = bulkkey;
- encode_data->pwfn = pwfn;
- encode_data->pwfnarg = pwfnarg;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_encode_fn, encode_data);
- else
- jar_moz_encode_fn (encode_data);
-#else
- jar_moz_encode_fn (encode_data);
-#endif
-
- PORT_SetError (encode_data->error);
- ret = encode_data->status;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(encode_data);
- return ret;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_verify
- *
- * Call SEC_PKCS7VerifyDetachedSignature inside
- * the mozilla thread
- *
- */
-
-struct EVIL_verify
- {
- int error;
- SECStatus status;
- SEC_PKCS7ContentInfo *cinfo;
- SECCertUsage certusage;
- SECItem *detached_digest;
- HASH_HashType digest_type;
- PRBool keepcerts;
- };
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_verify_fn (void *data)
- {
- PRBool result;
- struct EVIL_verify *verify_data = (struct EVIL_verify *)data;
-
- PORT_SetError (verify_data->error);
-
- result = SEC_PKCS7VerifyDetachedSignature
- (verify_data->cinfo, verify_data->certusage, verify_data->detached_digest,
- verify_data->digest_type, verify_data->keepcerts);
-
-
- verify_data->status = result==PR_TRUE ? SECSuccess : SECFailure;
- verify_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-SECStatus jar_moz_verify
- (
- SEC_PKCS7ContentInfo *cinfo,
- SECCertUsage certusage,
- SECItem *detached_digest,
- HASH_HashType digest_type,
- PRBool keepcerts
- )
- {
- SECStatus ret;
- ALLOC_OR_DEFINE(struct EVIL_verify, verify_data, SECFailure);
-
- verify_data->error = PORT_GetError();
- verify_data->cinfo = cinfo;
- verify_data->certusage = certusage;
- verify_data->detached_digest = detached_digest;
- verify_data->digest_type = digest_type;
- verify_data->keepcerts = keepcerts;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_verify_fn, verify_data);
- else
- jar_moz_verify_fn (verify_data);
-#else
- jar_moz_verify_fn (verify_data);
-#endif
-
- PORT_SetError (verify_data->error);
- ret = verify_data->status;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(verify_data);
- return ret;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_nickname
- *
- * Call CERT_FindCertByNickname inside
- * the mozilla thread
- *
- */
-
-struct EVIL_nickname
- {
- int error;
- CERTCertDBHandle *certdb;
- char *nickname;
- CERTCertificate *cert;
- };
-
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_nickname_fn (void *data)
- {
- CERTCertificate *cert;
- struct EVIL_nickname *nickname_data = (struct EVIL_nickname *)data;
-
- PORT_SetError (nickname_data->error);
-
- cert = CERT_FindCertByNickname (nickname_data->certdb, nickname_data->nickname);
-
- nickname_data->cert = cert;
- nickname_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-CERTCertificate *jar_moz_nickname (CERTCertDBHandle *certdb, char *nickname)
- {
- CERTCertificate *cert;
- ALLOC_OR_DEFINE(struct EVIL_nickname, nickname_data, NULL );
-
- nickname_data->error = PORT_GetError();
- nickname_data->certdb = certdb;
- nickname_data->nickname = nickname;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_nickname_fn, nickname_data);
- else
- jar_moz_nickname_fn (nickname_data);
-#else
- jar_moz_nickname_fn (nickname_data);
-#endif
-
- PORT_SetError (nickname_data->error);
- cert = nickname_data->cert;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(nickname_data);
- return cert;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_perm
- *
- * Call CERT_AddTempCertToPerm inside
- * the mozilla thread
- *
- */
-
-struct EVIL_perm
- {
- int error;
- SECStatus status;
- CERTCertificate *cert;
- char *nickname;
- CERTCertTrust *trust;
- };
-
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_perm_fn (void *data)
- {
- SECStatus status;
- struct EVIL_perm *perm_data = (struct EVIL_perm *)data;
-
- PORT_SetError (perm_data->error);
-
- status = CERT_AddTempCertToPerm (perm_data->cert, perm_data->nickname, perm_data->trust);
-
- perm_data->status = status;
- perm_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-SECStatus jar_moz_perm
- (CERTCertificate *cert, char *nickname, CERTCertTrust *trust)
- {
- SECStatus ret;
- ALLOC_OR_DEFINE(struct EVIL_perm, perm_data, SECFailure);
-
- perm_data->error = PORT_GetError();
- perm_data->cert = cert;
- perm_data->nickname = nickname;
- perm_data->trust = trust;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_perm_fn, perm_data);
- else
- jar_moz_perm_fn (perm_data);
-#else
- jar_moz_perm_fn (perm_data);
-#endif
-
- PORT_SetError (perm_data->error);
- ret = perm_data->status;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(perm_data);
- return ret;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_certkey
- *
- * Call CERT_FindCertByKey inside
- * the mozilla thread
- *
- */
-
-struct EVIL_certkey
- {
- int error;
- CERTCertificate *cert;
- CERTCertDBHandle *certdb;
- SECItem *seckey;
- };
-
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_certkey_fn (void *data)
- {
- CERTCertificate *cert;
- struct EVIL_certkey *certkey_data = (struct EVIL_certkey *)data;
-
- PORT_SetError (certkey_data->error);
-
- cert = CERT_FindCertByKey (certkey_data->certdb, certkey_data->seckey);
-
- certkey_data->cert = cert;
- certkey_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-CERTCertificate *jar_moz_certkey (CERTCertDBHandle *certdb, SECItem *seckey)
- {
- CERTCertificate *cert;
- ALLOC_OR_DEFINE(struct EVIL_certkey, certkey_data, NULL);
-
- certkey_data->error = PORT_GetError();
- certkey_data->certdb = certdb;
- certkey_data->seckey = seckey;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_certkey_fn, certkey_data);
- else
- jar_moz_certkey_fn (certkey_data);
-#else
- jar_moz_certkey_fn (certkey_data);
-#endif
-
- PORT_SetError (certkey_data->error);
- cert = certkey_data->cert;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(certkey_data);
- return cert;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_issuer
- *
- * Call CERT_FindCertIssuer inside
- * the mozilla thread
- *
- */
-
-struct EVIL_issuer
- {
- int error;
- CERTCertificate *cert;
- CERTCertificate *issuer;
- };
-
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_issuer_fn (void *data)
- {
- CERTCertificate *issuer;
- struct EVIL_issuer *issuer_data = (struct EVIL_issuer *)data;
-
- PORT_SetError (issuer_data->error);
-
- issuer = CERT_FindCertIssuer (issuer_data->cert, PR_Now(),
- certUsageObjectSigner);
-
- issuer_data->issuer = issuer;
- issuer_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-CERTCertificate *jar_moz_issuer (CERTCertificate *cert)
- {
- CERTCertificate *issuer_cert;
- ALLOC_OR_DEFINE(struct EVIL_issuer, issuer_data, NULL);
-
- issuer_data->error = PORT_GetError();
- issuer_data->cert = cert;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_issuer_fn, issuer_data);
- else
- jar_moz_issuer_fn (issuer_data);
-#else
- jar_moz_issuer_fn (issuer_data);
-#endif
-
- PORT_SetError (issuer_data->error);
- issuer_cert = issuer_data->issuer;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(issuer_data);
- return issuer_cert;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
-
-/*
- * JAR_MOZ_dup
- *
- * Call CERT_DupCertificate inside
- * the mozilla thread
- *
- */
-
-struct EVIL_dup
- {
- int error;
- CERTCertificate *cert;
- CERTCertificate *return_cert;
- };
-
-
-/* This is called inside the mozilla thread */
-
-PR_STATIC_CALLBACK(void) jar_moz_dup_fn (void *data)
- {
- CERTCertificate *return_cert;
- struct EVIL_dup *dup_data = (struct EVIL_dup *)data;
-
- PORT_SetError (dup_data->error);
-
- return_cert = CERT_DupCertificate (dup_data->cert);
-
- dup_data->return_cert = return_cert;
- dup_data->error = PORT_GetError();
- }
-
-
-/* Wrapper for the ET_MOZ call */
-
-CERTCertificate *jar_moz_dup (CERTCertificate *cert)
- {
- CERTCertificate *dup_cert;
- ALLOC_OR_DEFINE(struct EVIL_dup, dup_data, NULL);
-
- dup_data->error = PORT_GetError();
- dup_data->cert = cert;
-
- /* Synchronously invoke the callback function on the mozilla thread. */
-#ifdef MOZILLA_CLIENT
- if (mozilla_event_queue)
- ET_moz_CallFunction (jar_moz_dup_fn, dup_data);
- else
- jar_moz_dup_fn (dup_data);
-#else
- jar_moz_dup_fn (dup_data);
-#endif
-
- PORT_SetError (dup_data->error);
- dup_cert = dup_data->return_cert;
-
- /* Free the data passed to the callback function... */
- FREE_IF_ALLOC_IS_USED(dup_data);
- return dup_cert;
- }
-
-/* --- --- --- --- --- --- --- --- --- --- --- --- --- */
diff --git a/security/nss/lib/jar/jarnav.c b/security/nss/lib/jar/jarnav.c
deleted file mode 100644
index 2100948ab..000000000
--- a/security/nss/lib/jar/jarnav.c
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-/*
- * JARNAV.C
- *
- * JAR stuff needed for client only.
- *
- */
-
-#include "jar.h"
-#include "jarint.h"
-
-/* from proto.h */
-#ifdef MOZILLA_CLIENT
-extern MWContext *XP_FindSomeContext(void);
-#endif
-
-/* sigh */
-extern MWContext *FE_GetInitContext(void);
-
-/* To return an MWContext for Java */
-static MWContext *(*jar_fn_FindSomeContext) (void) = NULL;
-
-/* To fabricate an MWContext for FE_GetPassword */
-static MWContext *(*jar_fn_GetInitContext) (void) = NULL;
-
-/*
- * J A R _ i n i t
- *
- * Initialize the JAR functions.
- *
- */
-
-void JAR_init (void)
- {
-#ifdef MOZILLA_CLIENT
- JAR_init_callbacks (XP_GetString, XP_FindSomeContext, FE_GetInitContext);
-#else
- JAR_init_callbacks (XP_GetString, NULL, NULL);
-#endif
- }
-
-/*
- * J A R _ s e t _ c o n t e x t
- *
- * Set the jar window context for use by PKCS11, since
- * it may be needed to prompt the user for a password.
- *
- */
-
-int JAR_set_context (JAR *jar, MWContext *mw)
- {
- if (mw)
- {
- jar->mw = mw;
- }
- else
- {
- /* jar->mw = XP_FindSomeContext(); */
- jar->mw = NULL;
-
- /*
- * We can't find a context because we're in startup state and none
- * exist yet. go get an FE_InitContext that only works at initialization
- * time.
- */
-
- /* Turn on the mac when we get the FE_ function */
- if (jar->mw == NULL)
- {
- jar->mw = jar_fn_GetInitContext();
- }
- }
-
- return 0;
- }
diff --git a/security/nss/lib/jar/jarsign.c b/security/nss/lib/jar/jarsign.c
deleted file mode 100644
index 3518bfa26..000000000
--- a/security/nss/lib/jar/jarsign.c
+++ /dev/null
@@ -1,376 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-/*
- * JARSIGN
- *
- * Routines used in signing archives.
- */
-
-#define USE_MOZ_THREAD
-
-#include "jar.h"
-#include "jarint.h"
-
-#ifdef USE_MOZ_THREAD
-#include "jarevil.h"
-#endif
-
-#include "pk11func.h"
-
-/* from libevent.h */
-typedef void (*ETVoidPtrFunc) (void * data);
-
-#ifdef MOZILLA_CLIENT
-
-extern void ET_moz_CallFunction (ETVoidPtrFunc fn, void *data);
-
-/* from proto.h */
-/* extern MWContext *XP_FindSomeContext(void); */
-extern void *XP_FindSomeContext(void);
-
-#endif
-
-/* key database wrapper */
-
-/* static SECKEYKeyDBHandle *jar_open_key_database (void); */
-
-/* CHUNQ is our bite size */
-
-#define CHUNQ 64000
-#define FILECHUNQ 32768
-
-/*
- * J A R _ c a l c u l a t e _ d i g e s t
- *
- * Quick calculation of a digest for
- * the specified block of memory. Will calculate
- * for all supported algorithms, now MD5.
- *
- * This version supports huge pointers for WIN16.
- *
- */
-
-JAR_Digest * PR_CALLBACK JAR_calculate_digest (void ZHUGEP *data, long length)
- {
- long chunq;
- JAR_Digest *dig;
-
- unsigned int md5_length, sha1_length;
-
- PK11Context *md5 = 0;
- PK11Context *sha1 = 0;
-
- dig = (JAR_Digest *) PORT_ZAlloc (sizeof (JAR_Digest));
-
- if (dig == NULL)
- {
- /* out of memory allocating digest */
- return NULL;
- }
-
-#if defined(XP_WIN16)
- PORT_Assert ( !IsBadHugeReadPtr(data, length) );
-#endif
-
- md5 = PK11_CreateDigestContext (SEC_OID_MD5);
- sha1 = PK11_CreateDigestContext (SEC_OID_SHA1);
-
- if (length >= 0)
- {
- PK11_DigestBegin (md5);
- PK11_DigestBegin (sha1);
-
- do {
- chunq = length;
-
-#ifdef XP_WIN16
- if (length > CHUNQ) chunq = CHUNQ;
-
- /*
- * If the block of data crosses one or more segment
- * boundaries then only pass the chunk of data in the
- * first segment.
- *
- * This allows the data to be treated as FAR by the
- * PK11_DigestOp(...) routine.
- *
- */
-
- if (OFFSETOF(data) + chunq >= 0x10000)
- chunq = 0x10000 - OFFSETOF(data);
-#endif
-
- PK11_DigestOp (md5, (unsigned char*)data, chunq);
- PK11_DigestOp (sha1, (unsigned char*)data, chunq);
-
- length -= chunq;
- data = ((char ZHUGEP *) data + chunq);
- }
- while (length > 0);
-
- PK11_DigestFinal (md5, dig->md5, &md5_length, MD5_LENGTH);
- PK11_DigestFinal (sha1, dig->sha1, &sha1_length, SHA1_LENGTH);
-
- PK11_DestroyContext (md5, PR_TRUE);
- PK11_DestroyContext (sha1, PR_TRUE);
- }
-
- return dig;
- }
-
-/*
- * J A R _ d i g e s t _ f i l e
- *
- * Calculates the MD5 and SHA1 digests for a file
- * present on disk, and returns these in JAR_Digest struct.
- *
- */
-
-int JAR_digest_file (char *filename, JAR_Digest *dig)
- {
- JAR_FILE fp;
-
- int num;
- unsigned char *buf;
-
- PK11Context *md5 = 0;
- PK11Context *sha1 = 0;
-
- unsigned int md5_length, sha1_length;
-
- buf = (unsigned char *) PORT_ZAlloc (FILECHUNQ);
- if (buf == NULL)
- {
- /* out of memory */
- return JAR_ERR_MEMORY;
- }
-
- if ((fp = JAR_FOPEN (filename, "rb")) == 0)
- {
- /* perror (filename); FIX XXX XXX XXX XXX XXX XXX */
- PORT_Free (buf);
- return JAR_ERR_FNF;
- }
-
- md5 = PK11_CreateDigestContext (SEC_OID_MD5);
- sha1 = PK11_CreateDigestContext (SEC_OID_SHA1);
-
- if (md5 == NULL || sha1 == NULL)
- {
- /* can't generate digest contexts */
- PORT_Free (buf);
- JAR_FCLOSE (fp);
- return JAR_ERR_GENERAL;
- }
-
- PK11_DigestBegin (md5);
- PK11_DigestBegin (sha1);
-
- while (1)
- {
- if ((num = JAR_FREAD (fp, buf, FILECHUNQ)) == 0)
- break;
-
- PK11_DigestOp (md5, buf, num);
- PK11_DigestOp (sha1, buf, num);
- }
-
- PK11_DigestFinal (md5, dig->md5, &md5_length, MD5_LENGTH);
- PK11_DigestFinal (sha1, dig->sha1, &sha1_length, SHA1_LENGTH);
-
- PK11_DestroyContext (md5, PR_TRUE);
- PK11_DestroyContext (sha1, PR_TRUE);
-
- PORT_Free (buf);
- JAR_FCLOSE (fp);
-
- return 0;
- }
-
-/*
- * J A R _ o p e n _ k e y _ d a t a b a s e
- *
- */
-
-SECKEYKeyDBHandle *jar_open_key_database (void)
- {
- SECKEYKeyDBHandle *keydb;
-
- keydb = SECKEY_GetDefaultKeyDB();
-
- if (keydb == NULL)
- { /* open by file if this fails, if jartool is to call this */ ; }
-
- return keydb;
- }
-
-int jar_close_key_database (SECKEYKeyDBHandle *keydb)
- {
- /* We never do close it */
- return 0;
- }
-
-
-/*
- * j a r _ c r e a t e _ p k 7
- *
- */
-
-static void jar_pk7_out (void *arg, const char *buf, unsigned long len)
- {
- JAR_FWRITE ((JAR_FILE) arg, buf, len);
- }
-
-int jar_create_pk7
- (CERTCertDBHandle *certdb, SECKEYKeyDBHandle *keydb,
- CERTCertificate *cert, char *password, JAR_FILE infp, JAR_FILE outfp)
- {
- int nb;
- unsigned char buffer [4096], digestdata[32];
- SECHashObject *hashObj;
- void *hashcx;
- unsigned int len;
-
- int status = 0;
- char *errstring;
-
- SECItem digest;
- SEC_PKCS7ContentInfo *cinfo;
- SECStatus rv;
-
- void /*MWContext*/ *mw;
-
- if (outfp == NULL || infp == NULL || cert == NULL)
- return JAR_ERR_GENERAL;
-
- /* we sign with SHA */
- hashObj = &SECHashObjects [HASH_AlgSHA1];
-
- hashcx = (* hashObj->create)();
- if (hashcx == NULL)
- return JAR_ERR_GENERAL;
-
- (* hashObj->begin)(hashcx);
-
- while (1)
- {
- /* nspr2.0 doesn't support feof
- if (feof (infp)) break; */
-
- nb = JAR_FREAD (infp, buffer, sizeof (buffer));
- if (nb == 0)
- {
-#if 0
- if (ferror(infp))
- {
- /* PORT_SetError(SEC_ERROR_IO); */ /* FIX */
- (* hashObj->destroy) (hashcx, PR_TRUE);
- return JAR_ERR_GENERAL;
- }
-#endif
- /* eof */
- break;
- }
- (* hashObj->update) (hashcx, buffer, nb);
- }
-
- (* hashObj->end) (hashcx, digestdata, &len, 32);
- (* hashObj->destroy) (hashcx, PR_TRUE);
-
- digest.data = digestdata;
- digest.len = len;
-
- /* signtool must use any old context it can find since it's
- calling from inside javaland. */
-
-#ifdef MOZILLA_CLIENT
- mw = XP_FindSomeContext();
-#else
- mw = NULL;
-#endif
-
- PORT_SetError (0);
-
- cinfo = SEC_PKCS7CreateSignedData
- (cert, certUsageObjectSigner, NULL,
- SEC_OID_SHA1, &digest, NULL, (void *) mw);
-
- if (cinfo == NULL)
- return JAR_ERR_PK7;
-
- rv = SEC_PKCS7IncludeCertChain (cinfo, NULL);
- if (rv != SECSuccess)
- {
- status = PORT_GetError();
- SEC_PKCS7DestroyContentInfo (cinfo);
- return status;
- }
-
- /* Having this here forces signtool to always include
- signing time. */
-
- rv = SEC_PKCS7AddSigningTime (cinfo);
- if (rv != SECSuccess)
- {
- /* don't check error */
- }
-
- PORT_SetError (0);
-
-#ifdef USE_MOZ_THREAD
- /* if calling from mozilla */
- rv = jar_moz_encode
- (cinfo, jar_pk7_out, outfp,
- NULL, /* pwfn */ NULL, /* pwarg */ (void *) mw);
-#else
- /* if calling from mozilla thread*/
- rv = SEC_PKCS7Encode
- (cinfo, jar_pk7_out, outfp,
- NULL, /* pwfn */ NULL, /* pwarg */ (void *) mw):
-#endif
-
- if (rv != SECSuccess)
- status = PORT_GetError();
-
- SEC_PKCS7DestroyContentInfo (cinfo);
-
- if (rv != SECSuccess)
- {
- errstring = JAR_get_error (status);
- /*XP_TRACE (("Jar signing failed (reason %d = %s)", status, errstring));*/
- return status < 0 ? status : JAR_ERR_GENERAL;
- }
-
- return 0;
- }
diff --git a/security/nss/lib/jar/jarver.c b/security/nss/lib/jar/jarver.c
deleted file mode 100644
index 2f4f589fe..000000000
--- a/security/nss/lib/jar/jarver.c
+++ /dev/null
@@ -1,2029 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-
-/*
- * JARVER
- *
- * Jarnature Parsing & Verification
- */
-
-#define USE_MOZ_THREAD
-
-#include "jar.h"
-#include "jarint.h"
-
-#ifdef USE_MOZ_THREAD
-#include "jarevil.h"
-#endif
-#include "cdbhdl.h"
-
-/* to use huge pointers in win16 */
-
-#if !defined(XP_WIN16)
-#define xp_HUGE_MEMCPY PORT_Memcpy
-#define xp_HUGE_STRCPY PORT_Strcpy
-#define xp_HUGE_STRLEN PORT_Strlen
-#define xp_HUGE_STRNCASECMP PORT_Strncasecmp
-#else
-#define xp_HUGE_MEMCPY hmemcpy
-int xp_HUGE_STRNCASECMP (char ZHUGEP *buf, char *key, int len);
-size_t xp_HUGE_STRLEN (char ZHUGEP *s);
-char *xp_HUGE_STRCPY (char *to, char ZHUGEP *from);
-#endif
-
-/* from certdb.h */
-#define CERTDB_USER (1<<6)
-
-#if 0
-/* from certdb.h */
-extern PRBool SEC_CertNicknameConflict
- (char *nickname, CERTCertDBHandle *handle);
-/* from certdb.h */
-extern SECStatus SEC_AddTempNickname
- (CERTCertDBHandle *handle, char *nickname, SECItem *certKey);
-/* from certdb.h */
-typedef SECStatus (* PermCertCallback)(CERTCertificate *cert, SECItem *k, void *pdata);
-#endif
-
-/* from certdb.h */
-SECStatus SEC_TraversePermCerts
- (CERTCertDBHandle *handle, PermCertCallback certfunc, void *udata);
-
-
-#define SZ 512
-
-static int jar_validate_pkcs7
- (JAR *jar, JAR_Signer *signer, char *data, long length);
-
-static int jar_decode (JAR *jar, char *data, long length);
-
-static void jar_catch_bytes
- (void *arg, const char *buf, unsigned long len);
-
-static int jar_gather_signers
- (JAR *jar, JAR_Signer *signer, SEC_PKCS7ContentInfo *cinfo);
-
-static char ZHUGEP *jar_eat_line
- (int lines, int eating, char ZHUGEP *data, long *len);
-
-static JAR_Digest *jar_digest_section
- (char ZHUGEP *manifest, long length);
-
-static JAR_Digest *jar_get_mf_digest (JAR *jar, char *path);
-
-static int jar_parse_digital_signature
- (char *raw_manifest, JAR_Signer *signer, long length, JAR *jar);
-
-static int jar_add_cert
- (JAR *jar, JAR_Signer *signer, int type, CERTCertificate *cert);
-
-static CERTCertificate *jar_get_certificate
- (JAR *jar, long keylen, void *key, int *result);
-
-static char *jar_cert_element (char *name, char *tag, int occ);
-
-static char *jar_choose_nickname (CERTCertificate *cert);
-
-static char *jar_basename (const char *path);
-
-static int jar_signal
- (int status, JAR *jar, const char *metafile, char *pathname);
-
-static int jar_insanity_check (char ZHUGEP *data, long length);
-
-int jar_parse_mf
- (JAR *jar, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url);
-
-int jar_parse_sf
- (JAR *jar, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url);
-
-int jar_parse_sig
- (JAR *jar, const char *path, char ZHUGEP *raw_manifest, long length);
-
-int jar_parse_any
- (JAR *jar, int type, JAR_Signer *signer, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url);
-
-static int jar_internal_digest
- (JAR *jar, const char *path, char *x_name, JAR_Digest *dig);
-
-/*
- * J A R _ p a r s e _ m a n i f e s t
- *
- * Pass manifest files to this function. They are
- * decoded and placed into internal representations.
- *
- * Accepts both signature and manifest files. Use
- * the same "jar" for both.
- *
- */
-
-int JAR_parse_manifest
- (JAR *jar, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url)
- {
-
-#if defined(XP_WIN16)
- PORT_Assert( !IsBadHugeReadPtr(raw_manifest, length) );
-#endif
-
- /* fill in the path, if supplied. This is a the location
- of the jar file on disk, if known */
-
- if (jar->filename == NULL && path)
- {
- jar->filename = PORT_Strdup (path);
- if (jar->filename == NULL)
- return JAR_ERR_MEMORY;
- }
-
- /* fill in the URL, if supplied. This is the place
- from which the jar file was retrieved. */
-
- if (jar->url == NULL && url)
- {
- jar->url = PORT_Strdup (url);
- if (jar->url == NULL)
- return JAR_ERR_MEMORY;
- }
-
- /* Determine what kind of file this is from the META-INF
- directory. It could be MF, SF, or a binary RSA/DSA file */
-
- if (!xp_HUGE_STRNCASECMP (raw_manifest, "Manifest-Version:", 17))
- {
- return jar_parse_mf (jar, raw_manifest, length, path, url);
- }
- else if (!xp_HUGE_STRNCASECMP (raw_manifest, "Signature-Version:", 18))
- {
- return jar_parse_sf (jar, raw_manifest, length, path, url);
- }
- else
- {
- /* This is probably a binary signature */
- return jar_parse_sig (jar, path, raw_manifest, length);
- }
- }
-
-/*
- * j a r _ p a r s e _ s i g
- *
- * Pass some manner of RSA or DSA digital signature
- * on, after checking to see if it comes at an appropriate state.
- *
- */
-
-int jar_parse_sig
- (JAR *jar, const char *path, char ZHUGEP *raw_manifest, long length)
- {
- JAR_Signer *signer;
- int status = JAR_ERR_ORDER;
-
- if (length <= 128)
- {
- /* signature is way too small */
- return JAR_ERR_SIG;
- }
-
- /* make sure that MF and SF have already been processed */
-
- if (jar->globalmeta == NULL)
- return JAR_ERR_ORDER;
-
-#if 0
- /* XXX Turn this on to disable multiple signers */
- if (jar->digest == NULL)
- return JAR_ERR_ORDER;
-#endif
-
- /* Determine whether or not this RSA file has
- has an associated SF file */
-
- if (path)
- {
- char *owner;
- owner = jar_basename (path);
-
- if (owner == NULL)
- return JAR_ERR_MEMORY;
-
- signer = jar_get_signer (jar, owner);
-
- PORT_Free (owner);
- }
- else
- signer = jar_get_signer (jar, "*");
-
- if (signer == NULL)
- return JAR_ERR_ORDER;
-
-
- /* Do not pass a huge pointer to this function,
- since the underlying security code is unaware. We will
- never pass >64k through here. */
-
- if (length > 64000)
- {
- /* this digital signature is way too big */
- return JAR_ERR_SIG;
- }
-
-#ifdef XP_WIN16
- /*
- * For Win16, copy the portion of the raw_buffer containing the digital
- * signature into another buffer... This insures that the data will
- * NOT cross a segment boundary. Therefore,
- * jar_parse_digital_signature(...) does NOT need to deal with HUGE
- * pointers...
- */
-
- {
- unsigned char *manifest_copy;
-
- manifest_copy = (unsigned char *) PORT_ZAlloc (length);
- if (manifest_copy)
- {
- xp_HUGE_MEMCPY (manifest_copy, raw_manifest, length);
-
- status = jar_parse_digital_signature
- (manifest_copy, signer, length, jar);
-
- PORT_Free (manifest_copy);
- }
- else
- {
- /* out of memory */
- return JAR_ERR_MEMORY;
- }
- }
-#else
- /* don't expense unneeded calloc overhead on non-win16 */
- status = jar_parse_digital_signature
- (raw_manifest, signer, length, jar);
-#endif
-
- return status;
- }
-
-/*
- * j a r _ p a r s e _ m f
- *
- * Parse the META-INF/manifest.mf file, whose
- * information applies to all signers.
- *
- */
-
-int jar_parse_mf
- (JAR *jar, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url)
- {
- if (jar->globalmeta)
- {
- /* refuse a second manifest file, if passed for some reason */
- return JAR_ERR_ORDER;
- }
-
-
- /* remember a digest for the global section */
-
- jar->globalmeta = jar_digest_section (raw_manifest, length);
-
- if (jar->globalmeta == NULL)
- return JAR_ERR_MEMORY;
-
-
- return jar_parse_any
- (jar, jarTypeMF, NULL, raw_manifest, length, path, url);
- }
-
-/*
- * j a r _ p a r s e _ s f
- *
- * Parse META-INF/xxx.sf, a digitally signed file
- * pointing to a subset of MF sections.
- *
- */
-
-int jar_parse_sf
- (JAR *jar, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url)
- {
- JAR_Signer *signer = NULL;
- int status = JAR_ERR_MEMORY;
-
- if (jar->globalmeta == NULL)
- {
- /* It is a requirement that the MF file be passed before the SF file */
- return JAR_ERR_ORDER;
- }
-
- signer = JAR_new_signer();
-
- if (signer == NULL)
- goto loser;
-
- if (path)
- {
- signer->owner = jar_basename (path);
- if (signer->owner == NULL)
- goto loser;
- }
-
-
- /* check for priors. When someone doctors a jar file
- to contain identical path entries, prevent the second
- one from affecting JAR functions */
-
- if (jar_get_signer (jar, signer->owner))
- {
- /* someone is trying to spoof us */
- status = JAR_ERR_ORDER;
- goto loser;
- }
-
-
- /* remember its digest */
-
- signer->digest = JAR_calculate_digest (raw_manifest, length);
-
- if (signer->digest == NULL)
- goto loser;
-
- /* Add this signer to the jar */
-
- ADDITEM (jar->signers, jarTypeOwner,
- signer->owner, signer, sizeof (JAR_Signer));
-
-
- return jar_parse_any
- (jar, jarTypeSF, signer, raw_manifest, length, path, url);
-
-loser:
-
- if (signer)
- JAR_destroy_signer (signer);
-
- return status;
- }
-
-/*
- * j a r _ p a r s e _ a n y
- *
- * Parse a MF or SF manifest file.
- *
- */
-
-int jar_parse_any
- (JAR *jar, int type, JAR_Signer *signer, char ZHUGEP *raw_manifest,
- long length, const char *path, const char *url)
- {
- int status;
-
- long raw_len;
-
- JAR_Digest *dig, *mfdig = NULL;
-
- char line [SZ];
- char x_name [SZ], x_md5 [SZ], x_sha [SZ];
-
- char *x_info;
-
- char *sf_md5 = NULL, *sf_sha1 = NULL;
-
- *x_name = 0;
- *x_md5 = 0;
- *x_sha = 0;
-
- PORT_Assert( length > 0 );
- raw_len = length;
-
-#ifdef DEBUG
- if ((status = jar_insanity_check (raw_manifest, raw_len)) < 0)
- return status;
-#endif
-
-
- /* null terminate the first line */
- raw_manifest = jar_eat_line (0, PR_TRUE, raw_manifest, &raw_len);
-
-
- /* skip over the preliminary section */
- /* This is one section at the top of the file with global metainfo */
-
- while (raw_len)
- {
- JAR_Metainfo *met;
-
- raw_manifest = jar_eat_line (1, PR_TRUE, raw_manifest, &raw_len);
- if (!*raw_manifest) break;
-
- met = (JAR_Metainfo*)PORT_ZAlloc (sizeof (JAR_Metainfo));
- if (met == NULL)
- return JAR_ERR_MEMORY;
-
- /* Parse out the header & info */
-
- if (xp_HUGE_STRLEN (raw_manifest) >= SZ)
- {
- /* almost certainly nonsense */
- continue;
- }
-
- xp_HUGE_STRCPY (line, raw_manifest);
- x_info = line;
-
- while (*x_info && *x_info != ' ' && *x_info != '\t' && *x_info != ':')
- x_info++;
-
- if (*x_info) *x_info++ = 0;
-
- while (*x_info == ' ' || *x_info == '\t')
- x_info++;
-
- /* metainfo (name, value) pair is now (line, x_info) */
-
- met->header = PORT_Strdup (line);
- met->info = PORT_Strdup (x_info);
-
- if (type == jarTypeMF)
- {
- ADDITEM (jar->metainfo, jarTypeMeta,
- /* pathname */ NULL, met, sizeof (JAR_Metainfo));
- }
-
- /* For SF files, this metadata may be the digests
- of the MF file, still in the "met" structure. */
-
- if (type == jarTypeSF)
- {
- if (!PORT_Strcasecmp (line, "MD5-Digest"))
- sf_md5 = (char *) met->info;
-
- if (!PORT_Strcasecmp (line, "SHA1-Digest") || !PORT_Strcasecmp (line, "SHA-Digest"))
- sf_sha1 = (char *) met->info;
- }
- }
-
- if (type == jarTypeSF && jar->globalmeta)
- {
- /* this is a SF file which may contain a digest of the manifest.mf's
- global metainfo. */
-
- int match = 0;
- JAR_Digest *glob = jar->globalmeta;
-
- if (sf_md5)
- {
- unsigned int md5_length;
- unsigned char *md5_digest;
-
- md5_digest = ATOB_AsciiToData (sf_md5, &md5_length);
- PORT_Assert( md5_length == MD5_LENGTH );
-
- if (md5_length != MD5_LENGTH)
- return JAR_ERR_CORRUPT;
-
- match = PORT_Memcmp (md5_digest, glob->md5, MD5_LENGTH);
- }
-
- if (sf_sha1 && match == 0)
- {
- unsigned int sha1_length;
- unsigned char *sha1_digest;
-
- sha1_digest = ATOB_AsciiToData (sf_sha1, &sha1_length);
- PORT_Assert( sha1_length == SHA1_LENGTH );
-
- if (sha1_length != SHA1_LENGTH)
- return JAR_ERR_CORRUPT;
-
- match = PORT_Memcmp (sha1_digest, glob->sha1, SHA1_LENGTH);
- }
-
- if (match != 0)
- {
- /* global digest doesn't match, SF file therefore invalid */
- jar->valid = JAR_ERR_METADATA;
- return JAR_ERR_METADATA;
- }
- }
-
- /* done with top section of global data */
-
-
- while (raw_len)
- {
- *x_md5 = 0;
- *x_sha = 0;
- *x_name = 0;
-
-
- /* If this is a manifest file, attempt to get a digest of the following section,
- without damaging it. This digest will be saved later. */
-
- if (type == jarTypeMF)
- {
- char ZHUGEP *sec;
- long sec_len = raw_len;
-
- if (!*raw_manifest || *raw_manifest == '\n')
- {
- /* skip the blank line */
- sec = jar_eat_line (1, PR_FALSE, raw_manifest, &sec_len);
- }
- else
- sec = raw_manifest;
-
- if (!xp_HUGE_STRNCASECMP (sec, "Name:", 5))
- {
- if (type == jarTypeMF)
- mfdig = jar_digest_section (sec, sec_len);
- else
- mfdig = NULL;
- }
- }
-
-
- while (raw_len)
- {
- raw_manifest = jar_eat_line (1, PR_TRUE, raw_manifest, &raw_len);
- if (!*raw_manifest) break; /* blank line, done with this entry */
-
- if (xp_HUGE_STRLEN (raw_manifest) >= SZ)
- {
- /* almost certainly nonsense */
- continue;
- }
-
-
- /* Parse out the name/value pair */
-
- xp_HUGE_STRCPY (line, raw_manifest);
- x_info = line;
-
- while (*x_info && *x_info != ' ' && *x_info != '\t' && *x_info != ':')
- x_info++;
-
- if (*x_info) *x_info++ = 0;
-
- while (*x_info == ' ' || *x_info == '\t')
- x_info++;
-
-
- if (!PORT_Strcasecmp (line, "Name"))
- PORT_Strcpy (x_name, x_info);
-
- else if (!PORT_Strcasecmp (line, "MD5-Digest"))
- PORT_Strcpy (x_md5, x_info);
-
- else if (!PORT_Strcasecmp (line, "SHA1-Digest")
- || !PORT_Strcasecmp (line, "SHA-Digest"))
- {
- PORT_Strcpy (x_sha, x_info);
- }
-
- /* Algorithm list is meta info we don't care about; keeping it out
- of metadata saves significant space for large jar files */
-
- else if (!PORT_Strcasecmp (line, "Digest-Algorithms")
- || !PORT_Strcasecmp (line, "Hash-Algorithms"))
- {
- continue;
- }
-
- /* Meta info is only collected for the manifest.mf file,
- since the JAR_get_metainfo call does not support identity */
-
- else if (type == jarTypeMF)
- {
- JAR_Metainfo *met;
-
- /* this is meta-data */
-
- met = (JAR_Metainfo*)PORT_ZAlloc (sizeof (JAR_Metainfo));
-
- if (met == NULL)
- return JAR_ERR_MEMORY;
-
- /* metainfo (name, value) pair is now (line, x_info) */
-
- if ((met->header = PORT_Strdup (line)) == NULL)
- return JAR_ERR_MEMORY;
-
- if ((met->info = PORT_Strdup (x_info)) == NULL)
- return JAR_ERR_MEMORY;
-
- ADDITEM (jar->metainfo, jarTypeMeta,
- x_name, met, sizeof (JAR_Metainfo));
- }
- }
-
- if(!x_name || !*x_name) {
- /* Whatever that was, it wasn't an entry, because we didn't get a name.
- * We don't really have anything, so don't record this. */
- continue;
- }
-
- dig = (JAR_Digest*)PORT_ZAlloc (sizeof (JAR_Digest));
- if (dig == NULL)
- return JAR_ERR_MEMORY;
-
- if (*x_md5 )
- {
- unsigned int binary_length;
- unsigned char *binary_digest;
-
- binary_digest = ATOB_AsciiToData (x_md5, &binary_length);
- PORT_Assert( binary_length == MD5_LENGTH );
-
- if (binary_length != MD5_LENGTH)
- return JAR_ERR_CORRUPT;
-
- memcpy (dig->md5, binary_digest, MD5_LENGTH);
- dig->md5_status = jarHashPresent;
- }
-
- if (*x_sha )
- {
- unsigned int binary_length;
- unsigned char *binary_digest;
-
- binary_digest = ATOB_AsciiToData (x_sha, &binary_length);
- PORT_Assert( binary_length == SHA1_LENGTH );
-
- if (binary_length != SHA1_LENGTH)
- return JAR_ERR_CORRUPT;
-
- memcpy (dig->sha1, binary_digest, SHA1_LENGTH);
- dig->sha1_status = jarHashPresent;
- }
-
- PORT_Assert( type == jarTypeMF || type == jarTypeSF );
-
-
- if (type == jarTypeMF)
- {
- ADDITEM (jar->hashes, jarTypeMF, x_name, dig, sizeof (JAR_Digest));
- }
- else if (type == jarTypeSF)
- {
- ADDITEM (signer->sf, jarTypeSF, x_name, dig, sizeof (JAR_Digest));
- }
- else
- return JAR_ERR_ORDER;
-
- /* we're placing these calculated digests of manifest.mf
- sections in a list where they can subsequently be forgotten */
-
- if (type == jarTypeMF && mfdig)
- {
- ADDITEM (jar->manifest, jarTypeSect,
- x_name, mfdig, sizeof (JAR_Digest));
-
- mfdig = NULL;
- }
-
-
- /* Retrieve our saved SHA1 digest from saved copy and check digests.
- This is just comparing the digest of the MF section as indicated in
- the SF file with the one we remembered from parsing the MF file */
-
- if (type == jarTypeSF)
- {
- if ((status = jar_internal_digest (jar, path, x_name, dig)) < 0)
- return status;
- }
- }
-
- return 0;
- }
-
-static int jar_internal_digest
- (JAR *jar, const char *path, char *x_name, JAR_Digest *dig)
- {
- int cv;
- int status;
-
- JAR_Digest *savdig;
-
- savdig = jar_get_mf_digest (jar, x_name);
-
- if (savdig == NULL)
- {
- /* no .mf digest for this pathname */
- status = jar_signal (JAR_ERR_ENTRY, jar, path, x_name);
- if (status < 0)
- return 0; /* was continue; */
- else
- return status;
- }
-
- /* check for md5 consistency */
- if (dig->md5_status)
- {
- cv = PORT_Memcmp (savdig->md5, dig->md5, MD5_LENGTH);
- /* md5 hash of .mf file is not what expected */
- if (cv)
- {
- status = jar_signal (JAR_ERR_HASH, jar, path, x_name);
-
- /* bad hash, man */
-
- dig->md5_status = jarHashBad;
- savdig->md5_status = jarHashBad;
-
- if (status < 0)
- return 0; /* was continue; */
- else
- return status;
- }
- }
-
- /* check for sha1 consistency */
- if (dig->sha1_status)
- {
- cv = PORT_Memcmp (savdig->sha1, dig->sha1, SHA1_LENGTH);
- /* sha1 hash of .mf file is not what expected */
- if (cv)
- {
- status = jar_signal (JAR_ERR_HASH, jar, path, x_name);
-
- /* bad hash, man */
-
- dig->sha1_status = jarHashBad;
- savdig->sha1_status = jarHashBad;
-
- if (status < 0)
- return 0; /* was continue; */
- else
- return status;
- }
- }
- return 0;
- }
-
-#ifdef DEBUG
-/*
- * j a r _ i n s a n i t y _ c h e c k
- *
- * Check for illegal characters (or possibly so)
- * in the manifest files, to detect potential memory
- * corruption by our neighbors. Debug only, since
- * not I18N safe.
- *
- */
-
-static int jar_insanity_check (char ZHUGEP *data, long length)
- {
- int c;
- long off;
-
- for (off = 0; off < length; off++)
- {
- c = data [off];
-
- if (c == '\n' || c == '\r' || (c >= ' ' && c <= 128))
- continue;
-
- return JAR_ERR_CORRUPT;
- }
-
- return 0;
- }
-#endif
-
-/*
- * j a r _ p a r s e _ d i g i t a l _ s i g n a t u r e
- *
- * Parse an RSA or DSA (or perhaps other) digital signature.
- * Right now everything is PKCS7.
- *
- */
-
-static int jar_parse_digital_signature
- (char *raw_manifest, JAR_Signer *signer, long length, JAR *jar)
- {
-#if defined(XP_WIN16)
- PORT_Assert( LOWORD(raw_manifest) + length < 0xFFFF );
-#endif
- return jar_validate_pkcs7 (jar, signer, raw_manifest, length);
- }
-
-/*
- * j a r _ a d d _ c e r t
- *
- * Add information for the given certificate
- * (or whatever) to the JAR linked list. A pointer
- * is passed for some relevant reference, say
- * for example the original certificate.
- *
- */
-
-static int jar_add_cert
- (JAR *jar, JAR_Signer *signer, int type, CERTCertificate *cert)
- {
- JAR_Cert *fing;
-
- if (cert == NULL)
- return JAR_ERR_ORDER;
-
- fing = (JAR_Cert*)PORT_ZAlloc (sizeof (JAR_Cert));
-
- if (fing == NULL)
- goto loser;
-
-#ifdef USE_MOZ_THREAD
- fing->cert = jar_moz_dup (cert);
-#else
- fing->cert = CERT_DupCertificate (cert);
-#endif
-
- /* get the certkey */
-
- fing->length = cert->certKey.len;
-
- fing->key = (char *) PORT_ZAlloc (fing->length);
-
- if (fing->key == NULL)
- goto loser;
-
- PORT_Memcpy (fing->key, cert->certKey.data, fing->length);
-
- ADDITEM (signer->certs, type,
- /* pathname */ NULL, fing, sizeof (JAR_Cert));
-
- return 0;
-
-loser:
-
- if (fing)
- {
- if (fing->cert)
- CERT_DestroyCertificate (fing->cert);
-
- PORT_Free (fing);
- }
-
- return JAR_ERR_MEMORY;
- }
-
-/*
- * e a t _ l i n e
- *
- * Consume an ascii line from the top of a file kept
- * in memory. This destroys the file in place. This function
- * handles PC, Mac, and Unix style text files.
- *
- */
-
-static char ZHUGEP *jar_eat_line
- (int lines, int eating, char ZHUGEP *data, long *len)
- {
- char ZHUGEP *ret;
-
- ret = data;
- if (!*len) return ret;
-
- /* Eat the requisite number of lines, if any;
- prior to terminating the current line with a 0. */
-
- for (/* yip */ ; lines; lines--)
- {
- while (*data && *data != '\n')
- data++;
-
- /* After the CR, ok to eat one LF */
-
- if (*data == '\n')
- data++;
-
- /* If there are zeros, we put them there */
-
- while (*data == 0 && data - ret < *len)
- data++;
- }
-
- *len -= data - ret;
- ret = data;
-
- if (eating)
- {
- /* Terminate this line with a 0 */
-
- while (*data && *data != '\n' && *data != '\r')
- data++;
-
- /* In any case we are allowed to eat CR */
-
- if (*data == '\r')
- *data++ = 0;
-
- /* After the CR, ok to eat one LF */
-
- if (*data == '\n')
- *data++ = 0;
- }
-
- return ret;
- }
-
-/*
- * j a r _ d i g e s t _ s e c t i o n
- *
- * Return the digests of the next section of the manifest file.
- * Does not damage the manifest file, unlike parse_manifest.
- *
- */
-
-static JAR_Digest *jar_digest_section
- (char ZHUGEP *manifest, long length)
- {
- long global_len;
- char ZHUGEP *global_end;
-
- global_end = manifest;
- global_len = length;
-
- while (global_len)
- {
- global_end = jar_eat_line (1, PR_FALSE, global_end, &global_len);
- if (*global_end == 0 || *global_end == '\n')
- break;
- }
-
- return JAR_calculate_digest (manifest, global_end - manifest);
- }
-
-/*
- * J A R _ v e r i f y _ d i g e s t
- *
- * Verifies that a precalculated digest matches the
- * expected value in the manifest.
- *
- */
-
-int PR_CALLBACK JAR_verify_digest
- (JAR *jar, const char *name, JAR_Digest *dig)
- {
- JAR_Item *it;
-
- JAR_Digest *shindig;
-
- ZZLink *link;
- ZZList *list;
-
- int result1, result2;
-
- list = jar->hashes;
-
- result1 = result2 = 0;
-
- if (jar->valid < 0)
- {
- /* signature not valid */
- return JAR_ERR_SIG;
- }
-
- if (ZZ_ListEmpty (list))
- {
- /* empty list */
- return JAR_ERR_PNF;
- }
-
- for (link = ZZ_ListHead (list);
- !ZZ_ListIterDone (list, link);
- link = link->next)
- {
- it = link->thing;
- if (it->type == jarTypeMF
- && it->pathname && !PORT_Strcmp (it->pathname, name))
- {
- shindig = (JAR_Digest *) it->data;
-
- if (shindig->md5_status)
- {
- if (shindig->md5_status == jarHashBad)
- return JAR_ERR_HASH;
- else
- result1 = memcmp (dig->md5, shindig->md5, MD5_LENGTH);
- }
-
- if (shindig->sha1_status)
- {
- if (shindig->sha1_status == jarHashBad)
- return JAR_ERR_HASH;
- else
- result2 = memcmp (dig->sha1, shindig->sha1, SHA1_LENGTH);
- }
-
- return (result1 == 0 && result2 == 0) ? 0 : JAR_ERR_HASH;
- }
- }
-
- return JAR_ERR_PNF;
- }
-
-/*
- * J A R _ c e r t _ a t t r i b u t e
- *
- * Return the named certificate attribute from the
- * certificate specified by the given key.
- *
- */
-
-int PR_CALLBACK JAR_cert_attribute
- (JAR *jar, jarCert attrib, long keylen, void *key,
- void **result, unsigned long *length)
- {
- int status = 0;
- char *ret = NULL;
-
- CERTCertificate *cert;
-
- CERTCertDBHandle *certdb;
-
- JAR_Digest *dig;
- SECItem hexme;
-
- *length = 0;
-
- if (attrib == 0 || key == 0)
- return JAR_ERR_GENERAL;
-
- if (attrib == jarCertJavaHack)
- {
- cert = (CERTCertificate *) NULL;
- certdb = JAR_open_database();
-
- if (certdb)
- {
-#ifdef USE_MOZ_THREAD
- cert = jar_moz_nickname (certdb, (char*)key);
-#else
- cert = CERT_FindCertByNickname (certdb, key);
-#endif
-
- if (cert)
- {
- *length = cert->certKey.len;
-
- *result = (void *) PORT_ZAlloc (*length);
-
- if (*result)
- PORT_Memcpy (*result, cert->certKey.data, *length);
- else
- return JAR_ERR_MEMORY;
- }
- JAR_close_database (certdb);
- }
-
- return cert ? 0 : JAR_ERR_GENERAL;
- }
-
- if (jar && jar->pkcs7 == 0)
- return JAR_ERR_GENERAL;
-
- cert = jar_get_certificate (jar, keylen, key, &status);
-
- if (cert == NULL || status < 0)
- return JAR_ERR_GENERAL;
-
-#define SEP " <br> "
-#define SEPLEN (PORT_Strlen(SEP))
-
- switch (attrib)
- {
- case jarCertCompany:
-
- ret = cert->subjectName;
-
- /* This is pretty ugly looking but only used
- here for this one purpose. */
-
- if (ret)
- {
- int retlen = 0;
-
- char *cer_ou1, *cer_ou2, *cer_ou3;
- char *cer_cn, *cer_e, *cer_o, *cer_l;
-
- cer_cn = CERT_GetCommonName (&cert->subject);
- cer_e = CERT_GetCertEmailAddress (&cert->subject);
- cer_ou3 = jar_cert_element (ret, "OU=", 3);
- cer_ou2 = jar_cert_element (ret, "OU=", 2);
- cer_ou1 = jar_cert_element (ret, "OU=", 1);
- cer_o = CERT_GetOrgName (&cert->subject);
- cer_l = CERT_GetCountryName (&cert->subject);
-
- if (cer_cn) retlen += SEPLEN + PORT_Strlen (cer_cn);
- if (cer_e) retlen += SEPLEN + PORT_Strlen (cer_e);
- if (cer_ou1) retlen += SEPLEN + PORT_Strlen (cer_ou1);
- if (cer_ou2) retlen += SEPLEN + PORT_Strlen (cer_ou2);
- if (cer_ou3) retlen += SEPLEN + PORT_Strlen (cer_ou3);
- if (cer_o) retlen += SEPLEN + PORT_Strlen (cer_o);
- if (cer_l) retlen += SEPLEN + PORT_Strlen (cer_l);
-
- ret = (char *) PORT_ZAlloc (1 + retlen);
-
- if (cer_cn) { PORT_Strcpy (ret, cer_cn); PORT_Strcat (ret, SEP); }
- if (cer_e) { PORT_Strcat (ret, cer_e); PORT_Strcat (ret, SEP); }
- if (cer_ou1) { PORT_Strcat (ret, cer_ou1); PORT_Strcat (ret, SEP); }
- if (cer_ou2) { PORT_Strcat (ret, cer_ou2); PORT_Strcat (ret, SEP); }
- if (cer_ou3) { PORT_Strcat (ret, cer_ou3); PORT_Strcat (ret, SEP); }
- if (cer_o) { PORT_Strcat (ret, cer_o); PORT_Strcat (ret, SEP); }
- if (cer_l) PORT_Strcat (ret, cer_l);
-
- /* return here to avoid unsightly memory leak */
-
- *result = ret;
- *length = PORT_Strlen (ret);
-
- return 0;
- }
- break;
-
- case jarCertCA:
-
- ret = cert->issuerName;
-
- if (ret)
- {
- int retlen = 0;
-
- char *cer_ou1, *cer_ou2, *cer_ou3;
- char *cer_cn, *cer_e, *cer_o, *cer_l;
-
- /* This is pretty ugly looking but only used
- here for this one purpose. */
-
- cer_cn = CERT_GetCommonName (&cert->issuer);
- cer_e = CERT_GetCertEmailAddress (&cert->issuer);
- cer_ou3 = jar_cert_element (ret, "OU=", 3);
- cer_ou2 = jar_cert_element (ret, "OU=", 2);
- cer_ou1 = jar_cert_element (ret, "OU=", 1);
- cer_o = CERT_GetOrgName (&cert->issuer);
- cer_l = CERT_GetCountryName (&cert->issuer);
-
- if (cer_cn) retlen += SEPLEN + PORT_Strlen (cer_cn);
- if (cer_e) retlen += SEPLEN + PORT_Strlen (cer_e);
- if (cer_ou1) retlen += SEPLEN + PORT_Strlen (cer_ou1);
- if (cer_ou2) retlen += SEPLEN + PORT_Strlen (cer_ou2);
- if (cer_ou3) retlen += SEPLEN + PORT_Strlen (cer_ou3);
- if (cer_o) retlen += SEPLEN + PORT_Strlen (cer_o);
- if (cer_l) retlen += SEPLEN + PORT_Strlen (cer_l);
-
- ret = (char *) PORT_ZAlloc (1 + retlen);
-
- if (cer_cn) { PORT_Strcpy (ret, cer_cn); PORT_Strcat (ret, SEP); }
- if (cer_e) { PORT_Strcat (ret, cer_e); PORT_Strcat (ret, SEP); }
- if (cer_ou1) { PORT_Strcat (ret, cer_ou1); PORT_Strcat (ret, SEP); }
- if (cer_ou2) { PORT_Strcat (ret, cer_ou2); PORT_Strcat (ret, SEP); }
- if (cer_ou3) { PORT_Strcat (ret, cer_ou3); PORT_Strcat (ret, SEP); }
- if (cer_o) { PORT_Strcat (ret, cer_o); PORT_Strcat (ret, SEP); }
- if (cer_l) PORT_Strcat (ret, cer_l);
-
- /* return here to avoid unsightly memory leak */
-
- *result = ret;
- *length = PORT_Strlen (ret);
-
- return 0;
- }
-
- break;
-
- case jarCertSerial:
-
- ret = CERT_Hexify (&cert->serialNumber, 1);
- break;
-
- case jarCertExpires:
-
- ret = DER_UTCDayToAscii (&cert->validity.notAfter);
- break;
-
- case jarCertNickname:
-
- ret = jar_choose_nickname (cert);
- break;
-
- case jarCertFinger:
-
- dig = JAR_calculate_digest
- ((char *) cert->derCert.data, cert->derCert.len);
-
- if (dig)
- {
- hexme.len = sizeof (dig->md5);
- hexme.data = dig->md5;
- ret = CERT_Hexify (&hexme, 1);
- }
- break;
-
- default:
-
- return JAR_ERR_GENERAL;
- }
-
- *result = ret ? PORT_Strdup (ret) : NULL;
- *length = ret ? PORT_Strlen (ret) : 0;
-
- return 0;
- }
-
-/*
- * j a r _ c e r t _ e l e m e n t
- *
- * Retrieve an element from an x400ish ascii
- * designator, in a hackish sort of way. The right
- * thing would probably be to sort AVATags.
- *
- */
-
-static char *jar_cert_element (char *name, char *tag, int occ)
- {
- if (name && tag)
- {
- char *s;
- int found = 0;
-
- while (occ--)
- {
- if (PORT_Strstr (name, tag))
- {
- name = PORT_Strstr (name, tag) + PORT_Strlen (tag);
- found = 1;
- }
- else
- {
- name = PORT_Strstr (name, "=");
- if (name == NULL) return NULL;
- found = 0;
- }
- }
-
- if (!found) return NULL;
-
- /* must mangle only the copy */
- name = PORT_Strdup (name);
-
- /* advance to next equal */
- for (s = name; *s && *s != '='; s++)
- /* yip */ ;
-
- /* back up to previous comma */
- while (s > name && *s != ',') s--;
-
- /* zap the whitespace and return */
- *s = 0;
- }
-
- return name;
- }
-
-/*
- * j a r _ c h o o s e _ n i c k n a m e
- *
- * Attempt to determine a suitable nickname for
- * a certificate with a computer-generated "tmpcertxxx"
- * nickname. It needs to be something a user can
- * understand, so try a few things.
- *
- */
-
-static char *jar_choose_nickname (CERTCertificate *cert)
- {
- char *cert_cn;
- char *cert_o;
- char *cert_cn_o;
-
- int cn_o_length;
-
- /* is the existing name ok */
-
- if (cert->nickname && PORT_Strncmp (cert->nickname, "tmpcert", 7))
- return PORT_Strdup (cert->nickname);
-
- /* we have an ugly name here people */
-
- /* Try the CN */
- cert_cn = CERT_GetCommonName (&cert->subject);
-
- if (cert_cn)
- {
- /* check for duplicate nickname */
-
-#ifdef USE_MOZ_THREAD
- if (jar_moz_nickname (CERT_GetDefaultCertDB(), cert_cn) == NULL)
-#else
- if (CERT_FindCertByNickname (CERT_GetDefaultCertDB(), cert_cn) == NULL)
-#endif
- return cert_cn;
-
- /* Try the CN plus O */
- cert_o = CERT_GetOrgName (&cert->subject);
-
- cn_o_length = PORT_Strlen (cert_cn) + 3 + PORT_Strlen (cert_o) + 20;
- cert_cn_o = (char*)PORT_ZAlloc (cn_o_length);
-
- PR_snprintf (cert_cn_o, cn_o_length,
- "%s's %s Certificate", cert_cn, cert_o);
-
-#ifdef USE_MOZ_THREAD
- if (jar_moz_nickname (CERT_GetDefaultCertDB(), cert_cn_o) == NULL)
-#else
- if (CERT_FindCertByNickname (CERT_GetDefaultCertDB(), cert_cn_o) == NULL)
-#endif
- return cert_cn;
- }
-
- /* If all that failed, use the ugly nickname */
- return cert->nickname ? PORT_Strdup (cert->nickname) : NULL;
- }
-
-/*
- * J A R _ c e r t _ h t m l
- *
- * Return an HTML representation of the certificate
- * designated by the given fingerprint, in specified style.
- *
- * JAR is optional, but supply it if you can in order
- * to optimize.
- *
- */
-
-char *JAR_cert_html
- (JAR *jar, int style, long keylen, void *key, int *result)
- {
- char *html;
- CERTCertificate *cert;
-
- *result = -1;
-
- if (style != 0)
- return NULL;
-
- cert = jar_get_certificate (jar, keylen, key, result);
-
- if (cert == NULL || *result < 0)
- return NULL;
-
- *result = 0;
-
- html = CERT_HTMLCertInfo (cert, /* show images */ PR_TRUE,
- /*show issuer*/PR_TRUE);
-
- if (html == NULL)
- *result = -1;
-
- return html;
- }
-
-/*
- * J A R _ s t a s h _ c e r t
- *
- * Stash the certificate pointed to by this
- * fingerprint, in persistent storage somewhere.
- *
- */
-
-extern int PR_CALLBACK JAR_stash_cert
- (JAR *jar, long keylen, void *key)
- {
- int result = 0;
-
- char *nickname;
- CERTCertTrust trust;
-
- CERTCertDBHandle *certdb;
- CERTCertificate *cert, *newcert;
-
- cert = jar_get_certificate (jar, keylen, key, &result);
-
- if (result < 0)
- return result;
-
- if (cert == NULL)
- return JAR_ERR_GENERAL;
-
- if ((certdb = JAR_open_database()) == NULL)
- return JAR_ERR_GENERAL;
-
- /* Attempt to give a name to the newish certificate */
- nickname = jar_choose_nickname (cert);
-
-#ifdef USE_MOZ_THREAD
- newcert = jar_moz_nickname (certdb, nickname);
-#else
- newcert = CERT_FindCertByNickname (certdb, nickname);
-#endif
-
- if (newcert && newcert->isperm)
- {
- /* already in permanant database */
- return 0;
- }
-
- if (newcert) cert = newcert;
-
- /* FIX, since FindCert returns a bogus dbhandle
- set it ourselves */
-
- cert->dbhandle = certdb;
-
-#if 0
- nickname = cert->subjectName;
- if (nickname)
- {
- /* Not checking for a conflict here. But this should
- be a new cert or it would have been found earlier. */
-
- nickname = jar_cert_element (nickname, "CN=", 1);
-
- if (SEC_CertNicknameConflict (nickname, cert->dbhandle))
- {
- /* conflict */
- nickname = PORT_Realloc (&nickname, PORT_Strlen (nickname) + 3);
-
- /* Beyond one copy, there are probably serious problems
- so we will stop at two rather than counting.. */
-
- PORT_Strcat (nickname, " #2");
- }
- }
-#endif
-
- if (nickname != NULL)
- {
- PORT_Memset ((void *) &trust, 0, sizeof(trust));
-
-#ifdef USE_MOZ_THREAD
- if (jar_moz_perm (cert, nickname, &trust) != SECSuccess)
-#else
- if (CERT_AddTempCertToPerm (cert, nickname, &trust) != SECSuccess)
-#endif
- {
- /* XXX might want to call PORT_GetError here */
- result = JAR_ERR_GENERAL;
- }
- }
-
- JAR_close_database (certdb);
-
- return result;
- }
-
-/*
- * J A R _ f e t c h _ c e r t
- *
- * Given an opaque identifier of a certificate,
- * return the full certificate.
- *
- * The new function, which retrieves by key.
- *
- */
-
-void *JAR_fetch_cert (long length, void *key)
- {
- SECItem seckey;
- CERTCertificate *cert = NULL;
-
- CERTCertDBHandle *certdb;
-
- certdb = JAR_open_database();
-
- if (certdb)
- {
- seckey.len = length;
- seckey.data = (unsigned char*)key;
-
-#ifdef USE_MOZ_THREAD
- cert = jar_moz_certkey (certdb, &seckey);
-#else
- cert = CERT_FindCertByKey (certdb, &seckey);
-#endif
-
- JAR_close_database (certdb);
- }
-
- return (void *) cert;
- }
-
-/*
- * j a r _ g e t _ m f _ d i g e s t
- *
- * Retrieve a corresponding saved digest over a section
- * of the main manifest file.
- *
- */
-
-static JAR_Digest *jar_get_mf_digest (JAR *jar, char *pathname)
- {
- JAR_Item *it;
-
- JAR_Digest *dig;
-
- ZZLink *link;
- ZZList *list;
-
- list = jar->manifest;
-
- if (ZZ_ListEmpty (list))
- return NULL;
-
- for (link = ZZ_ListHead (list);
- !ZZ_ListIterDone (list, link);
- link = link->next)
- {
- it = link->thing;
- if (it->type == jarTypeSect
- && it->pathname && !PORT_Strcmp (it->pathname, pathname))
- {
- dig = (JAR_Digest *) it->data;
- return dig;
- }
- }
-
- return NULL;
- }
-
-/*
- * j a r _ b a s e n a m e
- *
- * Return the basename -- leading components of path stripped off,
- * extension ripped off -- of a path.
- *
- */
-
-static char *jar_basename (const char *path)
- {
- char *pith, *e, *basename, *ext;
-
- if (path == NULL)
- return PORT_Strdup ("");
-
- pith = PORT_Strdup (path);
-
- basename = pith;
-
- while (1)
- {
- for (e = basename; *e && *e != '/' && *e != '\\'; e++)
- /* yip */ ;
- if (*e)
- basename = ++e;
- else
- break;
- }
-
- if ((ext = PORT_Strrchr (basename, '.')) != NULL)
- *ext = 0;
-
- /* We already have the space allocated */
- PORT_Strcpy (pith, basename);
-
- return pith;
- }
-
-/*
- * + + + + + + + + + + + + + + +
- *
- * CRYPTO ROUTINES FOR JAR
- *
- * The following functions are the cryptographic
- * interface to PKCS7 for Jarnatures.
- *
- * + + + + + + + + + + + + + + +
- *
- */
-
-/*
- * j a r _ c a t c h _ b y t e s
- *
- * In the event signatures contain enveloped data, it will show up here.
- * But note that the lib/pkcs7 routines aren't ready for it.
- *
- */
-
-static void jar_catch_bytes
- (void *arg, const char *buf, unsigned long len)
- {
- /* Actually this should never be called, since there is
- presumably no data in the signature itself. */
- }
-
-/*
- * j a r _ v a l i d a t e _ p k c s 7
- *
- * Validate (and decode, if necessary) a binary pkcs7
- * signature in DER format.
- *
- */
-
-static int jar_validate_pkcs7
- (JAR *jar, JAR_Signer *signer, char *data, long length)
- {
- SECItem detdig;
-
- SEC_PKCS7ContentInfo *cinfo;
- SEC_PKCS7DecoderContext *dcx;
-
- int status = 0;
- char *errstring = NULL;
-
- PORT_Assert( jar != NULL && signer != NULL );
-
- if (jar == NULL || signer == NULL)
- return JAR_ERR_ORDER;
-
- signer->valid = JAR_ERR_SIG;
-
- /* We need a context if we can get one */
-
-#ifdef MOZILLA_CLIENT
- if (jar->mw == NULL) {
- JAR_set_context (jar, NULL);
- }
-#endif
-
-
- dcx = SEC_PKCS7DecoderStart
- (jar_catch_bytes, NULL /*cb_arg*/, NULL /*getpassword*/, jar->mw,
- NULL, NULL, NULL);
-
- if (dcx != NULL)
- {
- SEC_PKCS7DecoderUpdate (dcx, data, length);
- cinfo = SEC_PKCS7DecoderFinish (dcx);
- }
-
- if (cinfo == NULL)
- {
- /* strange pkcs7 failure */
- return JAR_ERR_PK7;
- }
-
- if (SEC_PKCS7ContentIsEncrypted (cinfo))
- {
- /* content was encrypted, fail */
- return JAR_ERR_PK7;
- }
-
- if (SEC_PKCS7ContentIsSigned (cinfo) == PR_FALSE)
- {
- /* content was not signed, fail */
- return JAR_ERR_PK7;
- }
-
- PORT_SetError (0);
-
- /* use SHA1 only */
-
- detdig.len = SHA1_LENGTH;
- detdig.data = signer->digest->sha1;
-
-#ifdef USE_MOZ_THREAD
- if (jar_moz_verify
- (cinfo, certUsageObjectSigner, &detdig, HASH_AlgSHA1, PR_FALSE)==
- SECSuccess)
-#else
- if (SEC_PKCS7VerifyDetachedSignature
- (cinfo, certUsageObjectSigner, &detdig, HASH_AlgSHA1, PR_FALSE)==
- PR_TRUE)
-#endif
- {
- /* signature is valid */
- signer->valid = 0;
- jar_gather_signers (jar, signer, cinfo);
- }
- else
- {
- status = PORT_GetError();
-
- PORT_Assert( status < 0 );
- if (status >= 0) status = JAR_ERR_SIG;
-
- jar->valid = status;
- signer->valid = status;
-
- errstring = JAR_get_error (status);
- /*XP_TRACE(("JAR signature invalid (reason %d = %s)", status, errstring));*/
- }
-
- jar->pkcs7 = PR_TRUE;
- signer->pkcs7 = PR_TRUE;
-
- SEC_PKCS7DestroyContentInfo (cinfo);
-
- return status;
- }
-
-/*
- * j a r _ g a t h e r _ s i g n e r s
- *
- * Add the single signer of this signature to the
- * certificate linked list.
- *
- */
-
-static int jar_gather_signers
- (JAR *jar, JAR_Signer *signer, SEC_PKCS7ContentInfo *cinfo)
- {
- int result;
-
- CERTCertificate *cert;
- CERTCertDBHandle *certdb;
-
- SEC_PKCS7SignedData *sdp;
- SEC_PKCS7SignerInfo **pksigners, *pksigner;
-
- sdp = cinfo->content.signedData;
-
- if (sdp == NULL)
- return JAR_ERR_PK7;
-
- pksigners = sdp->signerInfos;
-
- /* permit exactly one signer */
-
- if (pksigners == NULL || pksigners [0] == NULL || pksigners [1] != NULL)
- return JAR_ERR_PK7;
-
- pksigner = *pksigners;
- cert = pksigner->cert;
-
- if (cert == NULL)
- return JAR_ERR_PK7;
-
- certdb = JAR_open_database();
-
- if (certdb == NULL)
- return JAR_ERR_GENERAL;
-
- result = jar_add_cert (jar, signer, jarTypeSign, cert);
-
- JAR_close_database (certdb);
-
- return result;
- }
-
-/*
- * j a r _ o p e n _ d a t a b a s e
- *
- * Open the certificate database,
- * for use by JAR functions.
- *
- */
-
-CERTCertDBHandle *JAR_open_database (void)
- {
- int keepcerts = 0;
- CERTCertDBHandle *certdb;
-
- /* local_certdb will only be used if calling from a command line tool */
- static CERTCertDBHandle local_certdb;
-
- certdb = CERT_GetDefaultCertDB();
-
- if (certdb == NULL)
- {
- if (CERT_OpenCertDBFilename (&local_certdb, NULL, (PRBool)!keepcerts) !=
- SECSuccess)
- {
- return NULL;
- }
- certdb = &local_certdb;
- }
-
- return certdb;
- }
-
-/*
- * j a r _ c l o s e _ d a t a b a s e
- *
- * Close the certificate database.
- * For use by JAR functions.
- *
- */
-
-int JAR_close_database (CERTCertDBHandle *certdb)
- {
- CERTCertDBHandle *defaultdb;
-
- /* This really just retrieves the handle, nothing more */
- defaultdb = CERT_GetDefaultCertDB();
-
- /* If there is no default db, it means we opened
- the permanent database for some reason */
-
- if (defaultdb == NULL && certdb != NULL)
- CERT_ClosePermCertDB (certdb);
-
- return 0;
- }
-
-/*
- * j a r _ g e t _ c e r t i f i c a t e
- *
- * Return the certificate referenced
- * by a given fingerprint, or NULL if not found.
- * Error code is returned in result.
- *
- */
-
-static CERTCertificate *jar_get_certificate
- (JAR *jar, long keylen, void *key, int *result)
- {
- int found = 0;
-
- JAR_Item *it;
- JAR_Cert *fing;
-
- JAR_Context *ctx;
-
- if (jar == NULL)
- {
- void *cert;
- cert = JAR_fetch_cert (keylen, key);
- *result = (cert == NULL) ? JAR_ERR_GENERAL : 0;
- return (CERTCertificate *) cert;
- }
-
- ctx = JAR_find (jar, NULL, jarTypeSign);
-
- while (JAR_find_next (ctx, &it) >= 0)
- {
- fing = (JAR_Cert *) it->data;
-
- if (keylen != fing->length)
- continue;
-
- PORT_Assert( keylen < 0xFFFF );
- if (!PORT_Memcmp (fing->key, key, keylen))
- {
- found = 1;
- break;
- }
- }
-
- JAR_find_end (ctx);
-
- if (found == 0)
- {
- *result = JAR_ERR_GENERAL;
- return NULL;
- }
-
- *result = 0;
- return fing->cert;
- }
-
-/*
- * j a r _ s i g n a l
- *
- * Nonfatal errors come here to callback Java.
- *
- */
-
-static int jar_signal
- (int status, JAR *jar, const char *metafile, char *pathname)
- {
- char *errstring;
-
- errstring = JAR_get_error (status);
-
- if (jar->signal)
- {
- (*jar->signal) (status, jar, metafile, pathname, errstring);
- return 0;
- }
-
- return status;
- }
-
-/*
- * j a r _ a p p e n d
- *
- * Tack on an element to one of a JAR's linked
- * lists, with rudimentary error handling.
- *
- */
-
-int jar_append (ZZList *list, int type,
- char *pathname, void *data, size_t size)
- {
- JAR_Item *it;
- ZZLink *entity;
-
- it = (JAR_Item*)PORT_ZAlloc (sizeof (JAR_Item));
-
- if (it == NULL)
- goto loser;
-
- if (pathname)
- {
- it->pathname = PORT_Strdup (pathname);
- if (it->pathname == NULL)
- goto loser;
- }
-
- it->type = (jarType)type;
- it->data = (unsigned char *) data;
- it->size = size;
-
- entity = ZZ_NewLink (it);
-
- if (entity)
- {
- ZZ_AppendLink (list, entity);
- return 0;
- }
-
-loser:
-
- if (it)
- {
- if (it->pathname) PORT_Free (it->pathname);
- PORT_Free (it);
- }
-
- return JAR_ERR_MEMORY;
- }
-
-/*
- * W I N 1 6 s t u f f
- *
- * These functions possibly belong in xp_mem.c, they operate
- * on huge string pointers for win16.
- *
- */
-
-#if defined(XP_WIN16)
-int xp_HUGE_STRNCASECMP (char ZHUGEP *buf, char *key, int len)
- {
- while (len--)
- {
- char c1, c2;
-
- c1 = *buf++;
- c2 = *key++;
-
- if (c1 >= 'a' && c1 <= 'z') c1 -= ('a' - 'A');
- if (c2 >= 'a' && c2 <= 'z') c2 -= ('a' - 'A');
-
- if (c1 != c2)
- return (c1 < c2) ? -1 : 1;
- }
- return 0;
- }
-
-size_t xp_HUGE_STRLEN (char ZHUGEP *s)
- {
- size_t len = 0L;
- while (*s++) len++;
- return len;
- }
-
-char *xp_HUGE_STRCPY (char *to, char ZHUGEP *from)
- {
- char *ret = to;
-
- while (*from)
- *to++ = *from++;
- *to = 0;
-
- return ret;
- }
-#endif
diff --git a/security/nss/lib/pk11wrap/pk11skey.c b/security/nss/lib/pk11wrap/pk11skey.c
deleted file mode 100644
index 52f2ce30d..000000000
--- a/security/nss/lib/pk11wrap/pk11skey.c
+++ /dev/null
@@ -1,4790 +0,0 @@
-/*
- * The contents of this file are subject to the Mozilla Public
- * License Version 1.1 (the "License"); you may not use this file
- * except in compliance with the License. You may obtain a copy of
- * the License at http://www.mozilla.org/MPL/
- *
- * Software distributed under the License is distributed on an "AS
- * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
- * implied. See the License for the specific language governing
- * rights and limitations under the License.
- *
- * The Original Code is the Netscape security libraries.
- *
- * The Initial Developer of the Original Code is Netscape
- * Communications Corporation. Portions created by Netscape are
- * Copyright (C) 1994-2000 Netscape Communications Corporation. All
- * Rights Reserved.
- *
- * Contributor(s):
- *
- * Alternatively, the contents of this file may be used under the
- * terms of the GNU General Public License Version 2 or later (the
- * "GPL"), in which case the provisions of the GPL are applicable
- * instead of those above. If you wish to allow use of your
- * version of this file only under the terms of the GPL and not to
- * allow others to use your version of this file under the MPL,
- * indicate your decision by deleting the provisions above and
- * replace them with the notice and other provisions required by
- * the GPL. If you do not delete the provisions above, a recipient
- * may use your version of this file under either the MPL or the
- * GPL.
- */
-/*
- * This file implements the Symkey wrapper and the PKCS context
- * Interfaces.
- */
-
-#include "seccomon.h"
-#include "secmod.h"
-#include "prlock.h"
-#include "secmodi.h"
-#include "pkcs11.h"
-#include "pk11func.h"
-#include "secitem.h"
-#include "key.h"
-#include "secoid.h"
-#include "secasn1.h"
-#include "sechash.h"
-#include "cert.h"
-#include "secerr.h"
-
-#define PAIRWISE_SECITEM_TYPE siBuffer
-#define PAIRWISE_DIGEST_LENGTH SHA1_LENGTH /* 160-bits */
-#define PAIRWISE_MESSAGE_LENGTH 20 /* 160-bits */
-
-/* forward static declarations. */
-static PK11SymKey *pk11_DeriveWithTemplate(PK11SymKey *baseKey,
- CK_MECHANISM_TYPE derive, SECItem *param, CK_MECHANISM_TYPE target,
- CK_ATTRIBUTE_TYPE operation, int keySize, CK_ATTRIBUTE *userAttr,
- unsigned int numAttrs);
-
-
-/*
- * strip leading zero's from key material
- */
-void
-pk11_SignedToUnsigned(CK_ATTRIBUTE *attrib) {
- char *ptr = (char *)attrib->pValue;
- unsigned long len = attrib->ulValueLen;
-
- while (len && (*ptr == 0)) {
- len--;
- ptr++;
- }
- attrib->pValue = ptr;
- attrib->ulValueLen = len;
-}
-
-/*
- * get a new session on a slot. If we run out of session, use the slot's
- * 'exclusive' session. In this case owner becomes false.
- */
-static CK_SESSION_HANDLE
-pk11_GetNewSession(PK11SlotInfo *slot,PRBool *owner)
-{
- CK_SESSION_HANDLE session;
- *owner = PR_TRUE;
- if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
- if ( PK11_GETTAB(slot)->C_OpenSession(slot->slotID,CKF_SERIAL_SESSION,
- slot,pk11_notify,&session) != CKR_OK) {
- *owner = PR_FALSE;
- session = slot->session;
- }
- if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
-
- return session;
-}
-
-static void
-pk11_CloseSession(PK11SlotInfo *slot,CK_SESSION_HANDLE session,PRBool owner)
-{
- if (!owner) return;
- if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
- (void) PK11_GETTAB(slot)->C_CloseSession(session);
- if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
-}
-
-
-SECStatus
-PK11_CreateNewObject(PK11SlotInfo *slot, CK_SESSION_HANDLE session,
- CK_ATTRIBUTE *theTemplate, int count,
- PRBool token, CK_OBJECT_HANDLE *objectID)
-{
- CK_SESSION_HANDLE rwsession;
- CK_RV crv;
- SECStatus rv = SECSuccess;
-
- rwsession = session;
- if (rwsession == CK_INVALID_SESSION) {
- if (token) {
- rwsession = PK11_GetRWSession(slot);
- } else {
- rwsession = slot->session;
- PK11_EnterSlotMonitor(slot);
- }
- }
- crv = PK11_GETTAB(slot)->C_CreateObject(rwsession, theTemplate,
- count,objectID);
- if(crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- rv = SECFailure;
- }
-
- if (session == CK_INVALID_SESSION) {
- if (token) {
- PK11_RestoreROSession(slot, rwsession);
- } else {
- PK11_ExitSlotMonitor(slot);
- }
- }
-
- return rv;
-}
-
-static void
-pk11_EnterKeyMonitor(PK11SymKey *symKey) {
- if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
- PK11_EnterSlotMonitor(symKey->slot);
-}
-
-static void
-pk11_ExitKeyMonitor(PK11SymKey *symKey) {
- if (!symKey->sessionOwner || !(symKey->slot->isThreadSafe))
- PK11_ExitSlotMonitor(symKey->slot);
-}
-
-/*
- * create a symetric key:
- * Slot is the slot to create the key in.
- * type is the mechainism type
- */
-PK11SymKey *
-PK11_CreateSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, void *wincx)
-{
-
- PK11SymKey *symKey = (PK11SymKey *)PORT_Alloc(sizeof(PK11SymKey));
- if (symKey == NULL) {
- return NULL;
- }
- symKey->refLock = PR_NewLock();
- if (symKey->refLock == NULL) {
- PORT_Free(symKey);
- return NULL;
- }
- symKey->type = type;
- symKey->data.data = NULL;
- symKey->data.len = 0;
- symKey->owner = PR_TRUE;
- symKey->objectID = CK_INVALID_KEY;
- symKey->slot = slot;
- symKey->series = slot->series;
- symKey->cx = wincx;
- symKey->size = 0;
- symKey->refCount = 1;
- symKey->origin = PK11_OriginNULL;
- symKey->session = pk11_GetNewSession(slot,&symKey->sessionOwner);
- symKey->origin = PK11_OriginNULL;
- PK11_ReferenceSlot(slot);
- return symKey;
-}
-
-/*
- * destroy a symetric key
- */
-void
-PK11_FreeSymKey(PK11SymKey *symKey)
-{
- PRBool destroy = PR_FALSE;
-
- PK11_USE_THREADS(PR_Lock(symKey->refLock);)
- if (symKey->refCount-- == 1) {
- destroy= PR_TRUE;
- }
- PK11_USE_THREADS(PR_Unlock(symKey->refLock);)
- if (destroy) {
- if ((symKey->owner) && symKey->objectID != CK_INVALID_KEY) {
- pk11_EnterKeyMonitor(symKey);
- (void) PK11_GETTAB(symKey->slot)->
- C_DestroyObject(symKey->session, symKey->objectID);
- pk11_ExitKeyMonitor(symKey);
- }
- pk11_CloseSession(symKey->slot, symKey->session,symKey->sessionOwner);
- if (symKey->data.data) {
- PORT_Memset(symKey->data.data, 0, symKey->data.len);
- PORT_Free(symKey->data.data);
- }
- PK11_USE_THREADS(PR_DestroyLock(symKey->refLock);)
- PK11_FreeSlot(symKey->slot);
- PORT_Free(symKey);
- }
-}
-
-PK11SymKey *
-PK11_ReferenceSymKey(PK11SymKey *symKey)
-{
- PK11_USE_THREADS(PR_Lock(symKey->refLock);)
- symKey->refCount++;
- PK11_USE_THREADS(PR_Unlock(symKey->refLock);)
- return symKey;
-}
-
-/*
- * turn key handle into an appropriate key object
- */
-PK11SymKey *
-PK11_SymKeyFromHandle(PK11SlotInfo *slot, PK11SymKey *parent, PK11Origin origin,
- CK_MECHANISM_TYPE type, CK_OBJECT_HANDLE keyID, PRBool owner, void *wincx)
-{
- PK11SymKey *symKey;
-
- if (keyID == CK_INVALID_KEY) {
- return NULL;
- }
-
- symKey = PK11_CreateSymKey(slot,type,wincx);
- if (symKey == NULL) {
- return NULL;
- }
-
- symKey->objectID = keyID;
- symKey->origin = origin;
- symKey->owner = owner;
-
- /* adopt the parent's session */
- /* This is only used by SSL. What we really want here is a session
- * structure with a ref count so the session goes away only after all the
- * keys do. */
- if (owner && parent) {
- pk11_CloseSession(symKey->slot, symKey->session,symKey->sessionOwner);
- symKey->sessionOwner = parent->sessionOwner;
- symKey->session = parent->session;
- parent->sessionOwner = PR_FALSE;
- }
-
- return symKey;
-}
-
-/*
- * turn key handle into an appropriate key object
- */
-PK11SymKey *
-PK11_GetWrapKey(PK11SlotInfo *slot, int wrap, CK_MECHANISM_TYPE type,
- int series, void *wincx)
-{
- PK11SymKey *symKey = NULL;
-
- if (slot->series != series) return NULL;
- if (slot->refKeys[wrap] == CK_INVALID_KEY) return NULL;
- if (type == CKM_INVALID_MECHANISM) type = slot->wrapMechanism;
-
- symKey = PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive,
- slot->wrapMechanism, slot->refKeys[wrap], PR_FALSE, wincx);
- return symKey;
-}
-
-void
-PK11_SetWrapKey(PK11SlotInfo *slot, int wrap, PK11SymKey *wrapKey)
-{
- /* save the handle and mechanism for the wrapping key */
- /* mark the key and session as not owned by us to they don't get freed
- * when the key goes way... that lets us reuse the key later */
- slot->refKeys[wrap] = wrapKey->objectID;
- wrapKey->owner = PR_FALSE;
- wrapKey->sessionOwner = PR_FALSE;
- slot->wrapMechanism = wrapKey->type;
-}
-
-CK_MECHANISM_TYPE
-PK11_GetMechanism(PK11SymKey *symKey)
-{
- return symKey->type;
-}
-
-/*
- * figure out if a key is still valid or if it is stale.
- */
-PRBool
-PK11_VerifyKeyOK(PK11SymKey *key) {
- if (!PK11_IsPresent(key->slot)) {
- return PR_FALSE;
- }
- return (PRBool)(key->series == key->slot->series);
-}
-
-static PK11SymKey *
-pk11_ImportSymKeyWithTempl(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
- PK11Origin origin, CK_ATTRIBUTE *keyTemplate,
- unsigned int templateCount, SECItem *key, void *wincx)
-{
- PK11SymKey * symKey;
- CK_RV crv;
-
- symKey = PK11_CreateSymKey(slot,type,wincx);
- if (symKey == NULL) {
- return NULL;
- }
-
- symKey->size = key->len;
-
- if (SECITEM_CopyItem(NULL,&symKey->data,key) != SECSuccess) {
- PK11_FreeSymKey(symKey);
- return NULL;
- }
-
- symKey->origin = origin;
-
- /* import the keys */
- crv = PK11_CreateNewObject(slot, symKey->session, keyTemplate,
- templateCount, PR_FALSE, &symKey->objectID);
- if ( crv != CKR_OK) {
- PK11_FreeSymKey(symKey);
- PORT_SetError( PK11_MapError(crv));
- return NULL;
- }
-
- return symKey;
-}
-
-/*
- * turn key bits into an appropriate key object
- */
-PK11SymKey *
-PK11_ImportSymKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
- PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,void *wincx)
-{
- PK11SymKey * symKey;
- unsigned int templateCount = 0;
- CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
- CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
- CK_BBOOL cktrue = CK_TRUE; /* sigh */
- CK_ATTRIBUTE keyTemplate[5];
- CK_ATTRIBUTE * attrs = keyTemplate;
-
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
- PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, key->data, key->len); attrs++;
- templateCount = attrs - keyTemplate;
- PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
-
- keyType = PK11_GetKeyType(type,key->len);
- symKey = pk11_ImportSymKeyWithTempl(slot, type, origin, keyTemplate,
- templateCount, key, wincx);
- return symKey;
-}
-
-/*
- * import a public key into the desired slot
- */
-CK_OBJECT_HANDLE
-PK11_ImportPublicKey(PK11SlotInfo *slot, SECKEYPublicKey *pubKey,
- PRBool isToken)
-{
- CK_BBOOL cktrue = CK_TRUE;
- CK_BBOOL ckfalse = CK_FALSE;
- CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
- CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
- CK_OBJECT_HANDLE objectID;
- CK_ATTRIBUTE theTemplate[10];
- CK_ATTRIBUTE *signedattr = NULL;
- CK_ATTRIBUTE *attrs = theTemplate;
- int signedcount = 0;
- int templateCount = 0;
- CK_RV crv;
-
- /* if we already have an object in the desired slot, use it */
- if (!isToken && pubKey->pkcs11Slot == slot) {
- return pubKey->pkcs11ID;
- }
-
- /* free the existing key */
- if (pubKey->pkcs11Slot != NULL) {
- PK11SlotInfo *oSlot = pubKey->pkcs11Slot;
- PK11_EnterSlotMonitor(oSlot);
- (void) PK11_GETTAB(oSlot)->C_DestroyObject(oSlot->session,
- pubKey->pkcs11ID);
- PK11_ExitSlotMonitor(oSlot);
- PK11_FreeSlot(oSlot);
- pubKey->pkcs11Slot = NULL;
- }
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
- PK11_SETATTRS(attrs, CKA_TOKEN, isToken ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL) ); attrs++;
-
- /* now import the key */
- {
- switch (pubKey->keyType) {
- case rsaKey:
- keyType = CKK_RSA;
- PK11_SETATTRS(attrs, CKA_WRAP, &cktrue, sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_ENCRYPT, &cktrue,
- sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL)); attrs++;
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_MODULUS, pubKey->u.rsa.modulus.data,
- pubKey->u.rsa.modulus.len); attrs++;
- PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
- pubKey->u.rsa.publicExponent.data,
- pubKey->u.rsa.publicExponent.len); attrs++;
- break;
- case dsaKey:
- keyType = CKK_DSA;
- PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++;
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dsa.params.prime.data,
- pubKey->u.dsa.params.prime.len); attrs++;
- PK11_SETATTRS(attrs,CKA_SUBPRIME,pubKey->u.dsa.params.subPrime.data,
- pubKey->u.dsa.params.subPrime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dsa.params.base.data,
- pubKey->u.dsa.params.base.len); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dsa.publicValue.data,
- pubKey->u.dsa.publicValue.len); attrs++;
- break;
- case fortezzaKey:
- keyType = CKK_DSA;
- PK11_SETATTRS(attrs, CKA_VERIFY, &cktrue, sizeof(CK_BBOOL));attrs++;
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME,pubKey->u.fortezza.params.prime.data,
- pubKey->u.fortezza.params.prime.len); attrs++;
- PK11_SETATTRS(attrs,CKA_SUBPRIME,
- pubKey->u.fortezza.params.subPrime.data,
- pubKey->u.fortezza.params.subPrime.len);attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.fortezza.params.base.data,
- pubKey->u.fortezza.params.base.len); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.fortezza.DSSKey.data,
- pubKey->u.fortezza.DSSKey.len); attrs++;
- break;
- case dhKey:
- keyType = CKK_DH;
- PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL));attrs++;
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME, pubKey->u.dh.prime.data,
- pubKey->u.dh.prime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, pubKey->u.dh.base.data,
- pubKey->u.dh.base.len); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, pubKey->u.dh.publicValue.data,
- pubKey->u.dh.publicValue.len); attrs++;
- break;
- /* what about fortezza??? */
- default:
- PORT_SetError( SEC_ERROR_BAD_KEY );
- return CK_INVALID_KEY;
- }
-
- templateCount = attrs - theTemplate;
- signedcount = attrs - signedattr;
- PORT_Assert(templateCount <= (sizeof(theTemplate)/sizeof(CK_ATTRIBUTE)));
- for (attrs=signedattr; signedcount; attrs++, signedcount--) {
- pk11_SignedToUnsigned(attrs);
- }
- crv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, theTemplate,
- templateCount, isToken, &objectID);
- if ( crv != CKR_OK) {
- PORT_SetError (PK11_MapError(crv));
- return CK_INVALID_KEY;
- }
- }
-
- pubKey->pkcs11ID = objectID;
- pubKey->pkcs11Slot = PK11_ReferenceSlot(slot);
-
- return objectID;
-}
-
-
-/*
- * return the slot associated with a symetric key
- */
-PK11SlotInfo *
-PK11_GetSlotFromKey(PK11SymKey *symKey)
-{
- return PK11_ReferenceSlot(symKey->slot);
-}
-
-PK11SymKey *
-PK11_FindFixedKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *keyID,
- void *wincx)
-{
- CK_ATTRIBUTE findTemp[4];
- CK_ATTRIBUTE *attrs;
- CK_BBOOL ckTrue = CK_TRUE;
- CK_OBJECT_CLASS keyclass = CKO_SECRET_KEY;
- int tsize = 0;
- CK_OBJECT_HANDLE key_id;
-
- attrs = findTemp;
- PK11_SETATTRS(attrs, CKA_CLASS, &keyclass, sizeof(keyclass)); attrs++;
- PK11_SETATTRS(attrs, CKA_TOKEN, &ckTrue, sizeof(ckTrue)); attrs++;
- if (keyID) {
- PK11_SETATTRS(attrs, CKA_ID, keyID->data, keyID->len); attrs++;
- }
- tsize = attrs - findTemp;
- PORT_Assert(tsize <= sizeof(findTemp)/sizeof(CK_ATTRIBUTE));
-
- key_id = pk11_FindObjectByTemplate(slot,findTemp,tsize);
- if (key_id == CK_INVALID_KEY) {
- return NULL;
- }
- return PK11_SymKeyFromHandle(slot, NULL, PK11_OriginDerive, type, key_id,
- PR_FALSE, wincx);
-}
-
-void *
-PK11_GetWindow(PK11SymKey *key)
-{
- return key->cx;
-}
-
-
-/*
- * extract a symetric key value. NOTE: if the key is sensitive, we will
- * not be able to do this operation. This function is used to move
- * keys from one token to another */
-SECStatus
-PK11_ExtractKeyValue(PK11SymKey *symKey)
-{
-
- if (symKey->data.data != NULL) return SECSuccess;
-
- if (symKey->slot == NULL) {
- PORT_SetError( SEC_ERROR_INVALID_KEY );
- return SECFailure;
- }
-
- return PK11_ReadAttribute(symKey->slot,symKey->objectID,CKA_VALUE,NULL,
- &symKey->data);
-}
-
-SECItem *
-PK11_GetKeyData(PK11SymKey *symKey)
-{
- return &symKey->data;
-}
-
-/*
- * take an attribute and copy it into a secitem, converting unsigned to signed.
- */
-static CK_RV
-pk11_Attr2SecItem(PRArenaPool *arena, CK_ATTRIBUTE *attr, SECItem *item) {
- unsigned char *dataPtr;
-
- item->len = attr->ulValueLen;
- dataPtr = (unsigned char*) PORT_ArenaAlloc(arena, item->len+1);
- if ( dataPtr == NULL) {
- return CKR_HOST_MEMORY;
- }
- *dataPtr = 0;
- item->data = dataPtr+1;
- PORT_Memcpy(item->data,attr->pValue,item->len);
- if (item->data[0] & 0x80) {
- item->data = item->data-1;
- item->len++;
- }
- return CKR_OK;
-}
-/*
- * extract a public key from a slot and id
- */
-SECKEYPublicKey *
-PK11_ExtractPublicKey(PK11SlotInfo *slot,KeyType keyType,CK_OBJECT_HANDLE id)
-{
- CK_OBJECT_CLASS keyClass = CKO_PUBLIC_KEY;
- PRArenaPool *arena;
- PRArenaPool *tmp_arena;
- SECKEYPublicKey *pubKey;
- int templateCount = 0;
- CK_KEY_TYPE pk11KeyType;
- CK_RV crv;
- CK_ATTRIBUTE template[8];
- CK_ATTRIBUTE *attrs= template;
- CK_ATTRIBUTE *modulus,*exponent,*base,*prime,*subprime,*value;
-
- /* if we didn't know the key type, get it */
- if (keyType== nullKey) {
-
- pk11KeyType = PK11_ReadULongAttribute(slot,id,CKA_KEY_TYPE);
- if (pk11KeyType == CK_UNAVAILABLE_INFORMATION) {
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
- switch (pk11KeyType) {
- case CKK_RSA:
- keyType = rsaKey;
- break;
- case CKK_DSA:
- keyType = dsaKey;
- break;
- case CKK_DH:
- keyType = dhKey;
- break;
- default:
- PORT_SetError( SEC_ERROR_BAD_KEY );
- return NULL;
- }
- }
-
-
- /* now we need to create space for the public key */
- arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
- if (arena == NULL) return NULL;
- tmp_arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
- if (tmp_arena == NULL) {
- PORT_FreeArena (arena, PR_FALSE);
- return NULL;
- }
-
-
- pubKey = (SECKEYPublicKey *)
- PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
- if (pubKey == NULL) {
- PORT_FreeArena (arena, PR_FALSE);
- PORT_FreeArena (tmp_arena, PR_FALSE);
- return NULL;
- }
-
- pubKey->arena = arena;
- pubKey->keyType = keyType;
- pubKey->pkcs11Slot = PK11_ReferenceSlot(slot);
- pubKey->pkcs11ID = id;
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass,
- sizeof(keyClass)); attrs++;
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &pk11KeyType,
- sizeof(pk11KeyType) ); attrs++;
- switch (pubKey->keyType) {
- case rsaKey:
- modulus = attrs;
- PK11_SETATTRS(attrs, CKA_MODULUS, NULL, 0); attrs++;
- exponent = attrs;
- PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT, NULL, 0); attrs++;
-
- templateCount = attrs - template;
- PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE));
- crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount);
- if (crv != CKR_OK) break;
-
- if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_RSA)) {
- crv = CKR_OBJECT_HANDLE_INVALID;
- break;
- }
- crv = pk11_Attr2SecItem(arena,modulus,&pubKey->u.rsa.modulus);
- if (crv != CKR_OK) break;
- crv = pk11_Attr2SecItem(arena,exponent,&pubKey->u.rsa.publicExponent);
- if (crv != CKR_OK) break;
- break;
- case dsaKey:
- prime = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0); attrs++;
- subprime = attrs;
- PK11_SETATTRS(attrs, CKA_SUBPRIME, NULL, 0); attrs++;
- base = attrs;
- PK11_SETATTRS(attrs, CKA_BASE, NULL, 0); attrs++;
- value = attrs;
- PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0); attrs++;
- templateCount = attrs - template;
- PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE));
- crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount);
- if (crv != CKR_OK) break;
-
- if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DSA)) {
- crv = CKR_OBJECT_HANDLE_INVALID;
- break;
- }
- crv = pk11_Attr2SecItem(arena,prime,&pubKey->u.dsa.params.prime);
- if (crv != CKR_OK) break;
- crv = pk11_Attr2SecItem(arena,subprime,&pubKey->u.dsa.params.subPrime);
- if (crv != CKR_OK) break;
- crv = pk11_Attr2SecItem(arena,base,&pubKey->u.dsa.params.base);
- if (crv != CKR_OK) break;
- crv = pk11_Attr2SecItem(arena,value,&pubKey->u.dsa.publicValue);
- if (crv != CKR_OK) break;
- break;
- case dhKey:
- prime = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME, NULL, 0); attrs++;
- base = attrs;
- PK11_SETATTRS(attrs, CKA_BASE, NULL, 0); attrs++;
- value =attrs;
- PK11_SETATTRS(attrs, CKA_VALUE, NULL, 0); attrs++;
- templateCount = attrs - template;
- PR_ASSERT(templateCount <= sizeof(template)/sizeof(CK_ATTRIBUTE));
- crv = PK11_GetAttributes(tmp_arena,slot,id,template,templateCount);
- if (crv != CKR_OK) break;
-
- if ((keyClass != CKO_PUBLIC_KEY) || (pk11KeyType != CKK_DSA)) {
- crv = CKR_OBJECT_HANDLE_INVALID;
- break;
- }
- crv = pk11_Attr2SecItem(arena,prime,&pubKey->u.dh.prime);
- if (crv != CKR_OK) break;
- crv = pk11_Attr2SecItem(arena,base,&pubKey->u.dh.base);
- if (crv != CKR_OK) break;
- crv = pk11_Attr2SecItem(arena,value,&pubKey->u.dh.publicValue);
- if (crv != CKR_OK) break;
- break;
- case fortezzaKey:
- case nullKey:
- default:
- crv = CKR_OBJECT_HANDLE_INVALID;
- break;
- }
-
- PORT_FreeArena(tmp_arena,PR_FALSE);
-
- if (crv != CKR_OK) {
- PORT_FreeArena(arena,PR_FALSE);
- PK11_FreeSlot(slot);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
-
- return pubKey;
-}
-
-/*
- * Build a Private Key structure from raw PKCS #11 information.
- */
-SECKEYPrivateKey *
-PK11_MakePrivKey(PK11SlotInfo *slot, KeyType keyType,
- PRBool isTemp, CK_OBJECT_HANDLE privID, void *wincx)
-{
- PRArenaPool *arena;
- SECKEYPrivateKey *privKey;
-
- /* don't know? look it up */
- if (keyType == nullKey) {
- CK_KEY_TYPE pk11Type = CKK_RSA;
-
- pk11Type = PK11_ReadULongAttribute(slot,privID,CKA_KEY_TYPE);
- isTemp = (PRBool)!PK11_HasAttributeSet(slot,privID,CKA_TOKEN);
- switch (pk11Type) {
- case CKK_RSA: keyType = rsaKey; break;
- case CKK_DSA: keyType = dsaKey; break;
- case CKK_DH: keyType = dhKey; break;
- case CKK_KEA: keyType = fortezzaKey; break;
- default:
- break;
- }
- }
-
- /* now we need to create space for the private key */
- arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
- if (arena == NULL) return NULL;
-
- privKey = (SECKEYPrivateKey *)
- PORT_ArenaZAlloc(arena, sizeof(SECKEYPrivateKey));
- if (privKey == NULL) {
- PORT_FreeArena(arena, PR_FALSE);
- return NULL;
- }
-
- privKey->arena = arena;
- privKey->keyType = keyType;
- privKey->pkcs11Slot = PK11_ReferenceSlot(slot);
- privKey->pkcs11ID = privID;
- privKey->pkcs11IsTemp = isTemp;
- privKey->wincx = wincx;
-
- return privKey;
-}
-
-/* return the keylength if possible. '0' if not */
-unsigned int
-PK11_GetKeyLength(PK11SymKey *key)
-{
- if (key->size != 0) return key->size ;
- if (key->data.data == NULL) {
- PK11_ExtractKeyValue(key);
- }
- /* key is probably secret. Look up it's type and length */
- /* this is new PKCS #11 version 2.0 functionality. */
- if (key->size == 0) {
- CK_ULONG keyLength;
-
- keyLength = PK11_ReadULongAttribute(key->slot,key->objectID,CKA_VALUE_LEN);
- /* doesn't have a length field, check the known PKCS #11 key types,
- * which don't have this field */
- if (keyLength == CK_UNAVAILABLE_INFORMATION) {
- CK_KEY_TYPE keyType;
- keyType = PK11_ReadULongAttribute(key->slot,key->objectID,CKA_KEY_TYPE);
- switch (keyType) {
- case CKK_DES: key->size = 8; break;
- case CKK_DES2: key->size = 16; break;
- case CKK_DES3: key->size = 24; break;
- case CKK_SKIPJACK: key->size = 10; break;
- case CKK_BATON: key->size = 20; break;
- case CKK_JUNIPER: key->size = 20; break;
- case CKK_GENERIC_SECRET:
- if (key->type == CKM_SSL3_PRE_MASTER_KEY_GEN) {
- key->size=48;
- }
- break;
- default: break;
- }
- } else {
- key->size = (unsigned int)keyLength;
- }
- }
-
- return key->size;
-}
-
-/* return the strength of a key. This is different from length in that
- * 1) it returns the size in bits, and 2) it returns only the secret portions
- * of the key minus any checksums or parity.
- */
-unsigned int
-PK11_GetKeyStrength(PK11SymKey *key, SECAlgorithmID *algid)
-{
- int size=0;
- CK_MECHANISM_TYPE mechanism= CKM_INVALID_MECHANISM; /* RC2 only */
- SECItem *param = NULL; /* RC2 only */
- CK_RC2_CBC_PARAMS *rc2_params = NULL; /* RC2 ONLY */
- unsigned int effectiveBits = 0; /* RC2 ONLY */
-
- switch (PK11_GetKeyType(key->type,0)) {
- case CKK_CDMF:
- return 40;
- case CKK_DES:
- return 56;
- case CKK_DES3:
- case CKK_DES2:
- size = PK11_GetKeyLength(key);
- if (size == 16) {
- /* double des */
- return 112; /* 16*7 */
- }
- return 168;
- /*
- * RC2 has is different than other ciphers in that it allows the user
- * to deprecating keysize while still requiring all the bits for the
- * original key. The info
- * on what the effective key strength is in the parameter for the key.
- * In S/MIME this parameter is stored in the DER encoded algid. In Our
- * other uses of RC2, effectiveBits == keyBits, so this code functions
- * correctly without an algid.
- */
- case CKK_RC2:
- /* if no algid was provided, fall through to default */
- if (!algid) {
- break;
- }
- /* verify that the algid is for RC2 */
- mechanism = PK11_AlgtagToMechanism(SECOID_GetAlgorithmTag(algid));
- if ((mechanism != CKM_RC2_CBC) && (mechanism != CKM_RC2_ECB)) {
- break;
- }
-
- /* now get effective bits from the algorithm ID. */
- param = PK11_ParamFromAlgid(algid);
- /* if we couldn't get memory just use key length */
- if (param == NULL) {
- break;
- }
-
- rc2_params = (CK_RC2_CBC_PARAMS *) param->data;
- /* paranoia... shouldn't happen */
- PORT_Assert(param->data != NULL);
- if (param->data == NULL) {
- SECITEM_FreeItem(param,PR_TRUE);
- break;
- }
- effectiveBits = (unsigned int)rc2_params->ulEffectiveBits;
- SECITEM_FreeItem(param,PR_TRUE);
- param = NULL; rc2_params=NULL; /* paranoia */
-
- /* we have effective bits, is and allocated memory is free, now
- * we need to return the smaller of effective bits and keysize */
- size = PK11_GetKeyLength(key);
- if ((unsigned int)size*8 > effectiveBits) {
- return effectiveBits;
- }
-
- return size*8; /* the actual key is smaller, the strength can't be
- * greater than the actual key size */
-
- default:
- break;
- }
- return PK11_GetKeyLength(key) * 8;
-}
-
-/* Make a Key type to an appropriate signing/verification mechanism */
-static CK_MECHANISM_TYPE
-pk11_mapSignKeyType(KeyType keyType)
-{
- switch (keyType) {
- case rsaKey:
- return CKM_RSA_PKCS;
- case fortezzaKey:
- case dsaKey:
- return CKM_DSA;
- case dhKey:
- default:
- break;
- }
- return CKM_INVALID_MECHANISM;
-}
-
-static CK_MECHANISM_TYPE
-pk11_mapWrapKeyType(KeyType keyType)
-{
- switch (keyType) {
- case rsaKey:
- return CKM_RSA_PKCS;
- /* Add fortezza?? */
- default:
- break;
- }
- return CKM_INVALID_MECHANISM;
-}
-
-/*
- * Some non-compliant PKCS #11 vendors do not give us the modulus, so actually
- * set up a signature to get the signaure length.
- */
-static int
-pk11_backupGetSignLength(SECKEYPrivateKey *key)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- CK_MECHANISM mech = {0, NULL, 0 };
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_ULONG len;
- CK_RV crv;
- unsigned char h_data[20] = { 0 };
- unsigned char buf[20]; /* obviously to small */
- CK_ULONG smallLen = sizeof(buf);
-
- mech.mechanism = pk11_mapSignKeyType(key->keyType);
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_SignInit(session,&mech,key->pkcs11ID);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return -1;
- }
- len = 0;
- crv = PK11_GETTAB(slot)->C_Sign(session,h_data,sizeof(h_data),
- NULL, &len);
- /* now call C_Sign with too small a buffer to clear the session state */
- (void) PK11_GETTAB(slot)->
- C_Sign(session,h_data,sizeof(h_data),buf,&smallLen);
-
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return -1;
- }
- return len;
-}
-/*
- * get the length of a signature object based on the key
- */
-int
-PK11_SignatureLen(SECKEYPrivateKey *key)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- int val;
-
- switch (key->keyType) {
- case rsaKey:
- val = PK11_GetPrivateModulusLen(key);
- if (val == -1) {
- break; /* failed */
- }
- return (unsigned long) val;
-
- case fortezzaKey:
- case dsaKey:
- return 40;
-
- default:
- break;
- }
- PORT_SetError( SEC_ERROR_INVALID_KEY );
- return 0;
-}
-
-PK11SlotInfo *
-PK11_GetSlotFromPrivateKey(SECKEYPrivateKey *key)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- slot = PK11_ReferenceSlot(slot);
- return slot;
-}
-
-/*
- * Get the modulus length for raw parsing
- */
-int
-PK11_GetPrivateModulusLen(SECKEYPrivateKey *key)
-{
- CK_ATTRIBUTE theTemplate = { CKA_MODULUS, NULL, 0 };
- PK11SlotInfo *slot = key->pkcs11Slot;
- CK_RV crv;
- int length;
-
- switch (key->keyType) {
- case rsaKey:
- crv = PK11_GetAttributes(NULL, slot, key->pkcs11ID, &theTemplate, 1);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return -1;
- }
- length = theTemplate.ulValueLen;
- if ( *(unsigned char *)theTemplate.pValue == 0) {
- length--;
- }
- if (theTemplate.pValue != NULL)
- PORT_Free(theTemplate.pValue);
- return (int) length;
-
- case fortezzaKey:
- case dsaKey:
- case dhKey:
- default:
- break;
- }
- if (theTemplate.pValue != NULL)
- PORT_Free(theTemplate.pValue);
- PORT_SetError( SEC_ERROR_INVALID_KEY );
- return -1;
-}
-
-/*
- * copy a key (or any other object) on a token
- */
-CK_OBJECT_HANDLE
-PK11_CopyKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE srcObject)
-{
- CK_OBJECT_HANDLE destObject;
- CK_RV crv;
-
- PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_CopyObject(slot->session,srcObject,NULL,0,
- &destObject);
- PK11_ExitSlotMonitor(slot);
- if (crv == CKR_OK) return destObject;
- PORT_SetError( PK11_MapError(crv) );
- return CK_INVALID_KEY;
-}
-
-
-PK11SymKey *
-pk11_KeyExchange(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
- CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey);
-
-/*
- * The next two utilities are to deal with the fact that a given operation
- * may be a multi-slot affair. This creates a new key object that is copied
- * into the new slot.
- */
-PK11SymKey *
-pk11_CopyToSlot(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
- CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey)
-{
- SECStatus rv;
- PK11SymKey *newKey = NULL;
-
- /* Extract the raw key data if possible */
- if (symKey->data.data == NULL) {
- rv = PK11_ExtractKeyValue(symKey);
- /* KEY is sensitive, we're try key exchanging it. */
- if (rv != SECSuccess) {
- return pk11_KeyExchange(slot, type, operation, symKey);
- }
- }
- newKey = PK11_ImportSymKey(slot, type, symKey->origin, operation,
- &symKey->data, symKey->cx);
- if (newKey == NULL) newKey = pk11_KeyExchange(slot,type,operation,symKey);
- return newKey;
-}
-
-/*
- * Make sure the slot we are in the correct slot for the operation
- */
-static PK11SymKey *
-pk11_ForceSlot(PK11SymKey *symKey,CK_MECHANISM_TYPE type,
- CK_ATTRIBUTE_TYPE operation)
-{
- PK11SlotInfo *slot = symKey->slot;
- PK11SymKey *newKey = NULL;
-
- if ((slot== NULL) || !PK11_DoesMechanism(slot,type)) {
- slot = PK11_GetBestSlot(type,symKey->cx);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return NULL;
- }
- newKey = pk11_CopyToSlot(slot, type, operation, symKey);
- PK11_FreeSlot(slot);
- }
- return newKey;
-}
-
-/*
- * Use the token to Generate a key. keySize must be 'zero' for fixed key
- * length algorithms. NOTE: this means we can never generate a DES2 key
- * from this interface!
- */
-PK11SymKey *
-PK11_TokenKeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
- int keySize, SECItem *keyid, PRBool isToken, void *wincx)
-{
- PK11SymKey *symKey;
- CK_ATTRIBUTE genTemplate[4];
- CK_ATTRIBUTE *attrs = genTemplate;
- int count = sizeof(genTemplate)/sizeof(genTemplate[0]);
- CK_SESSION_HANDLE session;
- CK_MECHANISM mechanism;
- CK_RV crv;
- PRBool weird = PR_FALSE; /* hack for fortezza */
- CK_BBOOL ckfalse = CK_FALSE;
- CK_BBOOL cktrue = CK_TRUE;
-
- if ((keySize == -1) && (type == CKM_SKIPJACK_CBC64)) {
- weird = PR_TRUE;
- keySize = 0;
- }
-
- /* TNH: Isn't this redundant, since "handleKey" will set defaults? */
- PK11_SETATTRS(attrs, (!weird)
- ? CKA_ENCRYPT : CKA_DECRYPT, &cktrue, sizeof(CK_BBOOL)); attrs++;
-
- if (keySize != 0) {
- CK_ULONG key_size = keySize; /* Convert to PK11 type */
-
- PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size));
- attrs++;
- }
-
- /* Include key id value if provided */
- if (keyid) {
- PK11_SETATTRS(attrs, CKA_ID, keyid->data, keyid->len); attrs++;
- }
-
- if (isToken) {
- PK11_SETATTRS(attrs, CKA_TOKEN, &cktrue, sizeof(cktrue)); attrs++;
- }
-
- count = attrs - genTemplate;
- PR_ASSERT(count <= sizeof(genTemplate)/sizeof(CK_ATTRIBUTE));
-
- /* find a slot to generate the key into */
- /* Only do slot management if this is not a token key */
- if (!isToken && (slot == NULL || !PK11_DoesMechanism(slot,type))) {
- PK11SlotInfo *bestSlot;
-
- bestSlot = PK11_GetBestSlot(type,wincx); /* TNH: references the slot? */
- if (bestSlot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return NULL;
- }
-
- symKey = PK11_CreateSymKey(bestSlot,type,wincx);
-
- PK11_FreeSlot(bestSlot);
- } else {
- symKey = PK11_CreateSymKey(slot, type, wincx);
- }
- if (symKey == NULL) return NULL;
-
- symKey->size = keySize;
- symKey->origin = (!weird) ? PK11_OriginGenerated : PK11_OriginFortezzaHack;
-
- /* Initialize the Key Gen Mechanism */
- mechanism.mechanism = PK11_GetKeyGen(type);
- if (mechanism.mechanism == CKM_FAKE_RANDOM) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return NULL;
- }
-
- /* Set the parameters for the key gen if provided */
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
- if (param) {
- mechanism.pParameter = param->data;
- mechanism.ulParameterLen = param->len;
- }
-
- /* Get session and perform locking */
- if (isToken) {
- session = PK11_GetRWSession(symKey->slot); /* Should always be original slot */
- } else {
- session = symKey->session;
- pk11_EnterKeyMonitor(symKey);
- }
-
- crv = PK11_GETTAB(symKey->slot)->C_GenerateKey(session,
- &mechanism, genTemplate, count, &symKey->objectID);
-
- /* Release lock and session */
- if (isToken) {
- PK11_RestoreROSession(symKey->slot, session);
- } else {
- pk11_ExitKeyMonitor(symKey);
- }
-
- if (crv != CKR_OK) {
- PK11_FreeSymKey(symKey);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
-
- return symKey;
-}
-
-PK11SymKey *
-PK11_KeyGen(PK11SlotInfo *slot, CK_MECHANISM_TYPE type, SECItem *param,
- int keySize, void *wincx)
-{
- return PK11_TokenKeyGen(slot, type, param, keySize, 0, PR_FALSE, wincx);
-}
-
-/* --- */
-PK11SymKey *
-PK11_GenDES3TokenKey(PK11SlotInfo *slot, SECItem *keyid, void *cx)
-{
- return PK11_TokenKeyGen(slot, CKM_DES3_CBC, 0, 0, keyid, PR_TRUE, cx);
-}
-
-/*
- * PKCS #11 pairwise consistency check utilized to validate key pair.
- */
-static SECStatus
-pk11_PairwiseConsistencyCheck(SECKEYPublicKey *pubKey,
- SECKEYPrivateKey *privKey, CK_MECHANISM *mech, void* wincx )
-{
- /* Variables used for Encrypt/Decrypt functions. */
- unsigned char *known_message = (unsigned char *)"Known Crypto Message";
- CK_BBOOL isEncryptable = CK_FALSE;
- CK_BBOOL canSignVerify = CK_FALSE;
- CK_BBOOL isDerivable = CK_FALSE;
- unsigned char plaintext[PAIRWISE_MESSAGE_LENGTH];
- CK_ULONG bytes_decrypted;
- PK11SlotInfo *slot;
- CK_OBJECT_HANDLE id;
- unsigned char *ciphertext;
- unsigned char *text_compared;
- CK_ULONG max_bytes_encrypted;
- CK_ULONG bytes_encrypted;
- CK_ULONG bytes_compared;
- CK_RV crv;
-
- /* Variables used for Signature/Verification functions. */
- unsigned char *known_digest = (unsigned char *)"Mozilla Rules World!";
- SECItem signature;
- SECItem digest; /* always uses SHA-1 digest */
- int signature_length;
- SECStatus rv;
-
- /**************************************************/
- /* Pairwise Consistency Check of Encrypt/Decrypt. */
- /**************************************************/
-
- isEncryptable = PK11_HasAttributeSet( privKey->pkcs11Slot,
- privKey->pkcs11ID, CKA_DECRYPT );
-
- /* If the encryption attribute is set; attempt to encrypt */
- /* with the public key and decrypt with the private key. */
- if( isEncryptable ) {
- /* Find a module to encrypt against */
- slot = PK11_GetBestSlot(pk11_mapWrapKeyType(privKey->keyType),wincx);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return SECFailure;
- }
-
- id = PK11_ImportPublicKey(slot,pubKey,PR_FALSE);
- if (id == CK_INVALID_KEY) {
- PK11_FreeSlot(slot);
- return SECFailure;
- }
-
- /* Compute max bytes encrypted from modulus length of private key. */
- max_bytes_encrypted = PK11_GetPrivateModulusLen( privKey );
-
-
- /* Prepare for encryption using the public key. */
- PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB( slot )->C_EncryptInit( slot->session,
- mech, id );
- if( crv != CKR_OK ) {
- PK11_ExitSlotMonitor(slot);
- PORT_SetError( PK11_MapError( crv ) );
- PK11_FreeSlot(slot);
- return SECFailure;
- }
-
- /* Allocate space for ciphertext. */
- ciphertext = (unsigned char *) PORT_Alloc( max_bytes_encrypted );
- if( ciphertext == NULL ) {
- PK11_ExitSlotMonitor(slot);
- PORT_SetError( SEC_ERROR_NO_MEMORY );
- PK11_FreeSlot(slot);
- return SECFailure;
- }
-
- /* Initialize bytes encrypted to max bytes encrypted. */
- bytes_encrypted = max_bytes_encrypted;
-
- /* Encrypt using the public key. */
- crv = PK11_GETTAB( slot )->C_Encrypt( slot->session,
- known_message,
- PAIRWISE_MESSAGE_LENGTH,
- ciphertext,
- &bytes_encrypted );
- PK11_ExitSlotMonitor(slot);
- PK11_FreeSlot(slot);
- if( crv != CKR_OK ) {
- PORT_SetError( PK11_MapError( crv ) );
- PORT_Free( ciphertext );
- return SECFailure;
- }
-
- /* Always use the smaller of these two values . . . */
- bytes_compared = ( bytes_encrypted > PAIRWISE_MESSAGE_LENGTH )
- ? PAIRWISE_MESSAGE_LENGTH
- : bytes_encrypted;
-
- /* If there was a failure, the plaintext */
- /* goes at the end, therefore . . . */
- text_compared = ( bytes_encrypted > PAIRWISE_MESSAGE_LENGTH )
- ? (ciphertext + bytes_encrypted -
- PAIRWISE_MESSAGE_LENGTH )
- : ciphertext;
-
- /* Check to ensure that ciphertext does */
- /* NOT EQUAL known input message text */
- /* per FIPS PUB 140-1 directive. */
- if( ( bytes_encrypted != max_bytes_encrypted ) ||
- ( PORT_Memcmp( text_compared, known_message,
- bytes_compared ) == 0 ) ) {
- /* Set error to Invalid PRIVATE Key. */
- PORT_SetError( SEC_ERROR_INVALID_KEY );
- PORT_Free( ciphertext );
- return SECFailure;
- }
-
- slot = privKey->pkcs11Slot;
- /* Prepare for decryption using the private key. */
- PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB( slot )->C_DecryptInit( slot->session,
- mech,
- privKey->pkcs11ID );
- if( crv != CKR_OK ) {
- PK11_ExitSlotMonitor(slot);
- PORT_SetError( PK11_MapError(crv) );
- PORT_Free( ciphertext );
- PK11_FreeSlot(slot);
- return SECFailure;
- }
-
- /* Initialize bytes decrypted to be the */
- /* expected PAIRWISE_MESSAGE_LENGTH. */
- bytes_decrypted = PAIRWISE_MESSAGE_LENGTH;
-
- /* Decrypt using the private key. */
- /* NOTE: No need to reset the */
- /* value of bytes_encrypted. */
- crv = PK11_GETTAB( slot )->C_Decrypt( slot->session,
- ciphertext,
- bytes_encrypted,
- plaintext,
- &bytes_decrypted );
- PK11_ExitSlotMonitor(slot);
-
- /* Finished with ciphertext; free it. */
- PORT_Free( ciphertext );
-
- if( crv != CKR_OK ) {
- PORT_SetError( PK11_MapError(crv) );
- PK11_FreeSlot(slot);
- return SECFailure;
- }
-
- /* Check to ensure that the output plaintext */
- /* does EQUAL known input message text. */
- if( ( bytes_decrypted != PAIRWISE_MESSAGE_LENGTH ) ||
- ( PORT_Memcmp( plaintext, known_message,
- PAIRWISE_MESSAGE_LENGTH ) != 0 ) ) {
- /* Set error to Bad PUBLIC Key. */
- PORT_SetError( SEC_ERROR_BAD_KEY );
- PK11_FreeSlot(slot);
- return SECFailure;
- }
- }
-
- /**********************************************/
- /* Pairwise Consistency Check of Sign/Verify. */
- /**********************************************/
-
- canSignVerify = PK11_HasAttributeSet ( privKey->pkcs11Slot,
- privKey->pkcs11ID, CKA_VERIFY);
-
- if (canSignVerify)
- {
- /* Initialize signature and digest data. */
- signature.data = NULL;
- digest.data = NULL;
-
- /* Determine length of signature. */
- signature_length = PK11_SignatureLen( privKey );
- if( signature_length == 0 )
- goto failure;
-
- /* Allocate space for signature data. */
- signature.data = (unsigned char *) PORT_Alloc( signature_length );
- if( signature.data == NULL ) {
- PORT_SetError( SEC_ERROR_NO_MEMORY );
- goto failure;
- }
-
- /* Allocate space for known digest data. */
- digest.data = (unsigned char *) PORT_Alloc( PAIRWISE_DIGEST_LENGTH );
- if( digest.data == NULL ) {
- PORT_SetError( SEC_ERROR_NO_MEMORY );
- goto failure;
- }
-
- /* "Fill" signature type and length. */
- signature.type = PAIRWISE_SECITEM_TYPE;
- signature.len = signature_length;
-
- /* "Fill" digest with known SHA-1 digest parameters. */
- digest.type = PAIRWISE_SECITEM_TYPE;
- PORT_Memcpy( digest.data, known_digest, PAIRWISE_DIGEST_LENGTH );
- digest.len = PAIRWISE_DIGEST_LENGTH;
-
- /* Sign the known hash using the private key. */
- rv = PK11_Sign( privKey, &signature, &digest );
- if( rv != SECSuccess )
- goto failure;
-
- /* Verify the known hash using the public key. */
- rv = PK11_Verify( pubKey, &signature, &digest, wincx );
- if( rv != SECSuccess )
- goto failure;
-
- /* Free signature and digest data. */
- PORT_Free( signature.data );
- PORT_Free( digest.data );
- }
-
-
-
- /**********************************************/
- /* Pairwise Consistency Check for Derivation */
- /**********************************************/
-
- isDerivable = PK11_HasAttributeSet ( privKey->pkcs11Slot,
- privKey->pkcs11ID, CKA_DERIVE);
-
- if (isDerivable)
- {
- /*
- * We are not doing consistency check for Diffie-Hellman Key -
- * otherwise it would be here
- */
-
- }
-
- return SECSuccess;
-
-failure:
- if( signature.data != NULL )
- PORT_Free( signature.data );
- if( digest.data != NULL )
- PORT_Free( digest.data );
-
- return SECFailure;
-}
-
-
-
-/*
- * take a private key in one pkcs11 module and load it into another:
- * NOTE: the source private key is a rare animal... it can't be sensitive.
- * This is used to do a key gen using one pkcs11 module and storing the
- * result into another.
- */
-SECKEYPrivateKey *
-pk11_loadPrivKey(PK11SlotInfo *slot,SECKEYPrivateKey *privKey,
- SECKEYPublicKey *pubKey, PRBool token, PRBool sensitive)
-{
- CK_ATTRIBUTE privTemplate[] = {
- /* class must be first */
- { CKA_CLASS, NULL, 0 },
- { CKA_KEY_TYPE, NULL, 0 },
- /* these three must be next */
- { CKA_TOKEN, NULL, 0 },
- { CKA_PRIVATE, NULL, 0 },
- { CKA_SENSITIVE, NULL, 0 },
- { CKA_ID, NULL, 0 },
-#ifdef notdef
- { CKA_LABEL, NULL, 0 },
- { CKA_SUBJECT, NULL, 0 },
-#endif
- /* RSA */
- { CKA_MODULUS, NULL, 0 },
- { CKA_PRIVATE_EXPONENT, NULL, 0 },
- { CKA_PUBLIC_EXPONENT, NULL, 0 },
- { CKA_PRIME_1, NULL, 0 },
- { CKA_PRIME_2, NULL, 0 },
- { CKA_EXPONENT_1, NULL, 0 },
- { CKA_EXPONENT_2, NULL, 0 },
- { CKA_COEFFICIENT, NULL, 0 },
- };
- CK_ATTRIBUTE *attrs = NULL, *ap;
- int templateSize = sizeof(privTemplate)/sizeof(privTemplate[0]);
- PRArenaPool *arena;
- CK_OBJECT_HANDLE objectID;
- int i, count = 0;
- int extra_count = 0;
- CK_RV crv;
- SECStatus rv;
-
- for (i=0; i < templateSize; i++) {
- if (privTemplate[i].type == CKA_MODULUS) {
- attrs= &privTemplate[i];
- count = i;
- break;
- }
- }
- PORT_Assert(attrs != NULL);
- if (attrs == NULL) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return NULL;
- }
-
- ap = attrs;
-
- switch (privKey->keyType) {
- case rsaKey:
- count = templateSize;
- extra_count = templateSize - (attrs - privTemplate);
- break;
- case dsaKey:
- ap->type = CKA_PRIME; ap++; count++; extra_count++;
- ap->type = CKA_SUBPRIME; ap++; count++; extra_count++;
- ap->type = CKA_BASE; ap++; count++; extra_count++;
- ap->type = CKA_VALUE; ap++; count++; extra_count++;
- break;
- case dhKey:
- ap->type = CKA_PRIME; ap++; count++; extra_count++;
- ap->type = CKA_BASE; ap++; count++; extra_count++;
- ap->type = CKA_VALUE; ap++; count++; extra_count++;
- break;
- default:
- count = 0;
- extra_count = 0;
- break;
- }
-
- if (count == 0) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return NULL;
- }
-
- arena = PORT_NewArena( DER_DEFAULT_CHUNKSIZE);
- if (arena == NULL) return NULL;
- /*
- * read out the old attributes.
- */
- crv = PK11_GetAttributes(arena, privKey->pkcs11Slot, privKey->pkcs11ID,
- privTemplate,count);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- PORT_FreeArena(arena, PR_TRUE);
- return NULL;
- }
-
- /* Reset sensitive, token, and private */
- *(CK_BBOOL *)(privTemplate[2].pValue) = token ? CK_TRUE : CK_FALSE;
- *(CK_BBOOL *)(privTemplate[3].pValue) = token ? CK_TRUE : CK_FALSE;
- *(CK_BBOOL *)(privTemplate[4].pValue) = sensitive ? CK_TRUE : CK_FALSE;
-
- /* Not everyone can handle zero padded key values, give
- * them the raw data as unsigned */
- for (ap=attrs; extra_count; ap++, extra_count--) {
- pk11_SignedToUnsigned(ap);
- }
-
- /* now Store the puppies */
- rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION, privTemplate,
- count, token, &objectID);
- PORT_FreeArena(arena, PR_TRUE);
- if (rv != SECSuccess) {
- return NULL;
- }
-
- /* try loading the public key as a token object */
- if (pubKey) {
- PK11_ImportPublicKey(slot, pubKey, PR_TRUE);
- if (pubKey->pkcs11Slot) {
- PK11_FreeSlot(pubKey->pkcs11Slot);
- pubKey->pkcs11Slot = NULL;
- pubKey->pkcs11ID = CK_INVALID_KEY;
- }
- }
-
- /* build new key structure */
- return PK11_MakePrivKey(slot, privKey->keyType, (PRBool)!token,
- objectID, privKey->wincx);
-}
-
-
-/*
- * Use the token to Generate a key. keySize must be 'zero' for fixed key
- * length algorithms. NOTE: this means we can never generate a DES2 key
- * from this interface!
- */
-SECKEYPrivateKey *
-PK11_GenerateKeyPair(PK11SlotInfo *slot,CK_MECHANISM_TYPE type,
- void *param, SECKEYPublicKey **pubKey, PRBool token,
- PRBool sensitive, void *wincx)
-{
- /* we have to use these native types because when we call PKCS 11 modules
- * we have to make sure that we are using the correct sizes for all the
- * parameters. */
- CK_BBOOL ckfalse = CK_FALSE;
- CK_BBOOL cktrue = CK_TRUE;
- CK_ULONG modulusBits;
- CK_BYTE publicExponent[4];
- CK_ATTRIBUTE privTemplate[] = {
- { CKA_SENSITIVE, NULL, 0},
- { CKA_TOKEN, NULL, 0},
- { CKA_PRIVATE, NULL, 0},
- { CKA_DERIVE, NULL, 0},
- { CKA_UNWRAP, NULL, 0},
- { CKA_SIGN, NULL, 0},
- { CKA_DECRYPT, NULL, 0},
- };
- CK_ATTRIBUTE rsaPubTemplate[] = {
- { CKA_MODULUS_BITS, NULL, 0},
- { CKA_PUBLIC_EXPONENT, NULL, 0},
- { CKA_TOKEN, NULL, 0},
- { CKA_DERIVE, NULL, 0},
- { CKA_WRAP, NULL, 0},
- { CKA_VERIFY, NULL, 0},
- { CKA_VERIFY_RECOVER, NULL, 0},
- { CKA_ENCRYPT, NULL, 0},
- };
- CK_ATTRIBUTE dsaPubTemplate[] = {
- { CKA_PRIME, NULL, 0 },
- { CKA_SUBPRIME, NULL, 0 },
- { CKA_BASE, NULL, 0 },
- { CKA_TOKEN, NULL, 0},
- { CKA_DERIVE, NULL, 0},
- { CKA_WRAP, NULL, 0},
- { CKA_VERIFY, NULL, 0},
- { CKA_VERIFY_RECOVER, NULL, 0},
- { CKA_ENCRYPT, NULL, 0},
- };
- CK_ATTRIBUTE dhPubTemplate[] = {
- { CKA_PRIME, NULL, 0 },
- { CKA_BASE, NULL, 0 },
- { CKA_TOKEN, NULL, 0},
- { CKA_DERIVE, NULL, 0},
- { CKA_WRAP, NULL, 0},
- { CKA_VERIFY, NULL, 0},
- { CKA_VERIFY_RECOVER, NULL, 0},
- { CKA_ENCRYPT, NULL, 0},
- };
-
- int dsaPubCount = sizeof(dsaPubTemplate)/sizeof(dsaPubTemplate[0]);
- /*CK_ULONG key_size = 0;*/
- CK_ATTRIBUTE *pubTemplate;
- int privCount = sizeof(privTemplate)/sizeof(privTemplate[0]);
- int rsaPubCount = sizeof(rsaPubTemplate)/sizeof(rsaPubTemplate[0]);
- int dhPubCount = sizeof(dhPubTemplate)/sizeof(dhPubTemplate[0]);
- int pubCount = 0;
- PK11RSAGenParams *rsaParams;
- PQGParams *dsaParams;
- DHParams * dhParams;
- CK_MECHANISM mechanism;
- CK_MECHANISM test_mech;
- CK_SESSION_HANDLE session_handle;
- CK_RV crv;
- CK_OBJECT_HANDLE privID,pubID;
- SECKEYPrivateKey *privKey;
- KeyType keyType;
- PRBool restore;
- int peCount,i;
- CK_ATTRIBUTE *attrs;
- CK_ATTRIBUTE *privattrs;
- SECItem *pubKeyIndex;
- CK_ATTRIBUTE setTemplate;
- SECStatus rv;
- CK_MECHANISM_INFO mechanism_info;
- CK_OBJECT_CLASS keyClass;
- SECItem *cka_id;
- PRBool haslock = PR_FALSE;
- PRBool pubIsToken = PR_FALSE;
-
- PORT_Assert(slot != NULL);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE);
- return NULL;
- }
-
- /* if our slot really doesn't do this mechanism, Generate the key
- * in our internal token and write it out */
- if (!PK11_DoesMechanism(slot,type)) {
- PK11SlotInfo *int_slot = PK11_GetInternalSlot();
-
- /* don't loop forever looking for a slot */
- if (slot == int_slot) {
- PK11_FreeSlot(int_slot);
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return NULL;
- }
-
- /* if there isn't a suitable slot, then we can't do the keygen */
- if (int_slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return NULL;
- }
-
- /* generate the temporary key to load */
- privKey = PK11_GenerateKeyPair(int_slot,type, param, pubKey, PR_FALSE,
- PR_FALSE, wincx);
- PK11_FreeSlot(int_slot);
-
- /* if successful, load the temp key into the new token */
- if (privKey != NULL) {
- SECKEYPrivateKey *newPrivKey = pk11_loadPrivKey(slot,privKey,
- *pubKey,token,sensitive);
- SECKEY_DestroyPrivateKey(privKey);
- if (newPrivKey == NULL) {
- SECKEY_DestroyPublicKey(*pubKey);
- *pubKey = NULL;
- }
- return newPrivKey;
- }
- return NULL;
- }
-
-
- mechanism.mechanism = type;
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
- test_mech.pParameter = NULL;
- test_mech.ulParameterLen = 0;
-
- /* set up the private key template */
- privattrs = privTemplate;
- PK11_SETATTRS(privattrs, CKA_SENSITIVE, sensitive ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
- PK11_SETATTRS(privattrs, CKA_TOKEN, token ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
- PK11_SETATTRS(privattrs, CKA_PRIVATE, sensitive ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
-
- /* set up the mechanism specific info */
- switch (type) {
- case CKM_RSA_PKCS_KEY_PAIR_GEN:
- rsaParams = (PK11RSAGenParams *)param;
- modulusBits = rsaParams->keySizeInBits;
- peCount = 0;
-
- /* convert pe to a PKCS #11 string */
- for (i=0; i < 4; i++) {
- if (peCount || (rsaParams->pe &
- ((unsigned long)0xff000000L >> (i*8)))) {
- publicExponent[peCount] =
- (CK_BYTE)((rsaParams->pe >> (3-i)*8) & 0xff);
- peCount++;
- }
- }
- PORT_Assert(peCount != 0);
- attrs = rsaPubTemplate;
- PK11_SETATTRS(attrs, CKA_MODULUS_BITS,
- &modulusBits, sizeof(modulusBits)); attrs++;
- PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
- publicExponent, peCount);attrs++;
- pubTemplate = rsaPubTemplate;
- pubCount = rsaPubCount;
- keyType = rsaKey;
- test_mech.mechanism = CKM_RSA_PKCS;
- break;
- case CKM_DSA_KEY_PAIR_GEN:
- dsaParams = (PQGParams *)param;
- attrs = dsaPubTemplate;
- PK11_SETATTRS(attrs, CKA_PRIME, dsaParams->prime.data,
- dsaParams->prime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_SUBPRIME, dsaParams->subPrime.data,
- dsaParams->subPrime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, dsaParams->base.data,
- dsaParams->base.len); attrs++;
- pubTemplate = dsaPubTemplate;
- pubCount = dsaPubCount;
- keyType = dsaKey;
- test_mech.mechanism = CKM_DSA;
- break;
- case CKM_DH_PKCS_KEY_PAIR_GEN:
- dhParams = (DHParams *)param;
- attrs = dhPubTemplate;
- PK11_SETATTRS(attrs, CKA_PRIME, dhParams->prime.data,
- dhParams->prime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, dhParams->base.data,
- dhParams->base.len); attrs++;
- pubTemplate = dhPubTemplate;
- pubCount = dhPubCount;
- keyType = dhKey;
- test_mech.mechanism = CKM_DH_PKCS_DERIVE;
- break;
- default:
- PORT_SetError( SEC_ERROR_BAD_KEY );
- return NULL;
- }
-
- /* now query the slot to find out how "good" a key we can generate */
- if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,
- test_mech.mechanism,&mechanism_info);
- if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
- if ((crv != CKR_OK) || (mechanism_info.flags == 0)) {
- /* must be old module... guess what it should be... */
- switch (test_mech.mechanism) {
- case CKM_RSA_PKCS:
- mechanism_info.flags = (CKF_SIGN | CKF_DECRYPT |
- CKF_WRAP | CKF_VERIFY_RECOVER | CKF_ENCRYPT | CKF_WRAP);;
- break;
- case CKM_DSA:
- mechanism_info.flags = CKF_SIGN | CKF_VERIFY;
- break;
- case CKM_DH_PKCS_DERIVE:
- mechanism_info.flags = CKF_DERIVE;
- break;
- default:
- break;
- }
- }
- /* set the public key objects */
- PK11_SETATTRS(attrs, CKA_TOKEN, token ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(attrs, CKA_DERIVE,
- mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(attrs, CKA_WRAP,
- mechanism_info.flags & CKF_WRAP ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(attrs, CKA_VERIFY,
- mechanism_info.flags & CKF_VERIFY ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(attrs, CKA_VERIFY_RECOVER,
- mechanism_info.flags & CKF_VERIFY_RECOVER ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(attrs, CKA_ENCRYPT,
- mechanism_info.flags & CKF_ENCRYPT? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(privattrs, CKA_DERIVE,
- mechanism_info.flags & CKF_DERIVE ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
- PK11_SETATTRS(privattrs, CKA_UNWRAP,
- mechanism_info.flags & CKF_UNWRAP ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
- PK11_SETATTRS(privattrs, CKA_SIGN,
- mechanism_info.flags & CKF_SIGN ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
- PK11_SETATTRS(privattrs, CKA_DECRYPT,
- mechanism_info.flags & CKF_DECRYPT ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL)); privattrs++;
-
- if (token) {
- session_handle = PK11_GetRWSession(slot);
- haslock = PK11_RWSessionHasLock(slot,session_handle);
- restore = PR_TRUE;
- } else {
- PK11_EnterSlotMonitor(slot); /* gross!! */
- session_handle = slot->session;
- restore = PR_FALSE;
- haslock = PR_TRUE;
- }
-
- crv = PK11_GETTAB(slot)->C_GenerateKeyPair(session_handle, &mechanism,
- pubTemplate,pubCount,privTemplate,privCount,&pubID,&privID);
-
-
- if (crv != CKR_OK) {
- if (restore) {
- PK11_RestoreROSession(slot,session_handle);
- } else PK11_ExitSlotMonitor(slot);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
- /* This locking code is dangerous and needs to be more thought
- * out... the real problem is that we're holding the mutex open this long
- */
- if (haslock) { PK11_ExitSlotMonitor(slot); }
-
- /* swap around the ID's for older PKCS #11 modules */
- keyClass = PK11_ReadULongAttribute(slot,pubID,CKA_CLASS);
- if (keyClass != CKO_PUBLIC_KEY) {
- CK_OBJECT_HANDLE tmp = pubID;
- pubID = privID;
- privID = tmp;
- }
-
- *pubKey = PK11_ExtractPublicKey(slot, keyType, pubID);
- if (*pubKey == NULL) {
- if (restore) {
- /* we may have to restore the mutex so it get's exited properly
- * in RestoreROSession */
- if (haslock) PK11_EnterSlotMonitor(slot);
- PK11_RestoreROSession(slot,session_handle);
- }
- PK11_DestroyObject(slot,pubID);
- PK11_DestroyObject(slot,privID);
- return NULL;
- }
-
- /* set the ID to the public key so we can find it again */
- pubKeyIndex = NULL;
- switch (type) {
- case CKM_RSA_PKCS_KEY_PAIR_GEN:
- pubKeyIndex = &(*pubKey)->u.rsa.modulus;
- break;
- case CKM_DSA_KEY_PAIR_GEN:
- pubKeyIndex = &(*pubKey)->u.dsa.publicValue;
- break;
- case CKM_DH_PKCS_KEY_PAIR_GEN:
- pubKeyIndex = &(*pubKey)->u.dh.publicValue;
- break;
- }
- PORT_Assert(pubKeyIndex != NULL);
-
- cka_id = PK11_MakeIDFromPubKey(pubKeyIndex);
- pubIsToken = (PRBool)PK11_HasAttributeSet(slot,pubID, CKA_TOKEN);
-
- PK11_SETATTRS(&setTemplate, CKA_ID, cka_id->data, cka_id->len);
-
- if (haslock) { PK11_EnterSlotMonitor(slot); }
- crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, privID,
- &setTemplate, 1);
-
- if (crv == CKR_OK && pubIsToken) {
- crv = PK11_GETTAB(slot)->C_SetAttributeValue(session_handle, pubID,
- &setTemplate, 1);
- }
-
-
- if (restore) {
- PK11_RestoreROSession(slot,session_handle);
- } else {
- PK11_ExitSlotMonitor(slot);
- }
- SECITEM_FreeItem(cka_id,PR_TRUE);
-
-
- if (crv != CKR_OK) {
- PK11_DestroyObject(slot,pubID);
- PK11_DestroyObject(slot,privID);
- PORT_SetError( PK11_MapError(crv) );
- *pubKey = NULL;
- return NULL;
- }
-
- privKey = PK11_MakePrivKey(slot,keyType,(PRBool)!token,privID,wincx);
- if (privKey == NULL) {
- SECKEY_DestroyPublicKey(*pubKey);
- PK11_DestroyObject(slot,privID);
- *pubKey = NULL;
- return NULL; /* due to pairwise consistency check */
- }
-
- /* Perform PKCS #11 pairwise consistency check. */
- rv = pk11_PairwiseConsistencyCheck( *pubKey, privKey, &test_mech, wincx );
- if( rv != SECSuccess ) {
- SECKEY_DestroyPublicKey( *pubKey );
- SECKEY_DestroyPrivateKey( privKey );
- *pubKey = NULL;
- privKey = NULL;
- return NULL;
- }
-
- return privKey;
-}
-
-/*
- * This function does a straight public key wrap (which only RSA can do).
- * Use PK11_PubGenKey and PK11_WrapSymKey to implement the FORTEZZA and
- * Diffie-Hellman Ciphers. */
-SECStatus
-PK11_PubWrapSymKey(CK_MECHANISM_TYPE type, SECKEYPublicKey *pubKey,
- PK11SymKey *symKey, SECItem *wrappedKey)
-{
- PK11SlotInfo *slot;
- CK_ULONG len = wrappedKey->len;
- PK11SymKey *newKey = NULL;
- CK_OBJECT_HANDLE id;
- CK_MECHANISM mechanism;
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_RV crv;
-
- /* if this slot doesn't support the mechanism, go to a slot that does */
- newKey = pk11_ForceSlot(symKey,type,CKA_ENCRYPT);
- if (newKey != NULL) {
- symKey = newKey;
- }
-
- if ((symKey == NULL) || (symKey->slot == NULL)) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return SECFailure;
- }
-
- slot = symKey->slot;
- mechanism.mechanism = pk11_mapWrapKeyType(pubKey->keyType);
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
-
- id = PK11_ImportPublicKey(slot,pubKey,PR_FALSE);
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_WrapKey(session,&mechanism,
- id,symKey->objectID,wrappedKey->data,&len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- if (newKey) {
- PK11_FreeSymKey(newKey);
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- wrappedKey->len = len;
- return SECSuccess;
-}
-
-/*
- * this little function uses the Encrypt function to wrap a key, just in
- * case we have problems with the wrap implementation for a token.
- */
-static SECStatus
-pk11_HandWrap(PK11SymKey *wrappingKey, SECItem *param, CK_MECHANISM_TYPE type,
- SECItem *inKey, SECItem *outKey)
-{
- PK11SlotInfo *slot;
- CK_ULONG len;
- SECItem *data;
- CK_MECHANISM mech;
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_RV crv;
-
- slot = wrappingKey->slot;
- /* use NULL IV's for wrapping */
- mech.mechanism = type;
- if (param) {
- mech.pParameter = param->data;
- mech.ulParameterLen = param->len;
- } else {
- mech.pParameter = NULL;
- mech.ulParameterLen = 0;
- }
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_EncryptInit(session,&mech,
- wrappingKey->objectID);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
-
- /* keys are almost always aligned, but if we get this far,
- * we've gone above and beyond anyway... */
- data = PK11_BlockData(inKey,PK11_GetBlockSize(type,param));
- if (data == NULL) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError(SEC_ERROR_NO_MEMORY);
- return SECFailure;
- }
- len = outKey->len;
- crv = PK11_GETTAB(slot)->C_Encrypt(session,data->data,data->len,
- outKey->data, &len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- SECITEM_FreeItem(data,PR_TRUE);
- outKey->len = len;
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/*
- * This function does a symetric based wrap.
- */
-SECStatus
-PK11_WrapSymKey(CK_MECHANISM_TYPE type, SECItem *param,
- PK11SymKey *wrappingKey, PK11SymKey *symKey, SECItem *wrappedKey)
-{
- PK11SlotInfo *slot;
- CK_ULONG len = wrappedKey->len;
- PK11SymKey *newKey = NULL;
- SECItem *param_save = NULL;
- CK_MECHANISM mechanism;
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_RV crv;
- SECStatus rv;
-
- /* if this slot doesn't support the mechanism, go to a slot that does */
- /* Force symKey and wrappingKey into the same slot */
- if ((wrappingKey->slot == NULL) || (symKey->slot != wrappingKey->slot)) {
- /* first try copying the wrapping Key to the symKey slot */
- if (symKey->slot && PK11_DoesMechanism(symKey->slot,type)) {
- newKey = pk11_CopyToSlot(symKey->slot,type,CKA_WRAP,wrappingKey);
- }
- /* Nope, try it the other way */
- if (newKey == NULL) {
- if (wrappingKey->slot) {
- newKey = pk11_CopyToSlot(wrappingKey->slot,
- symKey->type, CKA_ENCRYPT, symKey);
- }
- /* just not playing... one last thing, can we get symKey's data?
- * If it's possible, we it should already be in the
- * symKey->data.data pointer because pk11_CopyToSlot would have
- * tried to put it there. */
- if (newKey == NULL) {
- /* Can't get symKey's data: Game Over */
- if (symKey->data.data == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return SECFailure;
- }
- if (param == NULL) {
- param_save = param = PK11_ParamFromIV(type,NULL);
- }
- rv = pk11_HandWrap(wrappingKey, param, type,
- &symKey->data,wrappedKey);
- if (param_save) SECITEM_FreeItem(param_save,PR_TRUE);
- return rv;
- }
- /* we successfully moved the sym Key */
- symKey = newKey;
- } else {
- /* we successfully moved the wrapping Key */
- wrappingKey = newKey;
- }
- }
-
- /* at this point both keys are in the same token */
- slot = wrappingKey->slot;
- mechanism.mechanism = type;
- /* use NULL IV's for wrapping */
- if (param == NULL) {
- param_save = param = PK11_ParamFromIV(type,NULL);
- }
- if (param) {
- mechanism.pParameter = param->data;
- mechanism.ulParameterLen = param->len;
- } else {
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
- }
-
- len = wrappedKey->len;
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_WrapKey(session, &mechanism,
- wrappingKey->objectID, symKey->objectID,
- wrappedKey->data, &len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- rv = SECSuccess;
- if (crv != CKR_OK) {
- /* can't wrap it? try hand wrapping it... */
- do {
- if (symKey->data.data == NULL) {
- rv = PK11_ExtractKeyValue(symKey);
- if (rv != SECSuccess) break;
- }
- rv = pk11_HandWrap(wrappingKey, param, type, &symKey->data,
- wrappedKey);
- } while (PR_FALSE);
- } else {
- wrappedKey->len = len;
- }
- if (newKey) PK11_FreeSymKey(newKey);
- if (param_save) SECITEM_FreeItem(param_save,PR_TRUE);
- return rv;
-}
-
-/*
- * This Generates a new key based on a symetricKey
- */
-PK11SymKey *
-PK11_Derive( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive, SECItem *param,
- CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
- int keySize)
-{
- return pk11_DeriveWithTemplate(baseKey, derive, param, target, operation,
- keySize, NULL, 0);
-}
-
-#define MAX_TEMPL_ATTRS 16 /* maximum attributes in template */
-
-/* This mask includes all CK_FLAGs with an equivalent CKA_ attribute. */
-#define CKF_KEY_OPERATION_FLAGS 0x000e7b00UL
-
-static unsigned int
-pk11_FlagsToAttributes(CK_FLAGS flags, CK_ATTRIBUTE *attrs, CK_BBOOL *ckTrue)
-{
-
- const static CK_ATTRIBUTE_TYPE attrTypes[12] = {
- CKA_ENCRYPT, CKA_DECRYPT, 0 /* DIGEST */, CKA_SIGN,
- CKA_SIGN_RECOVER, CKA_VERIFY, CKA_VERIFY_RECOVER, 0 /* GEN */,
- 0 /* GEN PAIR */, CKA_WRAP, CKA_UNWRAP, CKA_DERIVE
- };
-
- const CK_ATTRIBUTE_TYPE *pType = attrTypes;
- CK_ATTRIBUTE *attr = attrs;
- CK_FLAGS test = CKF_ENCRYPT;
-
-
- PR_ASSERT(!(flags & ~CKF_KEY_OPERATION_FLAGS));
- flags &= CKF_KEY_OPERATION_FLAGS;
-
- for (; flags && test <= CKF_DERIVE; test <<= 1, ++pType) {
- if (test & flags) {
- flags ^= test;
- PK11_SETATTRS(attr, *pType, ckTrue, sizeof *ckTrue);
- ++attr;
- }
- }
- return (attr - attrs);
-}
-
-PK11SymKey *
-PK11_DeriveWithFlags( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
- SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
- int keySize, CK_FLAGS flags)
-{
- CK_BBOOL ckTrue = CK_TRUE;
- CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
- unsigned int templateCount;
-
- templateCount = pk11_FlagsToAttributes(flags, keyTemplate, &ckTrue);
- return pk11_DeriveWithTemplate(baseKey, derive, param, target, operation,
- keySize, keyTemplate, templateCount);
-}
-
-static PRBool
-pk11_FindAttrInTemplate(CK_ATTRIBUTE * attr,
- unsigned int numAttrs,
- CK_ATTRIBUTE_TYPE target)
-{
- for (; numAttrs > 0; ++attr, --numAttrs) {
- if (attr->type == target)
- return PR_TRUE;
- }
- return PR_FALSE;
-}
-
-static PK11SymKey *
-pk11_DeriveWithTemplate( PK11SymKey *baseKey, CK_MECHANISM_TYPE derive,
- SECItem *param, CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
- int keySize, CK_ATTRIBUTE *userAttr, unsigned int numAttrs)
-{
- PK11SlotInfo * slot = baseKey->slot;
- PK11SymKey * symKey;
- PK11SymKey * newBaseKey = NULL;
- CK_BBOOL cktrue = CK_TRUE;
- CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
- CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
- CK_ULONG valueLen = 0;
- CK_MECHANISM mechanism;
- CK_RV crv;
- CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
- CK_ATTRIBUTE * attrs = keyTemplate;
- unsigned int templateCount;
-
- if (numAttrs > MAX_TEMPL_ATTRS) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return NULL;
- }
- /* first copy caller attributes in. */
- for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
- *attrs++ = *userAttr++;
- }
-
- /* We only add the following attributes to the template if the caller
- ** didn't already supply them.
- */
- if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass);
- attrs++;
- }
- if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
- keyType = PK11_GetKeyType(target, keySize);
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType );
- attrs++;
- }
- if (keySize > 0 &&
- !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
- valueLen = (CK_ULONG)keySize;
- PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen);
- attrs++;
- }
- if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
- PK11_SETATTRS(attrs, operation, &cktrue, sizeof cktrue); attrs++;
- }
-
- templateCount = attrs - keyTemplate;
- PR_ASSERT(templateCount <= MAX_TEMPL_ATTRS);
-
- /* move the key to a slot that can do the function */
- if (!PK11_DoesMechanism(slot,derive)) {
- /* get a new base key & slot */
- PK11SlotInfo *newSlot = PK11_GetBestSlot(derive, baseKey->cx);
-
- if (newSlot == NULL) return NULL;
-
- newBaseKey = pk11_CopyToSlot (newSlot, derive, CKA_DERIVE,
- baseKey);
- PK11_FreeSlot(newSlot);
- if (newBaseKey == NULL) return NULL;
- baseKey = newBaseKey;
- slot = baseKey->slot;
- }
-
-
- /* get our key Structure */
- symKey = PK11_CreateSymKey(slot,target,baseKey->cx);
- if (symKey == NULL) {
- return NULL;
- }
-
- symKey->size = keySize;
-
- mechanism.mechanism = derive;
- if (param) {
- mechanism.pParameter = param->data;
- mechanism.ulParameterLen = param->len;
- } else {
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
- }
- symKey->origin=PK11_OriginDerive;
-
- pk11_EnterKeyMonitor(symKey);
- crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
- baseKey->objectID, keyTemplate, templateCount, &symKey->objectID);
- pk11_ExitKeyMonitor(symKey);
-
- if (newBaseKey) PK11_FreeSymKey(newBaseKey);
- if (crv != CKR_OK) {
- PK11_FreeSymKey(symKey);
- return NULL;
- }
- return symKey;
-}
-
-/* build a public KEA key from the public value */
-SECKEYPublicKey *
-PK11_MakeKEAPubKey(unsigned char *keyData,int length)
-{
- SECKEYPublicKey *pubk;
- SECItem pkData;
- SECStatus rv;
- PRArenaPool *arena;
-
- pkData.data = keyData;
- pkData.len = length;
-
- arena = PORT_NewArena (DER_DEFAULT_CHUNKSIZE);
- if (arena == NULL)
- return NULL;
-
- pubk = (SECKEYPublicKey *) PORT_ArenaZAlloc(arena, sizeof(SECKEYPublicKey));
- if (pubk == NULL) {
- PORT_FreeArena (arena, PR_FALSE);
- return NULL;
- }
-
- pubk->arena = arena;
- pubk->pkcs11Slot = 0;
- pubk->pkcs11ID = CK_INVALID_KEY;
- pubk->keyType = fortezzaKey;
- rv = SECITEM_CopyItem(arena, &pubk->u.fortezza.KEAKey, &pkData);
- if (rv != SECSuccess) {
- PORT_FreeArena (arena, PR_FALSE);
- return NULL;
- }
- return pubk;
-}
-
-
-/*
- * This Generates a wrapping key based on a privateKey, publicKey, and two
- * random numbers. For Mail usage RandomB should be NULL. In the Sender's
- * case RandomA is generate, outherwize it is passed.
- */
-static unsigned char *rb_email = NULL;
-
-PK11SymKey *
-PK11_PubDerive(SECKEYPrivateKey *privKey, SECKEYPublicKey *pubKey,
- PRBool isSender, SECItem *randomA, SECItem *randomB,
- CK_MECHANISM_TYPE derive, CK_MECHANISM_TYPE target,
- CK_ATTRIBUTE_TYPE operation, int keySize,void *wincx)
-{
- PK11SlotInfo *slot = privKey->pkcs11Slot;
- CK_MECHANISM mechanism;
- PK11SymKey *symKey;
- CK_RV crv;
-
-
- if (rb_email == NULL) {
- rb_email = PORT_ZAlloc(128);
- if (rb_email == NULL) {
- return NULL;
- }
- rb_email[127] = 1;
- }
-
- /* get our key Structure */
- symKey = PK11_CreateSymKey(slot,target,wincx);
- if (symKey == NULL) {
- return NULL;
- }
-
- symKey->origin = PK11_OriginDerive;
-
- switch (privKey->keyType) {
- case rsaKey:
- case nullKey:
- PORT_SetError(SEC_ERROR_BAD_KEY);
- break;
- /* case keaKey: */
- case dsaKey:
- case fortezzaKey:
- {
- CK_KEA_DERIVE_PARAMS param;
- param.isSender = (CK_BBOOL) isSender;
- param.ulRandomLen = randomA->len;
- param.pRandomA = randomA->data;
- param.pRandomB = rb_email;
- if (randomB)
- param.pRandomB = randomB->data;
- if (pubKey->keyType == fortezzaKey) {
- param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
- param.pPublicData = pubKey->u.fortezza.KEAKey.data;
- } else {
- /* assert type == keaKey */
- /* XXX change to match key key types */
- param.ulPublicDataLen = pubKey->u.fortezza.KEAKey.len;
- param.pPublicData = pubKey->u.fortezza.KEAKey.data;
- }
-
- mechanism.mechanism = derive;
- mechanism.pParameter = &param;
- mechanism.ulParameterLen = sizeof(param);
-
- /* get a new symKey structure */
- pk11_EnterKeyMonitor(symKey);
- crv=PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
- privKey->pkcs11ID, NULL, 0, &symKey->objectID);
- pk11_ExitKeyMonitor(symKey);
- if (crv == CKR_OK) return symKey;
- PORT_SetError( PK11_MapError(crv) );
- }
- break;
- case dhKey:
- {
- CK_BBOOL cktrue = CK_TRUE;
- CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
- CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
- CK_ULONG key_size = 0;
- CK_ATTRIBUTE keyTemplate[4];
- int templateCount;
- CK_ATTRIBUTE *attrs = keyTemplate;
-
- if (pubKey->keyType != dhKey) {
- PORT_SetError(SEC_ERROR_BAD_KEY);
- break;
- }
-
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass));
- attrs++;
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType));
- attrs++;
- PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE_LEN, &key_size, sizeof(key_size));
- attrs++;
- templateCount = attrs - keyTemplate;
- PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
-
- keyType = PK11_GetKeyType(target,keySize);
- key_size = keySize;
- symKey->size = keySize;
- if (key_size == 0) templateCount--;
-
- mechanism.mechanism = derive;
-
- /* we can undefine these when we define diffie-helman keys */
- mechanism.pParameter = pubKey->u.dh.publicValue.data;
- mechanism.ulParameterLen = pubKey->u.dh.publicValue.len;
-
- pk11_EnterKeyMonitor(symKey);
- crv = PK11_GETTAB(slot)->C_DeriveKey(symKey->session, &mechanism,
- privKey->pkcs11ID, keyTemplate, templateCount, &symKey->objectID);
- pk11_ExitKeyMonitor(symKey);
- if (crv == CKR_OK) return symKey;
- PORT_SetError( PK11_MapError(crv) );
- }
- break;
- }
-
- PK11_FreeSymKey(symKey);
- return NULL;
-}
-
-/*
- * this little function uses the Decrypt function to unwrap a key, just in
- * case we are having problem with unwrap. NOTE: The key size may
- * not be preserved properly for some algorithms!
- */
-static PK11SymKey *
-pk11_HandUnwrap(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
- CK_MECHANISM *mech, SECItem *inKey, CK_MECHANISM_TYPE target,
- CK_ATTRIBUTE *keyTemplate, unsigned int templateCount,
- int key_size, void * wincx)
-{
- CK_ULONG len;
- SECItem outKey;
- PK11SymKey *symKey;
- CK_RV crv;
- PRBool owner = PR_TRUE;
- PRBool bool = PR_TRUE;
- CK_SESSION_HANDLE session;
-
- /* keys are almost always aligned, but if we get this far,
- * we've gone above and beyond anyway... */
- outKey.data = (unsigned char*)PORT_Alloc(inKey->len);
- if (outKey.data == NULL) {
- PORT_SetError( SEC_ERROR_NO_MEMORY );
- return NULL;
- }
- len = inKey->len;
-
- /* use NULL IV's for wrapping */
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_DecryptInit(session,mech,wrappingKey);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_Free(outKey.data);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
- crv = PK11_GETTAB(slot)->C_Decrypt(session,inKey->data,inKey->len,
- outKey.data, &len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- if (crv != CKR_OK) {
- PORT_Free(outKey.data);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
-
- outKey.len = (key_size == 0) ? len : key_size;
-
- if (PK11_DoesMechanism(slot,target)) {
- symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
- keyTemplate, templateCount,
- &outKey, wincx);
- } else {
- slot = PK11_GetBestSlot(target,wincx);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- PORT_Free(outKey.data);
- return NULL;
- }
- symKey = pk11_ImportSymKeyWithTempl(slot, target, PK11_OriginUnwrap,
- keyTemplate, templateCount,
- &outKey, wincx);
- PK11_FreeSlot(slot);
- }
- PORT_Free(outKey.data);
- return symKey;
-}
-
-/*
- * The wrap/unwrap function is pretty much the same for private and
- * public keys. It's just getting the Object ID and slot right. This is
- * the combined unwrap function.
- */
-static PK11SymKey *
-pk11_AnyUnwrapKey(PK11SlotInfo *slot, CK_OBJECT_HANDLE wrappingKey,
- CK_MECHANISM_TYPE wrapType, SECItem *param, SECItem *wrappedKey,
- CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize,
- void *wincx, CK_ATTRIBUTE *userAttr, unsigned int numAttrs)
-{
- PK11SymKey * symKey;
- SECItem * param_free = NULL;
- CK_BBOOL ckfalse = CK_FALSE;
- CK_BBOOL cktrue = CK_TRUE;
- CK_OBJECT_CLASS keyClass = CKO_SECRET_KEY;
- CK_KEY_TYPE keyType = CKK_GENERIC_SECRET;
- CK_ULONG valueLen = 0;
- CK_MECHANISM mechanism;
- CK_RV crv;
- CK_MECHANISM_INFO mechanism_info;
- CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
- CK_ATTRIBUTE * attrs = keyTemplate;
- unsigned int templateCount;
-
- if (numAttrs > MAX_TEMPL_ATTRS) {
- PORT_SetError(SEC_ERROR_INVALID_ARGS);
- return NULL;
- }
- /* first copy caller attributes in. */
- for (templateCount = 0; templateCount < numAttrs; ++templateCount) {
- *attrs++ = *userAttr++;
- }
-
- /* We only add the following attributes to the template if the caller
- ** didn't already supply them.
- */
- if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_CLASS)) {
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof keyClass);
- attrs++;
- }
- if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_KEY_TYPE)) {
- keyType = PK11_GetKeyType(target, keySize);
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof keyType );
- attrs++;
- }
- if (keySize > 0 &&
- !pk11_FindAttrInTemplate(keyTemplate, numAttrs, CKA_VALUE_LEN)) {
- valueLen = (CK_ULONG)keySize;
- PK11_SETATTRS(attrs, CKA_VALUE_LEN, &valueLen, sizeof valueLen);
- attrs++;
- }
- if (!pk11_FindAttrInTemplate(keyTemplate, numAttrs, operation)) {
- PK11_SETATTRS(attrs, operation, &cktrue, 1); attrs++;
- }
-
- templateCount = attrs - keyTemplate;
- PR_ASSERT(templateCount <= sizeof(keyTemplate)/sizeof(CK_ATTRIBUTE));
-
-
- /* find out if we can do wrap directly. Because the RSA case if *very*
- * common, cache the results for it. */
- if ((wrapType == CKM_RSA_PKCS) && (slot->hasRSAInfo)) {
- mechanism_info.flags = slot->RSAInfoFlags;
- } else {
- if (!slot->isThreadSafe) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_GetMechanismInfo(slot->slotID,wrapType,
- &mechanism_info);
- if (!slot->isThreadSafe) PK11_ExitSlotMonitor(slot);
- if (crv != CKR_OK) {
- mechanism_info.flags = 0;
- }
- if (wrapType == CKM_RSA_PKCS) {
- slot->RSAInfoFlags = mechanism_info.flags;
- slot->hasRSAInfo = PR_TRUE;
- }
- }
-
- /* initialize the mechanism structure */
- mechanism.mechanism = wrapType;
- /* use NULL IV's for wrapping */
- if (param == NULL) param = param_free = PK11_ParamFromIV(wrapType,NULL);
- if (param) {
- mechanism.pParameter = param->data;
- mechanism.ulParameterLen = param->len;
- } else {
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
- }
-
- if ((mechanism_info.flags & CKF_DECRYPT)
- && !PK11_DoesMechanism(slot,target)) {
- symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
- target, keyTemplate, templateCount, keySize,
- wincx);
- if (symKey) return symKey;
- /* fall through, maybe they incorrectly set CKF_DECRYPT */
- }
-
- /* get our key Structure */
- symKey = PK11_CreateSymKey(slot,target,wincx);
- if (symKey == NULL) {
- return NULL;
- }
-
- symKey->size = keySize;
- symKey->origin = PK11_OriginUnwrap;
-
- pk11_EnterKeyMonitor(symKey);
- crv = PK11_GETTAB(slot)->C_UnwrapKey(symKey->session,&mechanism,wrappingKey,
- wrappedKey->data, wrappedKey->len, keyTemplate, templateCount,
- &symKey->objectID);
- pk11_ExitKeyMonitor(symKey);
- if (param_free) SECITEM_FreeItem(param_free,PR_TRUE);
- if (crv != CKR_OK) {
- /* try hand Unwrapping */
- PK11_FreeSymKey(symKey);
- symKey = pk11_HandUnwrap(slot, wrappingKey, &mechanism, wrappedKey,
- target, keyTemplate, templateCount, keySize,
- wincx);
- }
-
- return symKey;
-}
-
-/* use a symetric key to unwrap another symetric key */
-PK11SymKey *
-PK11_UnwrapSymKey( PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
- SECItem *param, SECItem *wrappedKey,
- CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
- int keySize)
-{
- return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
- wrapType, param, wrappedKey, target, operation, keySize,
- wrappingKey->cx, NULL, 0);
-}
-
-/* use a symetric key to unwrap another symetric key */
-PK11SymKey *
-PK11_UnwrapSymKeyWithFlags(PK11SymKey *wrappingKey, CK_MECHANISM_TYPE wrapType,
- SECItem *param, SECItem *wrappedKey,
- CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation,
- int keySize, CK_FLAGS flags)
-{
- CK_BBOOL ckTrue = CK_TRUE;
- CK_ATTRIBUTE keyTemplate[MAX_TEMPL_ATTRS];
- unsigned int templateCount;
-
- templateCount = pk11_FlagsToAttributes(flags, keyTemplate, &ckTrue);
- return pk11_AnyUnwrapKey(wrappingKey->slot, wrappingKey->objectID,
- wrapType, param, wrappedKey, target, operation, keySize,
- wrappingKey->cx, keyTemplate, templateCount);
-}
-
-
-/* unwrap a symetric key with a private key. */
-PK11SymKey *
-PK11_PubUnwrapSymKey(SECKEYPrivateKey *wrappingKey, SECItem *wrappedKey,
- CK_MECHANISM_TYPE target, CK_ATTRIBUTE_TYPE operation, int keySize)
-{
- CK_MECHANISM_TYPE wrapType = pk11_mapWrapKeyType(wrappingKey->keyType);
-
- PK11_HandlePasswordCheck(wrappingKey->pkcs11Slot,wrappingKey->wincx);
-
- return pk11_AnyUnwrapKey(wrappingKey->pkcs11Slot, wrappingKey->pkcs11ID,
- wrapType, NULL, wrappedKey, target, operation, keySize,
- wrappingKey->wincx, NULL, 0);
-}
-
-/*
- * Recover the Signed data. We need this because our old verify can't
- * figure out which hash algorithm to use until we decryptted this.
- */
-SECStatus
-PK11_VerifyRecover(SECKEYPublicKey *key,
- SECItem *sig, SECItem *dsig, void *wincx)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- CK_OBJECT_HANDLE id = key->pkcs11ID;
- CK_MECHANISM mech = {0, NULL, 0 };
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_ULONG len;
- CK_RV crv;
-
- mech.mechanism = pk11_mapSignKeyType(key->keyType);
-
- if (slot == NULL) {
- slot = PK11_GetBestSlot(mech.mechanism,wincx);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return SECFailure;
- }
- id = PK11_ImportPublicKey(slot,key,PR_FALSE);
- }
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_VerifyRecoverInit(session,&mech,id);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- len = dsig->len;
- crv = PK11_GETTAB(slot)->C_VerifyRecover(session,sig->data,
- sig->len, dsig->data, &len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- dsig->len = len;
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/*
- * verify a signature from its hash.
- */
-SECStatus
-PK11_Verify(SECKEYPublicKey *key, SECItem *sig, SECItem *hash, void *wincx)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- PK11SlotInfo *tmpslot = key->pkcs11Slot;
- CK_OBJECT_HANDLE id = key->pkcs11ID;
- CK_MECHANISM mech = {0, NULL, 0 };
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_RV crv;
-
- mech.mechanism = pk11_mapSignKeyType(key->keyType);
-
- if (slot == NULL) {
- if (mech.mechanism == CKM_DSA) {
- slot = PK11_GetInternalSlot(); /* use internal slot for
- DSA verify */
- } else {
- slot = PK11_GetBestSlot(mech.mechanism,wincx);
- };
-
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return SECFailure;
- }
- id = PK11_ImportPublicKey(slot,key,PR_FALSE);
-
- }
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_VerifyInit(session,&mech,id);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- crv = PK11_GETTAB(slot)->C_Verify(session,hash->data,
- hash->len, sig->data, sig->len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/*
- * sign a hash. The algorithm is determined by the key.
- */
-SECStatus
-PK11_Sign(SECKEYPrivateKey *key, SECItem *sig, SECItem *hash)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- CK_MECHANISM mech = {0, NULL, 0 };
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_ULONG len;
- CK_RV crv;
-
- mech.mechanism = pk11_mapSignKeyType(key->keyType);
-
- PK11_HandlePasswordCheck(slot, key->wincx);
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_SignInit(session,&mech,key->pkcs11ID);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- len = sig->len;
- crv = PK11_GETTAB(slot)->C_Sign(session,hash->data,
- hash->len, sig->data, &len);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- sig->len = len;
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/*
- * Now SSL 2.0 uses raw RSA stuff. These next to functions *must* use
- * RSA keys, or they'll fail. We do the checks up front. If anyone comes
- * up with a meaning for rawdecrypt for any other public key operation,
- * then we need to move this check into some of PK11_PubDecrypt callers,
- * (namely SSL 2.0).
- */
-SECStatus
-PK11_PubDecryptRaw(SECKEYPrivateKey *key, unsigned char *data,
- unsigned *outLen, unsigned int maxLen, unsigned char *enc,
- unsigned encLen)
-{
- PK11SlotInfo *slot = key->pkcs11Slot;
- CK_MECHANISM mech = {CKM_RSA_X_509, NULL, 0 };
- CK_ULONG out = maxLen;
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_RV crv;
-
- if (key->keyType != rsaKey) {
- PORT_SetError( SEC_ERROR_INVALID_KEY );
- return SECFailure;
- }
-
- /* Why do we do a PK11_handle check here? for simple
- * decryption? .. because the user may have asked for 'ask always'
- * and this is a private key operation. In practice, thought, it's mute
- * since only servers wind up using this function */
- PK11_HandlePasswordCheck(slot, key->wincx);
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_DecryptInit(session,&mech,key->pkcs11ID);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- crv = PK11_GETTAB(slot)->C_Decrypt(session,enc, encLen,
- data, &out);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- *outLen = out;
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/* The encrypt version of the above function */
-SECStatus
-PK11_PubEncryptRaw(SECKEYPublicKey *key, unsigned char *enc,
- unsigned char *data, unsigned dataLen, void *wincx)
-{
- PK11SlotInfo *slot;
- CK_MECHANISM mech = {CKM_RSA_X_509, NULL, 0 };
- CK_OBJECT_HANDLE id;
- CK_ULONG out = dataLen;
- PRBool owner = PR_TRUE;
- CK_SESSION_HANDLE session;
- CK_RV crv;
-
- if (key->keyType != rsaKey) {
- PORT_SetError( SEC_ERROR_BAD_KEY );
- return SECFailure;
- }
-
- slot = PK11_GetBestSlot(mech.mechanism, wincx);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return SECFailure;
- }
-
- id = PK11_ImportPublicKey(slot,key,PR_FALSE);
-
- session = pk11_GetNewSession(slot,&owner);
- if (!owner || !(slot->isThreadSafe)) PK11_EnterSlotMonitor(slot);
- crv = PK11_GETTAB(slot)->C_EncryptInit(session,&mech,id);
- if (crv != CKR_OK) {
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- crv = PK11_GETTAB(slot)->C_Encrypt(session,data,dataLen,enc,&out);
- if (!owner || !(slot->isThreadSafe)) PK11_ExitSlotMonitor(slot);
- pk11_CloseSession(slot,session,owner);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-
-/**********************************************************************
- *
- * Now Deal with Crypto Contexts
- *
- **********************************************************************/
-
-/*
- * the monitors...
- */
-void
-PK11_EnterContextMonitor(PK11Context *cx) {
- /* if we own the session and our slot is ThreadSafe, only monitor
- * the Context */
- if ((cx->ownSession) && (cx->slot->isThreadSafe)) {
- /* Should this use monitors instead? */
- PR_Lock(cx->sessionLock);
- } else {
- PK11_EnterSlotMonitor(cx->slot);
- }
-}
-
-void
-PK11_ExitContextMonitor(PK11Context *cx) {
- /* if we own the session and our slot is ThreadSafe, only monitor
- * the Context */
- if ((cx->ownSession) && (cx->slot->isThreadSafe)) {
- /* Should this use monitors instead? */
- PR_Unlock(cx->sessionLock);
- } else {
- PK11_ExitSlotMonitor(cx->slot);
- }
-}
-
-/*
- * Free up a Cipher Context
- */
-void
-PK11_DestroyContext(PK11Context *context, PRBool freeit)
-{
- pk11_CloseSession(context->slot,context->session,context->ownSession);
- /* initialize the critical fields of the context */
- if (context->savedData != NULL ) PORT_Free(context->savedData);
- if (context->key) PK11_FreeSymKey(context->key);
- if (context->param) SECITEM_FreeItem(context->param, PR_TRUE);
- if (context->sessionLock) PR_DestroyLock(context->sessionLock);
- PK11_FreeSlot(context->slot);
- if (freeit) PORT_Free(context);
-}
-
-/*
- * save the current context. Allocate Space if necessary.
- */
-static void *
-pk11_saveContextHelper(PK11Context *context, void *space,
- unsigned long *savedLength, PRBool staticBuffer, PRBool recurse)
-{
- CK_ULONG length;
- CK_RV crv;
-
- if (staticBuffer) PORT_Assert(space != NULL);
-
- if (space == NULL) {
- crv =PK11_GETTAB(context->slot)->C_GetOperationState(context->session,
- NULL,&length);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
- space = PORT_Alloc(length);
- if (space == NULL) return NULL;
- *savedLength = length;
- }
- crv = PK11_GETTAB(context->slot)->C_GetOperationState(context->session,
- (CK_BYTE_PTR)space,savedLength);
- if (!staticBuffer && !recurse && (crv == CKR_BUFFER_TOO_SMALL)) {
- if (!staticBuffer) PORT_Free(space);
- return pk11_saveContextHelper(context, NULL,
- savedLength, PR_FALSE, PR_TRUE);
- }
- if (crv != CKR_OK) {
- if (!staticBuffer) PORT_Free(space);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
- return space;
-}
-
-void *
-pk11_saveContext(PK11Context *context, void *space, unsigned long *savedLength)
-{
- return pk11_saveContextHelper(context, space,
- savedLength, PR_FALSE, PR_FALSE);
-}
-
-/*
- * restore the current context
- */
-SECStatus
-pk11_restoreContext(PK11Context *context,void *space, unsigned long savedLength)
-{
- CK_RV crv;
- CK_OBJECT_HANDLE objectID = (context->key) ? context->key->objectID:
- CK_INVALID_KEY;
-
- PORT_Assert(space != NULL);
- if (space == NULL) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- return SECFailure;
- }
- crv = PK11_GETTAB(context->slot)->C_SetOperationState(context->session,
- (CK_BYTE_PTR)space, savedLength, objectID, 0);
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv));
- return SECFailure;
- }
- return SECSuccess;
-}
-
-SECStatus pk11_Finalize(PK11Context *context);
-
-/*
- * Context initialization. Used by all flavors of CreateContext
- */
-static SECStatus
-pk11_context_init(PK11Context *context, CK_MECHANISM *mech_info)
-{
- CK_RV crv;
- PK11SymKey *symKey = context->key;
- SECStatus rv = SECSuccess;
-
- switch (context->operation) {
- case CKA_ENCRYPT:
- crv=PK11_GETTAB(context->slot)->C_EncryptInit(context->session,
- mech_info, symKey->objectID);
- break;
- case CKA_DECRYPT:
- if (context->fortezzaHack) {
- CK_ULONG count = 0;;
- /* generate the IV for fortezza */
- crv=PK11_GETTAB(context->slot)->C_EncryptInit(context->session,
- mech_info, symKey->objectID);
- if (crv != CKR_OK) break;
- PK11_GETTAB(context->slot)->C_EncryptFinal(context->session,
- NULL, &count);
- }
- crv=PK11_GETTAB(context->slot)->C_DecryptInit(context->session,
- mech_info, symKey->objectID);
- break;
- case CKA_SIGN:
- crv=PK11_GETTAB(context->slot)->C_SignInit(context->session,
- mech_info, symKey->objectID);
- break;
- case CKA_VERIFY:
- crv=PK11_GETTAB(context->slot)->C_SignInit(context->session,
- mech_info, symKey->objectID);
- break;
- case CKA_DIGEST:
- crv=PK11_GETTAB(context->slot)->C_DigestInit(context->session,
- mech_info);
- break;
- default:
- crv = CKR_OPERATION_NOT_INITIALIZED;
- break;
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
-
- /*
- * handle session starvation case.. use our last session to multiplex
- */
- if (!context->ownSession) {
- context->savedData = pk11_saveContext(context,context->savedData,
- &context->savedLength);
- if (context->savedData == NULL) rv = SECFailure;
- /* clear out out session for others to use */
- pk11_Finalize(context);
- }
- return rv;
-}
-
-
-/*
- * Common Helper Function do come up with a new context.
- */
-static PK11Context *pk11_CreateNewContextInSlot(CK_MECHANISM_TYPE type,
- PK11SlotInfo *slot, CK_ATTRIBUTE_TYPE operation, PK11SymKey *symKey,
- SECItem *param)
-{
- CK_MECHANISM mech_info;
- PK11Context *context;
- SECStatus rv;
-
- context = (PK11Context *) PORT_Alloc(sizeof(PK11Context));
- if (context == NULL) {
- return NULL;
- }
-
- /* now deal with the fortezza hack... the fortezza hack is an attempt
- * to get around the issue of the card not allowing you to do a FORTEZZA
- * LoadIV/Encrypt, which was added because such a combination could be
- * use to circumvent the key escrow system. Unfortunately SSL needs to
- * do this kind of operation, so in SSL we do a loadIV (to verify it),
- * Then GenerateIV, and through away the first 8 bytes on either side
- * of the connection.*/
- context->fortezzaHack = PR_FALSE;
- if (type == CKM_SKIPJACK_CBC64) {
- if (symKey->origin == PK11_OriginFortezzaHack) {
- context->fortezzaHack = PR_TRUE;
- }
- }
-
- /* initialize the critical fields of the context */
- context->operation = operation;
- context->key = symKey ? PK11_ReferenceSymKey(symKey) : NULL;
- context->slot = PK11_ReferenceSlot(slot);
- context->session = pk11_GetNewSession(slot,&context->ownSession);
- context->cx = symKey ? symKey->cx : NULL;
- /* get our session */
- context->savedData = NULL;
-
- /* save the parameters so that some digesting stuff can do multiple
- * begins on a single context */
- context->type = type;
- context->param = SECITEM_DupItem(param);
- context->init = PR_FALSE;
- context->sessionLock = PR_NewLock();
- if ((context->param == NULL) || (context->sessionLock == NULL)) {
- PK11_DestroyContext(context,PR_TRUE);
- return NULL;
- }
-
- mech_info.mechanism = type;
- mech_info.pParameter = param->data;
- mech_info.ulParameterLen = param->len;
- PK11_EnterContextMonitor(context);
- rv = pk11_context_init(context,&mech_info);
- PK11_ExitContextMonitor(context);
-
- if (rv != SECSuccess) {
- PK11_DestroyContext(context,PR_TRUE);
- return NULL;
- }
- context->init = PR_TRUE;
- return context;
-}
-
-
-/*
- * put together the various PK11_Create_Context calls used by different
- * parts of libsec.
- */
-PK11Context *
-PK11_CreateContextByRawKey(PK11SlotInfo *slot, CK_MECHANISM_TYPE type,
- PK11Origin origin, CK_ATTRIBUTE_TYPE operation, SECItem *key,
- SECItem *param, void *wincx)
-{
- PK11SymKey *symKey;
- PK11Context *context;
-
- /* first get a slot */
- if (slot == NULL) {
- slot = PK11_GetBestSlot(type,wincx);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return NULL;
- }
- } else {
- PK11_ReferenceSlot(slot);
- }
-
- /* now import the key */
- symKey = PK11_ImportSymKey(slot, type, origin, operation, key, wincx);
- if (symKey == NULL) return NULL;
-
- context = PK11_CreateContextBySymKey(type, operation, symKey, param);
-
- PK11_FreeSymKey(symKey);
- PK11_FreeSlot(slot);
-
- return context;
-}
-
-
-/*
- * Create a context from a key. We really should make sure we aren't using
- * the same key in multiple session!
- */
-PK11Context *
-PK11_CreateContextBySymKey(CK_MECHANISM_TYPE type,CK_ATTRIBUTE_TYPE operation,
- PK11SymKey *symKey, SECItem *param)
-{
- PK11SymKey *newKey;
- PK11Context *context;
-
- /* if this slot doesn't support the mechanism, go to a slot that does */
- newKey = pk11_ForceSlot(symKey,type,operation);
- if (newKey == NULL) {
- PK11_ReferenceSymKey(symKey);
- } else {
- symKey = newKey;
- }
-
-
- /* Context Adopts the symKey.... */
- context = pk11_CreateNewContextInSlot(type, symKey->slot, operation, symKey,
- param);
- PK11_FreeSymKey(symKey);
- return context;
-}
-
-/*
- * Digest contexts don't need keys, but the do need to find a slot.
- * Macing should use PK11_CreateContextBySymKey.
- */
-PK11Context *
-PK11_CreateDigestContext(SECOidTag hashAlg)
-{
- /* digesting has to work without authentication to the slot */
- CK_MECHANISM_TYPE type;
- PK11SlotInfo *slot;
- PK11Context *context;
- SECItem param;
-
- type = PK11_AlgtagToMechanism(hashAlg);
- slot = PK11_GetBestSlot(type, NULL);
- if (slot == NULL) {
- PORT_SetError( SEC_ERROR_NO_MODULE );
- return NULL;
- }
-
- /* maybe should really be PK11_GenerateNewParam?? */
- param.data = NULL;
- param.len = 0;
-
- context = pk11_CreateNewContextInSlot(type, slot, CKA_DIGEST, NULL, &param);
- PK11_FreeSlot(slot);
- return context;
-}
-
-/*
- * create a new context which is the clone of the state of old context.
- */
-PK11Context * PK11_CloneContext(PK11Context *old)
-{
- PK11Context *newcx;
- PRBool needFree = PR_FALSE;
- SECStatus rv = SECSuccess;
- void *data;
- unsigned long len;
-
- newcx = pk11_CreateNewContextInSlot(old->type, old->slot, old->operation,
- old->key, old->param);
- if (newcx == NULL) return NULL;
-
- /* now clone the save state. First we need to find the save state
- * of the old session. If the old context owns it's session,
- * the state needs to be saved, otherwise the state is in saveData. */
- if (old->ownSession) {
- PK11_EnterContextMonitor(old);
- data=pk11_saveContext(old,NULL,&len);
- PK11_ExitContextMonitor(old);
- needFree = PR_TRUE;
- } else {
- data = old->savedData;
- len = old->savedLength;
- }
-
- if (data == NULL) {
- PK11_DestroyContext(newcx,PR_TRUE);
- return NULL;
- }
-
- /* now copy that state into our new context. Again we have different
- * work if the new context owns it's own session. If it does, we
- * restore the state gathered above. If it doesn't, we copy the
- * saveData pointer... */
- if (newcx->ownSession) {
- PK11_EnterContextMonitor(newcx);
- rv = pk11_restoreContext(newcx,data,len);
- PK11_ExitContextMonitor(newcx);
- } else {
- PORT_Assert(newcx->savedData != NULL);
- if ((newcx->savedData == NULL) || (newcx->savedLength < len)) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- rv = SECFailure;
- } else {
- PORT_Memcpy(newcx->savedData,data,len);
- newcx->savedLength = len;
- }
- }
-
- if (needFree) PORT_Free(data);
-
- if (rv != SECSuccess) {
- PK11_DestroyContext(newcx,PR_TRUE);
- return NULL;
- }
- return newcx;
-}
-
-/*
- * save the current context state into a variable. Required to make FORTEZZA
- * work.
- */
-SECStatus
-PK11_SaveContext(PK11Context *cx,unsigned char *save,int *len, int saveLength)
-{
- unsigned char * data = NULL;
- CK_ULONG length = saveLength;
-
- if (cx->ownSession) {
- PK11_EnterContextMonitor(cx);
- data = (unsigned char*)pk11_saveContextHelper(cx,save,&length,
- PR_FALSE,PR_FALSE);
- PK11_ExitContextMonitor(cx);
- if (data) *len = length;
- } else if (saveLength >= cx->savedLength) {
- data = (unsigned char*)cx->savedData;
- if (cx->savedData) {
- PORT_Memcpy(save,cx->savedData,cx->savedLength);
- }
- *len = cx->savedLength;
- }
- return (data != NULL) ? SECSuccess : SECFailure;
-}
-
-/*
- * restore the context state into a new running context. Also required for
- * FORTEZZA .
- */
-SECStatus
-PK11_RestoreContext(PK11Context *cx,unsigned char *save,int len)
-{
- SECStatus rv = SECSuccess;
- if (cx->ownSession) {
- PK11_EnterContextMonitor(cx);
- pk11_Finalize(cx);
- rv = pk11_restoreContext(cx,save,len);
- PK11_ExitContextMonitor(cx);
- } else {
- PORT_Assert(cx->savedData != NULL);
- if ((cx->savedData == NULL) || (cx->savedLength < (unsigned) len)) {
- PORT_SetError(SEC_ERROR_LIBRARY_FAILURE);
- rv = SECFailure;
- } else {
- PORT_Memcpy(cx->savedData,save,len);
- cx->savedLength = len;
- }
- }
- return rv;
-}
-
-/*
- * This is to get FIPS compliance until we can convert
- * libjar to use PK11_ hashing functions. It returns PR_FALSE
- * if we can't get a PK11 Context.
- */
-PRBool
-PK11_HashOK(SECOidTag algID) {
- PK11Context *cx;
-
- cx = PK11_CreateDigestContext(algID);
- if (cx == NULL) return PR_FALSE;
- PK11_DestroyContext(cx, PR_TRUE);
- return PR_TRUE;
-}
-
-
-
-/*
- * start a new digesting or Mac'ing operation on this context
- */
-SECStatus PK11_DigestBegin(PK11Context *cx)
-{
- CK_MECHANISM mech_info;
- SECStatus rv;
-
- if (cx->init == PR_TRUE) {
- return SECSuccess;
- }
-
- /*
- * make sure the old context is clear first
- */
- PK11_EnterContextMonitor(cx);
- pk11_Finalize(cx);
-
- mech_info.mechanism = cx->type;
- mech_info.pParameter = cx->param->data;
- mech_info.ulParameterLen = cx->param->len;
- rv = pk11_context_init(cx,&mech_info);
- PK11_ExitContextMonitor(cx);
-
- if (rv != SECSuccess) {
- return SECFailure;
- }
- cx->init = PR_TRUE;
- return SECSuccess;
-}
-
-SECStatus
-PK11_HashBuf(SECOidTag hashAlg, unsigned char *out, unsigned char *in,
- int32 len) {
- PK11Context *context;
- unsigned int max_length;
- unsigned int out_length;
- SECStatus rv;
-
- context = PK11_CreateDigestContext(hashAlg);
- if (context == NULL) return SECFailure;
-
- rv = PK11_DigestBegin(context);
- if (rv != SECSuccess) {
- PK11_DestroyContext(context, PR_TRUE);
- return rv;
- }
-
- rv = PK11_DigestOp(context, in, len);
- if (rv != SECSuccess) {
- PK11_DestroyContext(context, PR_TRUE);
- return rv;
- }
-
- /* we need the output length ... maybe this should be table driven...*/
- switch (hashAlg) {
- case SEC_OID_SHA1: max_length = SHA1_LENGTH; break;
- case SEC_OID_MD2: max_length = MD2_LENGTH; break;
- case SEC_OID_MD5: max_length = MD5_LENGTH; break;
- default: max_length = 16; break;
- }
-
- rv = PK11_DigestFinal(context,out,&out_length,max_length);
- PK11_DestroyContext(context, PR_TRUE);
- return rv;
-}
-
-
-/*
- * execute a bulk encryption operation
- */
-SECStatus
-PK11_CipherOp(PK11Context *context, unsigned char * out, int *outlen,
- int maxout, unsigned char *in, int inlen)
-{
- CK_RV crv = CKR_OK;
- CK_ULONG length = maxout;
- CK_ULONG offset =0;
- PK11SymKey *symKey = context->key;
- SECStatus rv = SECSuccess;
- unsigned char *saveOut = out;
- unsigned char *allocOut = NULL;
-
- /* if we ran out of session, we need to restore our previously stored
- * state.
- */
- PK11_EnterContextMonitor(context);
- if (!context->ownSession) {
- rv = pk11_restoreContext(context,context->savedData,
- context->savedLength);
- if (rv != SECSuccess) {
- PK11_ExitContextMonitor(context);
- return rv;
- }
- }
-
- /*
- * The fortezza hack is to send 8 extra bytes on the first encrypted and
- * loose them on the first decrypt.
- */
- if (context->fortezzaHack) {
- unsigned char random[8];
- if (context->operation == CKA_ENCRYPT) {
- PK11_ExitContextMonitor(context);
- rv = PK11_GenerateRandom(random,sizeof(random));
- PK11_EnterContextMonitor(context);
-
- /* since we are offseting the output, we can't encrypt back into
- * the same buffer... allocate a temporary buffer just for this
- * call. */
- allocOut = out = (unsigned char*)PORT_Alloc(maxout);
- if (out == NULL) {
- PK11_ExitContextMonitor(context);
- return SECFailure;
- }
- crv = PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session,
- random,sizeof(random),out,&length);
-
- out += length;
- maxout -= length;
- offset = length;
- } else if (context->operation == CKA_DECRYPT) {
- length = sizeof(random);
- crv = PK11_GETTAB(context->slot)->C_DecryptUpdate(context->session,
- in,sizeof(random),random,&length);
- inlen -= length;
- in += length;
- context->fortezzaHack = PR_FALSE;
- }
- }
-
- switch (context->operation) {
- case CKA_ENCRYPT:
- length = maxout;
- crv=PK11_GETTAB(context->slot)->C_EncryptUpdate(context->session,
- in, inlen, out, &length);
- length += offset;
- break;
- case CKA_DECRYPT:
- length = maxout;
- crv=PK11_GETTAB(context->slot)->C_DecryptUpdate(context->session,
- in, inlen, out, &length);
- break;
- default:
- crv = CKR_OPERATION_NOT_INITIALIZED;
- break;
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- *outlen = 0;
- rv = SECFailure;
- } else {
- *outlen = length;
- }
-
- if (context->fortezzaHack) {
- if (context->operation == CKA_ENCRYPT) {
- PORT_Assert(allocOut);
- PORT_Memcpy(saveOut, allocOut, length);
- PORT_Free(allocOut);
- }
- context->fortezzaHack = PR_FALSE;
- }
-
- /*
- * handle session starvation case.. use our last session to multiplex
- */
- if (!context->ownSession) {
- context->savedData = pk11_saveContext(context,context->savedData,
- &context->savedLength);
- if (context->savedData == NULL) rv = SECFailure;
-
- /* clear out out session for others to use */
- pk11_Finalize(context);
- }
- PK11_ExitContextMonitor(context);
- return rv;
-}
-
-/*
- * execute a digest/signature operation
- */
-SECStatus
-PK11_DigestOp(PK11Context *context, const unsigned char * in, unsigned inLen)
-{
- CK_RV crv = CKR_OK;
- SECStatus rv = SECSuccess;
-
- /* if we ran out of session, we need to restore our previously stored
- * state.
- */
- context->init = PR_FALSE;
- PK11_EnterContextMonitor(context);
- if (!context->ownSession) {
- rv = pk11_restoreContext(context,context->savedData,
- context->savedLength);
- if (rv != SECSuccess) {
- PK11_ExitContextMonitor(context);
- return rv;
- }
- }
-
- switch (context->operation) {
- /* also for MAC'ing */
- case CKA_SIGN:
- crv=PK11_GETTAB(context->slot)->C_SignUpdate(context->session,
- (unsigned char *)in,
- inLen);
- break;
- case CKA_VERIFY:
- crv=PK11_GETTAB(context->slot)->C_VerifyUpdate(context->session,
- (unsigned char *)in,
- inLen);
- break;
- case CKA_DIGEST:
- crv=PK11_GETTAB(context->slot)->C_DigestUpdate(context->session,
- (unsigned char *)in,
- inLen);
- break;
- default:
- crv = CKR_OPERATION_NOT_INITIALIZED;
- break;
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- rv = SECFailure;
- }
-
- /*
- * handle session starvation case.. use our last session to multiplex
- */
- if (!context->ownSession) {
- context->savedData = pk11_saveContext(context,context->savedData,
- &context->savedLength);
- if (context->savedData == NULL) rv = SECFailure;
-
- /* clear out out session for others to use */
- pk11_Finalize(context);
- }
- PK11_ExitContextMonitor(context);
- return rv;
-}
-
-/*
- * Digest a key if possible./
- */
-SECStatus
-PK11_DigestKey(PK11Context *context, PK11SymKey *key)
-{
- CK_RV crv = CKR_OK;
- SECStatus rv = SECSuccess;
- PK11SymKey *newKey = NULL;
-
- /* if we ran out of session, we need to restore our previously stored
- * state.
- */
- if (context->slot != key->slot) {
- newKey = pk11_CopyToSlot(context->slot,CKM_SSL3_SHA1_MAC,CKA_SIGN,key);
- } else {
- newKey = PK11_ReferenceSymKey(key);
- }
-
- context->init = PR_FALSE;
- PK11_EnterContextMonitor(context);
- if (!context->ownSession) {
- rv = pk11_restoreContext(context,context->savedData,
- context->savedLength);
- if (rv != SECSuccess) {
- PK11_ExitContextMonitor(context);
- PK11_FreeSymKey(newKey);
- return rv;
- }
- }
-
-
- if (newKey == NULL) {
- crv = CKR_KEY_TYPE_INCONSISTENT;
- if (key->data.data) {
- crv=PK11_GETTAB(context->slot)->C_DigestUpdate(context->session,
- key->data.data,key->data.len);
- }
- } else {
- crv=PK11_GETTAB(context->slot)->C_DigestKey(context->session,
- newKey->objectID);
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- rv = SECFailure;
- }
-
- /*
- * handle session starvation case.. use our last session to multiplex
- */
- if (!context->ownSession) {
- context->savedData = pk11_saveContext(context,context->savedData,
- &context->savedLength);
- if (context->savedData == NULL) rv = SECFailure;
-
- /* clear out out session for others to use */
- pk11_Finalize(context);
- }
- PK11_ExitContextMonitor(context);
- if (newKey) PK11_FreeSymKey(newKey);
- return rv;
-}
-
-/*
- * externally callable version of the lowercase pk11_finalize().
- */
-SECStatus
-PK11_Finalize(PK11Context *context) {
- SECStatus rv;
-
- PK11_EnterContextMonitor(context);
- rv = pk11_Finalize(context);
- PK11_ExitContextMonitor(context);
- return rv;
-}
-
-/*
- * clean up a cipher operation, so the session can be used by
- * someone new.
- */
-SECStatus
-pk11_Finalize(PK11Context *context)
-{
- CK_ULONG count = 0;
- CK_RV crv;
-
- if (!context->ownSession) {
- return SECSuccess;
- }
-
- switch (context->operation) {
- case CKA_ENCRYPT:
- crv=PK11_GETTAB(context->slot)->C_EncryptFinal(context->session,
- NULL,&count);
- break;
- case CKA_DECRYPT:
- crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session,
- NULL,&count);
- break;
- case CKA_SIGN:
- crv=PK11_GETTAB(context->slot)->C_SignFinal(context->session,
- NULL,&count);
- break;
- case CKA_VERIFY:
- crv=PK11_GETTAB(context->slot)->C_VerifyFinal(context->session,
- NULL,count);
- break;
- case CKA_DIGEST:
- crv=PK11_GETTAB(context->slot)->C_DigestFinal(context->session,
- NULL,&count);
- break;
- default:
- crv = CKR_OPERATION_NOT_INITIALIZED;
- break;
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/*
- * Return the final digested or signed data...
- * this routine can either take pre initialized data, or allocate data
- * either out of an arena or out of the standard heap.
- */
-SECStatus
-PK11_DigestFinal(PK11Context *context,unsigned char *data,
- unsigned int *outLen, unsigned int length)
-{
- CK_ULONG len;
- CK_RV crv;
- SECStatus rv;
-
-
- /* if we ran out of session, we need to restore our previously stored
- * state.
- */
- PK11_EnterContextMonitor(context);
- if (!context->ownSession) {
- rv = pk11_restoreContext(context,context->savedData,
- context->savedLength);
- if (rv != SECSuccess) {
- PK11_ExitContextMonitor(context);
- return rv;
- }
- }
-
- len = length;
- switch (context->operation) {
- case CKA_SIGN:
- crv=PK11_GETTAB(context->slot)->C_SignFinal(context->session,
- data,&len);
- break;
- case CKA_VERIFY:
- crv=PK11_GETTAB(context->slot)->C_VerifyFinal(context->session,
- data,len);
- break;
- case CKA_DIGEST:
- crv=PK11_GETTAB(context->slot)->C_DigestFinal(context->session,
- data,&len);
- break;
- case CKA_ENCRYPT:
- crv=PK11_GETTAB(context->slot)->C_EncryptFinal(context->session,
- data, &len);
- break;
- case CKA_DECRYPT:
- crv = PK11_GETTAB(context->slot)->C_DecryptFinal(context->session,
- data, &len);
- break;
- default:
- crv = CKR_OPERATION_NOT_INITIALIZED;
- break;
- }
- PK11_ExitContextMonitor(context);
-
- *outLen = (unsigned int) len;
- context->init = PR_FALSE; /* allow Begin to start up again */
-
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
- return SECSuccess;
-}
-
-/****************************************************************************
- *
- * Now Do The PBE Functions Here...
- *
- ****************************************************************************/
-
-SECAlgorithmID *
-PK11_CreatePBEAlgorithmID(SECOidTag algorithm, int iteration, SECItem *salt)
-{
- SECAlgorithmID *algid;
-
- algid = SEC_PKCS5CreateAlgorithmID(algorithm, salt, iteration);
- return algid;
-}
-
-PK11SymKey *
-PK11_PBEKeyGen(PK11SlotInfo *slot, SECAlgorithmID *algid, SECItem *pwitem,
- PRBool faulty3DES, void *wincx)
-{
- /* pbe stuff */
- CK_PBE_PARAMS *pbe_params;
- CK_MECHANISM_TYPE type;
- SECItem *mech;
- PK11SymKey *symKey;
-
- mech = PK11_ParamFromAlgid(algid);
- type = PK11_AlgtagToMechanism(SECOID_FindOIDTag(&algid->algorithm));
- if(faulty3DES && (type == CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC)) {
- type = CKM_NETSCAPE_PBE_SHA1_FAULTY_3DES_CBC;
- }
- if(mech == NULL) {
- return NULL;
- }
-
- pbe_params = (CK_PBE_PARAMS *)mech->data;
- pbe_params->pPassword = (CK_CHAR_PTR)PORT_ZAlloc(pwitem->len);
- if(pbe_params->pPassword != NULL) {
- PORT_Memcpy(pbe_params->pPassword, pwitem->data, pwitem->len);
- pbe_params->ulPasswordLen = pwitem->len;
- } else {
- SECITEM_ZfreeItem(mech, PR_TRUE);
- return NULL;
- }
-
- symKey = PK11_KeyGen(slot, type, mech, 0, wincx);
-
- PORT_ZFree(pbe_params->pPassword, pwitem->len);
- SECITEM_ZfreeItem(mech, PR_TRUE);
- return symKey;
-}
-
-
-SECStatus
-PK11_ImportEncryptedPrivateKeyInfo(PK11SlotInfo *slot,
- SECKEYEncryptedPrivateKeyInfo *epki, SECItem *pwitem,
- SECItem *nickname, SECItem *publicValue, PRBool isPerm,
- PRBool isPrivate, KeyType keyType, unsigned int keyUsage,
- void *wincx)
-{
- CK_MECHANISM_TYPE mechanism;
- SECItem *pbe_param, crypto_param;
- PK11SymKey *key = NULL;
- SECStatus rv = SECSuccess;
- CK_MECHANISM cryptoMech, pbeMech;
- CK_RV crv;
- SECKEYPrivateKey *privKey = NULL;
- PRBool faulty3DES = PR_FALSE;
- int usageCount;
- CK_KEY_TYPE key_type;
- CK_ATTRIBUTE_TYPE *usage;
- CK_ATTRIBUTE_TYPE rsaUsage[] = {
- CKA_UNWRAP, CKA_DECRYPT, CKA_SIGN, CKA_SIGN_RECOVER };
- CK_ATTRIBUTE_TYPE dsaUsage[] = { CKA_SIGN };
- CK_ATTRIBUTE_TYPE dhUsage[] = { CKA_DERIVE };
-
- if((epki == NULL) || (pwitem == NULL))
- return SECFailure;
-
- crypto_param.data = NULL;
-
- mechanism = PK11_AlgtagToMechanism(SECOID_FindOIDTag(
- &epki->algorithm.algorithm));
-
- switch (keyType) {
- default:
- case rsaKey:
- key_type = CKK_RSA;
- switch (keyUsage & (KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE)) {
- case KU_KEY_ENCIPHERMENT:
- usage = rsaUsage;
- usageCount = 2;
- break;
- case KU_DIGITAL_SIGNATURE:
- usage = &rsaUsage[2];
- usageCount = 2;
- break;
- case KU_KEY_ENCIPHERMENT|KU_DIGITAL_SIGNATURE:
- case 0: /* default to everything */
- usage = rsaUsage;
- usageCount = 4;
- break;
- }
- break;
- case dhKey:
- key_type = CKK_DH;
- usage = dhUsage;
- usageCount = sizeof(dhUsage)/sizeof(dhUsage[0]);
- break;
- case dsaKey:
- key_type = CKK_DSA;
- usage = dsaUsage;
- usageCount = sizeof(dsaUsage)/sizeof(dsaUsage[0]);
- break;
- }
-
-try_faulty_3des:
- pbe_param = PK11_ParamFromAlgid(&epki->algorithm);
-
- key = PK11_PBEKeyGen(slot, &epki->algorithm, pwitem, faulty3DES, wincx);
- if((key == NULL) || (pbe_param == NULL)) {
- rv = SECFailure;
- goto done;
- }
-
- pbeMech.mechanism = mechanism;
- pbeMech.pParameter = pbe_param->data;
- pbeMech.ulParameterLen = pbe_param->len;
-
- crv = PK11_MapPBEMechanismToCryptoMechanism(&pbeMech, &cryptoMech,
- pwitem, faulty3DES);
- if(crv != CKR_OK) {
- rv = SECFailure;
- goto done;
- }
-
- cryptoMech.mechanism = PK11_GetPadMechanism(cryptoMech.mechanism);
- crypto_param.data = (unsigned char*)cryptoMech.pParameter;
- crypto_param.len = cryptoMech.ulParameterLen;
-
- privKey = PK11_UnwrapPrivKey(slot, key, cryptoMech.mechanism,
- &crypto_param, &epki->encryptedData,
- nickname, publicValue, isPerm, isPrivate,
- key_type, usage, usageCount, wincx);
- if(privKey) {
- SECKEY_DestroyPrivateKey(privKey);
- privKey = NULL;
- rv = SECSuccess;
- goto done;
- }
-
- /* if we are unable to import the key and the mechanism is
- * CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC, then it is possible that
- * the encrypted blob was created with a buggy key generation method
- * which is described in the PKCS 12 implementation notes. So we
- * need to try importing via that method.
- */
- if((mechanism == CKM_NETSCAPE_PBE_SHA1_TRIPLE_DES_CBC) && (!faulty3DES)) {
- /* clean up after ourselves before redoing the key generation. */
-
- PK11_FreeSymKey(key);
- key = NULL;
-
- if(pbe_param) {
- SECITEM_ZfreeItem(pbe_param, PR_TRUE);
- pbe_param = NULL;
- }
-
- if(crypto_param.data) {
- SECITEM_ZfreeItem(&crypto_param, PR_FALSE);
- crypto_param.data = NULL;
- cryptoMech.pParameter = NULL;
- crypto_param.len = cryptoMech.ulParameterLen = 0;
- }
-
- faulty3DES = PR_TRUE;
- goto try_faulty_3des;
- }
-
- /* key import really did fail */
- rv = SECFailure;
-
-done:
- if(pbe_param != NULL) {
- SECITEM_ZfreeItem(pbe_param, PR_TRUE);
- pbe_param = NULL;
- }
-
- if(crypto_param.data != NULL) {
- SECITEM_ZfreeItem(&crypto_param, PR_FALSE);
- }
-
- if(key != NULL) {
- PK11_FreeSymKey(key);
- }
-
- return rv;
-}
-
-/*
- * import a private key info into the desired slot
- */
-SECStatus
-PK11_ImportPrivateKeyInfo(PK11SlotInfo *slot, SECKEYPrivateKeyInfo *pki,
- SECItem *nickname, SECItem *publicValue, PRBool isPerm,
- PRBool isPrivate, unsigned int keyUsage, void *wincx)
-{
- CK_BBOOL cktrue = CK_TRUE;
- CK_BBOOL ckfalse = CK_FALSE;
- CK_OBJECT_CLASS keyClass = CKO_PRIVATE_KEY;
- CK_KEY_TYPE keyType = CKK_RSA;
- CK_OBJECT_HANDLE objectID;
- CK_ATTRIBUTE theTemplate[20];
- int templateCount = 0;
- SECStatus rv = SECFailure;
- SECKEYLowPrivateKey *lpk = NULL;
- const SEC_ASN1Template *keyTemplate, *paramTemplate;
- void *paramDest = NULL;
- PRArenaPool *arena;
- CK_ATTRIBUTE *attrs;
- CK_ATTRIBUTE *signedattr = NULL;
- int signedcount = 0;
- CK_ATTRIBUTE *ap;
- SECItem *ck_id = NULL;
-
- arena = PORT_NewArena(2048);
- if(!arena) {
- return SECFailure;
- }
-
- /* need to change this to use RSA/DSA keys */
- lpk = (SECKEYLowPrivateKey *)PORT_ArenaZAlloc(arena,
- sizeof(SECKEYLowPrivateKey));
- if(lpk == NULL) {
- goto loser;
- }
- lpk->arena = arena;
-
- attrs = theTemplate;
- switch(SECOID_GetAlgorithmTag(&pki->algorithm)) {
- case SEC_OID_PKCS1_RSA_ENCRYPTION:
- keyTemplate = SECKEY_RSAPrivateKeyTemplate;
- paramTemplate = NULL;
- paramDest = NULL;
- lpk->keyType = rsaKey;
- keyType = CKK_RSA;
- break;
- case SEC_OID_ANSIX9_DSA_SIGNATURE:
- if(!publicValue) {
- goto loser;
- }
- keyTemplate = SECKEY_DSAPrivateKeyExportTemplate;
- paramTemplate = SECKEY_PQGParamsTemplate;
- paramDest = &(lpk->u.dsa.params);
- lpk->keyType = dsaKey;
- keyType = CKK_DSA;
- break;
- case SEC_OID_X942_DIFFIE_HELMAN_KEY:
- if(!publicValue) {
- goto loser;
- }
- keyTemplate = SECKEY_DHPrivateKeyExportTemplate;
- paramTemplate = NULL;
- paramDest = NULL;
- lpk->keyType = dhKey;
- keyType = CKK_DH;
- break;
-
- default:
- keyTemplate = NULL;
- paramTemplate = NULL;
- paramDest = NULL;
- break;
- }
-
- if(!keyTemplate) {
- goto loser;
- }
-
- /* decode the private key and any algorithm parameters */
- rv = SEC_ASN1DecodeItem(arena, lpk, keyTemplate, &pki->privateKey);
- if(rv != SECSuccess) {
- goto loser;
- }
- if(paramDest && paramTemplate) {
- rv = SEC_ASN1DecodeItem(arena, paramDest, paramTemplate,
- &(pki->algorithm.parameters));
- if(rv != SECSuccess) {
- goto loser;
- }
- }
-
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass) ); attrs++;
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType) ); attrs++;
- PK11_SETATTRS(attrs, CKA_TOKEN, isPerm ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_SENSITIVE, isPrivate ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_PRIVATE, isPrivate ? &cktrue : &ckfalse,
- sizeof(CK_BBOOL) ); attrs++;
-
- switch (lpk->keyType) {
- case rsaKey:
- PK11_SETATTRS(attrs, CKA_UNWRAP, (keyUsage & KU_KEY_ENCIPHERMENT) ?
- &cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_DECRYPT, (keyUsage & KU_DATA_ENCIPHERMENT) ?
- &cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_SIGN, (keyUsage & KU_DIGITAL_SIGNATURE) ?
- &cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
- PK11_SETATTRS(attrs, CKA_SIGN_RECOVER,
- (keyUsage & KU_DIGITAL_SIGNATURE) ?
- &cktrue : &ckfalse, sizeof(CK_BBOOL) ); attrs++;
- ck_id = PK11_MakeIDFromPubKey(&lpk->u.rsa.modulus);
- if (ck_id == NULL) {
- goto loser;
- }
- PK11_SETATTRS(attrs, CKA_ID, ck_id->data,ck_id->len); attrs++;
- if (nickname) {
- PK11_SETATTRS(attrs, CKA_LABEL, nickname->data, nickname->len); attrs++;
- }
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_MODULUS, lpk->u.rsa.modulus.data,
- lpk->u.rsa.modulus.len); attrs++;
- PK11_SETATTRS(attrs, CKA_PUBLIC_EXPONENT,
- lpk->u.rsa.publicExponent.data,
- lpk->u.rsa.publicExponent.len); attrs++;
- PK11_SETATTRS(attrs, CKA_PRIVATE_EXPONENT,
- lpk->u.rsa.privateExponent.data,
- lpk->u.rsa.privateExponent.len); attrs++;
- PK11_SETATTRS(attrs, CKA_PRIME_1,
- lpk->u.rsa.prime1.data,
- lpk->u.rsa.prime1.len); attrs++;
- PK11_SETATTRS(attrs, CKA_PRIME_2,
- lpk->u.rsa.prime2.data,
- lpk->u.rsa.prime2.len); attrs++;
- PK11_SETATTRS(attrs, CKA_EXPONENT_1,
- lpk->u.rsa.exponent1.data,
- lpk->u.rsa.exponent1.len); attrs++;
- PK11_SETATTRS(attrs, CKA_EXPONENT_2,
- lpk->u.rsa.exponent2.data,
- lpk->u.rsa.exponent2.len); attrs++;
- PK11_SETATTRS(attrs, CKA_COEFFICIENT,
- lpk->u.rsa.coefficient.data,
- lpk->u.rsa.coefficient.len); attrs++;
- break;
- case dsaKey:
- /* To make our intenal PKCS #11 module work correctly with
- * our database, we need to pass in the public key value for
- * this dsa key. We have a netscape only CKA_ value to do this.
- * Only send it to internal slots */
- if (PK11_IsInternal(slot)) {
- PK11_SETATTRS(attrs, CKA_NETSCAPE_DB,
- publicValue->data, publicValue->len); attrs++;
- }
- PK11_SETATTRS(attrs, CKA_SIGN, &cktrue, sizeof(CK_BBOOL)); attrs++;
- PK11_SETATTRS(attrs, CKA_SIGN_RECOVER, &cktrue, sizeof(CK_BBOOL)); attrs++;
- if(nickname) {
- PK11_SETATTRS(attrs, CKA_LABEL, nickname->data, nickname->len);
- attrs++;
- }
- ck_id = PK11_MakeIDFromPubKey(publicValue);
- if (ck_id == NULL) {
- goto loser;
- }
- PK11_SETATTRS(attrs, CKA_ID, ck_id->data,ck_id->len); attrs++;
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME, lpk->u.dsa.params.prime.data,
- lpk->u.dsa.params.prime.len); attrs++;
- PK11_SETATTRS(attrs,CKA_SUBPRIME,lpk->u.dsa.params.subPrime.data,
- lpk->u.dsa.params.subPrime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, lpk->u.dsa.params.base.data,
- lpk->u.dsa.params.base.len); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.dsa.privateValue.data,
- lpk->u.dsa.privateValue.len); attrs++;
- break;
- case dhKey:
- /* To make our intenal PKCS #11 module work correctly with
- * our database, we need to pass in the public key value for
- * this dh key. We have a netscape only CKA_ value to do this.
- * Only send it to internal slots */
- if (PK11_IsInternal(slot)) {
- PK11_SETATTRS(attrs, CKA_NETSCAPE_DB,
- publicValue->data, publicValue->len); attrs++;
- }
- PK11_SETATTRS(attrs, CKA_DERIVE, &cktrue, sizeof(CK_BBOOL)); attrs++;
- if(nickname) {
- PK11_SETATTRS(attrs, CKA_LABEL, nickname->data, nickname->len);
- attrs++;
- }
- ck_id = PK11_MakeIDFromPubKey(publicValue);
- if (ck_id == NULL) {
- goto loser;
- }
- PK11_SETATTRS(attrs, CKA_ID, ck_id->data,ck_id->len); attrs++;
- signedattr = attrs;
- PK11_SETATTRS(attrs, CKA_PRIME, lpk->u.dh.prime.data,
- lpk->u.dh.prime.len); attrs++;
- PK11_SETATTRS(attrs, CKA_BASE, lpk->u.dh.base.data,
- lpk->u.dh.base.len); attrs++;
- PK11_SETATTRS(attrs, CKA_VALUE, lpk->u.dh.privateValue.data,
- lpk->u.dh.privateValue.len); attrs++;
- break;
- /* what about fortezza??? */
- default:
- PORT_SetError(SEC_ERROR_BAD_KEY);
- goto loser;
- }
- templateCount = attrs - theTemplate;
- PR_ASSERT(templateCount <= sizeof(theTemplate)/sizeof(CK_ATTRIBUTE));
- signedcount = attrs - signedattr;
-
- for (ap=signedattr; signedcount; ap++, signedcount--) {
- pk11_SignedToUnsigned(ap);
- }
-
- rv = PK11_CreateNewObject(slot, CK_INVALID_SESSION,
- theTemplate, templateCount, isPerm, &objectID);
-
- if (ck_id) {
- SECITEM_ZfreeItem(ck_id, PR_TRUE);
- }
-
-loser:
- if (lpk!= NULL) {
- SECKEY_LowDestroyPrivateKey(lpk);
- }
-
- return rv;
-}
-
-SECKEYPrivateKeyInfo *
-PK11_ExportPrivateKeyInfo(CERTCertificate *cert, void *wincx)
-{
- return NULL;
-}
-
-static int
-pk11_private_key_encrypt_buffer_length(SECKEYPrivateKey *key)
-
-{
- CK_ATTRIBUTE rsaTemplate = { CKA_MODULUS, NULL, 0 };
- CK_ATTRIBUTE dsaTemplate = { CKA_PRIME, NULL, 0 };
- CK_ATTRIBUTE_PTR pTemplate;
- CK_RV crv;
- int length;
-
- if(!key) {
- return -1;
- }
-
- switch (key->keyType) {
- case rsaKey:
- pTemplate = &rsaTemplate;
- break;
- case dsaKey:
- case dhKey:
- pTemplate = &dsaTemplate;
- break;
- case fortezzaKey:
- default:
- pTemplate = NULL;
- }
-
- if(!pTemplate) {
- return -1;
- }
-
- crv = PK11_GetAttributes(NULL, key->pkcs11Slot, key->pkcs11ID,
- pTemplate, 1);
- if(crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return -1;
- }
-
- length = pTemplate->ulValueLen;
- length *= 10;
-
- if(pTemplate->pValue != NULL) {
- PORT_Free(pTemplate->pValue);
- }
-
- return length;
-}
-
-SECKEYEncryptedPrivateKeyInfo *
-PK11_ExportEncryptedPrivateKeyInfo(PK11SlotInfo *slot, SECOidTag algTag,
- SECItem *pwitem, CERTCertificate *cert, int iteration, void *wincx)
-{
- SECKEYEncryptedPrivateKeyInfo *epki = NULL;
- SECKEYPrivateKey *pk;
- PRArenaPool *arena = NULL;
- SECAlgorithmID *algid;
- CK_MECHANISM_TYPE mechanism;
- SECItem *pbe_param = NULL, crypto_param;
- PK11SymKey *key = NULL;
- SECStatus rv = SECSuccess;
- CK_MECHANISM pbeMech, cryptoMech;
- CK_RV crv;
- SECItem encryptedKey = {siBuffer,NULL,0};
- int encryptBufLen;
-
- if(!pwitem)
- return NULL;
-
- crypto_param.data = NULL;
-
- arena = PORT_NewArena(2048);
- epki = (SECKEYEncryptedPrivateKeyInfo *)PORT_ArenaZAlloc(arena,
- sizeof(SECKEYEncryptedPrivateKeyInfo));
- if(epki == NULL) {
- rv = SECFailure;
- goto loser;
- }
- epki->arena = arena;
- algid = SEC_PKCS5CreateAlgorithmID(algTag, NULL, iteration);
- if(algid == NULL) {
- rv = SECFailure;
- goto loser;
- }
-
- mechanism = PK11_AlgtagToMechanism(SECOID_FindOIDTag(&algid->algorithm));
- pbe_param = PK11_ParamFromAlgid(algid);
- pbeMech.mechanism = mechanism;
- pbeMech.pParameter = pbe_param->data;
- pbeMech.ulParameterLen = pbe_param->len;
- key = PK11_PBEKeyGen(slot, algid, pwitem, PR_FALSE, wincx);
-
- if((key == NULL) || (pbe_param == NULL)) {
- rv = SECFailure;
- goto loser;
- }
-
- crv = PK11_MapPBEMechanismToCryptoMechanism(&pbeMech, &cryptoMech,
- pwitem, PR_FALSE);
- if(crv != CKR_OK) {
- rv = SECFailure;
- goto loser;
- }
- cryptoMech.mechanism = PK11_GetPadMechanism(cryptoMech.mechanism);
- crypto_param.data = (unsigned char *)cryptoMech.pParameter;
- crypto_param.len = cryptoMech.ulParameterLen;
-
- pk = PK11_FindKeyByAnyCert(cert, wincx);
- if(pk == NULL) {
- rv = SECFailure;
- goto loser;
- }
-
- encryptBufLen = pk11_private_key_encrypt_buffer_length(pk);
- if(encryptBufLen == -1) {
- rv = SECFailure;
- goto loser;
- }
- encryptedKey.len = (unsigned int)encryptBufLen;
- encryptedKey.data = (unsigned char *)PORT_ZAlloc(encryptedKey.len);
- if(!encryptedKey.data) {
- rv = SECFailure;
- goto loser;
- }
-
- /* we are extracting an encrypted privateKey structure.
- * which needs to be freed along with the buffer into which it is
- * returned. eventually, we should retrieve an encrypted key using
- * pkcs8/pkcs5.
- */
- PK11_EnterSlotMonitor(pk->pkcs11Slot);
- crv = PK11_GETTAB(pk->pkcs11Slot)->C_WrapKey(pk->pkcs11Slot->session,
- &cryptoMech, key->objectID, pk->pkcs11ID, encryptedKey.data,
- (CK_ULONG_PTR)(&encryptedKey.len));
- PK11_ExitSlotMonitor(pk->pkcs11Slot);
- if(crv != CKR_OK) {
- rv = SECFailure;
- goto loser;
- }
-
- if(!encryptedKey.len) {
- rv = SECFailure;
- goto loser;
- }
-
- rv = SECITEM_CopyItem(arena, &epki->encryptedData, &encryptedKey);
- if(rv != SECSuccess) {
- goto loser;
- }
-
- rv = SECOID_CopyAlgorithmID(arena, &epki->algorithm, algid);
-
-loser:
- if(pbe_param != NULL) {
- SECITEM_ZfreeItem(pbe_param, PR_TRUE);
- pbe_param = NULL;
- }
-
- if(crypto_param.data != NULL) {
- SECITEM_ZfreeItem(&crypto_param, PR_FALSE);
- crypto_param.data = NULL;
- }
-
- if(key != NULL) {
- PK11_FreeSymKey(key);
- }
-
- if(rv == SECFailure) {
- if(arena != NULL) {
- PORT_FreeArena(arena, PR_TRUE);
- }
- epki = NULL;
- }
-
- return epki;
-}
-
-
-/*
- * This is required to allow FORTEZZA_NULL and FORTEZZA_RC4
- * working. This function simply gets a valid IV for the keys.
- */
-SECStatus
-PK11_GenerateFortezzaIV(PK11SymKey *symKey,unsigned char *iv,int len)
-{
- CK_MECHANISM mech_info;
- CK_ULONG count = 0;
- CK_RV crv;
- SECStatus rv = SECFailure;
-
- mech_info.mechanism = CKM_SKIPJACK_CBC64;
- mech_info.pParameter = iv;
- mech_info.ulParameterLen = len;
-
- /* generate the IV for fortezza */
- PK11_EnterSlotMonitor(symKey->slot);
- crv=PK11_GETTAB(symKey->slot)->C_EncryptInit(symKey->slot->session,
- &mech_info, symKey->objectID);
- if (crv == CKR_OK) {
- PK11_GETTAB(symKey->slot)->C_EncryptFinal(symKey->slot->session,
- NULL, &count);
- rv = SECSuccess;
- }
- PK11_ExitSlotMonitor(symKey->slot);
- return rv;
-}
-
-SECKEYPrivateKey *
-PK11_UnwrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
- CK_MECHANISM_TYPE wrapType, SECItem *param,
- SECItem *wrappedKey, SECItem *label,
- SECItem *idValue, PRBool perm, PRBool sensitive,
- CK_KEY_TYPE keyType, CK_ATTRIBUTE_TYPE *usage, int usageCount,
- void *wincx)
-{
- CK_BBOOL cktrue = CK_TRUE;
- CK_BBOOL ckfalse = CK_FALSE;
- CK_OBJECT_CLASS keyClass = CKO_PRIVATE_KEY;
- CK_ATTRIBUTE keyTemplate[15] ;
- int templateCount = 0;
- CK_OBJECT_HANDLE privKeyID;
- CK_MECHANISM mechanism;
- CK_ATTRIBUTE *attrs = keyTemplate;
- SECItem *param_free = NULL, *ck_id;
- CK_RV crv;
- CK_SESSION_HANDLE rwsession;
- PK11SymKey *newKey = NULL;
- int i;
-
- if(!slot || !wrappedKey || !idValue) {
- /* SET AN ERROR!!! */
- return NULL;
- }
-
- ck_id = PK11_MakeIDFromPubKey(idValue);
- if(!ck_id) {
- return NULL;
- }
-
- PK11_SETATTRS(attrs, CKA_TOKEN, perm ? &cktrue : &ckfalse,
- sizeof(cktrue)); attrs++;
- PK11_SETATTRS(attrs, CKA_CLASS, &keyClass, sizeof(keyClass)); attrs++;
- PK11_SETATTRS(attrs, CKA_KEY_TYPE, &keyType, sizeof(keyType)); attrs++;
- PK11_SETATTRS(attrs, CKA_PRIVATE, sensitive ? &cktrue : &ckfalse,
- sizeof(cktrue)); attrs++;
- PK11_SETATTRS(attrs, CKA_SENSITIVE, sensitive ? &cktrue : &ckfalse,
- sizeof(cktrue)); attrs++;
- PK11_SETATTRS(attrs, CKA_LABEL, label->data, label->len); attrs++;
- PK11_SETATTRS(attrs, CKA_ID, ck_id->data, ck_id->len); attrs++;
- for (i=0; i < usageCount; i++) {
- PK11_SETATTRS(attrs, usage[i], &cktrue, sizeof(cktrue)); attrs++;
- }
-
- if (PK11_IsInternal(slot)) {
- PK11_SETATTRS(attrs, CKA_NETSCAPE_DB, idValue->data,
- idValue->len); attrs++;
- }
-
- templateCount = attrs - keyTemplate;
- PR_ASSERT(templateCount <= (sizeof(keyTemplate) / sizeof(CK_ATTRIBUTE)) );
-
- mechanism.mechanism = wrapType;
- if(!param) param = param_free= PK11_ParamFromIV(wrapType, NULL);
- if(param) {
- mechanism.pParameter = param->data;
- mechanism.ulParameterLen = param->len;
- } else {
- mechanism.pParameter = NULL;
- mechanism.ulParameterLen = 0;
- }
-
- if (wrappingKey->slot != slot) {
- newKey = pk11_CopyToSlot(slot,wrapType,CKA_WRAP,wrappingKey);
- } else {
- newKey = PK11_ReferenceSymKey(wrappingKey);
- }
-
- if (newKey) {
- if (perm) {
- rwsession = PK11_GetRWSession(slot);
- } else {
- rwsession = slot->session;
- }
- crv = PK11_GETTAB(slot)->C_UnwrapKey(rwsession, &mechanism,
- newKey->objectID,
- wrappedKey->data,
- wrappedKey->len, keyTemplate,
- templateCount, &privKeyID);
-
- if (perm) PK11_RestoreROSession(slot, rwsession);
- PK11_FreeSymKey(newKey);
- } else {
- crv = CKR_FUNCTION_NOT_SUPPORTED;
- }
-
- if(ck_id) {
- SECITEM_FreeItem(ck_id, PR_TRUE);
- ck_id = NULL;
- }
-
- if (crv != CKR_OK) {
- /* we couldn't unwrap the key, use the internal module to do the
- * unwrap, then load the new key into the token */
- PK11SlotInfo *int_slot = PK11_GetInternalSlot();
-
- if (int_slot && (slot != int_slot)) {
- SECKEYPrivateKey *privKey = PK11_UnwrapPrivKey(int_slot,
- wrappingKey, wrapType, param, wrappedKey, label,
- idValue, PR_FALSE, PR_FALSE,
- keyType, usage, usageCount, wincx);
- if (privKey) {
- SECKEYPrivateKey *newPrivKey = pk11_loadPrivKey(slot,privKey,
- NULL,perm,sensitive);
- SECKEY_DestroyPrivateKey(privKey);
- PK11_FreeSlot(int_slot);
- return newPrivKey;
- }
- }
- if (int_slot) PK11_FreeSlot(int_slot);
- PORT_SetError( PK11_MapError(crv) );
- return NULL;
- }
- return PK11_MakePrivKey(slot, nullKey, PR_FALSE, privKeyID, wincx);
-}
-
-#define ALLOC_BLOCK 10
-
-/*
- * Now we're going to wrap a SECKEYPrivateKey with a PK11SymKey
- * The strategy is to get both keys to reside in the same slot,
- * one that can perform the desired crypto mechanism and then
- * call C_WrapKey after all the setup has taken place.
- */
-SECStatus
-PK11_WrapPrivKey(PK11SlotInfo *slot, PK11SymKey *wrappingKey,
- SECKEYPrivateKey *privKey, CK_MECHANISM_TYPE wrapType,
- SECItem *param, SECItem *wrappedKey, void *wincx)
-{
- PK11SlotInfo *privSlot = privKey->pkcs11Slot; /* The slot where
- * the private key
- * we are going to
- * wrap lives.
- */
- PK11SymKey *newSymKey = NULL;
- SECKEYPrivateKey *newPrivKey = NULL;
- SECItem *param_free = NULL;
- CK_ULONG len = wrappedKey->len;
- CK_MECHANISM mech;
- CK_RV crv;
-
- if (!privSlot || !PK11_DoesMechanism(privSlot, wrapType)) {
- /* Figure out a slot that does the mechanism and try to import
- * the private key onto that slot.
- */
- PK11SlotInfo *int_slot = PK11_GetInternalSlot();
-
- privSlot = int_slot; /* The private key has a new home */
- newPrivKey = pk11_loadPrivKey(privSlot,privKey,NULL,PR_FALSE,PR_FALSE);
- if (newPrivKey == NULL) {
- PK11_FreeSlot (int_slot);
- return SECFailure;
- }
- privKey = newPrivKey;
- }
-
- if (privSlot != wrappingKey->slot) {
- newSymKey = pk11_CopyToSlot (privSlot, wrapType, CKA_WRAP,
- wrappingKey);
- wrappingKey = newSymKey;
- }
-
- if (wrappingKey == NULL) {
- if (newPrivKey) {
- SECKEY_DestroyPrivateKey(newPrivKey);
- }
- return SECFailure;
- }
- mech.mechanism = wrapType;
- if (!param) {
- param = param_free = PK11_ParamFromIV(wrapType, NULL);
- }
- if (param) {
- mech.pParameter = param->data;
- mech.ulParameterLen = param->len;
- } else {
- mech.pParameter = NULL;
- mech.ulParameterLen = 0;
- }
-
- PK11_EnterSlotMonitor(privSlot);
- crv = PK11_GETTAB(privSlot)->C_WrapKey(privSlot->session, &mech,
- wrappingKey->objectID,
- privKey->pkcs11ID,
- wrappedKey->data, &len);
- PK11_ExitSlotMonitor(privSlot);
-
- if (newSymKey) {
- PK11_FreeSymKey(newSymKey);
- }
- if (newPrivKey) {
- SECKEY_DestroyPrivateKey(newPrivKey);
- }
-
- if (crv != CKR_OK) {
- PORT_SetError( PK11_MapError(crv) );
- return SECFailure;
- }
-
- wrappedKey->len = len;
- return SECSuccess;
-}
-
-void
-PK11_SetFortezzaHack(PK11SymKey *symKey) {
- symKey->origin = PK11_OriginFortezzaHack;
-}
-
diff --git a/security/nss/tests/ssl/ssl.sh b/security/nss/tests/ssl/ssl.sh
deleted file mode 100755
index 249345720..000000000
--- a/security/nss/tests/ssl/ssl.sh
+++ /dev/null
@@ -1,275 +0,0 @@
-#! /bin/ksh
-#
-# This is just a quick script so we can still run our testcases.
-# Longer term we need a scriptable test environment..
-#
-. ../common/init.sh
-CURDIR=`pwd`
-PORT=${PORT-8443}
-
-# Test case files
-SSLCOV=${CURDIR}/sslcov.txt
-SSLAUTH=${CURDIR}/sslauth.txt
-SSLSTRESS=${CURDIR}/sslstress.txt
-REQUEST_FILE=${CURDIR}/sslreq.txt
-
-#temparary files
-PWFILE=/tmp/tests.pw.$$
-CERTSCRIPT=/tmp/tests.certs.$$
-NOISE_FILE=/tmp/tests.noise.$$
-SERVEROUTFILE=/tmp/tests.server.$$
-
-TEMPFILES="${PWFILE} ${CERTSCRIPT} ${SERVEROUTFILE} ${NOISE_FILE}"
-
-none=1
-coverage=0
-auth=0
-stress=0
-certs=1
-fileout=0
-
-for i in $*
-do
- case $i in
- [aA][lL]*)
- none=0; coverage=1; auth=1; stress=1;;
- [aA][uU]*)
- none=0; auth=1;;
- [Nn][Oo][aA][uU]*)
- auth=0;;
- [Cc][Oo]*)
- none=0; coverage=1;;
- [Nn][Oo][Cc][Oo]*)
- coverage=0;;
- [Cc][Ee]*)
- none=0; certs=1;;
- [Nn][Oo][Cc][Ee]*)
- certs=0;;
- [Ss]*)
- none=0; stress=1;;
- [Nn][Oo][Ss]*)
- stress=0;;
- f)
- fileout=1;
- esac
-done
-
-if [ $none -eq 1 ]; then
- coverage=1
- auth=1
- stress=1
-fi
-
-
-#
-# should also try to kill any running server
-#
-trap "rm -f ${TEMPFILES}; exit" 2 3
-
-if [ $certs -eq 1 ]; then
-# Generate noise for our CA cert.
-#
-# NOTE: these keys are only suitable for testing, as this whole thing bypasses
-# the entropy gathering. Don't use this method to generate keys and certs for
-# product use or deployment.
-#
-ps -efl > ${NOISE_FILE} 2>&1
-ps aux >> ${NOISE_FILE} 2>&1
-netstat >> ${NOISE_FILE} 2>&1
-date >> ${NOISE_FILE} 2>&1
-
-#
-# build the TEMP CA used for testing purposes
-#
-echo "<TABLE BORDER=1><TR><TH COLSPAN=3>Certutil Tests</TH></TR>" >> ${RESULTS}
-echo "<TR><TH width=500>Test Case</TH><TH width=50>Result</TH></TR>" >> ${RESULTS}
-CADIR=${HOSTDIR}/CA
-echo "********************** Creating a CA Certificate **********************"
-if [ ! -d ${CADIR} ]; then
- mkdir -p ${CADIR}
-fi
-cd ${CADIR}
-echo nss > ${PWFILE}
-echo " certutil -N -d . -f ${PWFILE}"
-certutil -N -d . -f ${PWFILE}
-
-echo 5 > ${CERTSCRIPT}
-echo 9 >> ${CERTSCRIPT}
-echo n >> ${CERTSCRIPT}
-echo y >> ${CERTSCRIPT}
-echo 3 >> ${CERTSCRIPT}
-echo n >> ${CERTSCRIPT}
-echo 5 >> ${CERTSCRIPT}
-echo 6 >> ${CERTSCRIPT}
-echo 7 >> ${CERTSCRIPT}
-echo 9 >> ${CERTSCRIPT}
-echo n >> ${CERTSCRIPT}
-echo "certutil -S -n \"TestCA\" -s \"CN=NSS Test CA, O=BOGUS NSS, L=Mountain View, ST=California, C=US\" -t \"CTu,CTu,CTu\" -v 60 -x -d . -1 -2 -5 -f ${PWFILE} -z ${NOISE_FILE}"
-certutil -S -n "TestCA" -s "CN=NSS Test CA, O=BOGUS NSS, L=Mountain View, ST=California, C=US" -t "CTu,CTu,CTu" -v 60 -x -d . -1 -2 -5 -f ${PWFILE} -z ${NOISE_FILE} < ${CERTSCRIPT}
-
-if [ $? -ne 0 ]; then
- echo "<TR><TD>Creating CA Cert</TD><TD bgcolor=red>Failed</TD><TR>" >> ${RESULTS}
-else
- echo "<TR><TD>Creating CA Cert</TD><TD bgcolor=lightGreen>Passed</TD><TR>" >> ${RESULTS}
-fi
-
-echo "**************** Creating Client CA Issued Certificate ****************"
-netstat >> ${NOISE_FILE} 2>&1
-date >> ${NOISE_FILE} 2>&1
-CLIENTDIR=${HOSTDIR}/client
-if [ ! -d ${CLIENTDIR} ]; then
- mkdir -p ${CLIENTDIR}
-fi
-cd ${CLIENTDIR}
-cp ${CADIR}/*.db .
-echo "certutil -S -n \"TestUser\" -s \"CN=Test User, O=BOGUS Netscape, L=Mountain View, ST=California, C=US\" -t \"u,u,u\" -c "TestCA" -m 3 -v 60 -d . -f ${PWFILE} -z ${NOISE_FILE}"
-certutil -S -n "TestUser" -s "CN=Test User, O=BOGUS NSS, L=Mountain View, ST=California, C=US" -t "u,u,u" -c "TestCA" -m 3 -v 60 -d . -f ${PWFILE} -z ${NOISE_FILE}
-if [ $? -ne 0 ]; then
- echo "<TR><TD>Creating client Cert</TD><TD bgcolor=red>Failed</TD><TR>" >> ${RESULTS}
-else
- echo "<TR><TD>Creating client Cert</TD><TD bgcolor=lightGreen>Passed</TD><TR>" >> ${RESULTS}
-fi
-
-echo "***** Creating Server CA Issued Certificate for ${HOST}.${DOMSUF} *****"
-netstat >> ${NOISE_FILE} 2>&1
-date >> ${NOISE_FILE} 2>&1
-SERVERDIR=${HOSTDIR}/server
-if [ ! -d ${SERVERDIR} ]; then
- mkdir -p ${SERVERDIR}
-fi
-cd ${SERVERDIR}
-cp ../CA/*.db .
-echo "certutil -S -n \"${HOST}.${DOMSUF}\" -s \"CN=${HOST}.${DOMSUF}, O=BOGUS Netscape, L=Mountain View, ST=California, C=US\" -t \"Pu,Pu,Pu\" -c "TestCA" -v 60 -d . -f ${PWFILE} -z ${NOISE_FILE}"
-certutil -S -n "${HOST}.${DOMSUF}" -s "CN=${HOST}.${DOMSUF}, O=BOGUS Netscape, L=Mountain View, ST=California, C=US" -t "Pu,Pu,Pu" -c "TestCA" -m 1 -v 60 -d . -f ${PWFILE} -z ${NOISE_FILE}
-if [ $? -ne 0 ]; then
- echo "<TR><TD>Creating Server Cert</TD><TD bgcolor=red>Failed</TD><TR>" >> ${RESULTS}
-else
- echo "<TR><TD>Creating Server Cert</TD><TD bgcolor=lightGreen>Passed</TD><TR>" >> ${RESULTS}
-fi
-echo "</TABLE><BR>" >> ${RESULTS}
-
-rm -f ${TEMPFILES}
-fi
-
-
-# OK now lets run the tests....
-if [ $coverage -eq 1 ]; then
-echo "********************* SSL Cipher Coverage ****************************"
-echo "<TABLE BORDER=1><TR><TH COLSPAN=3>SSL Cipher Coverage</TH></TR>" >> ${RESULTS}
-echo "<TR><TH width=500>Test Case</TH><TH width=50>Result</TH></TR>" >> ${RESULTS}
-cd ${CLIENTDIR}
- cat ${SSLCOV} | while read tls param testname
-do
- if [ $tls != "#" ]; then
- echo "********************* $testname ****************************"
- TLS_FLAG=-T
- if [ $tls = "TLS" ]; then
- TLS_FLAG=""
- fi
- sparam=""
- if [ ${param} = "i" ]; then
- sparam='-c i'
- fi
- if [ ${fileout} -eq 1 ]; then
- selfserv -v -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} > ${SERVEROUTFILE} 2>&1 &
- else
- selfserv -v -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} &
- fi
- SERVERPID=$!
- sleep 10
-
- tstclnt -p ${PORT} -h ${HOST} -c ${param} ${TLS_FLAG} -f -d . < ${REQUEST_FILE}
- if [ $? -ne 0 ]; then
- echo "<TR><TD>"${testname}"</TD><TD bgcolor=red>Failed</TD><TR>" >> ${RESULTS}
- else
- echo "<TR><TD>"${testname}"</TD><TD bgcolor=lightGreen>Passed</TD><TR>" >> ${RESULTS}
- fi
- ${KILL} ${SERVERPID}
- wait ${SERVERPID}
- if [ ${fileout} -eq 1 ]; then
- cat ${SERVEROUTFILE}
- fi
- fi
-done
-
-echo "</TABLE><BR>" >> ${RESULTS}
-fi
-
-if [ $auth -eq 1 ]; then
-echo "********************* SSL Client Auth ****************************"
-cd ${CLIENTDIR}
-echo "<TABLE BORDER=1><TR><TH COLSPAN=3>SSL Client Authentication</TH></TR>" >> ${RESULTS}
-echo "<TR><TH width=500>Test Case</TH><TH width=50>Result</TH></TR>" >> ${RESULTS}
-
-cat ${SSLAUTH} | while read value sparam cparam testname
-do
- if [ $value != "#" ]; then
- echo "***** $testname ****"
- sparam=`echo $sparam | sed -e 's;_; ;g'`
- cparam=`echo $cparam | sed -e 's;_; ;g'`
- echo "selfserv -v -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} &"
- if [ ${fileout} -eq 1 ]; then
- selfserv -v -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} > ${SERVEROUTFILE} 2>&1 &
- else
- selfserv -v -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} &
- fi
- SERVERPID=$!
- sleep 10
- pwd
- echo "tstclnt -p ${PORT} -h ${HOST} -f -d ${CLIENTDIR} ${cparam}"
- tstclnt -p ${PORT} -h ${HOST} -f -d ${CLIENTDIR} ${cparam} < ${REQUEST_FILE}
- if [ $? -ne $value ]; then
- echo "<TR><TD>"${testname}"</TD><TD bgcolor=red>Failed</TD><TR>" >> ${RESULTS}
- else
- echo "<TR><TD>"${testname}"</TD><TD bgcolor=lightGreen>Passed</TD><TR>" >> ${RESULTS}
- fi
- ${KILL} ${SERVERPID}
- wait ${SERVERPID}
- if [ ${fileout} -eq 1 ]; then
- cat ${SERVEROUTFILE}
- fi
- fi
-done
-
-echo "</TABLE><BR>" >> ${RESULTS}
-fi
-
-
-if [ $stress -eq 1 ]; then
-echo "********************* Stress Test ****************************"
-cd ${CLIENTDIR}
-echo "<TABLE BORDER=1><TR><TH COLSPAN=3>SSL Stress Test</TH></TR>" >> ${RESULTS}
-echo "<TR><TH width=500>Test Case</TH><TH width=50>Result</TH></TR>" >> ${RESULTS}
-
-cat ${SSLSTRESS} | while read value sparam cparam testname
-do
- if [ $value != "#" ]; then
- echo "********************* $testname ****************************"
- sparam=`echo $sparam | sed -e 's;_; ;g'`
- cparam=`echo $cparam | sed -e 's;_; ;g'`
- if [ ${fileout} -eq 1 ]; then
- selfserv -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} > ${SERVEROUTFILE} 2>&1 &
- else
- selfserv -p ${PORT} -d ${SERVERDIR} -n ${HOST}.${DOMSUF} -w nss ${sparam} &
- fi
- SERVERPID=$!
- sleep 10
-
- strsclnt -p ${PORT} ${HOST} -d . -w nss $cparam
- if [ $? -ne $value ]; then
- echo "<TR><TD>"${testname}"</TD><TD bgcolor=red>Failed</TD><TR>" >> ${RESULTS}
- else
- echo "<TR><TD>"${testname}"</TD><TD bgcolor=lightGreen>Passed</TD><TR>" >> ${RESULTS}
- fi
- ${KILL} ${SERVERPID}
- wait ${SERVERPID}
- if [ ${fileout} -eq 1 ]; then
- cat ${SERVEROUTFILE}
- fi
- fi
-done
-
-echo "</TABLE><BR>" >> ${RESULTS}
-fi
-
-rm -f ${TEMPFILES}
diff --git a/security/nss/tests/ssl/sslstress.txt b/security/nss/tests/ssl/sslstress.txt
deleted file mode 100644
index 456431355..000000000
--- a/security/nss/tests/ssl/sslstress.txt
+++ /dev/null
@@ -1,14 +0,0 @@
-#
-# This file defines the tests for client auth.
-#
-# expected
-# return server client Test Case name
-# value params params
-# ------ ------ ------ ---------------
- 0 _ -c_1000_-C_A Stress SSL2 RC4 128 with MD5
- 0 _ -c_1000_-C_A Stress SSL3 RC4 128 with MD5
-# 0 _ -c_1000_-C_c Stress TLS RC4 128 with MD5
-#
-# add client auth versions here...
-#
-# 0 -r -n_"Test_User"_-w_bogus TLS Request don't require client auth (bad password)