aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorno-author <no-author@gcc.gnu.org>2004-09-28 17:08:09 +0000
committerno-author <no-author@gcc.gnu.org>2004-09-28 17:08:09 +0000
commit335df4f569e29d1ad3db4c42a38b1af09995f023 (patch)
tree17c3281a836116d4e0457d5c4db2ef28ee5b678f
parentf6f998ce577e698595b435e81728bdcddce125c3 (diff)
This commit was manufactured by cvs2svn to create branch
'structure-aliasing-branch'. git-svn-id: https://gcc.gnu.org/svn/gcc/branches/structure-aliasing-branch@88235 138bc75d-0d04-0410-961f-82ee72b054a4
-rw-r--r--config/codeset.m423
-rw-r--r--config/gcc-lib-path.m415
-rw-r--r--config/gettext-sister.m466
-rw-r--r--config/glibc21.m432
-rw-r--r--config/iconv.m4103
-rw-r--r--config/intdiv0.m472
-rw-r--r--config/inttypes-pri.m432
-rw-r--r--config/inttypes.m427
-rw-r--r--config/inttypes_h.m428
-rw-r--r--config/lcmessage.m432
-rw-r--r--config/lib-ld.m4110
-rw-r--r--config/lib-link.m4551
-rw-r--r--config/lib-prefix.m4155
-rw-r--r--config/mh-x86omitfp2
-rw-r--r--config/nls.m449
-rw-r--r--config/po.m4197
-rw-r--r--config/stdint_h.m428
-rw-r--r--config/uintmax_t.m432
-rw-r--r--config/ulonglong.m423
-rw-r--r--config/warnings.m497
-rw-r--r--gcc/config/s390/tpf-eh.c183
-rw-r--r--gcc/config/sparc/sol2-gas.h5
-rw-r--r--gcc/gthr-tpf.h157
-rw-r--r--gcc/testsuite/g++.dg/ext/attribute-test-1.C37
-rw-r--r--gcc/testsuite/g++.dg/ext/attribute-test-2.C48
-rw-r--r--gcc/testsuite/g++.dg/ext/attribute-test-3.C55
-rw-r--r--gcc/testsuite/g++.dg/ext/attribute-test-4.C48
-rw-r--r--gcc/testsuite/g++.dg/inherit/base2.C12
-rw-r--r--gcc/testsuite/g++.dg/lookup/ambig3.C18
-rw-r--r--gcc/testsuite/g++.dg/lookup/crash5.C9
-rw-r--r--gcc/testsuite/g++.dg/opt/pr17624.C23
-rw-r--r--gcc/testsuite/g++.dg/opt/pr7503-1.C148
-rw-r--r--gcc/testsuite/g++.dg/opt/pr7503-2.C79
-rw-r--r--gcc/testsuite/g++.dg/opt/pr7503-3.C26
-rw-r--r--gcc/testsuite/g++.dg/opt/pr7503-4.C81
-rw-r--r--gcc/testsuite/g++.dg/opt/pr7503-5.C81
-rw-r--r--gcc/testsuite/g++.dg/other/anon3.C7
-rw-r--r--gcc/testsuite/g++.dg/other/error9.C20
-rw-r--r--gcc/testsuite/g++.dg/template/crash23.C9
-rw-r--r--gcc/testsuite/g++.dg/template/static7.C16
-rw-r--r--gcc/testsuite/g++.dg/template/static8.C8
-rw-r--r--gcc/testsuite/g++.dg/tree-ssa/pr17517.C32
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/20040907-1.c13
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/20040909-1.c13
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/20040916-1.c12
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/pr16566-1.c15
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/pr16566-2.c13
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/pr16566-3.c12
-rw-r--r--gcc/testsuite/gcc.c-torture/compile/pr17558.c10
-rw-r--r--gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2-lib.c1
-rw-r--r--gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2.c47
-rw-r--r--gcc/testsuite/gcc.c-torture/execute/va-arg-26.c20
-rw-r--r--gcc/testsuite/gcc.dg/20040920-1.c12
-rw-r--r--gcc/testsuite/gcc.dg/Wbad-function-cast-1.c51
-rw-r--r--gcc/testsuite/gcc.dg/nested-redef-1.c44
-rw-r--r--gcc/testsuite/gcc.dg/pr11459-1.c6
-rw-r--r--gcc/testsuite/gcc.dg/pr13804-1.c28
-rw-r--r--gcc/testsuite/gcc.dg/pr17112-1.c32
-rw-r--r--gcc/testsuite/gcc.dg/pr17188-1.c31
-rw-r--r--gcc/testsuite/gcc.dg/pragma-re-3.c18
-rw-r--r--gcc/testsuite/gcc.dg/tree-ssa/loop-6.c26
-rw-r--r--gcc/testsuite/gcc.dg/tree-ssa/pr16721.c15
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-27a.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-29a.c50
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-48a.c58
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-56a.c56
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-62.c68
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-63.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-64.c86
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-65.c84
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-66.c82
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-67.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-68.c90
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-69.c117
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-72.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-72a.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-74.c46
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-75.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-76.c74
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-77.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-77a.c47
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-78.c48
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-79.c48
-rw-r--r--gcc/testsuite/gcc.dg/vect/vect-80.c48
-rw-r--r--gcc/testsuite/gcc.target/mips/asm-1.c14
-rw-r--r--gcc/testsuite/gfortran.dg/pr15164.f9016
-rw-r--r--gcc/testsuite/gfortran.dg/pr15957.f9027
-rw-r--r--gcc/testsuite/gfortran.dg/pr16938.f9027
-rw-r--r--gcc/testsuite/gfortran.dg/pr17286.f9045
-rw-r--r--gcc/testsuite/gfortran.dg/pr17615.f9019
-rw-r--r--gcc/testsuite/gfortran.fortran-torture/execute/iolength_2.f9024
-rw-r--r--gcc/tree-ssa-loop-unswitch.c291
-rw-r--r--intl/.cvsignore1
-rw-r--r--libjava/gnu/java/nio/VMPipe.java64
-rw-r--r--libjava/gnu/java/nio/VMSelector.java59
-rw-r--r--libjava/gnu/regexp/RETokenLookAhead.java87
-rw-r--r--libjava/java/security/cert/X509CRLSelector.java445
-rw-r--r--libjava/java/security/cert/X509CertSelector.java1111
-rw-r--r--libjava/java/util/VMTimeZone.java345
-rw-r--r--libjava/java/util/natVMTimeZone.cc145
-rw-r--r--libjava/javax/crypto/BadPaddingException.java79
-rw-r--r--libjava/javax/crypto/Cipher.java1097
-rw-r--r--libjava/javax/crypto/CipherInputStream.java383
-rw-r--r--libjava/javax/crypto/CipherOutputStream.java268
-rw-r--r--libjava/javax/crypto/CipherSpi.java398
-rw-r--r--libjava/javax/crypto/EncryptedPrivateKeyInfo.java284
-rw-r--r--libjava/javax/crypto/ExemptionMechanism.java226
-rw-r--r--libjava/javax/crypto/ExemptionMechanismException.java81
-rw-r--r--libjava/javax/crypto/ExemptionMechanismSpi.java149
-rw-r--r--libjava/javax/crypto/IllegalBlockSizeException.java71
-rw-r--r--libjava/javax/crypto/KeyAgreement.java373
-rw-r--r--libjava/javax/crypto/KeyAgreementSpi.java160
-rw-r--r--libjava/javax/crypto/KeyGenerator.java284
-rw-r--r--libjava/javax/crypto/KeyGeneratorSpi.java112
-rw-r--r--libjava/javax/crypto/Mac.java414
-rw-r--r--libjava/javax/crypto/MacSpi.java145
-rw-r--r--libjava/javax/crypto/NoSuchPaddingException.java71
-rw-r--r--libjava/javax/crypto/NullCipher.java62
-rw-r--r--libjava/javax/crypto/NullCipherImpl.java127
-rw-r--r--libjava/javax/crypto/SealedObject.java355
-rw-r--r--libjava/javax/crypto/SecretKey.java67
-rw-r--r--libjava/javax/crypto/SecretKeyFactory.java249
-rw-r--r--libjava/javax/crypto/SecretKeyFactorySpi.java108
-rw-r--r--libjava/javax/crypto/ShortBufferException.java70
-rw-r--r--libjava/javax/crypto/interfaces/DHKey.java61
-rw-r--r--libjava/javax/crypto/interfaces/DHPrivateKey.java70
-rw-r--r--libjava/javax/crypto/interfaces/DHPublicKey.java69
-rw-r--r--libjava/javax/crypto/interfaces/PBEKey.java91
-rw-r--r--libjava/javax/crypto/spec/DESKeySpec.java220
-rw-r--r--libjava/javax/crypto/spec/DESedeKeySpec.java151
-rw-r--r--libjava/javax/crypto/spec/DHGenParameterSpec.java100
-rw-r--r--libjava/javax/crypto/spec/DHParameterSpec.java135
-rw-r--r--libjava/javax/crypto/spec/DHPrivateKeySpec.java115
-rw-r--r--libjava/javax/crypto/spec/DHPublicKeySpec.java115
-rw-r--r--libjava/javax/crypto/spec/IvParameterSpec.java96
-rw-r--r--libjava/javax/crypto/spec/PBEKeySpec.java176
-rw-r--r--libjava/javax/crypto/spec/PBEParameterSpec.java100
-rw-r--r--libjava/javax/crypto/spec/RC2ParameterSpec.java166
-rw-r--r--libjava/javax/crypto/spec/RC5ParameterSpec.java202
-rw-r--r--libjava/javax/crypto/spec/SecretKeySpec.java154
-rw-r--r--libjava/javax/net/ServerSocketFactory.java122
-rw-r--r--libjava/javax/net/SocketFactory.java157
-rw-r--r--libjava/javax/net/VanillaServerSocketFactory.java82
-rw-r--r--libjava/javax/net/VanillaSocketFactory.java88
-rw-r--r--libjava/javax/net/ssl/HandshakeCompletedEvent.java152
-rw-r--r--libjava/javax/net/ssl/HandshakeCompletedListener.java57
-rw-r--r--libjava/javax/net/ssl/HostnameVerifier.java64
-rw-r--r--libjava/javax/net/ssl/HttpsURLConnection.java256
-rw-r--r--libjava/javax/net/ssl/KeyManager.java51
-rw-r--r--libjava/javax/net/ssl/KeyManagerFactory.java281
-rw-r--r--libjava/javax/net/ssl/KeyManagerFactorySpi.java102
-rw-r--r--libjava/javax/net/ssl/ManagerFactoryParameters.java50
-rw-r--r--libjava/javax/net/ssl/SSLContext.java269
-rw-r--r--libjava/javax/net/ssl/SSLContextSpi.java109
-rw-r--r--libjava/javax/net/ssl/SSLException.java59
-rw-r--r--libjava/javax/net/ssl/SSLHandshakeException.java51
-rw-r--r--libjava/javax/net/ssl/SSLKeyException.java52
-rw-r--r--libjava/javax/net/ssl/SSLPeerUnverifiedException.java51
-rw-r--r--libjava/javax/net/ssl/SSLPermission.java66
-rw-r--r--libjava/javax/net/ssl/SSLProtocolException.java53
-rw-r--r--libjava/javax/net/ssl/SSLServerSocket.java188
-rw-r--r--libjava/javax/net/ssl/SSLServerSocketFactory.java172
-rw-r--r--libjava/javax/net/ssl/SSLSession.java168
-rw-r--r--libjava/javax/net/ssl/SSLSessionBindingEvent.java94
-rw-r--r--libjava/javax/net/ssl/SSLSessionBindingListener.java65
-rw-r--r--libjava/javax/net/ssl/SSLSessionContext.java103
-rw-r--r--libjava/javax/net/ssl/SSLSocket.java229
-rw-r--r--libjava/javax/net/ssl/SSLSocketFactory.java192
-rw-r--r--libjava/javax/net/ssl/TrivialHostnameVerifier.java51
-rw-r--r--libjava/javax/net/ssl/TrustManager.java47
-rw-r--r--libjava/javax/net/ssl/TrustManagerFactory.java279
-rw-r--r--libjava/javax/net/ssl/TrustManagerFactorySpi.java88
-rw-r--r--libjava/javax/net/ssl/X509KeyManager.java108
-rw-r--r--libjava/javax/net/ssl/X509TrustManager.java76
-rw-r--r--libjava/javax/security/auth/AuthPermission.java146
-rw-r--r--libjava/javax/security/auth/DestroyFailedException.java67
-rw-r--r--libjava/javax/security/auth/Destroyable.java64
-rw-r--r--libjava/javax/security/auth/Policy.java79
-rw-r--r--libjava/javax/security/auth/PrivateCredentialPermission.java326
-rw-r--r--libjava/javax/security/auth/RefreshFailedException.java63
-rw-r--r--libjava/javax/security/auth/Refreshable.java65
-rw-r--r--libjava/javax/security/auth/Subject.java559
-rw-r--r--libjava/javax/security/auth/SubjectDomainCombiner.java96
-rw-r--r--libjava/javax/security/auth/callback/Callback.java65
-rw-r--r--libjava/javax/security/auth/callback/CallbackHandler.java156
-rw-r--r--libjava/javax/security/auth/callback/ChoiceCallback.java237
-rw-r--r--libjava/javax/security/auth/callback/ConfirmationCallback.java506
-rw-r--r--libjava/javax/security/auth/callback/LanguageCallback.java101
-rw-r--r--libjava/javax/security/auth/callback/NameCallback.java179
-rw-r--r--libjava/javax/security/auth/callback/PasswordCallback.java169
-rw-r--r--libjava/javax/security/auth/callback/TextInputCallback.java178
-rw-r--r--libjava/javax/security/auth/callback/TextOutputCallback.java141
-rw-r--r--libjava/javax/security/auth/callback/UnsupportedCallbackException.java102
-rw-r--r--libjava/javax/security/auth/login/AccountExpiredException.java64
-rw-r--r--libjava/javax/security/auth/login/AppConfigurationEntry.java135
-rw-r--r--libjava/javax/security/auth/login/Configuration.java109
-rw-r--r--libjava/javax/security/auth/login/CredentialExpiredException.java64
-rw-r--r--libjava/javax/security/auth/login/FailedLoginException.java63
-rw-r--r--libjava/javax/security/auth/login/LoginContext.java44
-rw-r--r--libjava/javax/security/auth/login/LoginException.java65
-rw-r--r--libjava/javax/security/auth/login/NullConfiguration.java64
-rw-r--r--libjava/javax/security/auth/x500/X500PrivateCredential.java148
-rw-r--r--libjava/javax/security/cert/Certificate.java176
-rw-r--r--libjava/javax/security/cert/CertificateEncodingException.java60
-rw-r--r--libjava/javax/security/cert/CertificateException.java60
-rw-r--r--libjava/javax/security/cert/CertificateExpiredException.java60
-rw-r--r--libjava/javax/security/cert/CertificateNotYetValidException.java60
-rw-r--r--libjava/javax/security/cert/CertificateParsingException.java59
-rw-r--r--libjava/javax/security/cert/X509CertBridge.java203
-rw-r--r--libjava/javax/security/cert/X509Certificate.java191
-rw-r--r--libjava/javax/security/sasl/AuthenticationException.java105
-rw-r--r--libjava/javax/security/sasl/AuthorizeCallback.java171
-rw-r--r--libjava/javax/security/sasl/RealmCallback.java75
-rw-r--r--libjava/javax/security/sasl/RealmChoiceCallback.java71
-rw-r--r--libjava/javax/security/sasl/Sasl.java691
-rw-r--r--libjava/javax/security/sasl/SaslClient.java231
-rw-r--r--libjava/javax/security/sasl/SaslClientFactory.java117
-rw-r--r--libjava/javax/security/sasl/SaslException.java185
-rw-r--r--libjava/javax/security/sasl/SaslServer.java226
-rw-r--r--libjava/javax/security/sasl/SaslServerFactory.java114
-rw-r--r--libjava/org/ietf/jgss/ChannelBinding.java215
-rw-r--r--libjava/org/ietf/jgss/GSSContext.java924
-rw-r--r--libjava/org/ietf/jgss/GSSCredential.java334
-rw-r--r--libjava/org/ietf/jgss/GSSException.java431
-rw-r--r--libjava/org/ietf/jgss/GSSManager.java501
-rw-r--r--libjava/org/ietf/jgss/GSSName.java269
-rw-r--r--libjava/org/ietf/jgss/MessageProp.java273
-rw-r--r--libjava/org/ietf/jgss/MessagesBundle.properties60
-rw-r--r--libjava/org/ietf/jgss/Oid.java385
-rw-r--r--libjava/testsuite/libjava.compile/AssertBug.java7
-rw-r--r--libjava/testsuite/libjava.compile/pr15656.java8
-rw-r--r--libjava/testsuite/libjava.compile/pr15656.xfail1
-rw-r--r--libjava/testsuite/libjava.compile/pr17329.java14
-rw-r--r--libjava/testsuite/libjava.compile/pr17500.java28
-rw-r--r--libjava/testsuite/libjava.lang/pr16789.java15
-rw-r--r--libjava/testsuite/libjava.lang/pr16789.out1
-rw-r--r--libstdc++-v3/testsuite/21_strings/basic_string/element_access/char/empty.cc48
-rw-r--r--libstdc++-v3/testsuite/21_strings/basic_string/element_access/wchar_t/empty.cc48
-rw-r--r--libstdc++-v3/testsuite/21_strings/basic_string/operations/char/1.cc42
-rw-r--r--libstdc++-v3/testsuite/21_strings/basic_string/operations/wchar_t/1.cc42
240 files changed, 29488 insertions, 0 deletions
diff --git a/config/codeset.m4 b/config/codeset.m4
new file mode 100644
index 00000000000..59535ebcff5
--- /dev/null
+++ b/config/codeset.m4
@@ -0,0 +1,23 @@
+# codeset.m4 serial AM1 (gettext-0.10.40)
+dnl Copyright (C) 2000-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([AM_LANGINFO_CODESET],
+[
+ AC_CACHE_CHECK([for nl_langinfo and CODESET], am_cv_langinfo_codeset,
+ [AC_TRY_LINK([#include <langinfo.h>],
+ [char* cs = nl_langinfo(CODESET);],
+ am_cv_langinfo_codeset=yes,
+ am_cv_langinfo_codeset=no)
+ ])
+ if test $am_cv_langinfo_codeset = yes; then
+ AC_DEFINE(HAVE_LANGINFO_CODESET, 1,
+ [Define if you have <langinfo.h> and nl_langinfo(CODESET).])
+ fi
+])
diff --git a/config/gcc-lib-path.m4 b/config/gcc-lib-path.m4
new file mode 100644
index 00000000000..88c4023d01b
--- /dev/null
+++ b/config/gcc-lib-path.m4
@@ -0,0 +1,15 @@
+AC_DEFUN([TL_AC_GNU_MAKE_GCC_LIB_PATH],
+[
+if test x"$SET_GCC_LIB_PATH_CMD" != x; then
+ # SET_GCC_LIB_PATH_CMD is "XXX=path; export XXX;". It is expanded to
+ #
+ # eval "set_gcc_lib_path=XXX=path; export XXX;"
+ #
+ eval "set_gcc_lib_path=$SET_GCC_LIB_PATH_CMD"
+ # It will set set_gcc_lib_path to "export XXX=path" for GNU make.
+ set_gcc_lib_path="export $set_gcc_lib_path"
+else
+ set_gcc_lib_path=
+fi
+AC_SUBST(set_gcc_lib_path)
+])dnl
diff --git a/config/gettext-sister.m4 b/config/gettext-sister.m4
new file mode 100644
index 00000000000..d10aae80b6b
--- /dev/null
+++ b/config/gettext-sister.m4
@@ -0,0 +1,66 @@
+# intl sister-directory configuration rules.
+#
+
+# The idea behind this macro is that there's no need to repeat all the
+# autoconf probes done by the intl directory - it's already done them
+# for us. In fact, there's no need even to look at the cache for the
+# answers. All we need to do is nab a few pieces of information.
+# The intl directory is set up to make this easy, by generating a
+# small file which can be sourced as a shell script; then we produce
+# the necessary substitutions and definitions for this directory.
+
+AC_DEFUN([ZW_GNU_GETTEXT_SISTER_DIR],
+[# If we haven't got the data from the intl directory,
+# assume NLS is disabled.
+USE_NLS=no AC_SUBST(USE_NLS)
+LIBINTL= AC_SUBST(LIBINTL)
+LIBINTL_DEP= AC_SUBST(LIBINTL_DEP)
+INCINTL= AC_SUBST(INCINTL)
+XGETTEXT= AC_SUBST(XGETTEXT)
+GMSGFMT= AC_SUBST(GMSGFMT)
+POSUB= AC_SUBST(POSUB)
+if test -f ../intl/config.intl; then
+ . ../intl/config.intl
+fi
+AC_MSG_CHECKING([whether NLS is requested])
+if test x"$USE_NLS" != xyes; then
+ AC_MSG_RESULT(no)
+else
+ AC_MSG_RESULT(yes)
+ AC_DEFINE(ENABLE_NLS, 1,
+ [Define to 1 if translation of program messages to the
+ user's native language is requested.])
+
+ AC_MSG_CHECKING(for catalogs to be installed)
+ # Look for .po and .gmo files in the source directory.
+ CATALOGS= AC_SUBST(CATALOGS)
+ XLINGUAS=
+ for cat in $srcdir/po/*.gmo $srcdir/po/*.po; do
+ # If there aren't any .gmo files the shell will give us the
+ # literal string "../path/to/srcdir/po/*.gmo" which has to be
+ # weeded out.
+ case "$cat" in *\**)
+ continue;;
+ esac
+ # The quadruple backslash is collapsed to a double backslash
+ # by the backticks, then collapsed again by the double quotes,
+ # leaving us with one backslash in the sed expression (right
+ # before the dot that mustn't act as a wildcard).
+ cat=`echo $cat | sed -e "s!$srcdir/!!" -e "s!\\\\.po!.gmo!"`
+ lang=`echo $cat | sed -e 's!po/!!' -e "s!\\\\.gmo!!"`
+ # The user is allowed to set LINGUAS to a list of languages to
+ # install catalogs for. If it's empty that means "all of them."
+ if test "x$LINGUAS" = x; then
+ CATALOGS="$CATALOGS $cat"
+ XLINGUAS="$XLINGUAS $lang"
+ else
+ case "$LINGUAS" in *$lang*)
+ CATALOGS="$CATALOGS $cat"
+ XLINGUAS="$XLINGUAS $lang"
+ ;;
+ esac
+ fi
+ done
+ LINGUAS="$XLINGUAS"
+ AC_MSG_RESULT($LINGUAS)
+fi])
diff --git a/config/glibc21.m4 b/config/glibc21.m4
new file mode 100644
index 00000000000..9c9f3db3036
--- /dev/null
+++ b/config/glibc21.m4
@@ -0,0 +1,32 @@
+# glibc21.m4 serial 2 (fileutils-4.1.3, gettext-0.10.40)
+dnl Copyright (C) 2000-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+# Test for the GNU C Library, version 2.1 or newer.
+# From Bruno Haible.
+
+AC_DEFUN([jm_GLIBC21],
+ [
+ AC_CACHE_CHECK(whether we are using the GNU C Library 2.1 or newer,
+ ac_cv_gnu_library_2_1,
+ [AC_EGREP_CPP([Lucky GNU user],
+ [
+#include <features.h>
+#ifdef __GNU_LIBRARY__
+ #if (__GLIBC__ == 2 && __GLIBC_MINOR__ >= 1) || (__GLIBC__ > 2)
+ Lucky GNU user
+ #endif
+#endif
+ ],
+ ac_cv_gnu_library_2_1=yes,
+ ac_cv_gnu_library_2_1=no)
+ ]
+ )
+ AC_SUBST(GLIBC21)
+ GLIBC21="$ac_cv_gnu_library_2_1"
+ ]
+)
diff --git a/config/iconv.m4 b/config/iconv.m4
new file mode 100644
index 00000000000..c5f3579827e
--- /dev/null
+++ b/config/iconv.m4
@@ -0,0 +1,103 @@
+# iconv.m4 serial AM4 (gettext-0.11.3)
+dnl Copyright (C) 2000-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([AM_ICONV_LINKFLAGS_BODY],
+[
+ dnl Prerequisites of AC_LIB_LINKFLAGS_BODY.
+ AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+ AC_REQUIRE([AC_LIB_RPATH])
+
+ dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV
+ dnl accordingly.
+ AC_LIB_LINKFLAGS_BODY([iconv])
+])
+
+AC_DEFUN([AM_ICONV_LINK],
+[
+ dnl Some systems have iconv in libc, some have it in libiconv (OSF/1 and
+ dnl those with the standalone portable GNU libiconv installed).
+
+ dnl Search for libiconv and define LIBICONV, LTLIBICONV and INCICONV
+ dnl accordingly.
+ AC_REQUIRE([AM_ICONV_LINKFLAGS_BODY])
+
+ dnl Add $INCICONV to CPPFLAGS before performing the following checks,
+ dnl because if the user has installed libiconv and not disabled its use
+ dnl via --without-libiconv-prefix, he wants to use it. The first
+ dnl AC_TRY_LINK will then fail, the second AC_TRY_LINK will succeed.
+ am_save_CPPFLAGS="$CPPFLAGS"
+ AC_LIB_APPENDTOVAR([CPPFLAGS], [$INCICONV])
+
+ AC_CACHE_CHECK(for iconv, am_cv_func_iconv, [
+ am_cv_func_iconv="no, consider installing GNU libiconv"
+ am_cv_lib_iconv=no
+ AC_TRY_LINK([#include <stdlib.h>
+#include <iconv.h>],
+ [iconv_t cd = iconv_open("","");
+ iconv(cd,NULL,NULL,NULL,NULL);
+ iconv_close(cd);],
+ am_cv_func_iconv=yes)
+ if test "$am_cv_func_iconv" != yes; then
+ am_save_LIBS="$LIBS"
+ LIBS="$LIBS $LIBICONV"
+ AC_TRY_LINK([#include <stdlib.h>
+#include <iconv.h>],
+ [iconv_t cd = iconv_open("","");
+ iconv(cd,NULL,NULL,NULL,NULL);
+ iconv_close(cd);],
+ am_cv_lib_iconv=yes
+ am_cv_func_iconv=yes)
+ LIBS="$am_save_LIBS"
+ fi
+ ])
+ if test "$am_cv_func_iconv" = yes; then
+ AC_DEFINE(HAVE_ICONV, 1, [Define if you have the iconv() function.])
+ fi
+ if test "$am_cv_lib_iconv" = yes; then
+ AC_MSG_CHECKING([how to link with libiconv])
+ AC_MSG_RESULT([$LIBICONV])
+ else
+ dnl If $LIBICONV didn't lead to a usable library, we don't need $INCICONV
+ dnl either.
+ CPPFLAGS="$am_save_CPPFLAGS"
+ LIBICONV=
+ LTLIBICONV=
+ fi
+ AC_SUBST(LIBICONV)
+ AC_SUBST(LTLIBICONV)
+])
+
+AC_DEFUN([AM_ICONV],
+[
+ AM_ICONV_LINK
+ if test "$am_cv_func_iconv" = yes; then
+ AC_MSG_CHECKING([for iconv declaration])
+ AC_CACHE_VAL(am_cv_proto_iconv, [
+ AC_TRY_COMPILE([
+#include <stdlib.h>
+#include <iconv.h>
+extern
+#ifdef __cplusplus
+"C"
+#endif
+#if defined(__STDC__) || defined(__cplusplus)
+size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);
+#else
+size_t iconv();
+#endif
+], [], am_cv_proto_iconv_arg1="", am_cv_proto_iconv_arg1="const")
+ am_cv_proto_iconv="extern size_t iconv (iconv_t cd, $am_cv_proto_iconv_arg1 char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft);"])
+ am_cv_proto_iconv=`echo "[$]am_cv_proto_iconv" | tr -s ' ' | sed -e 's/( /(/'`
+ AC_MSG_RESULT([$]{ac_t:-
+ }[$]am_cv_proto_iconv)
+ AC_DEFINE_UNQUOTED(ICONV_CONST, $am_cv_proto_iconv_arg1,
+ [Define as const if the declaration of iconv() needs const.])
+ fi
+])
diff --git a/config/intdiv0.m4 b/config/intdiv0.m4
new file mode 100644
index 00000000000..55dddcf1c24
--- /dev/null
+++ b/config/intdiv0.m4
@@ -0,0 +1,72 @@
+# intdiv0.m4 serial 1 (gettext-0.11.3)
+dnl Copyright (C) 2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+AC_DEFUN([gt_INTDIV0],
+[
+ AC_REQUIRE([AC_PROG_CC])dnl
+ AC_REQUIRE([AC_CANONICAL_HOST])dnl
+
+ AC_CACHE_CHECK([whether integer division by zero raises SIGFPE],
+ gt_cv_int_divbyzero_sigfpe,
+ [
+ AC_TRY_RUN([
+#include <stdlib.h>
+#include <signal.h>
+
+static void
+#ifdef __cplusplus
+sigfpe_handler (int sig)
+#else
+sigfpe_handler (sig) int sig;
+#endif
+{
+ /* Exit with code 0 if SIGFPE, with code 1 if any other signal. */
+ exit (sig != SIGFPE);
+}
+
+int x = 1;
+int y = 0;
+int z;
+int nan;
+
+int main ()
+{
+ signal (SIGFPE, sigfpe_handler);
+/* IRIX and AIX (when "xlc -qcheck" is used) yield signal SIGTRAP. */
+#if (defined (__sgi) || defined (_AIX)) && defined (SIGTRAP)
+ signal (SIGTRAP, sigfpe_handler);
+#endif
+/* Linux/SPARC yields signal SIGILL. */
+#if defined (__sparc__) && defined (__linux__)
+ signal (SIGILL, sigfpe_handler);
+#endif
+
+ z = x / y;
+ nan = y / y;
+ exit (1);
+}
+], gt_cv_int_divbyzero_sigfpe=yes, gt_cv_int_divbyzero_sigfpe=no,
+ [
+ # Guess based on the CPU.
+ case "$host_cpu" in
+ alpha* | i[34567]86 | m68k | s390*)
+ gt_cv_int_divbyzero_sigfpe="guessing yes";;
+ *)
+ gt_cv_int_divbyzero_sigfpe="guessing no";;
+ esac
+ ])
+ ])
+ case "$gt_cv_int_divbyzero_sigfpe" in
+ *yes) value=1;;
+ *) value=0;;
+ esac
+ AC_DEFINE_UNQUOTED(INTDIV0_RAISES_SIGFPE, $value,
+ [Define if integer division by zero raises signal SIGFPE.])
+])
diff --git a/config/inttypes-pri.m4 b/config/inttypes-pri.m4
new file mode 100644
index 00000000000..fd007c31289
--- /dev/null
+++ b/config/inttypes-pri.m4
@@ -0,0 +1,32 @@
+# inttypes-pri.m4 serial 1 (gettext-0.11.4)
+dnl Copyright (C) 1997-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+# Define PRI_MACROS_BROKEN if <inttypes.h> exists and defines the PRI*
+# macros to non-string values. This is the case on AIX 4.3.3.
+
+AC_DEFUN([gt_INTTYPES_PRI],
+[
+ AC_REQUIRE([gt_HEADER_INTTYPES_H])
+ if test $gt_cv_header_inttypes_h = yes; then
+ AC_CACHE_CHECK([whether the inttypes.h PRIxNN macros are broken],
+ gt_cv_inttypes_pri_broken,
+ [
+ AC_TRY_COMPILE([#include <inttypes.h>
+#ifdef PRId32
+char *p = PRId32;
+#endif
+], [], gt_cv_inttypes_pri_broken=no, gt_cv_inttypes_pri_broken=yes)
+ ])
+ fi
+ if test "$gt_cv_inttypes_pri_broken" = yes; then
+ AC_DEFINE_UNQUOTED(PRI_MACROS_BROKEN, 1,
+ [Define if <inttypes.h> exists and defines unusable PRI* macros.])
+ fi
+])
diff --git a/config/inttypes.m4 b/config/inttypes.m4
new file mode 100644
index 00000000000..ab370ffe005
--- /dev/null
+++ b/config/inttypes.m4
@@ -0,0 +1,27 @@
+# inttypes.m4 serial 1 (gettext-0.11.4)
+dnl Copyright (C) 1997-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Paul Eggert.
+
+# Define HAVE_INTTYPES_H if <inttypes.h> exists and doesn't clash with
+# <sys/types.h>.
+
+AC_DEFUN([gt_HEADER_INTTYPES_H],
+[
+ AC_CACHE_CHECK([for inttypes.h], gt_cv_header_inttypes_h,
+ [
+ AC_TRY_COMPILE(
+ [#include <sys/types.h>
+#include <inttypes.h>],
+ [], gt_cv_header_inttypes_h=yes, gt_cv_header_inttypes_h=no)
+ ])
+ if test $gt_cv_header_inttypes_h = yes; then
+ AC_DEFINE_UNQUOTED(HAVE_INTTYPES_H, 1,
+ [Define if <inttypes.h> exists and doesn't clash with <sys/types.h>.])
+ fi
+])
diff --git a/config/inttypes_h.m4 b/config/inttypes_h.m4
new file mode 100644
index 00000000000..f342eba39a5
--- /dev/null
+++ b/config/inttypes_h.m4
@@ -0,0 +1,28 @@
+# inttypes_h.m4 serial 5 (gettext-0.12)
+dnl Copyright (C) 1997-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Paul Eggert.
+
+# Define HAVE_INTTYPES_H_WITH_UINTMAX if <inttypes.h> exists,
+# doesn't clash with <sys/types.h>, and declares uintmax_t.
+
+AC_DEFUN([jm_AC_HEADER_INTTYPES_H],
+[
+ AC_CACHE_CHECK([for inttypes.h], jm_ac_cv_header_inttypes_h,
+ [AC_TRY_COMPILE(
+ [#include <sys/types.h>
+#include <inttypes.h>],
+ [uintmax_t i = (uintmax_t) -1;],
+ jm_ac_cv_header_inttypes_h=yes,
+ jm_ac_cv_header_inttypes_h=no)])
+ if test $jm_ac_cv_header_inttypes_h = yes; then
+ AC_DEFINE_UNQUOTED(HAVE_INTTYPES_H_WITH_UINTMAX, 1,
+ [Define if <inttypes.h> exists, doesn't clash with <sys/types.h>,
+ and declares uintmax_t. ])
+ fi
+])
diff --git a/config/lcmessage.m4 b/config/lcmessage.m4
new file mode 100644
index 00000000000..ffd4008b825
--- /dev/null
+++ b/config/lcmessage.m4
@@ -0,0 +1,32 @@
+# lcmessage.m4 serial 3 (gettext-0.11.3)
+dnl Copyright (C) 1995-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+dnl
+dnl This file can can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Library General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Library General Public License, and the rest of the GNU
+dnl gettext package package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl Ulrich Drepper <drepper@cygnus.com>, 1995.
+
+# Check whether LC_MESSAGES is available in <locale.h>.
+
+AC_DEFUN([AM_LC_MESSAGES],
+[
+ AC_CACHE_CHECK([for LC_MESSAGES], am_cv_val_LC_MESSAGES,
+ [AC_TRY_LINK([#include <locale.h>], [return LC_MESSAGES],
+ am_cv_val_LC_MESSAGES=yes, am_cv_val_LC_MESSAGES=no)])
+ if test $am_cv_val_LC_MESSAGES = yes; then
+ AC_DEFINE(HAVE_LC_MESSAGES, 1,
+ [Define if your <locale.h> file defines LC_MESSAGES.])
+ fi
+])
diff --git a/config/lib-ld.m4 b/config/lib-ld.m4
new file mode 100644
index 00000000000..11d0ce77342
--- /dev/null
+++ b/config/lib-ld.m4
@@ -0,0 +1,110 @@
+# lib-ld.m4 serial 2 (gettext-0.12)
+dnl Copyright (C) 1996-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl Subroutines of libtool.m4,
+dnl with replacements s/AC_/AC_LIB/ and s/lt_cv/acl_cv/ to avoid collision
+dnl with libtool.m4.
+
+dnl From libtool-1.4. Sets the variable with_gnu_ld to yes or no.
+AC_DEFUN([AC_LIB_PROG_LD_GNU],
+[AC_CACHE_CHECK([if the linker ($LD) is GNU ld], acl_cv_prog_gnu_ld,
+[# I'd rather use --version here, but apparently some GNU ld's only accept -v.
+if $LD -v 2>&1 </dev/null | egrep '(GNU|with BFD)' 1>&5; then
+ acl_cv_prog_gnu_ld=yes
+else
+ acl_cv_prog_gnu_ld=no
+fi])
+with_gnu_ld=$acl_cv_prog_gnu_ld
+])
+
+dnl From libtool-1.4. Sets the variable LD.
+AC_DEFUN([AC_LIB_PROG_LD],
+[AC_ARG_WITH(gnu-ld,
+[ --with-gnu-ld assume the C compiler uses GNU ld [default=no]],
+test "$withval" = no || with_gnu_ld=yes, with_gnu_ld=no)
+AC_REQUIRE([AC_PROG_CC])dnl
+AC_REQUIRE([AC_CANONICAL_HOST])dnl
+# Prepare PATH_SEPARATOR.
+# The user is always right.
+if test "${PATH_SEPARATOR+set}" != set; then
+ echo "#! /bin/sh" >conf$$.sh
+ echo "exit 0" >>conf$$.sh
+ chmod +x conf$$.sh
+ if (PATH="/nonexistent;."; conf$$.sh) >/dev/null 2>&1; then
+ PATH_SEPARATOR=';'
+ else
+ PATH_SEPARATOR=:
+ fi
+ rm -f conf$$.sh
+fi
+ac_prog=ld
+if test "$GCC" = yes; then
+ # Check if gcc -print-prog-name=ld gives a path.
+ AC_MSG_CHECKING([for ld used by GCC])
+ case $host in
+ *-*-mingw*)
+ # gcc leaves a trailing carriage return which upsets mingw
+ ac_prog=`($CC -print-prog-name=ld) 2>&5 | tr -d '\015'` ;;
+ *)
+ ac_prog=`($CC -print-prog-name=ld) 2>&5` ;;
+ esac
+ case $ac_prog in
+ # Accept absolute paths.
+ [[\\/]* | [A-Za-z]:[\\/]*)]
+ [re_direlt='/[^/][^/]*/\.\./']
+ # Canonicalize the path of ld
+ ac_prog=`echo $ac_prog| sed 's%\\\\%/%g'`
+ while echo $ac_prog | grep "$re_direlt" > /dev/null 2>&1; do
+ ac_prog=`echo $ac_prog| sed "s%$re_direlt%/%"`
+ done
+ test -z "$LD" && LD="$ac_prog"
+ ;;
+ "")
+ # If it fails, then pretend we aren't using GCC.
+ ac_prog=ld
+ ;;
+ *)
+ # If it is relative, then search for the first ld in PATH.
+ with_gnu_ld=unknown
+ ;;
+ esac
+elif test "$with_gnu_ld" = yes; then
+ AC_MSG_CHECKING([for GNU ld])
+else
+ AC_MSG_CHECKING([for non-GNU ld])
+fi
+AC_CACHE_VAL(acl_cv_path_LD,
+[if test -z "$LD"; then
+ IFS="${IFS= }"; ac_save_ifs="$IFS"; IFS="${IFS}${PATH_SEPARATOR-:}"
+ for ac_dir in $PATH; do
+ test -z "$ac_dir" && ac_dir=.
+ if test -f "$ac_dir/$ac_prog" || test -f "$ac_dir/$ac_prog$ac_exeext"; then
+ acl_cv_path_LD="$ac_dir/$ac_prog"
+ # Check to see if the program is GNU ld. I'd rather use --version,
+ # but apparently some GNU ld's only accept -v.
+ # Break only if it was the GNU/non-GNU ld that we prefer.
+ if "$acl_cv_path_LD" -v 2>&1 < /dev/null | egrep '(GNU|with BFD)' > /dev/null; then
+ test "$with_gnu_ld" != no && break
+ else
+ test "$with_gnu_ld" != yes && break
+ fi
+ fi
+ done
+ IFS="$ac_save_ifs"
+else
+ acl_cv_path_LD="$LD" # Let the user override the test with a path.
+fi])
+LD="$acl_cv_path_LD"
+if test -n "$LD"; then
+ AC_MSG_RESULT($LD)
+else
+ AC_MSG_RESULT(no)
+fi
+test -z "$LD" && AC_MSG_ERROR([no acceptable ld found in \$PATH])
+AC_LIB_PROG_LD_GNU
+])
diff --git a/config/lib-link.m4 b/config/lib-link.m4
new file mode 100644
index 00000000000..eeb200d266d
--- /dev/null
+++ b/config/lib-link.m4
@@ -0,0 +1,551 @@
+# lib-link.m4 serial 4 (gettext-0.12)
+dnl Copyright (C) 2001-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+dnl AC_LIB_LINKFLAGS(name [, dependencies]) searches for libname and
+dnl the libraries corresponding to explicit and implicit dependencies.
+dnl Sets and AC_SUBSTs the LIB${NAME} and LTLIB${NAME} variables and
+dnl augments the CPPFLAGS variable.
+AC_DEFUN([AC_LIB_LINKFLAGS],
+[
+ AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+ AC_REQUIRE([AC_LIB_RPATH])
+ define([Name],[translit([$1],[./-], [___])])
+ define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+ [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
+ AC_CACHE_CHECK([how to link with lib[]$1], [ac_cv_lib[]Name[]_libs], [
+ AC_LIB_LINKFLAGS_BODY([$1], [$2])
+ ac_cv_lib[]Name[]_libs="$LIB[]NAME"
+ ac_cv_lib[]Name[]_ltlibs="$LTLIB[]NAME"
+ ac_cv_lib[]Name[]_cppflags="$INC[]NAME"
+ ])
+ LIB[]NAME="$ac_cv_lib[]Name[]_libs"
+ LTLIB[]NAME="$ac_cv_lib[]Name[]_ltlibs"
+ INC[]NAME="$ac_cv_lib[]Name[]_cppflags"
+ AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME)
+ AC_SUBST([LIB]NAME)
+ AC_SUBST([LTLIB]NAME)
+ dnl Also set HAVE_LIB[]NAME so that AC_LIB_HAVE_LINKFLAGS can reuse the
+ dnl results of this search when this library appears as a dependency.
+ HAVE_LIB[]NAME=yes
+ undefine([Name])
+ undefine([NAME])
+])
+
+dnl AC_LIB_HAVE_LINKFLAGS(name, dependencies, includes, testcode)
+dnl searches for libname and the libraries corresponding to explicit and
+dnl implicit dependencies, together with the specified include files and
+dnl the ability to compile and link the specified testcode. If found, it
+dnl sets and AC_SUBSTs HAVE_LIB${NAME}=yes and the LIB${NAME} and
+dnl LTLIB${NAME} variables and augments the CPPFLAGS variable, and
+dnl #defines HAVE_LIB${NAME} to 1. Otherwise, it sets and AC_SUBSTs
+dnl HAVE_LIB${NAME}=no and LIB${NAME} and LTLIB${NAME} to empty.
+AC_DEFUN([AC_LIB_HAVE_LINKFLAGS],
+[
+ AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+ AC_REQUIRE([AC_LIB_RPATH])
+ define([Name],[translit([$1],[./-], [___])])
+ define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+ [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
+
+ dnl Search for lib[]Name and define LIB[]NAME, LTLIB[]NAME and INC[]NAME
+ dnl accordingly.
+ AC_LIB_LINKFLAGS_BODY([$1], [$2])
+
+ dnl Add $INC[]NAME to CPPFLAGS before performing the following checks,
+ dnl because if the user has installed lib[]Name and not disabled its use
+ dnl via --without-lib[]Name-prefix, he wants to use it.
+ ac_save_CPPFLAGS="$CPPFLAGS"
+ AC_LIB_APPENDTOVAR([CPPFLAGS], [$INC]NAME)
+
+ AC_CACHE_CHECK([for lib[]$1], [ac_cv_lib[]Name], [
+ ac_save_LIBS="$LIBS"
+ LIBS="$LIBS $LIB[]NAME"
+ AC_TRY_LINK([$3], [$4], [ac_cv_lib[]Name=yes], [ac_cv_lib[]Name=no])
+ LIBS="$ac_save_LIBS"
+ ])
+ if test "$ac_cv_lib[]Name" = yes; then
+ HAVE_LIB[]NAME=yes
+ AC_DEFINE([HAVE_LIB]NAME, 1, [Define if you have the $1 library.])
+ AC_MSG_CHECKING([how to link with lib[]$1])
+ AC_MSG_RESULT([$LIB[]NAME])
+ else
+ HAVE_LIB[]NAME=no
+ dnl If $LIB[]NAME didn't lead to a usable library, we don't need
+ dnl $INC[]NAME either.
+ CPPFLAGS="$ac_save_CPPFLAGS"
+ LIB[]NAME=
+ LTLIB[]NAME=
+ fi
+ AC_SUBST([HAVE_LIB]NAME)
+ AC_SUBST([LIB]NAME)
+ AC_SUBST([LTLIB]NAME)
+ undefine([Name])
+ undefine([NAME])
+])
+
+dnl Determine the platform dependent parameters needed to use rpath:
+dnl libext, shlibext, hardcode_libdir_flag_spec, hardcode_libdir_separator,
+dnl hardcode_direct, hardcode_minus_L.
+AC_DEFUN([AC_LIB_RPATH],
+[
+ AC_REQUIRE([AC_PROG_CC]) dnl we use $CC, $GCC, $LDFLAGS
+ AC_REQUIRE([AC_LIB_PROG_LD]) dnl we use $LD, $with_gnu_ld
+ AC_REQUIRE([AC_CANONICAL_HOST]) dnl we use $host
+ AC_REQUIRE([AC_CONFIG_AUX_DIR_DEFAULT]) dnl we use $ac_aux_dir
+ AC_CACHE_CHECK([for shared library run path origin], acl_cv_rpath, [
+ CC="$CC" GCC="$GCC" LDFLAGS="$LDFLAGS" LD="$LD" with_gnu_ld="$with_gnu_ld" \
+ ${CONFIG_SHELL-/bin/sh} "$ac_aux_dir/config.rpath" "$host" > conftest.sh
+ . ./conftest.sh
+ rm -f ./conftest.sh
+ acl_cv_rpath=done
+ ])
+ wl="$acl_cv_wl"
+ libext="$acl_cv_libext"
+ shlibext="$acl_cv_shlibext"
+ hardcode_libdir_flag_spec="$acl_cv_hardcode_libdir_flag_spec"
+ hardcode_libdir_separator="$acl_cv_hardcode_libdir_separator"
+ hardcode_direct="$acl_cv_hardcode_direct"
+ hardcode_minus_L="$acl_cv_hardcode_minus_L"
+ dnl Determine whether the user wants rpath handling at all.
+ AC_ARG_ENABLE(rpath,
+ [ --disable-rpath do not hardcode runtime library paths],
+ :, enable_rpath=yes)
+])
+
+dnl AC_LIB_LINKFLAGS_BODY(name [, dependencies]) searches for libname and
+dnl the libraries corresponding to explicit and implicit dependencies.
+dnl Sets the LIB${NAME}, LTLIB${NAME} and INC${NAME} variables.
+AC_DEFUN([AC_LIB_LINKFLAGS_BODY],
+[
+ define([NAME],[translit([$1],[abcdefghijklmnopqrstuvwxyz./-],
+ [ABCDEFGHIJKLMNOPQRSTUVWXYZ___])])
+ dnl By default, look in $includedir and $libdir.
+ use_additional=yes
+ AC_LIB_WITH_FINAL_PREFIX([
+ eval additional_includedir=\"$includedir\"
+ eval additional_libdir=\"$libdir\"
+ ])
+ AC_LIB_ARG_WITH([lib$1-prefix],
+[ --with-lib$1-prefix[=DIR] search for lib$1 in DIR/include and DIR/lib
+ --without-lib$1-prefix don't search for lib$1 in includedir and libdir],
+[
+ if test "X$withval" = "Xno"; then
+ use_additional=no
+ else
+ if test "X$withval" = "X"; then
+ AC_LIB_WITH_FINAL_PREFIX([
+ eval additional_includedir=\"$includedir\"
+ eval additional_libdir=\"$libdir\"
+ ])
+ else
+ additional_includedir="$withval/include"
+ additional_libdir="$withval/lib"
+ fi
+ fi
+])
+ dnl Search the library and its dependencies in $additional_libdir and
+ dnl $LDFLAGS. Using breadth-first-seach.
+ LIB[]NAME=
+ LTLIB[]NAME=
+ INC[]NAME=
+ rpathdirs=
+ ltrpathdirs=
+ names_already_handled=
+ names_next_round='$1 $2'
+ while test -n "$names_next_round"; do
+ names_this_round="$names_next_round"
+ names_next_round=
+ for name in $names_this_round; do
+ already_handled=
+ for n in $names_already_handled; do
+ if test "$n" = "$name"; then
+ already_handled=yes
+ break
+ fi
+ done
+ if test -z "$already_handled"; then
+ names_already_handled="$names_already_handled $name"
+ dnl See if it was already located by an earlier AC_LIB_LINKFLAGS
+ dnl or AC_LIB_HAVE_LINKFLAGS call.
+ uppername=`echo "$name" | sed -e 'y|abcdefghijklmnopqrstuvwxyz./-|ABCDEFGHIJKLMNOPQRSTUVWXYZ___|'`
+ eval value=\"\$HAVE_LIB$uppername\"
+ if test -n "$value"; then
+ if test "$value" = yes; then
+ eval value=\"\$LIB$uppername\"
+ test -z "$value" || LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$value"
+ eval value=\"\$LTLIB$uppername\"
+ test -z "$value" || LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$value"
+ else
+ dnl An earlier call to AC_LIB_HAVE_LINKFLAGS has determined
+ dnl that this library doesn't exist. So just drop it.
+ :
+ fi
+ else
+ dnl Search the library lib$name in $additional_libdir and $LDFLAGS
+ dnl and the already constructed $LIBNAME/$LTLIBNAME.
+ found_dir=
+ found_la=
+ found_so=
+ found_a=
+ if test $use_additional = yes; then
+ if test -n "$shlibext" && test -f "$additional_libdir/lib$name.$shlibext"; then
+ found_dir="$additional_libdir"
+ found_so="$additional_libdir/lib$name.$shlibext"
+ if test -f "$additional_libdir/lib$name.la"; then
+ found_la="$additional_libdir/lib$name.la"
+ fi
+ else
+ if test -f "$additional_libdir/lib$name.$libext"; then
+ found_dir="$additional_libdir"
+ found_a="$additional_libdir/lib$name.$libext"
+ if test -f "$additional_libdir/lib$name.la"; then
+ found_la="$additional_libdir/lib$name.la"
+ fi
+ fi
+ fi
+ fi
+ if test "X$found_dir" = "X"; then
+ for x in $LDFLAGS $LTLIB[]NAME; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ case "$x" in
+ -L*)
+ dir=`echo "X$x" | sed -e 's/^X-L//'`
+ if test -n "$shlibext" && test -f "$dir/lib$name.$shlibext"; then
+ found_dir="$dir"
+ found_so="$dir/lib$name.$shlibext"
+ if test -f "$dir/lib$name.la"; then
+ found_la="$dir/lib$name.la"
+ fi
+ else
+ if test -f "$dir/lib$name.$libext"; then
+ found_dir="$dir"
+ found_a="$dir/lib$name.$libext"
+ if test -f "$dir/lib$name.la"; then
+ found_la="$dir/lib$name.la"
+ fi
+ fi
+ fi
+ ;;
+ esac
+ if test "X$found_dir" != "X"; then
+ break
+ fi
+ done
+ fi
+ if test "X$found_dir" != "X"; then
+ dnl Found the library.
+ LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$found_dir -l$name"
+ if test "X$found_so" != "X"; then
+ dnl Linking with a shared library. We attempt to hardcode its
+ dnl directory into the executable's runpath, unless it's the
+ dnl standard /usr/lib.
+ if test "$enable_rpath" = no || test "X$found_dir" = "X/usr/lib"; then
+ dnl No hardcoding is needed.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+ else
+ dnl Use an explicit option to hardcode DIR into the resulting
+ dnl binary.
+ dnl Potentially add DIR to ltrpathdirs.
+ dnl The ltrpathdirs will be appended to $LTLIBNAME at the end.
+ haveit=
+ for x in $ltrpathdirs; do
+ if test "X$x" = "X$found_dir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ ltrpathdirs="$ltrpathdirs $found_dir"
+ fi
+ dnl The hardcoding into $LIBNAME is system dependent.
+ if test "$hardcode_direct" = yes; then
+ dnl Using DIR/libNAME.so during linking hardcodes DIR into the
+ dnl resulting binary.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+ else
+ if test -n "$hardcode_libdir_flag_spec" && test "$hardcode_minus_L" = no; then
+ dnl Use an explicit option to hardcode DIR into the resulting
+ dnl binary.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+ dnl Potentially add DIR to rpathdirs.
+ dnl The rpathdirs will be appended to $LIBNAME at the end.
+ haveit=
+ for x in $rpathdirs; do
+ if test "X$x" = "X$found_dir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ rpathdirs="$rpathdirs $found_dir"
+ fi
+ else
+ dnl Rely on "-L$found_dir".
+ dnl But don't add it if it's already contained in the LDFLAGS
+ dnl or the already constructed $LIBNAME
+ haveit=
+ for x in $LDFLAGS $LIB[]NAME; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X-L$found_dir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir"
+ fi
+ if test "$hardcode_minus_L" != no; then
+ dnl FIXME: Not sure whether we should use
+ dnl "-L$found_dir -l$name" or "-L$found_dir $found_so"
+ dnl here.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_so"
+ else
+ dnl We cannot use $hardcode_runpath_var and LD_RUN_PATH
+ dnl here, because this doesn't fit in flags passed to the
+ dnl compiler. So give up. No hardcoding. This affects only
+ dnl very old systems.
+ dnl FIXME: Not sure whether we should use
+ dnl "-L$found_dir -l$name" or "-L$found_dir $found_so"
+ dnl here.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name"
+ fi
+ fi
+ fi
+ fi
+ else
+ if test "X$found_a" != "X"; then
+ dnl Linking with a static library.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$found_a"
+ else
+ dnl We shouldn't come here, but anyway it's good to have a
+ dnl fallback.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$found_dir -l$name"
+ fi
+ fi
+ dnl Assume the include files are nearby.
+ additional_includedir=
+ case "$found_dir" in
+ */lib | */lib/)
+ basedir=`echo "X$found_dir" | sed -e 's,^X,,' -e 's,/lib/*$,,'`
+ additional_includedir="$basedir/include"
+ ;;
+ esac
+ if test "X$additional_includedir" != "X"; then
+ dnl Potentially add $additional_includedir to $INCNAME.
+ dnl But don't add it
+ dnl 1. if it's the standard /usr/include,
+ dnl 2. if it's /usr/local/include and we are using GCC on Linux,
+ dnl 3. if it's already present in $CPPFLAGS or the already
+ dnl constructed $INCNAME,
+ dnl 4. if it doesn't exist as a directory.
+ if test "X$additional_includedir" != "X/usr/include"; then
+ haveit=
+ if test "X$additional_includedir" = "X/usr/local/include"; then
+ if test -n "$GCC"; then
+ case $host_os in
+ linux*) haveit=yes;;
+ esac
+ fi
+ fi
+ if test -z "$haveit"; then
+ for x in $CPPFLAGS $INC[]NAME; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X-I$additional_includedir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ if test -d "$additional_includedir"; then
+ dnl Really add $additional_includedir to $INCNAME.
+ INC[]NAME="${INC[]NAME}${INC[]NAME:+ }-I$additional_includedir"
+ fi
+ fi
+ fi
+ fi
+ fi
+ dnl Look for dependencies.
+ if test -n "$found_la"; then
+ dnl Read the .la file. It defines the variables
+ dnl dlname, library_names, old_library, dependency_libs, current,
+ dnl age, revision, installed, dlopen, dlpreopen, libdir.
+ save_libdir="$libdir"
+ case "$found_la" in
+ */* | *\\*) . "$found_la" ;;
+ *) . "./$found_la" ;;
+ esac
+ libdir="$save_libdir"
+ dnl We use only dependency_libs.
+ for dep in $dependency_libs; do
+ case "$dep" in
+ -L*)
+ additional_libdir=`echo "X$dep" | sed -e 's/^X-L//'`
+ dnl Potentially add $additional_libdir to $LIBNAME and $LTLIBNAME.
+ dnl But don't add it
+ dnl 1. if it's the standard /usr/lib,
+ dnl 2. if it's /usr/local/lib and we are using GCC on Linux,
+ dnl 3. if it's already present in $LDFLAGS or the already
+ dnl constructed $LIBNAME,
+ dnl 4. if it doesn't exist as a directory.
+ if test "X$additional_libdir" != "X/usr/lib"; then
+ haveit=
+ if test "X$additional_libdir" = "X/usr/local/lib"; then
+ if test -n "$GCC"; then
+ case $host_os in
+ linux*) haveit=yes;;
+ esac
+ fi
+ fi
+ if test -z "$haveit"; then
+ haveit=
+ for x in $LDFLAGS $LIB[]NAME; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X-L$additional_libdir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ if test -d "$additional_libdir"; then
+ dnl Really add $additional_libdir to $LIBNAME.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-L$additional_libdir"
+ fi
+ fi
+ haveit=
+ for x in $LDFLAGS $LTLIB[]NAME; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X-L$additional_libdir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ if test -d "$additional_libdir"; then
+ dnl Really add $additional_libdir to $LTLIBNAME.
+ LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-L$additional_libdir"
+ fi
+ fi
+ fi
+ fi
+ ;;
+ -R*)
+ dir=`echo "X$dep" | sed -e 's/^X-R//'`
+ if test "$enable_rpath" != no; then
+ dnl Potentially add DIR to rpathdirs.
+ dnl The rpathdirs will be appended to $LIBNAME at the end.
+ haveit=
+ for x in $rpathdirs; do
+ if test "X$x" = "X$dir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ rpathdirs="$rpathdirs $dir"
+ fi
+ dnl Potentially add DIR to ltrpathdirs.
+ dnl The ltrpathdirs will be appended to $LTLIBNAME at the end.
+ haveit=
+ for x in $ltrpathdirs; do
+ if test "X$x" = "X$dir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ ltrpathdirs="$ltrpathdirs $dir"
+ fi
+ fi
+ ;;
+ -l*)
+ dnl Handle this in the next round.
+ names_next_round="$names_next_round "`echo "X$dep" | sed -e 's/^X-l//'`
+ ;;
+ *.la)
+ dnl Handle this in the next round. Throw away the .la's
+ dnl directory; it is already contained in a preceding -L
+ dnl option.
+ names_next_round="$names_next_round "`echo "X$dep" | sed -e 's,^X.*/,,' -e 's,^lib,,' -e 's,\.la$,,'`
+ ;;
+ *)
+ dnl Most likely an immediate library name.
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$dep"
+ LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }$dep"
+ ;;
+ esac
+ done
+ fi
+ else
+ dnl Didn't find the library; assume it is in the system directories
+ dnl known to the linker and runtime loader. (All the system
+ dnl directories known to the linker should also be known to the
+ dnl runtime loader, otherwise the system is severely misconfigured.)
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }-l$name"
+ LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-l$name"
+ fi
+ fi
+ fi
+ done
+ done
+ if test "X$rpathdirs" != "X"; then
+ if test -n "$hardcode_libdir_separator"; then
+ dnl Weird platform: only the last -rpath option counts, the user must
+ dnl pass all path elements in one option. We can arrange that for a
+ dnl single library, but not when more than one $LIBNAMEs are used.
+ alldirs=
+ for found_dir in $rpathdirs; do
+ alldirs="${alldirs}${alldirs:+$hardcode_libdir_separator}$found_dir"
+ done
+ dnl Note: hardcode_libdir_flag_spec uses $libdir and $wl.
+ acl_save_libdir="$libdir"
+ libdir="$alldirs"
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ libdir="$acl_save_libdir"
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag"
+ else
+ dnl The -rpath options are cumulative.
+ for found_dir in $rpathdirs; do
+ acl_save_libdir="$libdir"
+ libdir="$found_dir"
+ eval flag=\"$hardcode_libdir_flag_spec\"
+ libdir="$acl_save_libdir"
+ LIB[]NAME="${LIB[]NAME}${LIB[]NAME:+ }$flag"
+ done
+ fi
+ fi
+ if test "X$ltrpathdirs" != "X"; then
+ dnl When using libtool, the option that works for both libraries and
+ dnl executables is -R. The -R options are cumulative.
+ for found_dir in $ltrpathdirs; do
+ LTLIB[]NAME="${LTLIB[]NAME}${LTLIB[]NAME:+ }-R$found_dir"
+ done
+ fi
+])
+
+dnl AC_LIB_APPENDTOVAR(VAR, CONTENTS) appends the elements of CONTENTS to VAR,
+dnl unless already present in VAR.
+dnl Works only for CPPFLAGS, not for LIB* variables because that sometimes
+dnl contains two or three consecutive elements that belong together.
+AC_DEFUN([AC_LIB_APPENDTOVAR],
+[
+ for element in [$2]; do
+ haveit=
+ for x in $[$1]; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X$element"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ [$1]="${[$1]}${[$1]:+ }$element"
+ fi
+ done
+])
diff --git a/config/lib-prefix.m4 b/config/lib-prefix.m4
new file mode 100644
index 00000000000..c719bc80900
--- /dev/null
+++ b/config/lib-prefix.m4
@@ -0,0 +1,155 @@
+# lib-prefix.m4 serial 2 (gettext-0.12)
+dnl Copyright (C) 2001-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Bruno Haible.
+
+dnl AC_LIB_ARG_WITH is synonymous to AC_ARG_WITH in autoconf-2.13, and
+dnl similar to AC_ARG_WITH in autoconf 2.52...2.57 except that is doesn't
+dnl require excessive bracketing.
+ifdef([AC_HELP_STRING],
+[AC_DEFUN([AC_LIB_ARG_WITH], [AC_ARG_WITH([$1],[[$2]],[$3],[$4])])],
+[AC_DEFUN([AC_LIB_ARG_WITH], [AC_ARG_WITH([$1],[$2],[$3],[$4])])])
+
+dnl AC_LIB_PREFIX adds to the CPPFLAGS and LDFLAGS the flags that are needed
+dnl to access previously installed libraries. The basic assumption is that
+dnl a user will want packages to use other packages he previously installed
+dnl with the same --prefix option.
+dnl This macro is not needed if only AC_LIB_LINKFLAGS is used to locate
+dnl libraries, but is otherwise very convenient.
+AC_DEFUN([AC_LIB_PREFIX],
+[
+ AC_BEFORE([$0], [AC_LIB_LINKFLAGS])
+ AC_REQUIRE([AC_PROG_CC])
+ AC_REQUIRE([AC_CANONICAL_HOST])
+ AC_REQUIRE([AC_LIB_PREPARE_PREFIX])
+ dnl By default, look in $includedir and $libdir.
+ use_additional=yes
+ AC_LIB_WITH_FINAL_PREFIX([
+ eval additional_includedir=\"$includedir\"
+ eval additional_libdir=\"$libdir\"
+ ])
+ AC_LIB_ARG_WITH([lib-prefix],
+[ --with-lib-prefix[=DIR] search for libraries in DIR/include and DIR/lib
+ --without-lib-prefix don't search for libraries in includedir and libdir],
+[
+ if test "X$withval" = "Xno"; then
+ use_additional=no
+ else
+ if test "X$withval" = "X"; then
+ AC_LIB_WITH_FINAL_PREFIX([
+ eval additional_includedir=\"$includedir\"
+ eval additional_libdir=\"$libdir\"
+ ])
+ else
+ additional_includedir="$withval/include"
+ additional_libdir="$withval/lib"
+ fi
+ fi
+])
+ if test $use_additional = yes; then
+ dnl Potentially add $additional_includedir to $CPPFLAGS.
+ dnl But don't add it
+ dnl 1. if it's the standard /usr/include,
+ dnl 2. if it's already present in $CPPFLAGS,
+ dnl 3. if it's /usr/local/include and we are using GCC on Linux,
+ dnl 4. if it doesn't exist as a directory.
+ if test "X$additional_includedir" != "X/usr/include"; then
+ haveit=
+ for x in $CPPFLAGS; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X-I$additional_includedir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ if test "X$additional_includedir" = "X/usr/local/include"; then
+ if test -n "$GCC"; then
+ case $host_os in
+ linux*) haveit=yes;;
+ esac
+ fi
+ fi
+ if test -z "$haveit"; then
+ if test -d "$additional_includedir"; then
+ dnl Really add $additional_includedir to $CPPFLAGS.
+ CPPFLAGS="${CPPFLAGS}${CPPFLAGS:+ }-I$additional_includedir"
+ fi
+ fi
+ fi
+ fi
+ dnl Potentially add $additional_libdir to $LDFLAGS.
+ dnl But don't add it
+ dnl 1. if it's the standard /usr/lib,
+ dnl 2. if it's already present in $LDFLAGS,
+ dnl 3. if it's /usr/local/lib and we are using GCC on Linux,
+ dnl 4. if it doesn't exist as a directory.
+ if test "X$additional_libdir" != "X/usr/lib"; then
+ haveit=
+ for x in $LDFLAGS; do
+ AC_LIB_WITH_FINAL_PREFIX([eval x=\"$x\"])
+ if test "X$x" = "X-L$additional_libdir"; then
+ haveit=yes
+ break
+ fi
+ done
+ if test -z "$haveit"; then
+ if test "X$additional_libdir" = "X/usr/local/lib"; then
+ if test -n "$GCC"; then
+ case $host_os in
+ linux*) haveit=yes;;
+ esac
+ fi
+ fi
+ if test -z "$haveit"; then
+ if test -d "$additional_libdir"; then
+ dnl Really add $additional_libdir to $LDFLAGS.
+ LDFLAGS="${LDFLAGS}${LDFLAGS:+ }-L$additional_libdir"
+ fi
+ fi
+ fi
+ fi
+ fi
+])
+
+dnl AC_LIB_PREPARE_PREFIX creates variables acl_final_prefix,
+dnl acl_final_exec_prefix, containing the values to which $prefix and
+dnl $exec_prefix will expand at the end of the configure script.
+AC_DEFUN([AC_LIB_PREPARE_PREFIX],
+[
+ dnl Unfortunately, prefix and exec_prefix get only finally determined
+ dnl at the end of configure.
+ if test "X$prefix" = "XNONE"; then
+ acl_final_prefix="$ac_default_prefix"
+ else
+ acl_final_prefix="$prefix"
+ fi
+ if test "X$exec_prefix" = "XNONE"; then
+ acl_final_exec_prefix='${prefix}'
+ else
+ acl_final_exec_prefix="$exec_prefix"
+ fi
+ acl_save_prefix="$prefix"
+ prefix="$acl_final_prefix"
+ eval acl_final_exec_prefix=\"$acl_final_exec_prefix\"
+ prefix="$acl_save_prefix"
+])
+
+dnl AC_LIB_WITH_FINAL_PREFIX([statement]) evaluates statement, with the
+dnl variables prefix and exec_prefix bound to the values they will have
+dnl at the end of the configure script.
+AC_DEFUN([AC_LIB_WITH_FINAL_PREFIX],
+[
+ acl_save_prefix="$prefix"
+ prefix="$acl_final_prefix"
+ acl_save_exec_prefix="$exec_prefix"
+ exec_prefix="$acl_final_exec_prefix"
+ $1
+ exec_prefix="$acl_save_exec_prefix"
+ prefix="$acl_save_prefix"
+])
diff --git a/config/mh-x86omitfp b/config/mh-x86omitfp
new file mode 100644
index 00000000000..563f02ba0a9
--- /dev/null
+++ b/config/mh-x86omitfp
@@ -0,0 +1,2 @@
+# Add -fomit-frame-pointer to the usual BOOT_CFLAGS to speed up the compiler.
+BOOT_CFLAGS = -O2 -g -fomit-frame-pointer
diff --git a/config/nls.m4 b/config/nls.m4
new file mode 100644
index 00000000000..36bc49317c1
--- /dev/null
+++ b/config/nls.m4
@@ -0,0 +1,49 @@
+# nls.m4 serial 1 (gettext-0.12)
+dnl Copyright (C) 1995-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+dnl
+dnl This file can can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Library General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Library General Public License, and the rest of the GNU
+dnl gettext package package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl Bruno Haible <haible@clisp.cons.org>, 2000-2003.
+
+AC_DEFUN([AM_NLS],
+[
+ AC_MSG_CHECKING([whether NLS is requested])
+ dnl Default is enabled NLS
+ AC_ARG_ENABLE(nls,
+ [ --disable-nls do not use Native Language Support],
+ USE_NLS=$enableval, USE_NLS=yes)
+ AC_MSG_RESULT($USE_NLS)
+ AC_SUBST(USE_NLS)
+])
+
+AC_DEFUN([AM_MKINSTALLDIRS],
+[
+ dnl If the AC_CONFIG_AUX_DIR macro for autoconf is used we possibly
+ dnl find the mkinstalldirs script in another subdir but $(top_srcdir).
+ dnl Try to locate it.
+ MKINSTALLDIRS=
+ if test -n "$ac_aux_dir"; then
+ case "$ac_aux_dir" in
+ /*) MKINSTALLDIRS="$ac_aux_dir/mkinstalldirs" ;;
+ *) MKINSTALLDIRS="\$(top_builddir)/$ac_aux_dir/mkinstalldirs" ;;
+ esac
+ fi
+ if test -z "$MKINSTALLDIRS"; then
+ MKINSTALLDIRS="\$(top_srcdir)/mkinstalldirs"
+ fi
+ AC_SUBST(MKINSTALLDIRS)
+])
diff --git a/config/po.m4 b/config/po.m4
new file mode 100644
index 00000000000..861e3dec392
--- /dev/null
+++ b/config/po.m4
@@ -0,0 +1,197 @@
+# po.m4 serial 1 (gettext-0.12)
+dnl Copyright (C) 1995-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+dnl
+dnl This file can can be used in projects which are not available under
+dnl the GNU General Public License or the GNU Library General Public
+dnl License but which still want to provide support for the GNU gettext
+dnl functionality.
+dnl Please note that the actual code of the GNU gettext library is covered
+dnl by the GNU Library General Public License, and the rest of the GNU
+dnl gettext package package is covered by the GNU General Public License.
+dnl They are *not* in the public domain.
+
+dnl Authors:
+dnl Ulrich Drepper <drepper@cygnus.com>, 1995-2000.
+dnl Bruno Haible <haible@clisp.cons.org>, 2000-2003.
+
+dnl Checks for all prerequisites of the po subdirectory.
+AC_DEFUN([AM_PO_SUBDIRS],
+[
+ AC_REQUIRE([AC_PROG_MAKE_SET])dnl
+ AC_REQUIRE([AC_PROG_INSTALL])dnl
+ AC_REQUIRE([AM_MKINSTALLDIRS])dnl
+ AC_REQUIRE([AM_NLS])dnl
+
+ dnl Perform the following tests also if --disable-nls has been given,
+ dnl because they are needed for "make dist" to work.
+
+ dnl Search for GNU msgfmt in the PATH.
+ dnl The first test excludes Solaris msgfmt and early GNU msgfmt versions.
+ dnl The second test excludes FreeBSD msgfmt.
+ AM_PATH_PROG_WITH_TEST(MSGFMT, msgfmt,
+ [$ac_dir/$ac_word --statistics /dev/null >/dev/null 2>&1 &&
+ (if $ac_dir/$ac_word --statistics /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi)],
+ :)
+ AC_PATH_PROG(GMSGFMT, gmsgfmt, $MSGFMT)
+
+ dnl Search for GNU xgettext 0.12 or newer in the PATH.
+ dnl The first test excludes Solaris xgettext and early GNU xgettext versions.
+ dnl The second test excludes FreeBSD xgettext.
+ AM_PATH_PROG_WITH_TEST(XGETTEXT, xgettext,
+ [$ac_dir/$ac_word --omit-header --copyright-holder= --msgid-bugs-address= /dev/null >/dev/null 2>&1 &&
+ (if $ac_dir/$ac_word --omit-header --copyright-holder= --msgid-bugs-address= /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi)],
+ :)
+ dnl Remove leftover from FreeBSD xgettext call.
+ rm -f messages.po
+
+ dnl Search for GNU msgmerge 0.11 or newer in the PATH.
+ AM_PATH_PROG_WITH_TEST(MSGMERGE, msgmerge,
+ [$ac_dir/$ac_word --update -q /dev/null /dev/null >/dev/null 2>&1], :)
+
+ dnl This could go away some day; the PATH_PROG_WITH_TEST already does it.
+ dnl Test whether we really found GNU msgfmt.
+ if test "$GMSGFMT" != ":"; then
+ dnl If it is no GNU msgfmt we define it as : so that the
+ dnl Makefiles still can work.
+ if $GMSGFMT --statistics /dev/null >/dev/null 2>&1 &&
+ (if $GMSGFMT --statistics /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi); then
+ : ;
+ else
+ GMSGFMT=`echo "$GMSGFMT" | sed -e 's,^.*/,,'`
+ AC_MSG_RESULT(
+ [found $GMSGFMT program is not GNU msgfmt; ignore it])
+ GMSGFMT=":"
+ fi
+ fi
+
+ dnl This could go away some day; the PATH_PROG_WITH_TEST already does it.
+ dnl Test whether we really found GNU xgettext.
+ if test "$XGETTEXT" != ":"; then
+ dnl If it is no GNU xgettext we define it as : so that the
+ dnl Makefiles still can work.
+ if $XGETTEXT --omit-header --copyright-holder= --msgid-bugs-address= /dev/null >/dev/null 2>&1 &&
+ (if $XGETTEXT --omit-header --copyright-holder= --msgid-bugs-address= /dev/null 2>&1 >/dev/null | grep usage >/dev/null; then exit 1; else exit 0; fi); then
+ : ;
+ else
+ AC_MSG_RESULT(
+ [found xgettext program is not GNU xgettext; ignore it])
+ XGETTEXT=":"
+ fi
+ dnl Remove leftover from FreeBSD xgettext call.
+ rm -f messages.po
+ fi
+
+ AC_OUTPUT_COMMANDS([
+ for ac_file in $CONFIG_FILES; do
+ # Support "outfile[:infile[:infile...]]"
+ case "$ac_file" in
+ *:*) ac_file=`echo "$ac_file"|sed 's%:.*%%'` ;;
+ esac
+ # PO directories have a Makefile.in generated from Makefile.in.in.
+ case "$ac_file" in */Makefile.in)
+ # Adjust a relative srcdir.
+ ac_dir=`echo "$ac_file"|sed 's%/[^/][^/]*$%%'`
+ ac_dir_suffix="/`echo "$ac_dir"|sed 's%^\./%%'`"
+ ac_dots=`echo "$ac_dir_suffix"|sed 's%/[^/]*%../%g'`
+ # In autoconf-2.13 it is called $ac_given_srcdir.
+ # In autoconf-2.50 it is called $srcdir.
+ test -n "$ac_given_srcdir" || ac_given_srcdir="$srcdir"
+ case "$ac_given_srcdir" in
+ .) top_srcdir=`echo $ac_dots|sed 's%/$%%'` ;;
+ /*) top_srcdir="$ac_given_srcdir" ;;
+ *) top_srcdir="$ac_dots$ac_given_srcdir" ;;
+ esac
+ if test -f "$ac_given_srcdir/$ac_dir/POTFILES.in"; then
+ rm -f "$ac_dir/POTFILES"
+ test -n "$as_me" && echo "$as_me: creating $ac_dir/POTFILES" || echo "creating $ac_dir/POTFILES"
+ cat "$ac_given_srcdir/$ac_dir/POTFILES.in" | sed -e "/^#/d" -e "/^[ ]*\$/d" -e "s,.*, $top_srcdir/& \\\\," | sed -e "\$s/\(.*\) \\\\/\1/" > "$ac_dir/POTFILES"
+ POMAKEFILEDEPS="POTFILES.in"
+ # ALL_LINGUAS, POFILES, GMOFILES, UPDATEPOFILES, DUMMYPOFILES depend
+ # on $ac_dir but don't depend on user-specified configuration
+ # parameters.
+ if test -f "$ac_given_srcdir/$ac_dir/LINGUAS"; then
+ # The LINGUAS file contains the set of available languages.
+ if test -n "$OBSOLETE_ALL_LINGUAS"; then
+ test -n "$as_me" && echo "$as_me: setting ALL_LINGUAS in configure.in is obsolete" || echo "setting ALL_LINGUAS in configure.in is obsolete"
+ fi
+ ALL_LINGUAS_=`sed -e "/^#/d" "$ac_given_srcdir/$ac_dir/LINGUAS"`
+ # Hide the ALL_LINGUAS assigment from automake.
+ eval 'ALL_LINGUAS''=$ALL_LINGUAS_'
+ POMAKEFILEDEPS="$POMAKEFILEDEPS LINGUAS"
+ else
+ # The set of available languages was given in configure.in.
+ eval 'ALL_LINGUAS''=$OBSOLETE_ALL_LINGUAS'
+ fi
+ case "$ac_given_srcdir" in
+ .) srcdirpre= ;;
+ *) srcdirpre='$(srcdir)/' ;;
+ esac
+ POFILES=
+ GMOFILES=
+ UPDATEPOFILES=
+ DUMMYPOFILES=
+ for lang in $ALL_LINGUAS; do
+ POFILES="$POFILES $srcdirpre$lang.po"
+ GMOFILES="$GMOFILES $srcdirpre$lang.gmo"
+ UPDATEPOFILES="$UPDATEPOFILES $lang.po-update"
+ DUMMYPOFILES="$DUMMYPOFILES $lang.nop"
+ done
+ # CATALOGS depends on both $ac_dir and the user's LINGUAS
+ # environment variable.
+ INST_LINGUAS=
+ if test -n "$ALL_LINGUAS"; then
+ for presentlang in $ALL_LINGUAS; do
+ useit=no
+ if test "%UNSET%" != "$LINGUAS"; then
+ desiredlanguages="$LINGUAS"
+ else
+ desiredlanguages="$ALL_LINGUAS"
+ fi
+ for desiredlang in $desiredlanguages; do
+ # Use the presentlang catalog if desiredlang is
+ # a. equal to presentlang, or
+ # b. a variant of presentlang (because in this case,
+ # presentlang can be used as a fallback for messages
+ # which are not translated in the desiredlang catalog).
+ case "$desiredlang" in
+ "$presentlang"*) useit=yes;;
+ esac
+ done
+ if test $useit = yes; then
+ INST_LINGUAS="$INST_LINGUAS $presentlang"
+ fi
+ done
+ fi
+ CATALOGS=
+ if test -n "$INST_LINGUAS"; then
+ for lang in $INST_LINGUAS; do
+ CATALOGS="$CATALOGS $lang.gmo"
+ done
+ fi
+ test -n "$as_me" && echo "$as_me: creating $ac_dir/Makefile" || echo "creating $ac_dir/Makefile"
+ sed -e "/^POTFILES =/r $ac_dir/POTFILES" -e "/^# Makevars/r $ac_given_srcdir/$ac_dir/Makevars" -e "s|@POFILES@|$POFILES|g" -e "s|@GMOFILES@|$GMOFILES|g" -e "s|@UPDATEPOFILES@|$UPDATEPOFILES|g" -e "s|@DUMMYPOFILES@|$DUMMYPOFILES|g" -e "s|@CATALOGS@|$CATALOGS|g" -e "s|@POMAKEFILEDEPS@|$POMAKEFILEDEPS|g" "$ac_dir/Makefile.in" > "$ac_dir/Makefile"
+ for f in "$ac_given_srcdir/$ac_dir"/Rules-*; do
+ if test -f "$f"; then
+ case "$f" in
+ *.orig | *.bak | *~) ;;
+ *) cat "$f" >> "$ac_dir/Makefile" ;;
+ esac
+ fi
+ done
+ fi
+ ;;
+ esac
+ done],
+ [# Capture the value of obsolete ALL_LINGUAS because we need it to compute
+ # POFILES, GMOFILES, UPDATEPOFILES, DUMMYPOFILES, CATALOGS. But hide it
+ # from automake.
+ eval 'OBSOLETE_ALL_LINGUAS''="$ALL_LINGUAS"'
+ # Capture the value of LINGUAS because we need it to compute CATALOGS.
+ LINGUAS="${LINGUAS-%UNSET%}"
+ ])
+])
diff --git a/config/stdint_h.m4 b/config/stdint_h.m4
new file mode 100644
index 00000000000..32ba7ae77b0
--- /dev/null
+++ b/config/stdint_h.m4
@@ -0,0 +1,28 @@
+# stdint_h.m4 serial 3 (gettext-0.12)
+dnl Copyright (C) 1997-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Paul Eggert.
+
+# Define HAVE_STDINT_H_WITH_UINTMAX if <stdint.h> exists,
+# doesn't clash with <sys/types.h>, and declares uintmax_t.
+
+AC_DEFUN([jm_AC_HEADER_STDINT_H],
+[
+ AC_CACHE_CHECK([for stdint.h], jm_ac_cv_header_stdint_h,
+ [AC_TRY_COMPILE(
+ [#include <sys/types.h>
+#include <stdint.h>],
+ [uintmax_t i = (uintmax_t) -1;],
+ jm_ac_cv_header_stdint_h=yes,
+ jm_ac_cv_header_stdint_h=no)])
+ if test $jm_ac_cv_header_stdint_h = yes; then
+ AC_DEFINE_UNQUOTED(HAVE_STDINT_H_WITH_UINTMAX, 1,
+ [Define if <stdint.h> exists, doesn't clash with <sys/types.h>,
+ and declares uintmax_t. ])
+ fi
+])
diff --git a/config/uintmax_t.m4 b/config/uintmax_t.m4
new file mode 100644
index 00000000000..b5f28d4404a
--- /dev/null
+++ b/config/uintmax_t.m4
@@ -0,0 +1,32 @@
+# uintmax_t.m4 serial 7 (gettext-0.12)
+dnl Copyright (C) 1997-2003 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Paul Eggert.
+
+AC_PREREQ(2.13)
+
+# Define uintmax_t to 'unsigned long' or 'unsigned long long'
+# if it is not already defined in <stdint.h> or <inttypes.h>.
+
+AC_DEFUN([jm_AC_TYPE_UINTMAX_T],
+[
+ AC_REQUIRE([jm_AC_HEADER_INTTYPES_H])
+ AC_REQUIRE([jm_AC_HEADER_STDINT_H])
+ if test $jm_ac_cv_header_inttypes_h = no && test $jm_ac_cv_header_stdint_h = no; then
+ AC_REQUIRE([jm_AC_TYPE_UNSIGNED_LONG_LONG])
+ test $ac_cv_type_unsigned_long_long = yes \
+ && ac_type='unsigned long long' \
+ || ac_type='unsigned long'
+ AC_DEFINE_UNQUOTED(uintmax_t, $ac_type,
+ [Define to unsigned long or unsigned long long
+ if <stdint.h> and <inttypes.h> don't define.])
+ else
+ AC_DEFINE(HAVE_UINTMAX_T, 1,
+ [Define if you have the 'uintmax_t' type in <stdint.h> or <inttypes.h>.])
+ fi
+])
diff --git a/config/ulonglong.m4 b/config/ulonglong.m4
new file mode 100644
index 00000000000..c375e474c75
--- /dev/null
+++ b/config/ulonglong.m4
@@ -0,0 +1,23 @@
+# ulonglong.m4 serial 2 (fileutils-4.0.32, gettext-0.10.40)
+dnl Copyright (C) 1999-2002 Free Software Foundation, Inc.
+dnl This file is free software, distributed under the terms of the GNU
+dnl General Public License. As a special exception to the GNU General
+dnl Public License, this file may be distributed as part of a program
+dnl that contains a configuration script generated by Autoconf, under
+dnl the same distribution terms as the rest of that program.
+
+dnl From Paul Eggert.
+
+AC_DEFUN([jm_AC_TYPE_UNSIGNED_LONG_LONG],
+[
+ AC_CACHE_CHECK([for unsigned long long], ac_cv_type_unsigned_long_long,
+ [AC_TRY_LINK([unsigned long long ull = 1; int i = 63;],
+ [unsigned long long ullmax = (unsigned long long) -1;
+ return ull << i | ull >> i | ullmax / ull | ullmax % ull;],
+ ac_cv_type_unsigned_long_long=yes,
+ ac_cv_type_unsigned_long_long=no)])
+ if test $ac_cv_type_unsigned_long_long = yes; then
+ AC_DEFINE(HAVE_UNSIGNED_LONG_LONG, 1,
+ [Define if you have the unsigned long long type.])
+ fi
+])
diff --git a/config/warnings.m4 b/config/warnings.m4
new file mode 100644
index 00000000000..5501be92046
--- /dev/null
+++ b/config/warnings.m4
@@ -0,0 +1,97 @@
+# Autoconf include file defining macros related to compile-time warnings.
+
+# Copyright 2004 Free Software Foundation, Inc.
+
+#This file is part of GCC.
+
+#GCC is free software; you can redistribute it and/or modify it under
+#the terms of the GNU General Public License as published by the Free
+#Software Foundation; either version 2, or (at your option) any later
+#version.
+
+#GCC is distributed in the hope that it will be useful, but WITHOUT
+#ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+#FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+#for more details.
+
+#You should have received a copy of the GNU General Public License
+#along with GCC; see the file COPYING. If not, write to the Free
+#Software Foundation, 59 Temple Place - Suite 330, Boston, MA
+#02111-1307, USA.
+
+# ACX_PROG_CC_WARNING_OPTS([-Wfoo -Wbar -Wbaz])
+# Sets @WARN_CFLAGS@ to the subset of the given options which the
+# compiler accepts.
+AC_DEFUN([ACX_PROG_CC_WARNING_OPTS],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_SUBST([WARN_CFLAGS])dnl
+WARN_CFLAGS=
+save_CFLAGS="$CFLAGS"
+for option in $1; do
+ AS_VAR_PUSHDEF([acx_Woption], [acx_cv_prog_cc_warning_$option])
+ AC_CACHE_CHECK([whether $CC supports $option], acx_Woption,
+ [CFLAGS="$option"
+ AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],
+ [AS_VAR_SET(acx_Woption, yes)],
+ [AS_VAR_SET(acx_Woption, no)])
+ ])
+ AS_IF([test AS_VAR_GET(acx_Woption) = yes],
+ [WARN_CFLAGS="$WARN_CFLAGS${WARN_CFLAGS:+ }$option"])
+ AS_VAR_POPDEF([acx_Woption])dnl
+done
+CFLAGS="$save_CFLAGS"
+])# ACX_PROG_CC_WARNING_OPTS
+
+# ACX_PROG_CC_WARNING_ALMOST_PEDANTIC([-Wno-long-long ...])
+# Sets WARN_PEDANTIC to "-pedantic" + the argument, if the compiler
+# accepts all of those options simultaneously, otherwise to nothing.
+AC_DEFUN([ACX_PROG_CC_WARNING_ALMOST_PEDANTIC],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_SUBST([WARN_PEDANTIC])dnl
+AS_VAR_PUSHDEF([acx_Pedantic], [acx_cv_prog_cc_pedantic_$1])dnl
+WARN_PEDANTIC=
+AC_CACHE_CHECK([whether $CC supports -pedantic $1], acx_Pedantic,
+[save_CFLAGS="$CFLAGS"
+CFLAGS="-pedantic $1"
+AC_COMPILE_IFELSE([AC_LANG_PROGRAM([],[])],
+ [AS_VAR_SET(acx_Pedantic, yes)],
+ [AS_VAR_SET(acx_Pedantic, no)])
+CFLAGS="$save_CFLAGS"])
+AS_IF([test AS_VAR_GET(acx_Pedantic) = yes],
+ [WARN_PEDANTIC="-pedantic $1"])
+AS_VAR_POPDEF([acx_Pedantic])dnl
+])# ACX_PROG_CC_WARNING_ALMOST_PEDANTIC
+
+# ACX_PROG_CC_WARNINGS_ARE_ERRORS([x.y.z])
+# sets WERROR to "-Werror" if the compiler is GCC >=x.y.z, or if
+# --enable-werror-always was given on the command line, otherwise
+# to nothing.
+# If the argument is the word "manual" instead of a version number,
+# then WERROR will be set to -Werror only if --enable-werror-always
+# appeared on the configure command line.
+AC_DEFUN([ACX_PROG_CC_WARNINGS_ARE_ERRORS],
+[AC_REQUIRE([AC_PROG_CC])dnl
+AC_SUBST([WERROR])dnl
+WERROR=
+AC_ARG_ENABLE(werror-always,
+ AS_HELP_STRING([--enable-werror-always],
+ [enable -Werror despite compiler version]),
+[], [enable_werror_always=no])
+AS_IF([test $enable_werror_always = yes],
+ [WERROR=-Werror],
+ m4_if($1, [manual],,
+ [AS_VAR_PUSHDEF([acx_GCCvers], [acx_cv_prog_cc_gcc_$1_or_newer])dnl
+ AC_CACHE_CHECK([whether $CC is GCC >=$1], acx_GCCvers,
+ [set fnord `echo $1 | tr '.' ' '`
+ shift
+ AC_PREPROC_IFELSE(
+[#if __GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__ \
+ < [$]1 * 10000 + [$]2 * 100 + [$]3
+#error insufficient
+#endif],
+ [AS_VAR_SET(acx_GCCvers, yes)],
+ [AS_VAR_SET(acx_GCCvers, no)])])
+ AS_IF([test AS_VAR_GET(acx_GCCvers) = yes],
+ [WERROR=-WerrorB])
+ AS_VAR_POPDEF([acx_GCCvers])]))
+])# ACX_PROG_CC_WARNINGS_ARE_ERRORS
diff --git a/gcc/config/s390/tpf-eh.c b/gcc/config/s390/tpf-eh.c
new file mode 100644
index 00000000000..788857da26f
--- /dev/null
+++ b/gcc/config/s390/tpf-eh.c
@@ -0,0 +1,183 @@
+/* Exception handling routines for TPF.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+ Contributed by P.J. Darcy (darcypj@us.ibm.com).
+
+ This file is part of GCC.
+
+ GCC is free software; you can redistribute it and/or modify it
+ under the terms of the GNU General Public License as published by
+ the Free Software Foundation; either version 2, or (at your option)
+ any later version.
+
+ In addition to the permissions in the GNU General Public License, the
+ Free Software Foundation gives you unlimited permission to link the
+ compiled version of this file into combinations with other programs,
+ and to distribute those combinations without any restriction coming
+ from the use of this file. (The General Public License restrictions
+ do apply in other respects; for example, they cover modification of
+ the file, and distribution when not linked into a combined
+ executable.)
+
+ GCC is distributed in the hope that it will be useful, but WITHOUT
+ ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+ or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
+ License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with GCC; see the file COPYING. If not, write to the Free
+ Software Foundation, 59 Temple Place - Suite 330, Boston, MA
+ 02111-1307, USA. */
+
+#define __USE_GNU 1
+#define _GNU_SOURCE
+#include <dlfcn.h>
+#undef __USE_GNU
+#undef _GNU_SOURCE
+
+#define CURRENT_STACK_PTR() \
+ ({ register unsigned long int *stack_ptr asm ("%r15"); stack_ptr; })
+
+#define PREVIOUS_STACK_PTR() \
+ ((unsigned long int *)(*(CURRENT_STACK_PTR())))
+
+#define RA_OFFSET_FROM_START_OF_STACK_FRAME 112
+#define CURRENT_STACK_PTR_OFFSET 120
+#define TPFRA_OFFSET_FROM_START_OF_STACK_FRAME 168
+#define MIN_PATRANGE 0x10000
+#define MAX_PATRANGE 0x800000
+#define INVALID_RETURN 0
+
+/* Function Name: __isPATrange
+ Parameters passed into it: address to check
+ Return Value: A 1 if address is in pat code "range", 0 if not
+ Description: This function simply checks to see if the address
+ passed to it is in the CP pat code range. */
+
+unsigned int __isPATrange(void *addr)
+{
+ if (addr > (void *)MIN_PATRANGE && addr < (void *)MAX_PATRANGE)
+ return 1;
+ else
+ return 0;
+}
+
+/* Function Name: __tpf_eh_return
+ Parameters passed into it: Destination address to jump to.
+ Return Value: Converted Destination address if a Pat Stub exists.
+ Description: This function swaps the unwinding return address
+ with the cp stub code. The original target return address is
+ then stored into the tpf return address field. The cp stub
+ code is searched for by climbing back up the stack and
+ comparing the tpf stored return address object address to
+ that of the targets object address. */
+
+void *__tpf_eh_return (void *target)
+{
+ Dl_info targetcodeInfo, currentcodeInfo;
+ int retval;
+ void *current, *stackptr;
+ unsigned long int shifter;
+
+ /* Get code info for target return's address. */
+ retval = dladdr (target, &targetcodeInfo);
+
+ /* Get the return address of the stack frame to be replaced by
+ the exception unwinder. So that the __cxa_throw return is
+ replaced by the target return. */
+ current = (void *) *((unsigned long int *)
+ ((*((unsigned long int *)*(PREVIOUS_STACK_PTR())))
+ + RA_OFFSET_FROM_START_OF_STACK_FRAME));
+
+ /* Ensure the code info is valid (for target). */
+ if (retval != INVALID_RETURN)
+ {
+ /* Now check to see if the current RA is a PAT
+ stub return address. */
+ if ( __isPATrange(current))
+ {
+ /* It was! Then go into the TPF private stack area and fetch
+ the real address. */
+ current = (void *) *((unsigned long int *)
+ ((unsigned long int)*((unsigned long int *)
+ *(PREVIOUS_STACK_PTR()))
+ +TPFRA_OFFSET_FROM_START_OF_STACK_FRAME));
+ }
+
+ /* Get code info for current return address. */
+ retval = dladdr (current, &currentcodeInfo);
+
+ /* Ensure the code info is valid (for current frame). */
+ if (retval != INVALID_RETURN)
+ {
+ /* Get the stack pointer of the stack frame to be replaced by
+ the exception unwinder. So that we can begin our climb
+ there. */
+ stackptr = (void *) (*((unsigned long int *)
+ (*((unsigned long int *)(*(PREVIOUS_STACK_PTR()))))));
+
+ /* Begin looping through stack frames. Stop if invalid
+ code information is retrieved or if a match between the
+ current stack frame iteration shared object's address
+ matches that of the target, calculated above. */
+ while (retval != INVALID_RETURN
+ && targetcodeInfo.dli_fbase != currentcodeInfo.dli_fbase)
+ {
+ /* Get return address based on our stackptr iterator. */
+ current = (void *) *((unsigned long int *)
+ (stackptr+RA_OFFSET_FROM_START_OF_STACK_FRAME));
+
+ /* Is it a Pat Stub? */
+ if (__isPATrange (current))
+ {
+ /* Yes it was, get real return address
+ in TPF stack area. */
+ current = (void *) *((unsigned long int *)
+ (stackptr+TPFRA_OFFSET_FROM_START_OF_STACK_FRAME));
+ }
+
+ /* Get codeinfo on RA so that we can figure out
+ the module address. */
+ retval = dladdr (current, &currentcodeInfo);
+
+ /* Check that codeinfo for current stack frame is valid.
+ Then compare the module address of current stack frame
+ to target stack frame to determine if we have the pat
+ stub address we want. */
+ if (retval != INVALID_RETURN
+ && targetcodeInfo.dli_fbase == currentcodeInfo.dli_fbase)
+ {
+ /* Yes! They are in the same module. Now store the
+ real target address into the TPF stack area of
+ the target frame we are jumping to. */
+ *((unsigned long int *)(*((unsigned long int *)
+ (*PREVIOUS_STACK_PTR() + CURRENT_STACK_PTR_OFFSET))
+ + TPFRA_OFFSET_FROM_START_OF_STACK_FRAME))
+ = (unsigned long int) target;
+
+ /* Before returning the desired pat stub address to
+ the exception handling unwinder so that it can
+ actually do the "leap" shift out the low order
+ bit designated to determine if we are in 64BIT mode.
+ This is necessary for CTOA stubs.
+ Otherwise we leap one byte past where we want to
+ go to in the TPF pat stub linkage code. */
+ shifter = *((unsigned long int *)
+ (stackptr + RA_OFFSET_FROM_START_OF_STACK_FRAME));
+
+ shifter &= ~1ul;
+
+ return (void *) shifter;
+ }
+
+ /* Desired module pat stub not found ...
+ Bump stack frame iterator. */
+ stackptr = (void *) *(unsigned long int *) stackptr;
+ }
+ }
+ }
+
+ /* No pat stub found, could be a problem? Simply return unmodified
+ target address. */
+ return target;
+}
+
diff --git a/gcc/config/sparc/sol2-gas.h b/gcc/config/sparc/sol2-gas.h
new file mode 100644
index 00000000000..7e808f7acaf
--- /dev/null
+++ b/gcc/config/sparc/sol2-gas.h
@@ -0,0 +1,5 @@
+/* Definitions of target machine for GCC, for SPARC running Solaris 2
+ using the GNU assembler. */
+
+/* Undefine this so that BNSYM/ENSYM pairs are emitted by STABS+. */
+#undef NO_DBX_BNSYM_ENSYM
diff --git a/gcc/gthr-tpf.h b/gcc/gthr-tpf.h
new file mode 100644
index 00000000000..9831c666dc4
--- /dev/null
+++ b/gcc/gthr-tpf.h
@@ -0,0 +1,157 @@
+/* Threads compatibility routines for libgcc2 and libobjc.
+ Compile this one with gcc.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it under
+the terms of the GNU General Public License as published by the Free
+Software Foundation; either version 2, or (at your option) any later
+version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT ANY
+WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING. If not, write to the Free
+Software Foundation, 59 Temple Place - Suite 330, Boston, MA
+02111-1307, USA. */
+
+/* As a special exception, if you link this library with other files,
+ some of which are compiled with GCC, to produce an executable,
+ this library does not by itself cause the resulting executable
+ to be covered by the GNU General Public License.
+ This exception does not however invalidate any other reasons why
+ the executable file might be covered by the GNU General Public License. */
+
+
+/* TPF needs its own version of gthr-*.h because TPF always links to
+ the thread library. However, for performance reasons we still do not
+ want to issue thread api calls unless a check is made to see that we
+ are running as a thread. */
+
+#ifndef GCC_GTHR_TPF_H
+#define GCC_GTHR_TPF_H
+
+/* POSIX threads specific definitions.
+ Easy, since the interface is just one-to-one mapping. */
+
+#define __GTHREADS 1
+
+/* Some implementations of <pthread.h> require this to be defined. */
+#ifndef _REENTRANT
+#define _REENTRANT 1
+#endif
+
+#include <pthread.h>
+#include <unistd.h>
+
+typedef pthread_key_t __gthread_key_t;
+typedef pthread_once_t __gthread_once_t;
+typedef pthread_mutex_t __gthread_mutex_t;
+
+#define __GTHREAD_MUTEX_INIT PTHREAD_MUTEX_INITIALIZER
+#define __GTHREAD_ONCE_INIT PTHREAD_ONCE_INIT
+
+#define NOTATHREAD 00
+#define ECBBASEPTR (unsigned long int) *(unsigned int *)0x00000514u
+#define ECBPG2PTR ECBBASEPTR + 0x1000
+#define CE2THRCPTR *((unsigned char *)(ECBPG2PTR + 208))
+#define __tpf_pthread_active() (CE2THRCPTR != NOTATHREAD)
+
+#if SUPPORTS_WEAK && GTHREAD_USE_WEAK
+
+#pragma weak pthread_once
+#pragma weak pthread_key_create
+#pragma weak pthread_key_delete
+#pragma weak pthread_getspecific
+#pragma weak pthread_setspecific
+#pragma weak pthread_create
+
+#pragma weak pthread_mutex_lock
+#pragma weak pthread_mutex_trylock
+#pragma weak pthread_mutex_unlock
+
+#endif /* SUPPORTS_WEAK */
+
+static inline int
+__gthread_active_p (void)
+{
+ return 1;
+}
+
+static inline int
+__gthread_once (__gthread_once_t *once, void (*func) (void))
+{
+ if (__tpf_pthread_active ())
+ return pthread_once (once, func);
+ else
+ return -1;
+}
+
+static inline int
+__gthread_key_create (__gthread_key_t *key, void (*dtor) (void *))
+{
+ if (__tpf_pthread_active ())
+ return pthread_key_create (key, dtor);
+ else
+ return -1;
+}
+
+static inline int
+__gthread_key_delete (__gthread_key_t key)
+{
+ if (__tpf_pthread_active ())
+ return pthread_key_delete (key);
+ else
+ return -1;
+}
+
+static inline void *
+__gthread_getspecific (__gthread_key_t key)
+{
+ if (__tpf_pthread_active ())
+ return pthread_getspecific (key);
+ else
+ return NULL;
+}
+
+static inline int
+__gthread_setspecific (__gthread_key_t key, const void *ptr)
+{
+ if (__tpf_pthread_active ())
+ return pthread_setspecific (key, ptr);
+ else
+ return -1;
+}
+
+static inline int
+__gthread_mutex_lock (__gthread_mutex_t *mutex)
+{
+ if (__tpf_pthread_active ())
+ return pthread_mutex_lock (mutex);
+ else
+ return 0;
+}
+
+static inline int
+__gthread_mutex_trylock (__gthread_mutex_t *mutex)
+{
+ if (__tpf_pthread_active ())
+ return pthread_mutex_trylock (mutex);
+ else
+ return 0;
+}
+
+static inline int
+__gthread_mutex_unlock (__gthread_mutex_t *mutex)
+{
+ if (__tpf_pthread_active ())
+ return pthread_mutex_unlock (mutex);
+ else
+ return 0;
+}
+
+#endif /* ! GCC_GTHR_TPF_H */
diff --git a/gcc/testsuite/g++.dg/ext/attribute-test-1.C b/gcc/testsuite/g++.dg/ext/attribute-test-1.C
new file mode 100644
index 00000000000..926f5811a64
--- /dev/null
+++ b/gcc/testsuite/g++.dg/ext/attribute-test-1.C
@@ -0,0 +1,37 @@
+// { dg-do run }
+// { dg-options "" }
+// PR c++/13989
+
+extern "C" void abort();
+
+#define vector __attribute__((vector_size(16)))
+
+struct Constants {
+ inline vector unsigned int deadbeef(void) const {
+ return (vector unsigned int){0xdeadbeef, 0xabababab, 0x55555555, 0x12345678};
+ };
+};
+
+inline vector unsigned int const_deadbeef(Constants &C)
+{
+ return C.deadbeef();
+}
+
+union u {
+ unsigned int f[4];
+ vector unsigned int v;
+} data;
+
+int main()
+{
+ Constants c;
+ data.v = const_deadbeef(c);
+
+ if (data.f[0] != 0xdeadbeef || data.f[1] != 0xabababab
+ || data.f[2] != 0x55555555 || data.f[3] != 0x12345678)
+ abort();
+
+ return 0;
+}
+
+
diff --git a/gcc/testsuite/g++.dg/ext/attribute-test-2.C b/gcc/testsuite/g++.dg/ext/attribute-test-2.C
new file mode 100644
index 00000000000..795fe2b6347
--- /dev/null
+++ b/gcc/testsuite/g++.dg/ext/attribute-test-2.C
@@ -0,0 +1,48 @@
+// { dg-do run }
+// { dg-options "" }
+// PR c++/9844
+
+extern "C" void abort();
+
+#define vector __attribute__((vector_size(16)))
+
+class vector_holder
+{
+ char __attribute__((vector_size(16))) vec;
+ char __attribute__((vector_size(16))) vec1;
+public:
+ operator __attribute__((vector_size(16))) short (void) {
+ return (__attribute__((vector_size(16))) short) vec;
+ }
+
+ operator __attribute__((vector_size(16))) int (void) {
+ return (__attribute__((vector_size(16))) int) vec1;
+ }
+
+ vector_holder () {
+ vec = (__attribute__((vector_size(16))) char) {'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd',
+ 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'};
+ vec1 = (__attribute__((vector_size(16))) char) {'m', 'n', 'o', 'q', 'm', 'n', 'o', 'p',
+ 'm', 'n', 'o', 'q', 'm', 'n', 'o', 'p'};
+ }
+};
+
+union u {
+ char f[16];
+ vector unsigned int v;
+} data;
+
+
+vector_holder vh;
+
+int main()
+{
+ data.v = (__attribute__((vector_size(16))) short) vh;
+ if (data.f[0] != 'a' || data.f[15] != 'd')
+ abort();
+ data.v = (__attribute__((vector_size(16))) int) vh;
+ if (data.f[0] != 'm' || data.f[15] != 'p')
+ abort();
+
+ return 0;
+}
diff --git a/gcc/testsuite/g++.dg/ext/attribute-test-3.C b/gcc/testsuite/g++.dg/ext/attribute-test-3.C
new file mode 100644
index 00000000000..76045f7f845
--- /dev/null
+++ b/gcc/testsuite/g++.dg/ext/attribute-test-3.C
@@ -0,0 +1,55 @@
+// { dg-do run }
+
+#define vector __attribute__((vector_size(16)))
+
+extern "C" void abort();
+
+class Star
+{
+ public:
+ inline vector float foo() const;
+
+ Star()
+ {
+ data.f[0] = 1.0; data.f[1] = 2.0; data.f[2] = 3.0, data.f[3] = 4.0;
+ }
+
+ private:
+ union {
+ float f[4];
+ vector float v;
+ } data;
+
+ friend vector float fTest(const Star &);
+};
+
+vector float Star::foo() const
+{
+ return data.v;
+}
+
+vector float fTest(const Star & val)
+{
+ vector float vf = val.foo();
+ return vf;
+}
+
+int main() {
+
+ Star s;
+
+ union u {
+ float f[4];
+ vector float v;
+ } data;
+
+ data.v = fTest(s);
+ for (int i=0 ; i < 4; i++)
+ if (data.f[i] != (float)(i+1))
+ abort();
+ return 0;
+}
+
+
+
+
diff --git a/gcc/testsuite/g++.dg/ext/attribute-test-4.C b/gcc/testsuite/g++.dg/ext/attribute-test-4.C
new file mode 100644
index 00000000000..d06365ca8f8
--- /dev/null
+++ b/gcc/testsuite/g++.dg/ext/attribute-test-4.C
@@ -0,0 +1,48 @@
+// { dg-do run }
+
+#define vector __attribute__((vector_size(16)))
+
+extern "C" void abort();
+
+union U {
+ float f[4];
+ vector float v;
+} data;
+
+class Star
+{
+ public:
+ static vector float foo();
+
+ Star()
+ {
+ data.f[0] = 1.0; data.f[1] = 2.0; data.f[2] = 3.0, data.f[3] = 4.0;
+ }
+
+ private:
+ friend vector float fTest();
+};
+
+vector float Star::foo()
+{
+ return data.v;
+}
+
+vector float fTest()
+{
+ vector float vf = Star::foo();
+ return vf;
+}
+
+int main() {
+
+ U data;
+ Star s;
+
+
+ data.v = fTest();
+ for (int i=0 ; i < 4; i++)
+ if (data.f[i] != (float)(i+1))
+ abort();
+ return 0;
+}
diff --git a/gcc/testsuite/g++.dg/inherit/base2.C b/gcc/testsuite/g++.dg/inherit/base2.C
new file mode 100644
index 00000000000..5c7d812c760
--- /dev/null
+++ b/gcc/testsuite/g++.dg/inherit/base2.C
@@ -0,0 +1,12 @@
+// Copyright (C) 2004 Free Software Foundation, Inc.
+// Contributed by Nathan Sidwell 23 Sep 2004 <nathan@codesourcery.com>
+
+// Origin: Wolfgang Bangerth <bangerth@dealii.org>
+// Bug 17620. Bogus duplicate base error.
+
+struct S {};
+
+typedef S B;
+
+struct D1 : B {};
+struct D2 : B {};
diff --git a/gcc/testsuite/g++.dg/lookup/ambig3.C b/gcc/testsuite/g++.dg/lookup/ambig3.C
new file mode 100644
index 00000000000..7a0a8377a91
--- /dev/null
+++ b/gcc/testsuite/g++.dg/lookup/ambig3.C
@@ -0,0 +1,18 @@
+// { dg-do compile }
+
+// Copyright (C) 2004 Free Software Foundation, Inc.
+// Contributed by Nathan Sidwell 23 Sep 2004 <nathan@codesourcery.com>
+// Origin: Wolfgang Bangerth <bangerth@dealii.org>
+
+// Follow on from Bug 16889:Undetected ambiguity.
+
+struct B {
+ int f(); // { dg-error "int B::f" "" }
+};
+
+struct B1 : virtual B {};
+struct B2 : B {};
+struct B2_2 : B2 {};
+struct BB : B1, B2_2 {};
+
+int i = BB().f(); // { dg-error "ambiguous" "" }
diff --git a/gcc/testsuite/g++.dg/lookup/crash5.C b/gcc/testsuite/g++.dg/lookup/crash5.C
new file mode 100644
index 00000000000..6584ee64505
--- /dev/null
+++ b/gcc/testsuite/g++.dg/lookup/crash5.C
@@ -0,0 +1,9 @@
+// { dg-do compile }
+//
+// PR 17618
+
+void foo()
+{
+ p; // { dg-error "not declared" }
+ (void*) p;
+}
diff --git a/gcc/testsuite/g++.dg/opt/pr17624.C b/gcc/testsuite/g++.dg/opt/pr17624.C
new file mode 100644
index 00000000000..07fbf14da36
--- /dev/null
+++ b/gcc/testsuite/g++.dg/opt/pr17624.C
@@ -0,0 +1,23 @@
+// { dg-do compile }
+// { dg-options "-O2" }
+
+extern void foo (void);
+int c;
+void foo (int n)
+{
+ int j = 0;
+ try
+ {
+ for(;;)
+ {
+ foo ();
+ if (j ++ == n)
+ break;
+ foo ();
+ }
+ }
+ catch (...)
+ {
+ c = j;
+ }
+}
diff --git a/gcc/testsuite/g++.dg/opt/pr7503-1.C b/gcc/testsuite/g++.dg/opt/pr7503-1.C
new file mode 100644
index 00000000000..d366a618030
--- /dev/null
+++ b/gcc/testsuite/g++.dg/opt/pr7503-1.C
@@ -0,0 +1,148 @@
+// PR c++/7503
+// { dg-do run }
+// { dg-options "-O2" }
+
+extern "C" void abort();
+
+void test1a()
+{
+ int A = 4;
+ int B = 4;
+
+ (A > B ? A : B) = 1;
+ if (A != 4 || B != 1)
+ abort ();
+}
+
+void test1b()
+{
+ int A = 3;
+ int B = 5;
+
+ (A > B ? A : B) = 1;
+ if (A != 3 || B != 1)
+ abort ();
+}
+
+void test1c()
+{
+ int A = 5;
+ int B = 3;
+
+ (A > B ? A : B) = 1;
+ if (A != 1 || B != 3)
+ abort ();
+}
+
+void test2a()
+{
+ int A = 4;
+ int B = 4;
+
+ (A >= B ? A : B) = 1;
+ if (A != 1 || B != 4)
+ abort ();
+}
+
+void test2b()
+{
+ int A = 3;
+ int B = 5;
+
+ (A >= B ? A : B) = 1;
+ if (A != 3 || B != 1)
+ abort ();
+}
+
+void test2c()
+{
+ int A = 5;
+ int B = 3;
+
+ (A >= B ? A : B) = 1;
+ if (A != 1 || B != 3)
+ abort ();
+}
+
+void test3a()
+{
+ int A = 4;
+ int B = 4;
+
+ (A < B ? A : B) = 1;
+ if (A != 4 || B != 1)
+ abort ();
+}
+
+void test3b()
+{
+ int A = 3;
+ int B = 5;
+
+ (A < B ? A : B) = 1;
+ if (A != 1 || B != 5)
+ abort ();
+}
+
+void test3c()
+{
+ int A = 5;
+ int B = 3;
+
+ (A < B ? A : B) = 1;
+ if (A != 5 || B != 1)
+ abort ();
+}
+
+void test4a()
+{
+ int A = 4;
+ int B = 4;
+
+ (A <= B ? A : B) = 1;
+ if (A != 1 || B != 4)
+ abort ();
+}
+
+void test4b()
+{
+ int A = 3;
+ int B = 5;
+
+ (A <= B ? A : B) = 1;
+ if (A != 1 || B != 5)
+ abort ();
+}
+
+void test4c()
+{
+ int A = 5;
+ int B = 3;
+
+ (A <= B ? A : B) = 1;
+ if (A != 5 || B != 1)
+ abort ();
+}
+
+
+int main()
+{
+ test1a();
+ test1b();
+ test1c();
+
+ test2a();
+ test2b();
+ test2c();
+
+ test3a();
+ test3b();
+ test3c();
+
+ test4a();
+ test4b();
+ test4c();
+
+ return 0;
+}
+
diff --git a/gcc/testsuite/g++.dg/opt/pr7503-2.C b/gcc/testsuite/g++.dg/opt/pr7503-2.C
new file mode 100644
index 00000000000..68bb143e45e
--- /dev/null
+++ b/gcc/testsuite/g++.dg/opt/pr7503-2.C
@@ -0,0 +1,79 @@
+// PR c++/7503
+// { dg-do run }
+// { dg-options "-O2" }
+
+extern "C" void abort();
+
+void test1a()
+{
+ int A = 4;
+ int B = 4;
+
+ (A >? B) = 1;
+ if (A != 1 || B != 4)
+ abort ();
+}
+
+void test1b()
+{
+ int A = 3;
+ int B = 5;
+
+ (A >? B) = 1;
+ if (A != 3 || B != 1)
+ abort ();
+}
+
+void test1c()
+{
+ int A = 5;
+ int B = 3;
+
+ (A >? B) = 1;
+ if (A != 1 || B != 3)
+ abort ();
+}
+
+
+void test2a()
+{
+ int A = 4;
+ int B = 4;
+
+ (A <? B) = 1;
+ if (A != 1 || B != 4)
+ abort ();
+}
+
+void test2b()
+{
+ int A = 3;
+ int B = 5;
+
+ (A <? B) = 1;
+ if (A != 1 || B != 5)
+ abort ();
+}
+
+void test2c()
+{
+ int A = 5;
+ int B = 3;
+
+ (A <? B) = 1;
+ if (A != 5 || B != 1)
+ abort ();
+}
+
+
+int main()
+{
+ test1a();
+ test1b();
+ test1c();
+ test2a();
+ test2b();
+ test2c();
+ return 0;
+}
+
diff --git a/gcc/testsuite/g++.dg/opt/pr7503-3.C b/gcc/testsuite/g++.dg/opt/pr7503-3.C
new file mode 100644
index 00000000000..ed223f4dc2c
--- /dev/null
+++ b/gcc/testsuite/g++.dg/opt/pr7503-3.C
@@ -0,0 +1,26 @@
+// PR c++/7503
+// { dg-do compile }
+// { dg-options "-O2" }
+
+extern int A, B;
+
+void test1()
+{
+ (A++ <? B) = 0; // { dg-error "non-lvalue in assignment" }
+}
+
+void test2()
+{
+ (A <? B++) = 0; // { dg-error "non-lvalue in assignment" }
+}
+
+void test3()
+{
+ (A++ >? B) = 0; // { dg-error "non-lvalue in assignment" }
+}
+
+void test4()
+{
+ (A >? B++) = 0; // { dg-error "non-lvalue in assignment" }
+}
+
diff --git a/gcc/testsuite/g++.dg/opt/pr7503-4.C b/gcc/testsuite/g++.dg/opt/pr7503-4.C
new file mode 100644
index 00000000000..06ac901229f
--- /dev/null
+++ b/gcc/testsuite/g++.dg/opt/pr7503-4.C
@@ -0,0 +1,81 @@
+// PR c++/7503
+// { dg-do run }
+// { dg-options "-O2" }
+
+extern "C" void abort();
+
+void test1a()
+{
+ int A = 4;
+ int B = 4;
+
+ A >?= B;
+ if (A != 4 || B != 4)
+ abort ();
+}
+
+void test1b()
+{
+ int A = 3;
+ int B = 5;
+
+ A >?= B;
+ if (A != 5 || B != 5)
+ abort ();
+}
+
+void test1c()
+{
+ int A = 5;
+ int B = 3;
+
+ A >?= B;
+ if (A != 5 || B != 3)
+ abort ();
+}
+
+
+void test2a()
+{
+ int A = 4;
+ int B = 4;
+
+ A <?= B;
+ if (A != 4 || B != 4)
+ abort ();
+}
+
+void test2b()
+{
+ int A = 3;
+ int B = 5;
+
+ A <?= B;
+ if (A != 3 || B != 5)
+ abort ();
+}
+
+void test2c()
+{
+ int A = 5;
+ int B = 3;
+
+ A <?= B;
+ if (A != 3 || B != 3)
+ abort ();
+}
+
+
+int main()
+{
+ test1a();
+ test1b();
+ test1c();
+
+ test2a();
+ test2b();
+ test2c();
+
+ return 0;
+}
+
diff --git a/gcc/testsuite/g++.dg/opt/pr7503-5.C b/gcc/testsuite/g++.dg/opt/pr7503-5.C
new file mode 100644
index 00000000000..9e1e719f5c2
--- /dev/null
+++ b/gcc/testsuite/g++.dg/opt/pr7503-5.C
@@ -0,0 +1,81 @@
+// PR c++/7503
+// { dg-do run }
+// { dg-options "-O2" }
+
+extern "C" void abort();
+
+void test1a()
+{
+ int A = 4;
+ int B = 4;
+
+ A >?= B++;
+ if (A != 4 || B != 5)
+ abort ();
+}
+
+void test1b()
+{
+ int A = 3;
+ int B = 5;
+
+ A >?= B++;
+ if (A != 5 || B != 6)
+ abort ();
+}
+
+void test1c()
+{
+ int A = 5;
+ int B = 3;
+
+ A >?= B++;
+ if (A != 5 || B != 4)
+ abort ();
+}
+
+
+void test2a()
+{
+ int A = 4;
+ int B = 4;
+
+ A <?= B++;
+ if (A != 4 || B != 5)
+ abort ();
+}
+
+void test2b()
+{
+ int A = 3;
+ int B = 5;
+
+ A <?= B++;
+ if (A != 3 || B != 6)
+ abort ();
+}
+
+void test2c()
+{
+ int A = 5;
+ int B = 3;
+
+ A <?= B++;
+ if (A != 3 || B != 4)
+ abort ();
+}
+
+
+int main()
+{
+ test1a();
+ test1b();
+ test1c();
+
+ test2a();
+ test2b();
+ test2c();
+
+ return 0;
+}
+
diff --git a/gcc/testsuite/g++.dg/other/anon3.C b/gcc/testsuite/g++.dg/other/anon3.C
new file mode 100644
index 00000000000..87cbfb544cd
--- /dev/null
+++ b/gcc/testsuite/g++.dg/other/anon3.C
@@ -0,0 +1,7 @@
+// pr c++/15049
+// Origin: Matt Austern <austern@apple.com>
+// Test that we can declare a global variable whose type is anonymous.
+
+// { dg-do compile }
+
+enum { a = 3 } x;
diff --git a/gcc/testsuite/g++.dg/other/error9.C b/gcc/testsuite/g++.dg/other/error9.C
new file mode 100644
index 00000000000..65a9c58ceb2
--- /dev/null
+++ b/gcc/testsuite/g++.dg/other/error9.C
@@ -0,0 +1,20 @@
+// { dg-options -Wall }
+
+// Copyright (C) 2004 Free Software Foundation, Inc.
+// Contributed by Nathan Sidwell 27 Sept 2004 <nathan@codesourcery.com>
+
+// Origin: v.haisman@sh.cvut.cz
+// Bug 17681: bad diagnostic text.
+
+struct A
+{ };
+
+struct B
+{ };
+
+struct C : public B, public A
+{
+ C () // { dg-warning "when initialized" "" }
+ : A(), B() // { dg-warning "base .\[AB\]." "" }
+ { }
+};
diff --git a/gcc/testsuite/g++.dg/template/crash23.C b/gcc/testsuite/g++.dg/template/crash23.C
new file mode 100644
index 00000000000..0c3eac1acbf
--- /dev/null
+++ b/gcc/testsuite/g++.dg/template/crash23.C
@@ -0,0 +1,9 @@
+// PR c++/17642
+
+template<int dim>
+int f(const int* const lsh, const int* const bbox, const int* const nghostzones, int d)
+{
+ for (int d=0; d<dim; ++d)
+ lsh[d] - (bbox[2*d+1] ? 0 : nghostzones[d]);
+}
+
diff --git a/gcc/testsuite/g++.dg/template/static7.C b/gcc/testsuite/g++.dg/template/static7.C
new file mode 100644
index 00000000000..edb8e6a8db0
--- /dev/null
+++ b/gcc/testsuite/g++.dg/template/static7.C
@@ -0,0 +1,16 @@
+// PR c++/17530
+// { dg-do link }
+
+typedef void (*Func) ();
+void f (Func) {}
+struct B
+{
+ static void staticfunc () {}
+};
+template <int>
+void C(){ f (B::staticfunc); }
+int main ()
+{
+ C<0>();
+ return 0;
+}
diff --git a/gcc/testsuite/g++.dg/template/static8.C b/gcc/testsuite/g++.dg/template/static8.C
new file mode 100644
index 00000000000..f8229fd827e
--- /dev/null
+++ b/gcc/testsuite/g++.dg/template/static8.C
@@ -0,0 +1,8 @@
+// PR c++/17585
+
+template <void (*p)(void)> struct S03 {};
+class C03 {
+public:
+ static void f(void) {}
+ void g(void) { S03<&f> s03; }
+};
diff --git a/gcc/testsuite/g++.dg/tree-ssa/pr17517.C b/gcc/testsuite/g++.dg/tree-ssa/pr17517.C
new file mode 100644
index 00000000000..bcd5e91dbae
--- /dev/null
+++ b/gcc/testsuite/g++.dg/tree-ssa/pr17517.C
@@ -0,0 +1,32 @@
+// Test PR 17517. Test case provided by Serge Belyshev.
+
+ /* { dg-do compile } */
+ /* { dg-options "-O2" } */
+
+
+extern void foo ();
+
+struct Ptr {
+ int * ptr;
+ Ptr () { ptr = 0; }
+ ~Ptr() { delete ptr; }
+ Ptr &operator= (int * p) { ptr = p; return *this; }
+};
+
+int *new_checker () { foo (); return 0; }
+
+void pipe (int c)
+{
+ Ptr checker;
+
+ foo ();
+ for (;;)
+ {
+ switch (c)
+ {
+ case '-':
+ checker = new_checker ();
+ break;
+ }
+ }
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/20040907-1.c b/gcc/testsuite/gcc.c-torture/compile/20040907-1.c
new file mode 100644
index 00000000000..d1dd6f22ddc
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/20040907-1.c
@@ -0,0 +1,13 @@
+void ProdWord_bla ( gtL, gtRes, lnL )
+ int *gtL, *gtRes;
+ int lnL;
+{
+ while ( 1 < lnL )
+ {
+ *gtRes++ = *gtL++;
+ --lnL;
+ }
+ if ( 0 < lnL )
+ if ( gtL[0] == gtL[1] )
+ *gtRes++ = 0;
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/20040909-1.c b/gcc/testsuite/gcc.c-torture/compile/20040909-1.c
new file mode 100644
index 00000000000..8bbf90191b4
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/20040909-1.c
@@ -0,0 +1,13 @@
+static __inline__ int
+one_utf8_to_utf16 () { }
+
+static __inline__ unsigned char
+conversion_loop (int (*const one_conversion)())
+{
+return one_conversion ();
+}
+static unsigned char
+convert_utf8_utf16 ()
+{
+ return conversion_loop (one_utf8_to_utf16);
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/20040916-1.c b/gcc/testsuite/gcc.c-torture/compile/20040916-1.c
new file mode 100644
index 00000000000..1a6a9f47fe8
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/20040916-1.c
@@ -0,0 +1,12 @@
+/* PR tree-optimization/17512
+
+ We used to try to fold "(char) (X ^ Y)", where '^' is
+ TRUTH_XOR_EXPR into ((char) X ^ (char) Y), creating TRUTH_XOR_EXPR
+ with its operands being of type char, which is invalid. */
+
+char
+foo (int p)
+{
+ int q = p;
+ return (p != 0) == (p == q);
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr16566-1.c b/gcc/testsuite/gcc.c-torture/compile/pr16566-1.c
new file mode 100644
index 00000000000..4ed4ab730e6
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr16566-1.c
@@ -0,0 +1,15 @@
+/* ICE with flexible arrays in non-lvalue structures. Bug 16566
+ (comment #3). */
+
+struct S;
+
+struct C {
+ int i;
+ struct S *tab[];
+};
+
+struct S { struct C c; };
+
+void foo (struct S *x) {
+ foo(((void)1, x->c).tab[0]);
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr16566-2.c b/gcc/testsuite/gcc.c-torture/compile/pr16566-2.c
new file mode 100644
index 00000000000..c0036f0fc64
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr16566-2.c
@@ -0,0 +1,13 @@
+/* ICE with flexible arrays in non-lvalue structures. Bug 16566
+ (comment #5). */
+
+struct A
+{
+ int i;
+ int x[];
+};
+
+int foo(struct A a)
+{
+ return (a,a).x[0];
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr16566-3.c b/gcc/testsuite/gcc.c-torture/compile/pr16566-3.c
new file mode 100644
index 00000000000..954aa361da2
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr16566-3.c
@@ -0,0 +1,12 @@
+/* ICE with flexible arrays in non-lvalue structures. Bug 16566
+ (testcase from duplicate bug 16575). */
+
+struct S;
+struct C {
+ int i;
+ struct S *tab[];
+};
+struct S { struct C c; };
+void foo (struct S *x) {
+ ((void)1, x->c).tab[0] = 0;
+}
diff --git a/gcc/testsuite/gcc.c-torture/compile/pr17558.c b/gcc/testsuite/gcc.c-torture/compile/pr17558.c
new file mode 100644
index 00000000000..bc66552851c
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/compile/pr17558.c
@@ -0,0 +1,10 @@
+struct xobject {
+ char type;
+};
+extern struct xobject *t1_Xform ( struct xobject *obj);
+struct xobject *
+t1_Xform(struct xobject *obj)
+{
+ register struct font *F = (struct font *) obj;
+ return((struct xobject*)F);
+}
diff --git a/gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2-lib.c b/gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2-lib.c
new file mode 100644
index 00000000000..b10dfcb0d79
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2-lib.c
@@ -0,0 +1 @@
+#include "lib/strcpy.c"
diff --git a/gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2.c b/gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2.c
new file mode 100644
index 00000000000..c3cb6d0e521
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/execute/builtins/strcpy-2.c
@@ -0,0 +1,47 @@
+/* Copyright (C) 2004 Free Software Foundation.
+
+ Ensure builtin strcpy is optimized into memcpy
+ even when there is more than one possible string literal
+ passed to it, but all string literals passed to it
+ have equal length.
+
+ Written by Jakub Jelinek, 9/15/2004. */
+
+extern void abort (void);
+extern char *strcpy (char *, const char *);
+typedef __SIZE_TYPE__ size_t;
+extern void *memcpy (void *, const void *, size_t);
+extern int memcmp (const void *, const void *, size_t);
+
+char buf[32], *p;
+int i;
+
+char *
+__attribute__((noinline))
+test (void)
+{
+ int j;
+ const char *q = "abcdefg";
+ for (j = 0; j < 3; ++j)
+ {
+ if (j == i)
+ q = "bcdefgh";
+ else if (j == i + 1)
+ q = "cdefghi";
+ else if (j == i + 2)
+ q = "defghij";
+ }
+ p = strcpy (buf, q);
+ return strcpy (buf + 16, q);
+}
+
+void
+main_test (void)
+{
+#ifndef __OPTIMIZE_SIZE__
+ /* For -Os, strcpy above is not replaced with
+ memcpy (buf, q, 8);, as that is larger. */
+ if (test () != buf + 16 || p != buf)
+ abort ();
+#endif
+}
diff --git a/gcc/testsuite/gcc.c-torture/execute/va-arg-26.c b/gcc/testsuite/gcc.c-torture/execute/va-arg-26.c
new file mode 100644
index 00000000000..8221e9c42a5
--- /dev/null
+++ b/gcc/testsuite/gcc.c-torture/execute/va-arg-26.c
@@ -0,0 +1,20 @@
+#include <stdarg.h>
+
+double f (float f1, float f2, float f3, float f4,
+ float f5, float f6, ...)
+{
+ va_list ap;
+ double d;
+
+ va_start (ap, f6);
+ d = va_arg (ap, double);
+ va_end (ap);
+ return d;
+}
+
+int main ()
+{
+ if (f (1, 2, 3, 4, 5, 6, 7.0) != 7.0)
+ abort ();
+ exit (0);
+}
diff --git a/gcc/testsuite/gcc.dg/20040920-1.c b/gcc/testsuite/gcc.dg/20040920-1.c
new file mode 100644
index 00000000000..8813963f973
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/20040920-1.c
@@ -0,0 +1,12 @@
+/* { dg-do compile } */
+int bob;
+struct a
+{
+ int foo;
+};
+int main(void)
+{
+ struct a bar;
+ bob(5); /* { dg-error "called object 'bob\\({anonymous}\\)' is not a function" } */
+ bar.foo(); /* { dg-error "called object 'bar.foo\\({anonymous}\\)' is not a function" } */
+}
diff --git a/gcc/testsuite/gcc.dg/Wbad-function-cast-1.c b/gcc/testsuite/gcc.dg/Wbad-function-cast-1.c
new file mode 100644
index 00000000000..4a0547f0b52
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/Wbad-function-cast-1.c
@@ -0,0 +1,51 @@
+/* Test operation of -Wbad-function-cast. Bug 6980 complained of the
+ wording of the diagnostic. */
+/* Origin: Joseph Myers <jsm@polyomino.org.uk> */
+/* { dg-do compile } */
+/* { dg-options "-Wbad-function-cast" } */
+
+void vf(void);
+int if1(void);
+char if2(void);
+long if3(void);
+float rf1(void);
+double rf2(void);
+_Complex double cf(void);
+enum e { E1 } ef(void);
+_Bool bf(void);
+char *pf1(void);
+int *pf2(void);
+
+void
+foo(void)
+{
+ /* Casts to void types are always OK. */
+ (void)vf();
+ (void)if1();
+ (void)cf();
+ (const void)bf();
+ /* Casts to the same type or similar types are OK. */
+ (int)if1();
+ (long)if2();
+ (char)if3();
+ (float)rf1();
+ (long double)rf2();
+ (_Complex float)cf();
+ (enum f { F1 })ef();
+ (_Bool)bf();
+ (void *)pf1();
+ (char *)pf2();
+ /* Casts to types with different TREE_CODE (which is how this
+ warning has been defined) are not OK, except for casts to void
+ types. */
+ (float)if1(); /* { dg-warning "cast from function call of type 'int' to non-matching type 'float'" } */
+ (double)if2(); /* { dg-warning "cast from function call of type 'char' to non-matching type 'double'" } */
+ (_Bool)if3(); /* { dg-warning "cast from function call of type 'long int' to non-matching type '_Bool'" } */
+ (int)rf1(); /* { dg-warning "cast from function call of type 'float' to non-matching type 'int'" } */
+ (long)rf2(); /* { dg-warning "cast from function call of type 'double' to non-matching type 'long int'" } */
+ (double)cf(); /* { dg-warning "cast from function call of type 'complex double' to non-matching type 'double'" } */
+ (int)ef(); /* { dg-warning "cast from function call of type 'enum e' to non-matching type 'int'" } */
+ (int)bf(); /* { dg-warning "cast from function call of type '_Bool' to non-matching type 'int'" } */
+ (__SIZE_TYPE__)pf1(); /* { dg-warning "cast from function call of type 'char \\*' to non-matching type '\[^\\n\]*'" } */
+ (__PTRDIFF_TYPE__)pf2(); /* { dg-warning "cast from function call of type 'int \\*' to non-matching type '\[^\\n\]*'" } */
+}
diff --git a/gcc/testsuite/gcc.dg/nested-redef-1.c b/gcc/testsuite/gcc.dg/nested-redef-1.c
new file mode 100644
index 00000000000..34b92d8f571
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/nested-redef-1.c
@@ -0,0 +1,44 @@
+/* Test diagnosis of nested tag redefinitions. */
+/* Origin: Joseph Myers <jsm@polyomino.org.uk> */
+/* { dg-do compile } */
+/* { dg-options "" } */
+
+struct s0 {
+ struct s0 { int a; } x; /* { dg-error "error: nested redefinition of 'struct s0'" } */
+};
+
+struct s1 {
+ const struct s1 { int b; } x; /* { dg-error "error: nested redefinition of 'struct s1'" } */
+};
+
+struct s2 {
+ struct s2 { int c; } *x; /* { dg-error "error: nested redefinition of 'struct s2'" } */
+};
+
+struct s3 {
+ struct s4 {
+ struct s5 {
+ struct s3 { int a; } **x; /* { dg-error "error: nested redefinition of 'struct s3'" } */
+ } y;
+ } z;
+};
+
+struct s6;
+struct s6 { struct s6 *p; };
+
+union u0 {
+ union u0 { int c; } *x; /* { dg-error "error: nested redefinition of 'union u0'" } */
+};
+
+enum e0 {
+ E0 = sizeof(enum e0 { E1 }) /* { dg-error "error: nested redefinition of 'enum e0'" } */
+};
+
+enum e1 {
+ E2 = sizeof(enum e2 { E2 }), /* { dg-error "error: redeclaration of enumerator 'E2'" } */
+ /* { dg-error "previous definition" "previous E2" { target *-*-* } 38 } */
+ E3
+};
+
+enum e3;
+enum e3 { E4 = 0 };
diff --git a/gcc/testsuite/gcc.dg/pr11459-1.c b/gcc/testsuite/gcc.dg/pr11459-1.c
new file mode 100644
index 00000000000..1edd94f814b
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pr11459-1.c
@@ -0,0 +1,6 @@
+/* -ansi -std=c99 should mean -std=c99, but the specs reordered the
+ options. Bug 11459. */
+/* { dg-do compile } */
+/* { dg-options "-ansi -std=c99 -pedantic" } */
+
+long long i;
diff --git a/gcc/testsuite/gcc.dg/pr13804-1.c b/gcc/testsuite/gcc.dg/pr13804-1.c
new file mode 100644
index 00000000000..2dbd731fd69
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pr13804-1.c
@@ -0,0 +1,28 @@
+/* Diagnostics for attempts to access a member not in a structure or
+ union should name the type involved. Bug 13804. */
+/* Origin: Joseph Myers <jsm@polyomino.org.uk> */
+/* { dg-do compile } */
+/* { dg-options "" } */
+
+struct s0 { int a; };
+union u0 { long b; };
+typedef struct s0 S0;
+typedef union u0 U0;
+
+struct s0 x0;
+S0 x1;
+union u0 x2;
+U0 x3;
+struct s0 *x4;
+union u0 *x5;
+
+void
+f (void)
+{
+ x0.c; /* { dg-error "error: 'struct s0' has no member named 'c'" } */
+ x1.c; /* { dg-error "error: 'S0' has no member named 'c'" } */
+ x2.c; /* { dg-error "error: 'union u0' has no member named 'c'" } */
+ x3.c; /* { dg-error "error: 'U0' has no member named 'c'" } */
+ x4->c; /* { dg-error "error: 'struct s0' has no member named 'c'" } */
+ x5->c; /* { dg-error "error: 'union u0' has no member named 'c'" } */
+}
diff --git a/gcc/testsuite/gcc.dg/pr17112-1.c b/gcc/testsuite/gcc.dg/pr17112-1.c
new file mode 100644
index 00000000000..7c8b7aa0432
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pr17112-1.c
@@ -0,0 +1,32 @@
+/* PR middle-end/17112 */
+/* { dg-do run } */
+/* { dg-options "-O2" } */
+
+extern void abort(void);
+
+typedef struct {
+ int int24:24 __attribute__ ((packed));
+} myint24;
+
+myint24 x[3] = {
+ 0x123456,
+ 0x789abc,
+ 0xdef012
+};
+
+myint24 y[3]; // starts out as zeros
+
+void foo()
+{
+ y[1] = x[1];
+}
+
+int main()
+{
+ foo();
+
+ if (y[0].int24 != 0 || y[2].int24 != 0)
+ abort();
+ return 0;
+}
+
diff --git a/gcc/testsuite/gcc.dg/pr17188-1.c b/gcc/testsuite/gcc.dg/pr17188-1.c
new file mode 100644
index 00000000000..634e60c0363
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pr17188-1.c
@@ -0,0 +1,31 @@
+/* A redefinition of an empty struct should be diagnosed the same as a
+ redefinition of any other tag, but formerly only s2 and s4 were
+ diagnosed. Bug 17188. */
+/* Origin: Joseph Myers <jsm@polyomino.org.uk> */
+/* { dg-do compile } */
+/* { dg-options "" } */
+
+struct s0 { };
+struct s0;
+struct s0 { }; /* { dg-error "error: redefinition of 'struct s0'" } */
+
+struct s1 { };
+struct s1 { }; /* { dg-error "error: redefinition of 'struct s1'" } */
+
+struct s2 { int a : 1; };
+struct s2 { int a : 1; }; /* { dg-error "error: redefinition of 'struct s2'" } */
+
+struct s3 { };
+struct s3 { int a : 1; }; /* { dg-error "error: redefinition of 'struct s3'" } */
+
+struct s4 { int a : 1; };
+struct s4 { }; /* { dg-error "error: redefinition of 'struct s4'" } */
+
+struct s5 { int a : 1; };
+struct s5;
+
+struct s6;
+struct s6 { int a : 1; };
+
+struct s7;
+struct s7 { };
diff --git a/gcc/testsuite/gcc.dg/pragma-re-3.c b/gcc/testsuite/gcc.dg/pragma-re-3.c
new file mode 100644
index 00000000000..4a73c414b92
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pragma-re-3.c
@@ -0,0 +1,18 @@
+/* { dg-do link { target *-*-solaris* } } */
+
+#pragma redefine_extname f1 f
+#pragma redefine_extname g1 g
+
+void f() {
+ extern int f1();
+ f1();
+}
+
+void g() {
+ g1();
+}
+
+int main () {
+ f();
+ g();
+}
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/loop-6.c b/gcc/testsuite/gcc.dg/tree-ssa/loop-6.c
new file mode 100644
index 00000000000..e96f5e27c70
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/loop-6.c
@@ -0,0 +1,26 @@
+/* { dg-do compile } */
+/* { dg-options "-O1 -funswitch-loops -fdump-tree-unswitch-details -fdump-tree-vars" } */
+
+int ch;
+int a[100];
+
+void xxx(void)
+{
+ int i;
+
+ for (i = 0; i < 100; i++)
+ {
+ if (ch)
+ a[i] = ch;
+ else
+ a[i] = i;
+ }
+}
+
+/* Loop should be unswitched. */
+
+/* { dg-final { scan-tree-dump-times "Unswitching loop" 1 "unswitch" } } */
+
+/* In effect there should be exactly three conditional jumps in the final program. */
+
+/* { dg-final { scan-tree-dump-times "else" 3 "vars" } } */
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr16721.c b/gcc/testsuite/gcc.dg/tree-ssa/pr16721.c
new file mode 100644
index 00000000000..869ab96497e
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/pr16721.c
@@ -0,0 +1,15 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -fno-strict-aliasing -fdump-tree-optimized" } */
+
+struct data {
+ volatile unsigned long *addr;
+} *p;
+
+int test()
+{
+ *p->addr;
+ return 0;
+}
+
+/* The load from p->addr should not disappear. */
+/* { dg-final { scan-tree-dump-times "\->addr" 1 "optimized"} } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-27a.c b/gcc/testsuite/gcc.dg/vect/vect-27a.c
new file mode 100644
index 00000000000..9dd75498676
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-27a.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -mmmx" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 128
+
+/* unaligned load. */
+
+int main1 ()
+{
+ int i;
+ int ia[N];
+ int ib[N+1];
+
+ for (i=0; i < N; i++)
+ {
+ ib[i] = i;
+ }
+
+ for (i = 1; i <= N; i++)
+ {
+ ia[i-1] = ib[i];
+ }
+
+ /* check results: */
+ for (i = 1; i <= N; i++)
+ {
+ if (ia[i-1] != ib[i])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-29a.c b/gcc/testsuite/gcc.dg/vect/vect-29a.c
new file mode 100644
index 00000000000..13cd5c9d3f2
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-29a.c
@@ -0,0 +1,50 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -mmmx" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 128
+#define OFF 3
+
+/* unaligned load. */
+
+int main1 (int off)
+{
+ int i;
+ int ia[N];
+ int ib[N+OFF];
+
+ for (i = 0; i < N+OFF; i++)
+ {
+ ib[i] = i;
+ }
+
+ for (i = 0; i < N; i++)
+ {
+ ia[i] = ib[i+off];
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (ia[i] != ib[i+off])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (0); /* aligned */
+ main1 (OFF); /* unaligned */
+ return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-48a.c b/gcc/testsuite/gcc.dg/vect/vect-48a.c
new file mode 100644
index 00000000000..0422edcbf6b
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-48a.c
@@ -0,0 +1,58 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -mmmx" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 256
+
+typedef short ashort __attribute__ ((__aligned__(16)));
+
+void bar (short *pa, short *pb, short *pc)
+{
+ int i;
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (pa[i] != (pb[i] + pc[i]))
+ abort ();
+ }
+
+ return;
+}
+
+
+int
+main1 (ashort * __restrict__ pa, short * __restrict__ pb, short * __restrict__ pc)
+{
+ int i;
+
+ for (i = 0; i < N; i++)
+ {
+ pa[i] = pb[i] + pc[i];
+ }
+
+ bar (pa,pb,pc);
+
+ return 0;
+}
+
+int main (void)
+{
+ int i;
+ ashort a[N];
+ ashort b[N+1] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57,60};
+ ashort c[N] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
+
+ check_vect ();
+
+ main1 (a,b,c);
+ main1 (a,&b[1],c);
+
+ return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-56a.c b/gcc/testsuite/gcc.dg/vect/vect-56a.c
new file mode 100644
index 00000000000..5d8ed115f18
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-56a.c
@@ -0,0 +1,56 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -mmmx" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 256
+
+typedef short ashort __attribute__ ((__aligned__(16)));
+
+void bar (ashort *pa, ashort *pb, ashort *pc)
+{
+ int i;
+
+ /* check results: */
+ for (i = 0; i < N/2; i++)
+ {
+ if (pa[i] != (pb[i+1] + pc[i+1]))
+ abort ();
+ }
+
+ return;
+}
+
+
+int
+main1 (ashort * __restrict__ pa, ashort * __restrict__ pb, ashort * __restrict__ pc)
+{
+ int i;
+
+ for (i = 0; i < N/2; i++)
+ {
+ pa[i] = pb[i+1] + pc[i+1];
+ }
+
+ bar (pa,pb,pc);
+
+ return 0;
+}
+
+int main (void)
+{
+ int i;
+ ashort a[N];
+ ashort b[N] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57};
+ ashort c[N] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19};
+
+ check_vect ();
+
+ main1 (a,b,c);
+ return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-62.c b/gcc/testsuite/gcc.dg/vect/vect-62.c
new file mode 100644
index 00000000000..28154c1f2c3
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-62.c
@@ -0,0 +1,68 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+int main1 ()
+{
+ int i, j;
+ int ib[N] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45};
+ int ia[N][4][N+8];
+
+ /* Multidimensional array. Aligned. The "inner" dimensions
+ are invariant in the inner loop. Store. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ia[i][1][j+8] = ib[i];
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ia[i][1][j+8] != ib[i])
+ abort();
+ }
+ }
+
+ /* Multidimensional array. Aligned. The "inner" dimensions
+ are invariant in the inner loop. Store. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ia[i][1][8] = ib[i];
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ia[i][1][8] != ib[i])
+ abort();
+ }
+ }
+
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 2 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-63.c b/gcc/testsuite/gcc.dg/vect/vect-63.c
new file mode 100644
index 00000000000..b68a0597930
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-63.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+int main1 ()
+{
+ int i, j;
+ int ib[N] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45};
+ int ia[N*2][4][N];
+
+ /* Multidimensional array. Aligned.
+ The first dimension depends on j: not vectorizable. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ia[i + j][1][j] = ib[i];
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ia[i + j][1][j] != ib[i])
+ abort();
+ }
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail *-*-* } } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-64.c b/gcc/testsuite/gcc.dg/vect/vect-64.c
new file mode 100644
index 00000000000..eaed89229f8
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-64.c
@@ -0,0 +1,86 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+int main1 ()
+{
+ int i, j;
+ int ib[N] = {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45};
+ int ia[N][4][N+1];
+ int ic[N][N][3][13];
+ int id[N][N][N];
+
+ /* Multidimensional array. Not aligned: not vectorizable. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ia[i][1][j] = ib[i];
+ }
+ }
+
+ /* Multidimensional array. Aligned: vectorizable. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ic[i][1][1][j] = ib[i];
+ }
+ }
+
+ /* Multidimensional array. Not aligned: not vectorizable. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ id[i][1][j+1] = ib[i];
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ia[i][1][j] != ib[i])
+ abort();
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ic[i][1][1][j] != ib[i])
+ abort();
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (id[i][1][j+1] != ib[i])
+ abort();
+ }
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-65.c b/gcc/testsuite/gcc.dg/vect/vect-65.c
new file mode 100644
index 00000000000..0ec838d309b
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-65.c
@@ -0,0 +1,84 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+#define M 4
+
+int main1 ()
+{
+ int i, j;
+ int ib[M][M][N] = {{{0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45}},
+ {{0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45}},
+ {{0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45}},
+ {{0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45},
+ {0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45}}};
+ int ia[M][M][N];
+ int ic[N];
+
+ /* Multidimensional array. Aligned. The "inner" dimensions
+ are invariant in the inner loop. Load and store. */
+ for (i = 0; i < M; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ia[i][1][j] = ib[2][i][j];
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < M; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ia[i][1][j] != ib[2][i][j])
+ abort();
+ }
+ }
+
+ /* Multidimensional array. Aligned. The "inner" dimensions
+ are invariant in the inner loop. Load. */
+ for (i = 0; i < M; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ic[j] = ib[2][i][j];
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < M; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ic[j] != ib[2][i][j])
+ abort();
+ }
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 2 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-66.c b/gcc/testsuite/gcc.dg/vect/vect-66.c
new file mode 100644
index 00000000000..9773953043a
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-66.c
@@ -0,0 +1,82 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+int main1 ()
+{
+ int i, j;
+ int ib[6] = {0,3,6,9,12,15};
+ int ia[8][5][6];
+ int ic[16][16][5][6];
+
+ /* Multidimensional array. Aligned. */
+ for (i = 0; i < 16; i++)
+ {
+ for (j = 0; j < 4; j++)
+ {
+ ia[2][6][j] = 5;
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < 16; i++)
+ {
+ for (j = 0; j < 4; j++)
+ {
+ if (ia[2][6][j] != 5)
+ abort();
+ }
+ }
+ /* Multidimensional array. Aligned. */
+ for (i = 0; i < 16; i++)
+ {
+ for (j = 0; j < 4; j++)
+ ia[3][6][j+2] = 5;
+ }
+
+ /* check results: */
+ for (i = 0; i < 16; i++)
+ {
+ for (j = 2; j < 6; j++)
+ {
+ if (ia[3][6][j] != 5)
+ abort();
+ }
+ }
+
+ /* Multidimensional array. Not aligned. */
+ for (i = 0; i < 16; i++)
+ {
+ for (j = 0; j < 4; j++)
+ {
+ ic[2][1][6][j] = 5;
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < 16; i++)
+ {
+ for (j = 0; j < 4; j++)
+ {
+ if (ic[2][1][6][j] != 5)
+ abort();
+ }
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 2 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-67.c b/gcc/testsuite/gcc.dg/vect/vect-67.c
new file mode 100644
index 00000000000..ade2ace6e02
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-67.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+int main1 (int a, int b)
+{
+ int i, j;
+ int ia[N][4][N+8];
+
+ /* Multidimensional array. Aligned. The "inner" dimensions
+ are invariant in the inner loop. Store.
+ Not vectorizable: unsupported operation. */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ ia[i][1][j+8] = (a == b);
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (ia[i][1][j+8] != (a == b))
+ abort();
+ }
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 (2 ,7);
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail *-*-* } } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-68.c b/gcc/testsuite/gcc.dg/vect/vect-68.c
new file mode 100644
index 00000000000..3812cead7e9
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-68.c
@@ -0,0 +1,90 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 32
+
+struct s{
+ int m;
+ int n[N][N][N];
+};
+
+struct test1{
+ struct s a; /* array a.n is unaligned */
+ int b;
+ int c;
+ struct s e; /* array e.n is aligned */
+};
+
+int main1 ()
+{
+ int i,j;
+ struct test1 tmp1;
+
+ /* 1. unaligned */
+ for (i = 0; i < N; i++)
+ {
+ tmp1.a.n[1][2][i] = 5;
+ }
+
+ /* check results: */
+ for (i = 0; i <N; i++)
+ {
+ if (tmp1.a.n[1][2][i] != 5)
+ abort ();
+ }
+
+ /* 2. aligned */
+ for (i = 3; i < N-1; i++)
+ {
+ tmp1.a.n[1][2][i] = 6;
+ }
+
+ /* check results: */
+ for (i = 3; i < N-1; i++)
+ {
+ if (tmp1.a.n[1][2][i] != 6)
+ abort ();
+ }
+
+ /* 3. aligned */
+ for (i = 0; i < N; i++)
+ {
+ tmp1.e.n[1][2][i] = 7;
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (tmp1.e.n[1][2][i] != 7)
+ abort ();
+ }
+
+ /* 4. unaligned */
+ for (i = 3; i < N-3; i++)
+ {
+ tmp1.e.n[1][2][i] = 8;
+ }
+
+ /* check results: */
+ for (i = 3; i <N-3; i++)
+ {
+ if (tmp1.e.n[1][2][i] != 8)
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 2 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-69.c b/gcc/testsuite/gcc.dg/vect/vect-69.c
new file mode 100644
index 00000000000..92b4ef298d5
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-69.c
@@ -0,0 +1,117 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 32
+
+struct s{
+ int m;
+ int n[N][N][N];
+};
+
+struct s2{
+ int m;
+ int n[N-1][N-1][N-1];
+};
+
+struct test1{
+ struct s a; /* array a.n is unaligned */
+ int b;
+ int c;
+ struct s e; /* array e.n is aligned */
+};
+
+struct test2{
+ struct s2 a; /* array a.n is unaligned */
+ int b;
+ int c;
+ struct s2 e; /* array e.n is aligned */
+};
+
+
+struct test1 tmp1[4];
+struct test2 tmp2[4];
+
+int main1 ()
+{
+ int i,j;
+
+ /* 1. unaligned */
+ for (i = 0; i < N; i++)
+ {
+ tmp1[2].a.n[1][2][i] = 5;
+ }
+
+ /* check results: */
+ for (i = 0; i <N; i++)
+ {
+ if (tmp1[2].a.n[1][2][i] != 5)
+ abort ();
+ }
+
+ /* 2. aligned */
+ for (i = 3; i < N-1; i++)
+ {
+ tmp1[2].a.n[1][2][i] = 6;
+ }
+
+ /* check results: */
+ for (i = 3; i < N-1; i++)
+ {
+ if (tmp1[2].a.n[1][2][i] != 6)
+ abort ();
+ }
+
+ /* 3. aligned */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ tmp1[2].e.n[1][i][j] = 8;
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ for (j = 0; j < N; j++)
+ {
+ if (tmp1[2].e.n[1][i][j] != 8)
+ abort ();
+ }
+ }
+
+ /* 4. unaligned */
+ for (i = 0; i < N-4; i++)
+ {
+ for (j = 0; j < N-4; j++)
+ {
+ tmp2[2].e.n[1][i][j] = 8;
+ }
+ }
+
+ /* check results: */
+ for (i = 0; i < N-4; i++)
+ {
+ for (j = 0; j < N-4; j++)
+ {
+ if (tmp2[2].e.n[1][i][j] != 8)
+ abort ();
+ }
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 2 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-72.c b/gcc/testsuite/gcc.dg/vect/vect-72.c
new file mode 100644
index 00000000000..1a2ad070963
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-72.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 128
+
+/* unaligned load. */
+
+int main1 ()
+{
+ int i;
+ char ia[N];
+ char ib[N+1];
+
+ for (i=0; i < N+1; i++)
+ {
+ ib[i] = i;
+ }
+
+ for (i = 1; i < N+1; i++)
+ {
+ ia[i-1] = ib[i];
+ }
+
+ /* check results: */
+ for (i = 1; i <= N; i++)
+ {
+ if (ia[i-1] != ib[i])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail i?86-*-* x86_64-*-* } } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-72a.c b/gcc/testsuite/gcc.dg/vect/vect-72a.c
new file mode 100644
index 00000000000..71fda70badc
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-72a.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -mmmx" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 128
+
+/* unaligned load. */
+
+int main1 ()
+{
+ int i;
+ char ia[N];
+ char ib[N+1];
+
+ for (i=0; i < N+1; i++)
+ {
+ ib[i] = i;
+ }
+
+ for (i = 1; i < N+1; i++)
+ {
+ ia[i-1] = ib[i];
+ }
+
+ /* check results: */
+ for (i = 1; i <= N; i++)
+ {
+ if (ia[i-1] != ib[i])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ return main1 ();
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-74.c b/gcc/testsuite/gcc.dg/vect/vect-74.c
new file mode 100644
index 00000000000..a8b950f39cf
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-74.c
@@ -0,0 +1,46 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+typedef float afloat __attribute__ ((__aligned__(16)));
+
+afloat a[N];
+afloat b[N+4] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 7.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0};
+afloat c[N] = {0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5};
+
+int
+main1 (afloat *__restrict__ pa, afloat * __restrict__ pb, afloat * __restrict__ pc)
+{
+ int i;
+ afloat *q = pb + 4;
+
+ for (i = 0; i < N; i++)
+ {
+ pa[i] = q[i] * pc[i];
+ }
+
+ for (i = 0; i < N; i++)
+ {
+ if (pa[i] != q[i] * pc[i])
+ abort();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (a, b, c);
+
+ return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-75.c b/gcc/testsuite/gcc.dg/vect/vect-75.c
new file mode 100644
index 00000000000..f5fee582d2d
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-75.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 8
+#define OFF 8
+
+typedef int aint __attribute__ ((__aligned__(16)));
+
+aint ib[N+OFF] = {0, 1, 3, 5, 7, 11, 13, 17, 0, 2, 6, 10, 14, 22, 26, 34};
+
+int main1 (aint *ib)
+{
+ int i;
+ int ia[N];
+
+ for (i = 0; i < N; i++)
+ {
+ ia[i] = ib[i+OFF];
+ }
+
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (ia[i] != ib[i+OFF])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (ib);
+ return 0;
+}
+
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-76.c b/gcc/testsuite/gcc.dg/vect/vect-76.c
new file mode 100644
index 00000000000..17d6ff7b52f
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-76.c
@@ -0,0 +1,74 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 8
+#define OFF 4
+
+typedef int aint __attribute__ ((__aligned__(16)));
+
+aint ib[N+OFF] = {0, 1, 3, 5, 7, 11, 13, 17, 0, 2, 6, 10};
+
+int main1 (aint *pib)
+{
+ int i;
+ int ia[N+OFF];
+ int ic[N+OFF] = {0, 1, 3, 5, 7, 11, 13, 17, 0, 2, 6, 10};
+
+ for (i = OFF; i < N; i++)
+ {
+ ia[i] = pib[i - OFF];
+ }
+
+
+ /* check results: */
+ for (i = OFF; i < N; i++)
+ {
+ if (ia[i] != pib[i - OFF])
+ abort ();
+ }
+
+ for (i = 0; i < N; i++)
+ {
+ ia[i] = pib[i - OFF];
+ }
+
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (ia[i] != pib[i - OFF])
+ abort ();
+ }
+
+ for (i = OFF; i < N; i++)
+ {
+ ia[i] = ic[i - OFF];
+ }
+
+
+ /* check results: */
+ for (i = OFF; i < N; i++)
+ {
+ if (ia[i] != ic[i - OFF])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (&ib[OFF]);
+ return 0;
+}
+
+
+/* { dg-final { scan-tree-dump-times "vectorized 3 loops" 1 "vect" } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-77.c b/gcc/testsuite/gcc.dg/vect/vect-77.c
new file mode 100644
index 00000000000..9f5697d6035
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-77.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 8
+#define OFF 8
+
+typedef int aint __attribute__ ((__aligned__(16)));
+
+aint ib[N+OFF] = {0, 1, 3, 5, 7, 11, 13, 17, 0, 2, 6, 10, 14, 22, 26, 34};
+
+int main1 (aint *ib, int off)
+{
+ int i;
+ int ia[N];
+
+ for (i = 0; i < N; i++)
+ {
+ ia[i] = ib[i+off];
+ }
+
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (ia[i] != ib[i+off])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (ib, 8);
+ return 0;
+}
+
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail i?86-*-* x86_64-*-* } } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-77a.c b/gcc/testsuite/gcc.dg/vect/vect-77a.c
new file mode 100644
index 00000000000..afa0c494d3b
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-77a.c
@@ -0,0 +1,47 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -mmmx" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 8
+#define OFF 8
+
+typedef int aint __attribute__ ((__aligned__(16)));
+
+aint ib[N+OFF] = {0, 1, 3, 5, 7, 11, 13, 17, 0, 2, 6, 10, 14, 22, 26, 34};
+
+int main1 (aint *ib, int off)
+{
+ int i;
+ int ia[N];
+
+ for (i = 0; i < N; i++)
+ {
+ ia[i] = ib[i+off];
+ }
+
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (ia[i] != ib[i+off])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (ib, 8);
+ return 0;
+}
+
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-78.c b/gcc/testsuite/gcc.dg/vect/vect-78.c
new file mode 100644
index 00000000000..75ad3c29843
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-78.c
@@ -0,0 +1,48 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 8
+#define OFF 8
+
+typedef int aint __attribute__ ((__aligned__(16)));
+
+aint ib[N+OFF] = {0, 1, 3, 5, 7, 11, 13, 17, 0, 2, 6, 10, 14, 22, 26, 34};
+int off = 8;
+
+int main1 (aint *ib)
+{
+ int i;
+ int ia[N];
+
+ for (i = 0; i < N; i++)
+ {
+ ia[i] = ib[i+off];
+ }
+
+
+ /* check results: */
+ for (i = 0; i < N; i++)
+ {
+ if (ia[i] != ib[i+off])
+ abort ();
+ }
+
+ return 0;
+}
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (ib);
+ return 0;
+}
+
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail *-*-* } } } */
+
diff --git a/gcc/testsuite/gcc.dg/vect/vect-79.c b/gcc/testsuite/gcc.dg/vect/vect-79.c
new file mode 100644
index 00000000000..a05642d5451
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-79.c
@@ -0,0 +1,48 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+typedef float afloat __attribute__ ((__aligned__(16)));
+
+afloat a[N];
+afloat b[N+4] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 7.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0};
+afloat c[N] = {0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5};
+
+/* Not vectorizable. Alias. */
+int
+main1 (afloat *pa, afloat *pb, afloat *pc)
+{
+ int i;
+ afloat *q = pb + 4;
+
+ for (i = 0; i < N; i++)
+ {
+ pa[i] = q[i] * pc[i];
+ }
+
+ for (i = 0; i < N; i++)
+ {
+ if (pa[i] != q[i] * pc[i])
+ abort();
+ }
+
+ return 0;
+}
+
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (a, b, c);
+
+ return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail *-*-* } } } */
diff --git a/gcc/testsuite/gcc.dg/vect/vect-80.c b/gcc/testsuite/gcc.dg/vect/vect-80.c
new file mode 100644
index 00000000000..cc0b9ec5352
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/vect/vect-80.c
@@ -0,0 +1,48 @@
+/* { dg-do run { target powerpc*-*-* } } */
+/* { dg-do run { target i?86-*-* x86_64-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -maltivec" { target powerpc*-*-* } } */
+/* { dg-options "-O2 -ftree-vectorize -fdump-tree-vect-stats -msse2" { target i?86-*-* x86_64-*-* } } */
+
+#include <stdarg.h>
+#include "tree-vect.h"
+
+#define N 16
+
+typedef float afloat __attribute__ ((__aligned__(16)));
+
+afloat fa[N];
+afloat fb[N+4] = {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 7.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0};
+afloat fc[N] = {0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5};
+
+/* Not vectorizable: not aligned pointers. */
+int
+main1 (float * __restrict__ pa, float * __restrict__ pb, float *__restrict__ pc)
+{
+ int i;
+ float *q = pb + 4;
+
+ for (i = 0; i < N; i++)
+ {
+ pa[i] = q[i] * pc[i];
+ }
+
+ for (i = 0; i < N; i++)
+ {
+ if (pa[i] != q[i] * pc[i])
+ abort();
+ }
+
+ return 0;
+}
+
+
+int main (void)
+{
+ check_vect ();
+
+ main1 (fa, fb, fc);
+
+ return 0;
+}
+
+/* { dg-final { scan-tree-dump-times "vectorized 1 loops" 1 "vect" { xfail *-*-* } } } */
diff --git a/gcc/testsuite/gcc.target/mips/asm-1.c b/gcc/testsuite/gcc.target/mips/asm-1.c
new file mode 100644
index 00000000000..1a64e8754fd
--- /dev/null
+++ b/gcc/testsuite/gcc.target/mips/asm-1.c
@@ -0,0 +1,14 @@
+/* PR target/17565. GCC used to put the asm into the delay slot
+ of the call. */
+/* { dg-do assemble } */
+/* { dg-options "-O" } */
+int foo (int n)
+{
+ register int k asm ("$16") = n;
+ if (k > 0)
+ {
+ bar ();
+ asm ("li %0,0x12345678" : "=r" (k));
+ }
+ return k;
+}
diff --git a/gcc/testsuite/gfortran.dg/pr15164.f90 b/gcc/testsuite/gfortran.dg/pr15164.f90
new file mode 100644
index 00000000000..f4fef7069f7
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr15164.f90
@@ -0,0 +1,16 @@
+! { dg-do compile }
+! I couldn't reproduce the failure with a compiler built from the
+! 2004-09-26 sources
+ module specfiles
+ contains
+ subroutine split(instring,outstrings,lenout,n,i)
+ integer(kind=4),intent(in) :: lenout,n
+ character(len=*),intent(in) :: instring
+ character(len=lenout),dimension(n),intent(out) :: outstrings
+ integer(kind=4) :: i,j,k
+ j=1; k=1
+ outstrings(j)(k:k)=instring(i:i)
+ return
+ end subroutine split
+ end module specfiles
+
diff --git a/gcc/testsuite/gfortran.dg/pr15957.f90 b/gcc/testsuite/gfortran.dg/pr15957.f90
new file mode 100644
index 00000000000..b1439131f89
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr15957.f90
@@ -0,0 +1,27 @@
+! { dg-do run }
+! PR 15957
+! we used to return the wrong shape when the order parameter was used
+! in reshape.
+!
+INTEGER, parameter :: i(2,3) = reshape ((/1,2,3,4,5,6/), (/2,3/)), &
+ j(2,4) = reshape ((/1,2,3,4,5,6/), (/2,4/), (/0,0/), (/2,1/))
+
+integer :: k(2,3), m(2,4), n(2,3), o(2,4)
+
+k(1,:) = (/ 1, 3, 5 /)
+k(2,:) = (/ 2, 4, 6 /)
+
+m(1,:) = (/ 1, 2, 3, 4 /)
+m(2,:) = (/ 5, 6, 0, 0 /)
+
+! check that reshape does the right thing while constant folding
+if (any(i /= k)) call abort()
+if (any(j /= m)) call abort()
+
+! check that reshape does the right thing at runtime
+n = reshape ((/1,2,3,4,5,6/), (/2,3/))
+if (any(n /= k)) call abort()
+o = reshape ((/1,2,3,4,5,6/), (/2,4/), (/0,0/), (/2,1/))
+if (any(o /= m)) call abort()
+end
+
diff --git a/gcc/testsuite/gfortran.dg/pr16938.f90 b/gcc/testsuite/gfortran.dg/pr16938.f90
new file mode 100644
index 00000000000..8a9c286ef3e
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr16938.f90
@@ -0,0 +1,27 @@
+! { dg-do run }
+! We used to get an internal error in the backend when trying to compile this
+! Added some code which verifies that we're actually doing the right thing.
+ program Array_List
+ implicit none
+
+ type :: Compound
+ integer :: Count
+ character (len = 4) :: Name
+ end type Compound
+
+ type :: Table
+ type (Compound) :: Data (2)
+ integer :: L_Size
+ end type Table
+
+ type (Table) :: ElementTable
+ ElementTable%Data(1) = Compound(1,"one")
+ ElementTable%Data(2) = Compound(2,"two")
+ ElementTable%L_size = 2
+
+ if (elementtable%data(1)%count /= 1) call abort
+ if (elementtable%data(2)%count /= 2) call abort
+ if (elementtable%data(1)%name /= "one ") call abort
+ if (elementtable%data(2)%name /= "two ") call abort
+ if (elementtable%l_size /= 2) call abort
+ end program Array_List
diff --git a/gcc/testsuite/gfortran.dg/pr17286.f90 b/gcc/testsuite/gfortran.dg/pr17286.f90
new file mode 100644
index 00000000000..ccd100f93b0
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr17286.f90
@@ -0,0 +1,45 @@
+! pr17286
+! namelist read fails when spaces exist between the '=' and the numbers
+! this is a libgfortran bug
+! derived from testcase provided by Paul Thomas <paulthomas2@wanadoo.fr
+
+
+ program bug3
+ integer num1 , num2 , num3 , num4
+ data num3 / 42 /
+ data num4 / 56 /
+ namelist /mynml1/ num1,num2
+ namelist /mynml2/ num3,num4
+ logical dbg
+ data dbg / .FALSE. /
+ open(unit=10,status='SCRATCH')
+ write(10,'(A)') "&mynml1,num1=16,num2=32,&end"
+!
+! write mynml2
+!
+ write(10,mynml2)
+ rewind(10)
+!
+! now read back
+!
+ num1 = -1
+ num2 = -1
+ read(10,mynml1)
+ if (num1.eq.16.and.num2.eq.32) then
+ if (dbg) write(*,mynml1)
+ else
+ if (dbg) print *, 'expected 16 32 got ',num1,num2
+ call abort
+ endif
+ num3 = -1
+ num4 = -1
+ read(10,mynml2)
+ if (num3.eq.42.and.num4.eq.56) then
+ if (dbg) write(*,mynml2)
+ else
+ if (dbg) print *, 'expected 42 56 got ',num3,num4
+ call abort
+ endif
+
+ close(10)
+ end
diff --git a/gcc/testsuite/gfortran.dg/pr17615.f90 b/gcc/testsuite/gfortran.dg/pr17615.f90
new file mode 100644
index 00000000000..13b90334a7b
--- /dev/null
+++ b/gcc/testsuite/gfortran.dg/pr17615.f90
@@ -0,0 +1,19 @@
+! { dg-do compile }
+! we didn't look at the right symbol when genrating code. This broke
+! when array valued functions came into play.
+module module_vec3d
+ INTERFACE cross_product
+ MODULE PROCEDURE cross_product3_R4_R8
+ END INTERFACE
+CONTAINS
+ FUNCTION cross_product3_R4_R8 ()
+ real(8) :: cross_product3_r4_r8(3)
+ cross_product3_r4_r8 = 0
+ END FUNCTION cross_product3_R4_R8
+END MODULE module_vec3d
+
+PROGRAM TEST
+ use module_vec3d, only: cross_product
+ real(8) :: c(3)
+ c = cross_product()
+END PROGRAM TEST
diff --git a/gcc/testsuite/gfortran.fortran-torture/execute/iolength_2.f90 b/gcc/testsuite/gfortran.fortran-torture/execute/iolength_2.f90
new file mode 100644
index 00000000000..ac65778639e
--- /dev/null
+++ b/gcc/testsuite/gfortran.fortran-torture/execute/iolength_2.f90
@@ -0,0 +1,24 @@
+! Test that IOLENGTH works for derived types containing arrays
+module iolength_2_mod
+ integer, parameter :: &
+ ! 32 bit, i.e. 4 byte integer (every gcc architecture should have this?)
+ int32 = selected_int_kind(9), &
+ ! IEEE double precision, i.e. 8 bytes
+ dp = selected_real_kind(15, 307)
+ type foo
+ ! This type should take up 5*4+4+8=32 bytes
+ integer(int32) :: a(5), b
+ real(dp) :: c
+ end type foo
+end module iolength_2_mod
+
+program iolength_2
+ use iolength_2_mod
+ implicit none
+ integer :: iol
+ type(foo) :: d
+ inquire (iolength = iol) d
+ if ( 32 /= iol) then
+ call abort
+ end if
+end program iolength_2
diff --git a/gcc/tree-ssa-loop-unswitch.c b/gcc/tree-ssa-loop-unswitch.c
new file mode 100644
index 00000000000..d4ab19263ae
--- /dev/null
+++ b/gcc/tree-ssa-loop-unswitch.c
@@ -0,0 +1,291 @@
+/* Loop unswitching.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GCC.
+
+GCC is free software; you can redistribute it and/or modify it
+under the terms of the GNU General Public License as published by the
+Free Software Foundation; either version 2, or (at your option) any
+later version.
+
+GCC is distributed in the hope that it will be useful, but WITHOUT
+ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+for more details.
+
+You should have received a copy of the GNU General Public License
+along with GCC; see the file COPYING. If not, write to the Free
+Software Foundation, 59 Temple Place - Suite 330, Boston, MA
+02111-1307, USA. */
+
+#include "config.h"
+#include "system.h"
+#include "coretypes.h"
+#include "tm.h"
+#include "tree.h"
+#include "rtl.h"
+#include "tm_p.h"
+#include "hard-reg-set.h"
+#include "basic-block.h"
+#include "output.h"
+#include "diagnostic.h"
+#include "tree-flow.h"
+#include "tree-dump.h"
+#include "timevar.h"
+#include "cfgloop.h"
+#include "domwalk.h"
+#include "params.h"
+#include "tree-pass.h"
+
+/* This file implements the loop unswitching, i.e. transformation of loops like
+
+ while (A)
+ {
+ if (inv)
+ B;
+
+ X;
+
+ if (!inv)
+ C;
+ }
+
+ where inv is the loop invariant, into
+
+ if (inv)
+ {
+ while (A)
+ {
+ B;
+ X;
+ }
+ }
+ else
+ {
+ while (A)
+ {
+ X;
+ C;
+ }
+ }
+
+ Inv is considered invariant iff the values it compares are both invariant;
+ tree-ssa-loop-im.c ensures that all the suitable conditions are in this
+ shape. */
+
+static struct loop *tree_unswitch_loop (struct loops *, struct loop *, basic_block,
+ tree);
+static bool tree_unswitch_single_loop (struct loops *, struct loop *, int);
+static tree tree_may_unswitch_on (basic_block, struct loop *);
+
+/* Main entry point. Perform loop unswitching on all suitable LOOPS. */
+
+void
+tree_ssa_unswitch_loops (struct loops *loops)
+{
+ int i, num;
+ struct loop *loop;
+ bool changed = false;
+
+ /* Go through inner loops (only original ones). */
+ num = loops->num;
+
+ for (i = 1; i < num; i++)
+ {
+ /* Removed loop? */
+ loop = loops->parray[i];
+ if (!loop)
+ continue;
+
+ if (loop->inner)
+ continue;
+
+ changed |= tree_unswitch_single_loop (loops, loop, 0);
+#ifdef ENABLE_CHECKING
+ verify_dominators (CDI_DOMINATORS);
+ verify_loop_structure (loops);
+#endif
+ }
+
+#if 0
+ /* The necessary infrastructure is not in yet. */
+ if (changed)
+ cleanup_tree_cfg_loop ();
+#endif
+}
+
+/* Checks whether we can unswitch LOOP on condition at end of BB -- one of its
+ basic blocks (for what it means see comments below). */
+
+static tree
+tree_may_unswitch_on (basic_block bb, struct loop *loop)
+{
+ tree stmt, def, cond;
+ basic_block def_bb;
+ use_optype uses;
+ unsigned i;
+
+ /* BB must end in a simple conditional jump. */
+ stmt = last_stmt (bb);
+ if (!stmt || TREE_CODE (stmt) != COND_EXPR)
+ return NULL_TREE;
+
+ /* Condition must be invariant. */
+ get_stmt_operands (stmt);
+ uses = STMT_USE_OPS (stmt);
+ for (i = 0; i < NUM_USES (uses); i++)
+ {
+ def = SSA_NAME_DEF_STMT (USE_OP (uses, i));
+ def_bb = bb_for_stmt (def);
+ if (def_bb
+ && flow_bb_inside_loop_p (loop, def_bb))
+ return NULL_TREE;
+ }
+
+ cond = COND_EXPR_COND (stmt);
+ /* To keep the things simple, we do not directly remove the conditions,
+ but just replace tests with 0/1. Prevent the infinite loop where we
+ would unswitch again on such a condition. */
+ if (integer_zerop (cond) || integer_nonzerop (cond))
+ return NULL_TREE;
+
+ return cond;
+}
+
+/* Simplifies COND using checks in front of the entry of the LOOP. Just very
+ simplish (sufficient to prevent us from duplicating loop in unswitching
+ unnecessarily). */
+
+static tree
+simplify_using_entry_checks (struct loop *loop, tree cond)
+{
+ edge e = loop_preheader_edge (loop);
+ tree stmt;
+
+ while (1)
+ {
+ stmt = last_stmt (e->src);
+ if (stmt
+ && TREE_CODE (stmt) == COND_EXPR
+ && operand_equal_p (COND_EXPR_COND (stmt), cond, 0))
+ return (e->flags & EDGE_TRUE_VALUE
+ ? boolean_true_node
+ : boolean_false_node);
+
+ if (EDGE_COUNT (e->src->preds) > 1)
+ return cond;
+
+ e = EDGE_PRED (e->src, 0);
+ if (e->src == ENTRY_BLOCK_PTR)
+ return cond;
+ }
+}
+
+/* Unswitch single LOOP. NUM is number of unswitchings done; we do not allow
+ it to grow too much, it is too easy to create example on that the code would
+ grow exponentially. */
+
+static bool
+tree_unswitch_single_loop (struct loops *loops, struct loop *loop, int num)
+{
+ basic_block *bbs;
+ struct loop *nloop;
+ unsigned i;
+ tree cond = NULL_TREE, stmt;
+ bool changed = false;
+
+ /* Do not unswitch too much. */
+ if (num > PARAM_VALUE (PARAM_MAX_UNSWITCH_LEVEL))
+ {
+ if (dump_file && (dump_flags & TDF_DETAILS))
+ fprintf (dump_file, ";; Not unswitching anymore, hit max level\n");
+ return false;
+ }
+
+ /* Only unswitch innermost loops. */
+ if (loop->inner)
+ {
+ if (dump_file && (dump_flags & TDF_DETAILS))
+ fprintf (dump_file, ";; Not unswitching, not innermost loop\n");
+ return false;
+ }
+
+ /* The loop should not be too large, to limit code growth. */
+ if (tree_num_loop_insns (loop)
+ > (unsigned) PARAM_VALUE (PARAM_MAX_UNSWITCH_INSNS))
+ {
+ if (dump_file && (dump_flags & TDF_DETAILS))
+ fprintf (dump_file, ";; Not unswitching, loop too big\n");
+ return false;
+ }
+
+ i = 0;
+ bbs = get_loop_body (loop);
+
+ while (1)
+ {
+ /* Find a bb to unswitch on. */
+ for (; i < loop->num_nodes; i++)
+ if ((cond = tree_may_unswitch_on (bbs[i], loop)))
+ break;
+
+ if (i == loop->num_nodes)
+ {
+ free (bbs);
+ return changed;
+ }
+
+ cond = simplify_using_entry_checks (loop, cond);
+ stmt = last_stmt (bbs[i]);
+ if (integer_nonzerop (cond))
+ {
+ /* Remove false path. */
+ COND_EXPR_COND (stmt) = boolean_true_node;
+ changed = true;
+ }
+ else if (integer_zerop (cond))
+ {
+ /* Remove true path. */
+ COND_EXPR_COND (stmt) = boolean_false_node;
+ changed = true;
+ }
+ else
+ break;
+
+ modify_stmt (stmt);
+ i++;
+ }
+
+ if (dump_file && (dump_flags & TDF_DETAILS))
+ fprintf (dump_file, ";; Unswitching loop\n");
+
+ /* Unswitch the loop on this condition. */
+ nloop = tree_unswitch_loop (loops, loop, bbs[i], cond);
+ if (!nloop)
+ return changed;
+
+ /* Invoke itself on modified loops. */
+ tree_unswitch_single_loop (loops, nloop, num + 1);
+ tree_unswitch_single_loop (loops, loop, num + 1);
+ return true;
+}
+
+/* Unswitch a LOOP w.r. to given basic block UNSWITCH_ON. We only support
+ unswitching of innermost loops. COND is the condition determining which
+ loop is entered -- the new loop is entered if COND is true. Returns NULL
+ if impossible, new loop otherwise. */
+
+static struct loop *
+tree_unswitch_loop (struct loops *loops, struct loop *loop,
+ basic_block unswitch_on, tree cond)
+{
+ basic_block condition_bb;
+
+ /* Some sanity checking. */
+ gcc_assert (flow_bb_inside_loop_p (loop, unswitch_on));
+ gcc_assert (EDGE_COUNT (unswitch_on->succs) == 2);
+ gcc_assert (loop->inner == NULL);
+
+ return tree_ssa_loop_version (loops, loop, unshare_expr (cond),
+ &condition_bb);
+}
diff --git a/intl/.cvsignore b/intl/.cvsignore
new file mode 100644
index 00000000000..d89921897ae
--- /dev/null
+++ b/intl/.cvsignore
@@ -0,0 +1 @@
+autom4te.cache
diff --git a/libjava/gnu/java/nio/VMPipe.java b/libjava/gnu/java/nio/VMPipe.java
new file mode 100644
index 00000000000..15693e52e2c
--- /dev/null
+++ b/libjava/gnu/java/nio/VMPipe.java
@@ -0,0 +1,64 @@
+/* VMPipe.java -- Reference implementation for VM hooks used by PipeImpl
+ Copyright (C) 2004 Free Software Foundation
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.nio;
+
+import java.io.IOException;
+import java.nio.channels.spi.SelectorProvider;
+import gnu.classpath.Configuration;
+
+/**
+ * This class contains the native methods for gnu.java.nio.PipeImpl
+ * As such, it needs help from the VM.
+ *
+ * @author Patrik Reali
+ */
+final class VMPipe
+{
+
+ static
+ {
+ // load the shared library needed for native methods.
+ if (Configuration.INIT_LOAD_LIBRARY)
+ {
+ System.loadLibrary ("javanio");
+ }
+ }
+
+ static native void init(PipeImpl self, SelectorProvider provider)
+ throws IOException;
+}
diff --git a/libjava/gnu/java/nio/VMSelector.java b/libjava/gnu/java/nio/VMSelector.java
new file mode 100644
index 00000000000..7d0606a7706
--- /dev/null
+++ b/libjava/gnu/java/nio/VMSelector.java
@@ -0,0 +1,59 @@
+/* VMSelector.java --
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.java.nio;
+
+import gnu.classpath.Configuration;
+import java.io.IOException;
+
+public final class VMSelector
+{
+ static
+ {
+ // load the shared library needed for native methods.
+ if (Configuration.INIT_LOAD_LIBRARY)
+ {
+ System.loadLibrary ("javanio");
+ }
+ }
+
+ // A timeout value of 0 means block forever.
+ static native int select (int[] read, int[] write,
+ int[] except, long timeout)
+ throws IOException;
+
+}
diff --git a/libjava/gnu/regexp/RETokenLookAhead.java b/libjava/gnu/regexp/RETokenLookAhead.java
new file mode 100644
index 00000000000..650bb351b10
--- /dev/null
+++ b/libjava/gnu/regexp/RETokenLookAhead.java
@@ -0,0 +1,87 @@
+/* gnu/regexp/RETokenLookAhead.java
+ Copyright (C) 1998-2001, 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+package gnu.regexp;
+
+/**
+ * @since gnu.regexp 1.1.3
+ * @author Shashank Bapat
+ */
+final class RETokenLookAhead extends REToken
+{
+ REToken re;
+ boolean negative;
+
+ RETokenLookAhead(REToken re, boolean negative) throws REException {
+ super(0);
+ this.re = re;
+ this.negative = negative;
+ }
+
+ boolean match(CharIndexed input, REMatch mymatch)
+ {
+ REMatch trymatch = (REMatch)mymatch.clone();
+ REMatch trymatch1 = (REMatch)mymatch.clone();
+ REMatch newMatch = null;
+ if (re.match(input, trymatch)) {
+ if (negative) return false;
+ if (next(input, trymatch1))
+ newMatch = trymatch1;
+ }
+
+ if (newMatch != null) {
+ if (negative) return false;
+ //else
+ mymatch.assignFrom(newMatch);
+ return true;
+ }
+ else { // no match
+ if (negative)
+ return next(input, mymatch);
+ //else
+ return false;
+ }
+ }
+
+ void dump(StringBuffer os) {
+ os.append("(?");
+ os.append(negative ? '!' : '=');
+ re.dumpAll(os);
+ os.append(')');
+ }
+}
+
diff --git a/libjava/java/security/cert/X509CRLSelector.java b/libjava/java/security/cert/X509CRLSelector.java
new file mode 100644
index 00000000000..a59791e6759
--- /dev/null
+++ b/libjava/java/security/cert/X509CRLSelector.java
@@ -0,0 +1,445 @@
+/* X509CRLSelector.java -- selects X.509 CRLs by criteria.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.security.cert;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import java.math.BigInteger;
+
+import java.security.AccessController;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+
+import javax.security.auth.x500.X500Principal;
+
+import gnu.java.security.action.GetPropertyAction;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+/**
+ * A class for matching X.509 certificate revocation lists by criteria.
+ *
+ * <p>Use of this class requires extensive knowledge of the Internet
+ * Engineering Task Force's Public Key Infrastructure (X.509). The primary
+ * document describing this standard is <a
+ * href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509
+ * Public Key Infrastructure Certificate and Certificate Revocation List
+ * (CRL) Profile</a>.
+ *
+ * <p>Note that this class is not thread-safe. If multiple threads will
+ * use or modify this class then they need to synchronize on the object.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class X509CRLSelector implements CRLSelector, Cloneable
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private static final String CRL_NUMBER_ID = "2.5.29.20";
+
+ private List issuerNames;
+ private BigInteger maxCrlNumber;
+ private BigInteger minCrlNumber;
+ private Date date;
+ private X509Certificate cert;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Creates a new CRL selector with no criteria enabled; i.e., every CRL
+ * will be matched.
+ */
+ public X509CRLSelector()
+ {
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Add an issuer name to the set of issuer names criteria, as the DER
+ * encoded form.
+ *
+ * @param name The name to add, as DER bytes.
+ * @throws IOException If the argument is not a valid DER-encoding.
+ */
+ public void addIssuerName(byte[] name) throws IOException
+ {
+ X500Principal p = null;
+ try
+ {
+ p = new X500Principal(name);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed name");
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ if (issuerNames == null)
+ issuerNames = new LinkedList();
+ issuerNames.add(p);
+ }
+
+ /**
+ * Add an issuer name to the set of issuer names criteria, as a
+ * String representation.
+ *
+ * @param name The name to add.
+ * @throws IOException If the argument is not a valid name.
+ */
+ public void addIssuerName(String name) throws IOException
+ {
+ X500Principal p = null;
+ try
+ {
+ p = new X500Principal(name);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed name: " + name);
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ if (issuerNames == null)
+ issuerNames = new LinkedList();
+ issuerNames.add(p);
+ }
+
+ /**
+ * Sets the issuer names criterion. Pass <code>null</code> to clear this
+ * value. CRLs matched by this selector must have an issuer name in this
+ * set.
+ *
+ * @param names The issuer names.
+ * @throws IOException If any of the elements in the collection is not
+ * a valid name.
+ */
+ public void setIssuerNames(Collection names) throws IOException
+ {
+ if (names == null)
+ {
+ issuerNames = null;
+ return;
+ }
+ List l = new ArrayList(names.size());
+ for (Iterator it = names.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (o instanceof X500Principal)
+ l.add(o);
+ else if (o instanceof String)
+ {
+ try
+ {
+ l.add(new X500Principal((String) o));
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed name: " + o);
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ }
+ else if (o instanceof byte[])
+ {
+ try
+ {
+ l.add(new X500Principal((byte[]) o));
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed name");
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ }
+ else if (o instanceof InputStream)
+ {
+ try
+ {
+ l.add(new X500Principal((InputStream) o));
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed name");
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ }
+ else
+ throw new IOException("not a valid name: " +
+ (o != null ? o.getClass().getName() : "null"));
+
+ }
+ issuerNames = l;
+ }
+
+ /**
+ * Returns the set of issuer names that are matched by this selector,
+ * or <code>null</code> if this criteria is not set. The returned
+ * collection is not modifiable.
+ *
+ * @return The set of issuer names.
+ */
+ public Collection getIssuerNames()
+ {
+ if (issuerNames != null)
+ return Collections.unmodifiableList(issuerNames);
+ else
+ return null;
+ }
+
+ /**
+ * Returns the maximum value of the CRLNumber extension present in
+ * CRLs matched by this selector, or <code>null</code> if this
+ * criteria is not set.
+ *
+ * @return The maximum CRL number.
+ */
+ public BigInteger getMaxCRL()
+ {
+ return maxCrlNumber;
+ }
+
+ /**
+ * Returns the minimum value of the CRLNumber extension present in
+ * CRLs matched by this selector, or <code>null</code> if this
+ * criteria is not set.
+ *
+ * @return The minimum CRL number.
+ */
+ public BigInteger getMinCRL()
+ {
+ return minCrlNumber;
+ }
+
+ /**
+ * Sets the maximum value of the CRLNumber extension present in CRLs
+ * matched by this selector. Specify <code>null</code> to clear this
+ * criterion.
+ *
+ * @param maxCrlNumber The maximum CRL number.
+ */
+ public void setMaxCRLNumber(BigInteger maxCrlNumber)
+ {
+ this.maxCrlNumber = maxCrlNumber;
+ }
+
+ /**
+ * Sets the minimum value of the CRLNumber extension present in CRLs
+ * matched by this selector. Specify <code>null</code> to clear this
+ * criterion.
+ *
+ * @param minCrlNumber The minimum CRL number.
+ */
+ public void setMinCRLNumber(BigInteger minCrlNumber)
+ {
+ this.minCrlNumber = minCrlNumber;
+ }
+
+ /**
+ * Returns the date when this CRL must be valid; that is, the date
+ * must be after the thisUpdate date, but before the nextUpdate date.
+ * Returns <code>null</code> if this criterion is not set.
+ *
+ * @return The date.
+ */
+ public Date getDateAndTime()
+ {
+ return date != null ? (Date) date.clone() : null;
+ }
+
+ /**
+ * Sets the date at which this CRL must be valid. Specify
+ * <code>null</code> to clear this criterion.
+ *
+ * @param date The date.
+ */
+ public void setDateAndTime(Date date)
+ {
+ this.date = date != null ? (Date) date.clone() : null;
+ }
+
+ /**
+ * Returns the certificate being checked, or <code>null</code> if this
+ * value is not set.
+ *
+ * @return The certificate.
+ */
+ public X509Certificate getCertificateChecking()
+ {
+ return cert;
+ }
+
+ /**
+ * Sets the certificate being checked. This is not a criterion, but
+ * info used by certificate store implementations to aid in searching.
+ *
+ * @param cert The certificate.
+ */
+ public void setCertificateChecking(X509Certificate cert)
+ {
+ this.cert = cert;
+ }
+
+ /**
+ * Returns a string representation of this selector. The string will
+ * only describe the enabled criteria, so if none are enabled this will
+ * return a string that contains little else besides the class name.
+ *
+ * @return The string.
+ */
+ public String toString()
+ {
+ StringBuffer str = new StringBuffer(X509CRLSelector.class.getName());
+ GetPropertyAction getProp = new GetPropertyAction("line.separator");
+ String nl = (String) AccessController.doPrivileged(getProp);
+ String eol = ";" + nl;
+
+ str.append(" {").append(nl);
+ if (issuerNames != null)
+ str.append(" issuer names = ").append(issuerNames).append(eol);
+ if (maxCrlNumber != null)
+ str.append(" max CRL = ").append(maxCrlNumber).append(eol);
+ if (minCrlNumber != null)
+ str.append(" min CRL = ").append(minCrlNumber).append(eol);
+ if (date != null)
+ str.append(" date = ").append(date).append(eol);
+ if (cert != null)
+ str.append(" certificate = ").append(cert).append(eol);
+ str.append("}").append(nl);
+ return str.toString();
+ }
+
+ /**
+ * Checks a CRL against the criteria of this selector, returning
+ * <code>true</code> if the given CRL matches all the criteria.
+ *
+ * @param _crl The CRL being checked.
+ * @return True if the CRL matches, false otherwise.
+ */
+ public boolean match(CRL _crl)
+ {
+ if (!(_crl instanceof X509CRL))
+ return false;
+ X509CRL crl = (X509CRL) _crl;
+ if (issuerNames != null)
+ {
+ if (!issuerNames.contains(crl.getIssuerX500Principal()))
+ return false;
+ }
+ BigInteger crlNumber = null;
+ if (maxCrlNumber != null)
+ {
+ byte[] b = crl.getExtensionValue(CRL_NUMBER_ID);
+ if (b == null)
+ return false;
+ try
+ {
+ DERValue val = DERReader.read(b);
+ if (!(val.getValue() instanceof BigInteger))
+ return false;
+ crlNumber = (BigInteger) val.getValue();
+ }
+ catch (IOException ioe)
+ {
+ return false;
+ }
+ if (maxCrlNumber.compareTo(crlNumber) < 0)
+ return false;
+ }
+ if (minCrlNumber != null)
+ {
+ if (crlNumber == null)
+ {
+ byte[] b = crl.getExtensionValue(CRL_NUMBER_ID);
+ if (b == null)
+ return false;
+ try
+ {
+ DERValue val = DERReader.read(b);
+ if (!(val.getValue() instanceof BigInteger))
+ return false;
+ crlNumber = (BigInteger) val.getValue();
+ }
+ catch (IOException ioe)
+ {
+ return false;
+ }
+ }
+ if (minCrlNumber.compareTo(crlNumber) > 0)
+ return false;
+ }
+ if (date != null)
+ {
+ if (date.compareTo(crl.getThisUpdate()) < 0 ||
+ date.compareTo(crl.getNextUpdate()) > 0)
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * Returns a copy of this object.
+ *
+ * @return The copy.
+ */
+ public Object clone()
+ {
+ try
+ {
+ return super.clone();
+ }
+ catch (CloneNotSupportedException shouldNotHappen)
+ {
+ throw new Error(shouldNotHappen);
+ }
+ }
+}
diff --git a/libjava/java/security/cert/X509CertSelector.java b/libjava/java/security/cert/X509CertSelector.java
new file mode 100644
index 00000000000..c7914c140fd
--- /dev/null
+++ b/libjava/java/security/cert/X509CertSelector.java
@@ -0,0 +1,1111 @@
+/* X509CertSelector.java -- selects X.509 certificates by criteria.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.security.cert;
+
+import java.io.IOException;
+
+import java.math.BigInteger;
+
+import java.security.AccessController;
+import java.security.KeyFactory;
+import java.security.PublicKey;
+import java.security.spec.X509EncodedKeySpec;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.List;
+import java.util.Set;
+
+import javax.security.auth.x500.X500Principal;
+
+import gnu.java.security.OID;
+import gnu.java.security.action.GetPropertyAction;
+
+/**
+ * A concrete implementation of {@link CertSelector} for X.509 certificates,
+ * which allows a number of criteria to be set when accepting certificates,
+ * from validity dates, to issuer and subject distinguished names, to some
+ * of the various X.509 extensions.
+ *
+ * <p>Use of this class requires extensive knowledge of the Internet
+ * Engineering Task Force's Public Key Infrastructure (X.509). The primary
+ * document describing this standard is <a
+ * href="http://www.ietf.org/rfc/rfc3280.txt">RFC 3280: Internet X.509
+ * Public Key Infrastructure Certificate and Certificate Revocation List
+ * (CRL) Profile</a>.
+ *
+ * <p>Note that this class is not thread-safe. If multiple threads will
+ * use or modify this class then they need to synchronize on the object.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class X509CertSelector implements CertSelector, Cloneable
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ private static final String AUTH_KEY_ID = "2.5.29.35";
+ private static final String SUBJECT_KEY_ID = "2.5.29.14";
+ private static final String NAME_CONSTRAINTS_ID = "2.5.29.30";
+
+ private int basicConstraints;
+ private X509Certificate cert;
+ private BigInteger serialNo;
+ private X500Principal issuer;
+ private X500Principal subject;
+ private byte[] subjectKeyId;
+ private byte[] authKeyId;
+ private boolean[] keyUsage;
+ private Date certValid;
+ private OID sigId;
+ private PublicKey subjectKey;
+ private X509EncodedKeySpec subjectKeySpec;
+ private Set keyPurposeSet;
+ private List altNames;
+ private boolean matchAllNames;
+ private byte[] nameConstraints;
+ private Set policy;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates a new X.509 certificate selector. The new selector will be
+ * empty, and will accept any certificate (provided that it is an
+ * {@link X509Certificate}).
+ */
+ public X509CertSelector()
+ {
+ basicConstraints = -1;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns the certificate criterion, or <code>null</code> if this value
+ * was not set.
+ *
+ * @return The certificate.
+ */
+ public X509Certificate getCertificate()
+ {
+ return cert;
+ }
+
+ /**
+ * Sets the certificate criterion. If set, only certificates that are
+ * equal to the certificate passed here will be accepted.
+ *
+ * @param cert The certificate.
+ */
+ public void setCertificate(X509Certificate cert)
+ {
+ this.cert = cert;
+ }
+
+ /**
+ * Returns the serial number criterion, or <code>null</code> if this
+ * value was not set.
+ *
+ * @return The serial number.
+ */
+ public BigInteger getSerialNumber()
+ {
+ return serialNo;
+ }
+
+ /**
+ * Sets the serial number of the desired certificate. Only certificates that
+ * contain this serial number are accepted.
+ *
+ * @param serialNo The serial number.
+ */
+ public void setSerialNumber(BigInteger serialNo)
+ {
+ this.serialNo = serialNo;
+ }
+
+ /**
+ * Returns the issuer criterion as a string, or <code>null</code> if this
+ * value was not set.
+ *
+ * @return The issuer.
+ */
+ public String getIssuerAsString()
+ {
+ if (issuer != null)
+ return issuer.getName();
+ else
+ return null;
+ }
+
+ /**
+ * Returns the issuer criterion as a sequence of DER bytes, or
+ * <code>null</code> if this value was not set.
+ *
+ * @return The issuer.
+ */
+ public byte[] getIssuerAsBytes() throws IOException
+ {
+ if (issuer != null)
+ return issuer.getEncoded();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the issuer, specified as a string representation of the issuer's
+ * distinguished name. Only certificates issued by this issuer will
+ * be accepted.
+ *
+ * @param name The string representation of the issuer's distinguished name.
+ * @throws IOException If the given name is incorrectly formatted.
+ */
+ public void setIssuer(String name) throws IOException
+ {
+ if (name != null)
+ {
+ try
+ {
+ issuer = new X500Principal(name);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ throw new IOException(iae.getMessage());
+ }
+ }
+ else
+ issuer = null;
+ }
+
+ /**
+ * Sets the issuer, specified as the DER encoding of the issuer's
+ * distinguished name. Only certificates issued by this issuer will
+ * be accepted.
+ *
+ * @param name The DER encoding of the issuer's distinguished name.
+ * @throws IOException If the given name is incorrectly formatted.
+ */
+ public void setIssuer(byte[] name) throws IOException
+ {
+ if (name != null)
+ {
+ try
+ {
+ issuer = new X500Principal(name);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ throw new IOException(iae.getMessage());
+ }
+ }
+ else
+ issuer = null;
+ }
+
+ /**
+ * Returns the subject criterion as a string, of <code>null</code> if
+ * this value was not set.
+ *
+ * @return The subject.
+ */
+ public String getSubjectAsString()
+ {
+ if (subject != null)
+ return subject.getName();
+ else
+ return null;
+ }
+
+ /**
+ * Returns the subject criterion as a sequence of DER bytes, or
+ * <code>null</code> if this value is not set.
+ *
+ * @return The subject.
+ */
+ public byte[] getSubjectAsBytes() throws IOException
+ {
+ if (subject != null)
+ return subject.getEncoded();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the subject, specified as a string representation of the
+ * subject's distinguished name. Only certificates with the given
+ * subject will be accepted.
+ *
+ * @param name The string representation of the subject's distinguished name.
+ * @throws IOException If the given name is incorrectly formatted.
+ */
+ public void setSubject(String name) throws IOException
+ {
+ if (name != null)
+ {
+ try
+ {
+ subject = new X500Principal(name);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ throw new IOException(iae.getMessage());
+ }
+ }
+ else
+ subject = null;
+ }
+
+ /**
+ * Sets the subject, specified as the DER encoding of the subject's
+ * distinguished name. Only certificates with the given subject will
+ * be accepted.
+ *
+ * @param name The DER encoding of the subject's distinguished name.
+ * @throws IOException If the given name is incorrectly formatted.
+ */
+ public void setSubject(byte[] name) throws IOException
+ {
+ if (name != null)
+ {
+ try
+ {
+ subject = new X500Principal(name);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ throw new IOException(iae.getMessage());
+ }
+ }
+ else
+ subject = null;
+ }
+
+ /**
+ * Returns the subject key identifier criterion, or <code>null</code> if
+ * this value was not set. Note that the byte array is cloned to prevent
+ * modification.
+ *
+ * @return The subject key identifier.
+ */
+ public byte[] getSubjectKeyIdentifier()
+ {
+ if (subjectKeyId != null)
+ return (byte[]) subjectKeyId.clone();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the subject key identifier criterion, or <code>null</code> to clear
+ * this criterion. Note that the byte array is cloned to prevent modification.
+ *
+ * @param subjectKeyId The subject key identifier.
+ */
+ public void setSubjectKeyIdentifier(byte[] subjectKeyId)
+ {
+ this.subjectKeyId = subjectKeyId != null ? (byte[]) subjectKeyId.clone() :
+ null;
+ }
+
+ /**
+ * Returns the authority key identifier criterion, or <code>null</code> if
+ * this value was not set. Note that the byte array is cloned to prevent
+ * modification.
+ *
+ * @return The authority key identifier.
+ */
+ public byte[] getAuthorityKeyIdentifier()
+ {
+ if (authKeyId != null)
+ return (byte[]) authKeyId.clone();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the authority key identifier criterion, or <code>null</code> to clear
+ * this criterion. Note that the byte array is cloned to prevent modification.
+ *
+ * @param subjectKeyId The subject key identifier.
+ */
+ public void setAuthorityKeyIdentifier(byte[] authKeyId)
+ {
+ this.authKeyId = authKeyId != null ? (byte[]) authKeyId.clone() : null;
+ }
+
+ /**
+ * Returns the date at which certificates must be valid, or <code>null</code>
+ * if this criterion was not set.
+ *
+ * @return The target certificate valitity date.
+ */
+ public Date getCertificateValid()
+ {
+ if (certValid != null)
+ return (Date) certValid.clone();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the date at which certificates must be valid. Specify
+ * <code>null</code> to clear this criterion.
+ *
+ * @param certValid The certificate validity date.
+ */
+ public void setCertificateValid(Date certValid)
+ {
+ this.certValid = certValid != null ? (Date) certValid.clone() : null;
+ }
+
+ /**
+ * This method, and its related X.509 certificate extension &mdash; the
+ * private key usage period &mdash; is not supported under the Internet
+ * PKI for X.509 certificates (PKIX), described in RFC 3280. As such, this
+ * method is not supported either.
+ *
+ * <p>Do not use this method. It is not deprecated, as it is not deprecated
+ * in the Java standard, but it is basically a no-operation and simply
+ * returns <code>null</code>.
+ *
+ * @return Null.
+ */
+ public Date getPrivateKeyValid()
+ {
+ return null;
+ }
+
+ /**
+ * This method, and its related X.509 certificate extension &mdash; the
+ * private key usage period &mdash; is not supported under the Internet
+ * PKI for X.509 certificates (PKIX), described in RFC 3280. As such, this
+ * method is not supported either.
+ *
+ * <p>Do not use this method. It is not deprecated, as it is not deprecated
+ * in the Java standard, but it is basically a no-operation.
+ *
+ * @param UNUSED Is silently ignored.
+ */
+ public void setPrivateKeyValid(Date UNUSED)
+ {
+ }
+
+ /**
+ * Returns the public key algorithm ID that matching certificates must have,
+ * or <code>null</code> if this criterion was not set.
+ *
+ * @return The public key algorithm ID.
+ */
+ public String getSubjectPublicKeyAlgID()
+ {
+ return String.valueOf(sigId);
+ }
+
+ /**
+ * Sets the public key algorithm ID that matching certificates must have.
+ * Specify <code>null</code> to clear this criterion.
+ *
+ * @param sigId The public key ID.
+ * @throws IOException If the specified ID is not a valid object identifier.
+ */
+ public void setSubjectPublicKeyAlgID(String sigId) throws IOException
+ {
+ if (sigId != null)
+ {
+ try
+ {
+ OID oid = new OID(sigId);
+ int[] comp = oid.getIDs();
+ if (!checkOid(comp))
+ throw new IOException("malformed OID: " + sigId);
+ this.sigId = oid;
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed OID: " + sigId);
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ }
+ else
+ this.sigId = null;
+ }
+
+ /**
+ * Returns the subject public key criterion, or <code>null</code> if this
+ * value is not set.
+ *
+ * @return The subject public key.
+ */
+ public PublicKey getSubjectPublicKey()
+ {
+ return subjectKey;
+ }
+
+ /**
+ * Sets the subject public key criterion as an opaque representation.
+ * Specify <code>null</code> to clear this criterion.
+ *
+ * @param key The public key.
+ */
+ public void setSubjectPublicKey(PublicKey key)
+ {
+ this.subjectKey = key;
+ if (key == null)
+ {
+ subjectKeySpec = null;
+ return;
+ }
+ try
+ {
+ KeyFactory enc = KeyFactory.getInstance("X.509");
+ subjectKeySpec = (X509EncodedKeySpec)
+ enc.getKeySpec(key, X509EncodedKeySpec.class);
+ }
+ catch (Exception x)
+ {
+ subjectKey = null;
+ subjectKeySpec = null;
+ }
+ }
+
+ /**
+ * Sets the subject public key criterion as a DER-encoded key. Specify
+ * <code>null</code> to clear this value.
+ *
+ * @param key The DER-encoded key bytes.
+ * @throws IOException If the argument is not a valid DER-encoded key.
+ */
+ public void setSubjectPublicKey(byte[] key) throws IOException
+ {
+ if (key == null)
+ {
+ subjectKey = null;
+ subjectKeySpec = null;
+ return;
+ }
+ try
+ {
+ subjectKeySpec = new X509EncodedKeySpec(key);
+ KeyFactory enc = KeyFactory.getInstance("X.509");
+ subjectKey = enc.generatePublic(subjectKeySpec);
+ }
+ catch (Exception x)
+ {
+ subjectKey = null;
+ subjectKeySpec = null;
+ IOException ioe = new IOException(x.getMessage());
+ ioe.initCause(x);
+ throw ioe;
+ }
+ }
+
+ /**
+ * Returns the public key usage criterion, or <code>null</code> if this
+ * value is not set. Note that the array is cloned to prevent modification.
+ *
+ * @return The public key usage.
+ */
+ public boolean[] getKeyUsage()
+ {
+ if (keyUsage != null)
+ return (boolean[]) keyUsage.clone();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the public key usage criterion. Specify <code>null</code> to clear
+ * this value.
+ *
+ * @param keyUsage The public key usage.
+ */
+ public void setKeyUsage(boolean[] keyUsage)
+ {
+ this.keyUsage = keyUsage != null ? (boolean[]) keyUsage.clone() : null;
+ }
+
+ /**
+ * Returns the set of extended key purpose IDs, as an unmodifiable set
+ * of OID strings. Returns <code>null</code> if this criterion is not
+ * set.
+ *
+ * @return The set of key purpose OIDs (strings).
+ */
+ public Set getExtendedKeyUsage()
+ {
+ if (keyPurposeSet != null)
+ return Collections.unmodifiableSet(keyPurposeSet);
+ else
+ return null;
+ }
+
+ /**
+ * Sets the extended key usage criterion, as a set of OID strings. Specify
+ * <code>null</code> to clear this value.
+ *
+ * @param keyPurposeSet The set of key purpose OIDs.
+ * @throws IOException If any element of the set is not a valid OID string.
+ */
+ public void setExtendedKeyUsage(Set keyPurposeSet) throws IOException
+ {
+ if (keyPurposeSet == null)
+ {
+ this.keyPurposeSet = null;
+ return;
+ }
+ Set s = new HashSet();
+ for (Iterator it = keyPurposeSet.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (!(o instanceof String))
+ throw new IOException("not a string: " + o);
+ try
+ {
+ OID oid = new OID((String) o);
+ int[] comp = oid.getIDs();
+ if (!checkOid(comp))
+ throw new IOException("malformed OID: " + o);
+ }
+ catch (IllegalArgumentException iae)
+ {
+ IOException ioe = new IOException("malformed OID: " + o);
+ ioe.initCause(iae);
+ throw ioe;
+ }
+ }
+ this.keyPurposeSet = s;
+ }
+
+ /**
+ * Returns whether or not all specified alternative names must match.
+ * If false, a certificate is considered a match if <em>one</em> of the
+ * specified alternative names matches.
+ *
+ * @return true if all names must match.
+ */
+ public boolean getMatchAllSubjectAltNames()
+ {
+ return matchAllNames;
+ }
+
+ /**
+ * Sets whether or not all subject alternative names must be matched.
+ * If false, then a certificate will be considered a match if one
+ * alternative name matches.
+ *
+ * @param matchAllNames Whether or not all alternative names must be
+ * matched.
+ */
+ public void setMatchAllSubjectAltNames(boolean matchAllNames)
+ {
+ this.matchAllNames = matchAllNames;
+ }
+
+ /**
+ * Sets the subject alternative names critertion. Each element of the
+ * argument must be a {@link java.util.List} that contains exactly two
+ * elements: the first an {@link Integer}, representing the type of
+ * name, and the second either a {@link String} or a byte array,
+ * representing the name itself.
+ *
+ * @param altNames The alternative names.
+ * @throws IOException If any element of the argument is invalid.
+ */
+ public void setSubjectAlternativeNames(Collection altNames)
+ throws IOException
+ {
+ if (altNames == null)
+ {
+ this.altNames = null;
+ return;
+ }
+ List l = new ArrayList(altNames.size());
+ for (Iterator it = altNames.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (!(o instanceof List) || ((List) o).size() != 2 ||
+ !(((List) o).get(0) instanceof Integer) ||
+ !(((List) o).get(1) instanceof String) ||
+ !(((List) o).get(1) instanceof byte[]))
+ throw new IOException("illegal alternative name: " + o);
+ Integer i = (Integer) ((List) o).get(0);
+ if (i.intValue() < 0 || i.intValue() > 8)
+ throw new IOException("illegal alternative name: " + o +
+ ", bad id: " + i);
+ l.add(new ArrayList((List) o));
+ }
+ this.altNames = l;
+ }
+
+ /**
+ * Add a name to the subject alternative names criterion.
+ *
+ * @param id The type of name this is. Must be in the range [0,8].
+ * @param name The name.
+ * @throws IOException If the id is out of range, or if the name
+ * is null.
+ */
+ public void addSubjectAlternativeName(int id, String name)
+ throws IOException
+ {
+ if (id < 0 || id > 8 || name == null)
+ throw new IOException("illegal alternative name");
+ if (altNames == null)
+ altNames = new LinkedList();
+ ArrayList l = new ArrayList(2);
+ l.add(new Integer(id));
+ l.add(name);
+ altNames.add(l);
+ }
+
+ /**
+ * Add a name, as DER-encoded bytes, to the subject alternative names
+ * criterion.
+ *
+ * @param id The type of name this is.
+ */
+ public void addSubjectAlternativeName(int id, byte[] name)
+ throws IOException
+ {
+ if (id < 0 || id > 8 || name == null)
+ throw new IOException("illegal alternative name");
+ if (altNames == null)
+ altNames = new LinkedList();
+ ArrayList l = new ArrayList(2);
+ l.add(new Integer(id));
+ l.add(name);
+ altNames.add(l);
+ }
+
+ /**
+ * Returns the name constraints criterion, or <code>null</code> if this
+ * value is not set. Note that the byte array is cloned to prevent
+ * modification.
+ *
+ * @return The name constraints.
+ */
+ public byte[] getNameConstraints()
+ {
+ if (nameConstraints != null)
+ return (byte[]) nameConstraints.clone();
+ else
+ return null;
+ }
+
+ /**
+ * Sets the name constraints criterion; specify <code>null</code> to
+ * clear this criterion. Note that if non-null, the argument will be
+ * cloned to prevent modification.
+ *
+ * @param nameConstraints The new name constraints.
+ * @throws IOException If the argument is not a valid DER-encoded
+ * name constraints.
+ */
+ public void setNameConstraints(byte[] nameConstraints)
+ throws IOException
+ {
+ // FIXME check if the argument is valid.
+ this.nameConstraints = nameConstraints != null
+ ? (byte[]) nameConstraints.clone() : null;
+ }
+
+ /**
+ * Returns the basic constraints criterion, or -1 if this value is not set.
+ *
+ * @return The basic constraints.
+ */
+ public int getBasicConstraints()
+ {
+ return basicConstraints;
+ }
+
+ /**
+ * Sets the basic constraints criterion. Specify -1 to clear this parameter.
+ *
+ * @param basicConstraints The new basic constraints value.
+ */
+ public void setBasicConstraints(int basicConstraints)
+ {
+ if (basicConstraints < -1)
+ basicConstraints = -1;
+ this.basicConstraints = basicConstraints;
+ }
+
+ // The last two criteria not yet implemented are certificate policies
+ // and path-to-names. Both of these are somewhat advanced extensions
+ // (you could probably count the applications that actually use them
+ // on one hand), and they both have no support in the X509Certificate
+ // class.
+ //
+ // Not having support in X509Certificate is not always a problem; for
+ // example, we can compare DER-encoded values as byte arrays for some
+ // extensions. We can't, however, compare them if they are specified
+ // in a set (as policies are). We need to parse the actual value in the
+ // certificate, and check it against the specified set.
+
+ // FIXME
+// public void setPolicy(Set policy) throws IOException
+// {
+// if (policy != null)
+// {
+// for (Iterator it = policy.iterator(); it.hasNext(); )
+// try
+// {
+// OID oid = new OID((String) it.next());
+// int[] i = oid.getIDs();
+// if (!checkOid(i))
+// throw new IOException("invalid OID");
+// }
+// catch (Exception x)
+// {
+// throw new IOException("invalid OID");
+// }
+// }
+// this.policy = policy != null ? new HashSet(policy) : null;
+// }
+
+ // FIXME
+// public void setPathToNames(Collection names) throws IOException
+// {
+// if (names == null)
+// {
+// this.names = null;
+// return;
+// }
+// for (Iterator it = names.iterator(); it.hasNext(); )
+// {
+// try
+// {
+// List l = (List) it.next();
+// if (l.get(1) instanceof String)
+// addPathToName(((Integer)l.get(0)).intValue(), (String)l.get(1));
+// else
+// addPathToName(((Integer)l.get(0)).intValue(), (byte[])l.get(1));
+// }
+// catch (Exception x)
+// {
+// this.names = null;
+// throw new IOException("invalid names");
+// }
+// }
+// }
+
+ // FIXME
+// public void addPathToName(int id, String name) throws IOException
+// {
+// }
+
+ // FIXME
+// public void addPathToName(int id, byte[] name) throws IOException
+// {
+// }
+
+ // FIXME
+// public Collection getSubjectAlternativeNames()
+// {
+// return null;
+// }
+
+ // FIXME
+// public Set getPolicy()
+// {
+// return null;
+// }
+
+ // FIXME
+// public Collection getPathToNames()
+// {
+// return null;
+// }
+
+ /**
+ * Match a certificate. This method will check the given certificate
+ * against all the enabled criteria of this selector, and will return
+ * <code>true</code> if the given certificate matches.
+ *
+ * @param certificate The certificate to check.
+ * @return true if the certificate matches all criteria.
+ */
+ public boolean match(Certificate certificate)
+ {
+ if (!(certificate instanceof X509Certificate))
+ return false;
+ X509Certificate cert = (X509Certificate) certificate;
+ if (this.cert != null)
+ {
+ try
+ {
+ byte[] e1 = this.cert.getEncoded();
+ byte[] e2 = cert.getEncoded();
+ if (!Arrays.equals(e1, e2))
+ return false;
+ }
+ catch (CertificateEncodingException cee)
+ {
+ return false;
+ }
+ }
+ if (serialNo != null)
+ {
+ if (!serialNo.equals(cert.getSerialNumber()))
+ return false;
+ }
+ if (certValid != null)
+ {
+ try
+ {
+ cert.checkValidity(certValid);
+ }
+ catch (CertificateException ce)
+ {
+ return false;
+ }
+ }
+ if (issuer != null)
+ {
+ if (!issuer.equals(cert.getIssuerX500Principal()))
+ return false;
+ }
+ if (subject != null)
+ {
+ if (!subject.equals(cert.getSubjectX500Principal()))
+ return false;
+ }
+ if (sigId != null)
+ {
+ if (!sigId.equals(cert.getSigAlgOID()))
+ return false;
+ }
+ if (subjectKeyId != null)
+ {
+ byte[] b = cert.getExtensionValue(SUBJECT_KEY_ID);
+ if (!Arrays.equals(b, subjectKeyId))
+ return false;
+ }
+ if (authKeyId != null)
+ {
+ byte[] b = cert.getExtensionValue(AUTH_KEY_ID);
+ if (!Arrays.equals(b, authKeyId))
+ return false;
+ }
+ if (keyUsage != null)
+ {
+ boolean[] b = cert.getKeyUsage();
+ if (!Arrays.equals(b, keyUsage))
+ return false;
+ }
+ if (basicConstraints >= 0)
+ {
+ if (cert.getBasicConstraints() != basicConstraints)
+ return false;
+ }
+ if (keyPurposeSet != null)
+ {
+ List kp = null;
+ try
+ {
+ kp = cert.getExtendedKeyUsage();
+ }
+ catch (CertificateParsingException cpe)
+ {
+ return false;
+ }
+ if (kp == null)
+ return false;
+ for (Iterator it = keyPurposeSet.iterator(); it.hasNext(); )
+ {
+ if (!kp.contains(it.next()))
+ return false;
+ }
+ }
+ if (altNames != null)
+ {
+ Collection an = null;
+ try
+ {
+ an = cert.getSubjectAlternativeNames();
+ }
+ catch (CertificateParsingException cpe)
+ {
+ return false;
+ }
+ if (an == null)
+ return false;
+ int match = 0;
+ for (Iterator it = altNames.iterator(); it.hasNext(); )
+ {
+ List l = (List) it.next();
+ Integer id = (Integer) l.get(0);
+ String s = null;
+ byte[] b = null;
+ if (l.get(1) instanceof String)
+ s = (String) l.get(1);
+ else if (l.get(1) instanceof byte[])
+ b = (byte[]) l.get(1);
+ else
+ return false;
+ for (Iterator it2 = an.iterator(); it2.hasNext(); )
+ {
+ Object o = it2.next();
+ if (!(o instanceof List))
+ continue;
+ List l2 = (List) o;
+ if (l2.size() != 2)
+ continue;
+ if (!id.equals(l2.get(0)))
+ continue;
+ if (s != null && (l2.get(1) instanceof String) &&
+ s.equals(l2.get(1)))
+ match++;
+ else if (b != null && (l2.get(1) instanceof byte[]) &&
+ Arrays.equals(b, (byte[]) l2.get(1)))
+ match++;
+ }
+ if (match == 0 || (matchAllNames && match != altNames.size()))
+ return false;
+ }
+ }
+ if (nameConstraints != null)
+ {
+ byte[] nc = cert.getExtensionValue(NAME_CONSTRAINTS_ID);
+ if (!Arrays.equals(nameConstraints, nc))
+ return false;
+ }
+
+ // FIXME check policies.
+ // FIXME check path-to-names.
+
+ return true;
+ }
+
+ public String toString()
+ {
+ StringBuffer str = new StringBuffer(X509CertSelector.class.getName());
+ GetPropertyAction getProp = new GetPropertyAction("line.separator");
+ String nl = (String) AccessController.doPrivileged(getProp);
+ String eol = ";" + nl;
+ str.append(" {").append(nl);
+ if (cert != null)
+ str.append(" certificate = ").append(cert).append(eol);
+ if (basicConstraints >= 0)
+ str.append(" basic constraints = ").append(basicConstraints).append(eol);
+ if (serialNo != null)
+ str.append(" serial number = ").append(serialNo).append(eol);
+ if (certValid != null)
+ str.append(" valid date = ").append(certValid).append(eol);
+ if (issuer != null)
+ str.append(" issuer = ").append(issuer).append(eol);
+ if (subject != null)
+ str.append(" subject = ").append(subject).append(eol);
+ if (sigId != null)
+ str.append(" signature OID = ").append(sigId).append(eol);
+ if (subjectKey != null)
+ str.append(" subject public key = ").append(subjectKey).append(eol);
+ if (subjectKeyId != null)
+ {
+ str.append(" subject key ID = ");
+ for (int i = 0; i < subjectKeyId.length; i++)
+ {
+ str.append(Character.forDigit((subjectKeyId[i] & 0xF0) >>> 8, 16));
+ str.append(Character.forDigit((subjectKeyId[i] & 0x0F), 16));
+ if (i < subjectKeyId.length - 1)
+ str.append(':');
+ }
+ str.append(eol);
+ }
+ if (authKeyId != null)
+ {
+ str.append(" authority key ID = ");
+ for (int i = 0; i < authKeyId.length; i++)
+ {
+ str.append(Character.forDigit((authKeyId[i] & 0xF0) >>> 8, 16));
+ str.append(Character.forDigit((authKeyId[i] & 0x0F), 16));
+ if (i < authKeyId.length - 1)
+ str.append(':');
+ }
+ str.append(eol);
+ }
+ if (keyUsage != null)
+ {
+ str.append(" key usage = ");
+ for (int i = 0; i < keyUsage.length; i++)
+ str.append(keyUsage[i] ? '1' : '0');
+ str.append(eol);
+ }
+ if (keyPurposeSet != null)
+ str.append(" key purpose = ").append(keyPurposeSet).append(eol);
+ if (altNames != null)
+ str.append(" alternative names = ").append(altNames).append(eol);
+ if (nameConstraints != null)
+ str.append(" name constraints = <blob of data>").append(eol);
+ str.append("}").append(nl);
+ return str.toString();
+ }
+
+ public Object clone()
+ {
+ try
+ {
+ return super.clone();
+ }
+ catch (CloneNotSupportedException shouldNotHappen)
+ {
+ throw new Error(shouldNotHappen);
+ }
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private static boolean checkOid(int[] oid)
+ {
+ return (oid != null && oid.length > 2 &&
+ (oid[0] >= 0 && oid[0] <= 2) && (oid[1] >= 0 && oid[1] <= 39));
+ }
+}
diff --git a/libjava/java/util/VMTimeZone.java b/libjava/java/util/VMTimeZone.java
new file mode 100644
index 00000000000..77c055b2a64
--- /dev/null
+++ b/libjava/java/util/VMTimeZone.java
@@ -0,0 +1,345 @@
+/* java.util.VMTimeZone
+ Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
+ Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package java.util;
+
+import gnu.classpath.Configuration;
+
+import java.io.*;
+
+/**
+ *
+ */
+final class VMTimeZone
+{
+ static
+ {
+ if (Configuration.INIT_LOAD_LIBRARY)
+ {
+ System.loadLibrary("javautil");
+ }
+ }
+
+ /**
+ * This method returns a time zone id string which is in the form
+ * (standard zone name) or (standard zone name)(GMT offset) or
+ * (standard zone name)(GMT offset)(daylight time zone name). The
+ * GMT offset can be in seconds, or where it is evenly divisible by
+ * 3600, then it can be in hours. The offset must be the time to
+ * add to the local time to get GMT. If a offset is given and the
+ * time zone observes daylight saving then the (daylight time zone
+ * name) must also be given (otherwise it is assumed the time zone
+ * does not observe any daylight savings).
+ * <p>
+ * The result of this method is given to the method
+ * TimeZone.getDefaultTimeZone(String) which tries to map the time
+ * zone id to a known TimeZone. See that method on how the returned
+ * String is mapped to a real TimeZone object.
+ * <p>
+ * The reference implementation which is made for GNU/Posix like
+ * systems calls <code>System.getenv("TZ")</code>,
+ * <code>readTimeZoneFile("/etc/timezone")</code>,
+ * <code>readtzFile("/etc/localtime")</code> and finally
+ * <code>getSystemTimeZoneId()</code> till a supported TimeZone is
+ * found through <code>TimeZone.getDefaultTimeZone(String)</code>.
+ * If every method fails <code>null</code> is returned (which means
+ * the TimeZone code will fall back on GMT as default time zone).
+ * <p>
+ * Note that this method is called inside a
+ * <code>AccessController.doPrivileged()</code> block and runs with
+ * the priviliges of the java.util system classes. It will only be
+ * called when the default time zone is not yet set, the system
+ * property user.timezone isn't set and it is requested for the
+ * first time.
+ */
+ static TimeZone getDefaultTimeZoneId()
+ {
+ TimeZone zone = null;
+
+ // See if TZ environment variable is set and accessible.
+ String tzid = System.getenv("TZ");
+ if (tzid != null && !tzid.equals(""))
+ zone = TimeZone.getDefaultTimeZone(tzid);
+
+ // Try to parse /etc/timezone.
+ if (zone == null)
+ {
+ tzid = readTimeZoneFile("/etc/timezone");
+ if (tzid != null && !tzid.equals(""))
+ zone = TimeZone.getDefaultTimeZone(tzid);
+ }
+
+ // Try to parse /etc/localtime
+ if (zone == null)
+ {
+ tzid = readtzFile("/etc/localtime");
+ if (tzid != null && !tzid.equals(""))
+ zone = TimeZone.getDefaultTimeZone(tzid);
+ }
+
+ // Try some system specific way
+ if (zone == null)
+ {
+ tzid = getSystemTimeZoneId();
+ if (tzid != null && !tzid.equals(""))
+ zone = TimeZone.getDefaultTimeZone(tzid);
+ }
+
+ return zone;
+ }
+
+ /**
+ * Tries to read the time zone name from a file. Only the first
+ * consecutive letters, digits, slashes, dashes and underscores are
+ * read from the file. If the file cannot be read or an IOException
+ * occurs null is returned.
+ * <p>
+ * The /etc/timezone file is not standard, but a lot of systems have
+ * it. If it exist the first line always contains a string
+ * describing the timezone of the host of domain. Some systems
+ * contain a /etc/TIMEZONE file which is used to set the TZ
+ * environment variable (which is checked before /etc/timezone is
+ * read).
+ */
+ private static String readTimeZoneFile(String file)
+ {
+ File f = new File(file);
+ if (!f.exists())
+ return null;
+
+ InputStreamReader isr = null;
+ try
+ {
+ FileInputStream fis = new FileInputStream(f);
+ BufferedInputStream bis = new BufferedInputStream(fis);
+ isr = new InputStreamReader(bis);
+
+ StringBuffer sb = new StringBuffer();
+ int i = isr.read();
+ while (i != -1)
+ {
+ char c = (char) i;
+ if (Character.isLetter(c) || Character.isDigit(c)
+ || c == '/' || c == '-' || c == '_')
+ {
+ sb.append(c);
+ i = isr.read();
+ }
+ else
+ break;
+ }
+ return sb.toString();
+ }
+ catch (IOException ioe)
+ {
+ // Parse error, not a proper tzfile.
+ return null;
+ }
+ finally
+ {
+ try
+ {
+ if (isr != null)
+ isr.close();
+ }
+ catch (IOException ioe)
+ {
+ // Error while close, nothing we can do.
+ }
+ }
+ }
+
+ /**
+ * Tries to read a file as a "standard" tzfile and return a time
+ * zone id string as expected by <code>getDefaultTimeZone(String)</code>.
+ * If the file doesn't exist, an IOException occurs or it isn't a tzfile
+ * that can be parsed null is returned.
+ * <p>
+ * The tzfile structure (as also used by glibc) is described in the Olson
+ * tz database archive as can be found at
+ * <code>ftp://elsie.nci.nih.gov/pub/</code>.
+ * <p>
+ * At least the following platforms support the tzdata file format
+ * and /etc/localtime (GNU/Linux, Darwin, Solaris and FreeBSD at
+ * least). Some systems (like Darwin) don't start the file with the
+ * required magic bytes 'TZif', this implementation can handle
+ * that).
+ */
+ private static String readtzFile(String file)
+ {
+ File f = new File(file);
+ if (!f.exists())
+ return null;
+
+ DataInputStream dis = null;
+ try
+ {
+ FileInputStream fis = new FileInputStream(f);
+ BufferedInputStream bis = new BufferedInputStream(fis);
+ dis = new DataInputStream(bis);
+
+ // Make sure we are reading a tzfile.
+ byte[] tzif = new byte[4];
+ dis.readFully(tzif);
+ if (tzif[0] == 'T' && tzif[1] == 'Z'
+ && tzif[2] == 'i' && tzif[3] == 'f')
+ // Reserved bytes, ttisgmtcnt, ttisstdcnt and leapcnt
+ skipFully(dis, 16 + 3 * 4);
+ else
+ // Darwin has tzdata files that don't start with the TZif marker
+ skipFully(dis, 16 + 3 * 4 - 4);
+
+ int timecnt = dis.readInt();
+ int typecnt = dis.readInt();
+ if (typecnt > 0)
+ {
+ int charcnt = dis.readInt();
+ // Transition times plus indexed transition times.
+ skipFully(dis, timecnt * (4 + 1));
+
+ // Get last gmt_offset and dst/non-dst time zone names.
+ int abbrind = -1;
+ int dst_abbrind = -1;
+ int gmt_offset = 0;
+ while (typecnt-- > 0)
+ {
+ // gmtoff
+ int offset = dis.readInt();
+ int dst = dis.readByte();
+ if (dst == 0)
+ {
+ abbrind = dis.readByte();
+ gmt_offset = offset;
+ }
+ else
+ dst_abbrind = dis.readByte();
+ }
+
+ // gmt_offset is the offset you must add to UTC/GMT to
+ // get the local time, we need the offset to add to
+ // the local time to get UTC/GMT.
+ gmt_offset *= -1;
+
+ // Turn into hours if possible.
+ if (gmt_offset % 3600 == 0)
+ gmt_offset /= 3600;
+
+ if (abbrind >= 0)
+ {
+ byte[] names = new byte[charcnt];
+ dis.readFully(names);
+ int j = abbrind;
+ while (j < charcnt && names[j] != 0)
+ j++;
+
+ String zonename = new String(names, abbrind, j - abbrind,
+ "ASCII");
+
+ String dst_zonename;
+ if (dst_abbrind >= 0)
+ {
+ j = dst_abbrind;
+ while (j < charcnt && names[j] != 0)
+ j++;
+ dst_zonename = new String(names, dst_abbrind,
+ j - dst_abbrind, "ASCII");
+ }
+ else
+ dst_zonename = "";
+
+ // Only use gmt offset when necessary.
+ // Also special case GMT+/- timezones.
+ String offset_string;
+ if ("".equals(dst_zonename)
+ && (gmt_offset == 0
+ || zonename.startsWith("GMT+")
+ || zonename.startsWith("GMT-")))
+ offset_string = "";
+ else
+ offset_string = Integer.toString(gmt_offset);
+
+ String id = zonename + offset_string + dst_zonename;
+
+ return id;
+ }
+ }
+
+ // Something didn't match while reading the file.
+ return null;
+ }
+ catch (IOException ioe)
+ {
+ // Parse error, not a proper tzfile.
+ return null;
+ }
+ finally
+ {
+ try
+ {
+ if (dis != null)
+ dis.close();
+ }
+ catch(IOException ioe)
+ {
+ // Error while close, nothing we can do.
+ }
+ }
+ }
+
+ /**
+ * Skips the requested number of bytes in the given InputStream.
+ * Throws EOFException if not enough bytes could be skipped.
+ * Negative numbers of bytes to skip are ignored.
+ */
+ private static void skipFully(InputStream is, long l) throws IOException
+ {
+ while (l > 0)
+ {
+ long k = is.skip(l);
+ if (k <= 0)
+ throw new EOFException();
+ l -= k;
+ }
+ }
+
+ /**
+ * Tries to get the system time zone id through native code.
+ */
+ private static native String getSystemTimeZoneId();
+}
diff --git a/libjava/java/util/natVMTimeZone.cc b/libjava/java/util/natVMTimeZone.cc
new file mode 100644
index 00000000000..a6d701642f6
--- /dev/null
+++ b/libjava/java/util/natVMTimeZone.cc
@@ -0,0 +1,145 @@
+// natVMTimeZone.cc -- Native side of VMTimeZone class.
+
+/* Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004
+ Free Software Foundation
+
+ This file is part of libgcj.
+
+This software is copyrighted work licensed under the terms of the
+Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
+details. */
+
+#include <config.h>
+#include <platform.h>
+
+#include <gcj/cni.h>
+#include <jvm.h>
+
+#include <java/util/VMTimeZone.h>
+#include <java/lang/Character.h>
+#include <java/lang/Integer.h>
+
+#include <stdio.h>
+
+#if TIME_WITH_SYS_TIME
+# include <sys/time.h>
+# include <time.h>
+#else
+# if HAVE_SYS_TIME_H
+# include <sys/time.h>
+# else
+# include <time.h>
+# endif
+#endif
+
+#include <string.h>
+
+/**
+ * This method returns a time zone id string which is in the form
+ * (standard zone name) or (standard zone name)(GMT offset) or
+ * (standard zone name)(GMT offset)(daylight time zone name). The
+ * GMT offset can be in seconds, or where it is evenly divisible by
+ * 3600, then it can be in hours. The offset must be the time to
+ * add to the local time to get GMT. If a offset is given and the
+ * time zone observes daylight saving then the (daylight time zone
+ * name) must also be given (otherwise it is assumed the time zone
+ * does not observe any daylight savings).
+ * <p>
+ * The result of this method is given to getDefaultTimeZone(String)
+ * which tries to map the time zone id to a known TimeZone. See
+ * that method on how the returned String is mapped to a real
+ * TimeZone object.
+ */
+jstring
+java::util::VMTimeZone::getSystemTimeZoneId()
+{
+ struct tm tim;
+#ifndef HAVE_LOCALTIME_R
+ struct tm *lt_tim;
+#endif
+#ifdef HAVE_TM_ZONE
+ int month;
+#endif
+ time_t current_time;
+ long tzoffset;
+ const char *tz1, *tz2;
+ char *tzid;
+
+ time(&current_time);
+#ifdef HAVE_LOCALTIME_R
+ localtime_r(&current_time, &tim);
+#else
+ /* Fall back on non-thread safe localtime. */
+ lt_tim = localtime(&current_time);
+ memcpy(&tim, lt_tim, sizeof (struct tm));
+#endif
+ mktime(&tim);
+
+#ifdef HAVE_TM_ZONE
+ /* We will cycle through the months to make sure we hit dst. */
+ month = tim.tm_mon;
+ tz1 = tz2 = NULL;
+ while (tz1 == NULL || tz2 == NULL)
+ {
+ if (tim.tm_isdst > 0)
+ tz2 = tim.tm_zone;
+ else if (tz1 == NULL)
+ {
+ tz1 = tim.tm_zone;
+ month = tim.tm_mon;
+ }
+
+ if (tz1 == NULL || tz2 == NULL)
+ {
+ tim.tm_mon++;
+ tim.tm_mon %= 12;
+ }
+
+ if (tim.tm_mon == month && tz2 == NULL)
+ tz2 = "";
+ else
+ mktime(&tim);
+ }
+ /* We want to make sure the tm struct we use later on is not dst. */
+ tim.tm_mon = month;
+ mktime(&tim);
+#elif defined (HAVE_TZNAME)
+ /* If dst is never used, tzname[1] is the empty string. */
+ tzset();
+ tz1 = tzname[0];
+ tz2 = tzname[1];
+#else
+ /* Some targets have no concept of timezones. Assume GMT without dst. */
+ tz1 = "GMT";
+ tz2 = "";
+#endif
+
+#ifdef STRUCT_TM_HAS_GMTOFF
+ /* tm_gmtoff is the number of seconds that you must add to GMT to get
+ local time, we need the number of seconds to add to the local time
+ to get GMT. */
+ tzoffset = -1L * tim.tm_gmtoff;
+#elif HAVE_UNDERSCORE_TIMEZONE
+ tzoffset = _timezone;
+#elif HAVE_TIMEZONE
+ /* timezone is secs WEST of UTC. */
+ tzoffset = timezone;
+#else
+ /* FIXME: there must be another global if neither tm_gmtoff nor timezone
+ is available, esp. if tzname is valid.
+ Richard Earnshaw <rearnsha@arm.com> has suggested using difftime to
+ calculate between gmtime and localtime (and accounting for possible
+ daylight savings time) as an alternative. */
+ tzoffset = 0L;
+#endif
+
+ if ((tzoffset % 3600) == 0)
+ tzoffset = tzoffset / 3600;
+
+ tzid = (char*) _Jv_Malloc (strlen(tz1) + strlen(tz2) + 6);
+ sprintf(tzid, "%s%ld%s", tz1, tzoffset, tz2);
+ jstring retval = JvNewStringUTF (tzid);
+ _Jv_Free (tzid);
+
+ return retval;
+}
diff --git a/libjava/javax/crypto/BadPaddingException.java b/libjava/javax/crypto/BadPaddingException.java
new file mode 100644
index 00000000000..d15224f3e52
--- /dev/null
+++ b/libjava/javax/crypto/BadPaddingException.java
@@ -0,0 +1,79 @@
+/* BadPaddingException -- Signals bad padding bytes on decryption.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * This exception is thrown during decryption when the decrypted input
+ * does not have the proper padding bytes that are expected by the padding
+ * mechanism.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class BadPaddingException extends GeneralSecurityException
+{
+
+ // Constant.
+ // ------------------------------------------------------------------------
+
+ /** Serialization constant. */
+ private static final long serialVersionUID = -5315033893984728443L;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates a new bad padding exception with no detail message.
+ */
+ public BadPaddingException()
+ {
+ super();
+ }
+
+ /**
+ * Creates a new bad padding exception with a detail message.
+ *
+ * @param message The detail message.
+ */
+ public BadPaddingException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/crypto/Cipher.java b/libjava/javax/crypto/Cipher.java
new file mode 100644
index 00000000000..d768d6ad7d3
--- /dev/null
+++ b/libjava/javax/crypto/Cipher.java
@@ -0,0 +1,1097 @@
+/* Cipher.java -- Interface to a cryptographic cipher.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.cert.Certificate;
+import java.security.cert.X509Certificate;
+import java.security.spec.AlgorithmParameterSpec;
+
+import java.util.Enumeration;
+import java.util.StringTokenizer;
+
+import gnu.java.security.Engine;
+
+/**
+ * <p>This class implements a cryptographic cipher for transforming
+ * data.</p>
+ *
+ * <p>Ciphers cannot be instantiated directly; rather one of the
+ * <code>getInstance</code> must be used to instantiate a given
+ * <i>transformation</i>, optionally with a specific provider.</p>
+ *
+ * <p>A transformation is of the form:</p>
+ *
+ * <ul>
+ * <li><i>algorithm</i>/<i>mode</i>/<i>padding</i>, or</li>
+ * <li><i>algorithm</i>
+ * </ul>
+ *
+ * <p>where <i>algorithm</i> is the base name of a cryptographic cipher
+ * (such as "AES"), <i>mode</i> is the abbreviated name of a block
+ * cipher mode (such as "CBC" for cipher block chaining mode), and
+ * <i>padding</i> is the name of a padding scheme (such as
+ * "PKCS5Padding"). If only the algorithm name is supplied, then the
+ * provider-specific default mode and padding will be used.</p>
+ *
+ * <p>An example transformation is:</p>
+ *
+ * <blockquote><code>Cipher c =
+ * Cipher.getInstance("AES/CBC/PKCS5Padding");</code></blockquote>
+ *
+ * <p>Finally, when requesting a block cipher in stream cipher mode
+ * (such as <acronym title="Advanced Encryption Standard">AES</acronym>
+ * in OFB or CFB mode) the number of bits to be processed
+ * at a time may be specified by appending it to the name of the mode;
+ * e.g. <code>"AES/OFB8/NoPadding"</code>. If no such number is
+ * specified a provider-specific default value is used.</p>
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @see java.security.KeyGenerator
+ * @see javax.crypto.SecretKey
+ */
+public class Cipher
+{
+
+ // Constants and variables.
+ // ------------------------------------------------------------------------
+
+ private static final String SERVICE = "Cipher";
+
+ /**
+ * The decryption operation mode.
+ */
+ public static final int DECRYPT_MODE = 2;
+
+ /**
+ * The encryption operation mode.
+ */
+ public static final int ENCRYPT_MODE = 1;
+
+ /**
+ * Constant for when the key to be unwrapped is a private key.
+ */
+ public static final int PRIVATE_KEY = 2;
+
+ /**
+ * Constant for when the key to be unwrapped is a public key.
+ */
+ public static final int PUBLIC_KEY = 1;
+
+ /**
+ * Constant for when the key to be unwrapped is a secret key.
+ */
+ public static final int SECRET_KEY = 3;
+
+ /**
+ * The key unwrapping operation mode.
+ */
+ public static final int UNWRAP_MODE = 4;
+
+ /**
+ * The key wrapping operation mode.
+ */
+ public static final int WRAP_MODE = 3;
+
+ /**
+ * The uninitialized state. This state signals that any of the
+ * <code>init</code> methods have not been called, and therefore no
+ * transformations can be done.
+ */
+ private static final int INITIAL_STATE = 0;
+
+ /** The underlying cipher service provider interface. */
+ private CipherSpi cipherSpi;
+
+ /** The provider from which this instance came. */
+ private Provider provider;
+
+ /** The transformation requested. */
+ private String transformation;
+
+ /** Our current state (encrypting, wrapping, etc.) */
+ private int state;
+
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * <p>Creates a new cipher instance for the given transformation.</p>
+ *
+ * <p>The installed providers are tried in order for an
+ * implementation, and the first appropriate instance is returned. If
+ * no installed provider can provide the implementation, an
+ * appropriate exception is thrown.</p>
+ *
+ * @param transformation The transformation to create.
+ * @return An appropriate cipher for this transformation.
+ * @throws java.security.NoSuchAlgorithmException If no installed
+ * provider can supply the appropriate cipher or mode.
+ * @throws javax.crypto.NoSuchPaddingException If no installed
+ * provider can supply the appropriate padding.
+ */
+ public static final Cipher getInstance(String transformation)
+ throws NoSuchAlgorithmException, NoSuchPaddingException
+ {
+ Provider[] providers = Security.getProviders();
+ NoSuchPaddingException ex = null;
+ String msg = "";
+ for (int i = 0; i < providers.length; i++)
+ {
+ try
+ {
+ return getInstance(transformation, providers[i]);
+ }
+ catch (NoSuchAlgorithmException nsae)
+ {
+ msg = nsae.getMessage();
+ ex = null;
+ }
+ catch (NoSuchPaddingException nspe)
+ {
+ ex = nspe;
+ }
+ }
+ if (ex != null)
+ {
+ throw ex;
+ }
+ throw new NoSuchAlgorithmException(msg);
+ }
+
+ /**
+ * <p>Creates a new cipher instance for the given transformation and
+ * the named provider.</p>
+ *
+ * @param transformation The transformation to create.
+ * @param provider The name of the provider to use.
+ * @return An appropriate cipher for this transformation.
+ * @throws java.security.NoSuchAlgorithmException If the provider cannot
+ * supply the appropriate cipher or mode.
+ * @throws java.security.NoSuchProviderException If the named provider
+ * is not installed.
+ * @throws javax.crypto.NoSuchPaddingException If the provider cannot
+ * supply the appropriate padding.
+ */
+ public static final Cipher getInstance(String transformation, String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException,
+ NoSuchPaddingException
+ {
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(transformation, p);
+ }
+
+ /**
+ * Creates a new cipher instance for the given transform and the given
+ * provider.
+ *
+ * @param transformation The transformation to create.
+ * @param provider The provider to use.
+ * @return An appropriate cipher for this transformation.
+ * @throws java.security.NoSuchAlgorithmException If the given
+ * provider cannot supply the appropriate cipher or mode.
+ * @throws javax.crypto.NoSuchPaddingException If the given
+ * provider cannot supply the appropriate padding scheme.
+ */
+ public static final Cipher getInstance(String transformation, Provider provider)
+ throws NoSuchAlgorithmException, NoSuchPaddingException
+ {
+ CipherSpi result = null;
+ String key = null;
+ String alg = null, mode = null, pad = null;
+ String msg = "";
+ if (transformation.indexOf('/') < 0)
+ {
+ try
+ {
+ result = (CipherSpi) Engine.getInstance(SERVICE, transformation,
+ provider);
+ return new Cipher(result, provider, transformation);
+ }
+ catch (Exception e)
+ {
+ msg = e.getMessage();
+ }
+ }
+ else
+ {
+ StringTokenizer tok = new StringTokenizer(transformation, "/");
+ if (tok.countTokens() != 3)
+ {
+ throw new NoSuchAlgorithmException("badly formed transformation");
+ }
+ alg = tok.nextToken();
+ mode = tok.nextToken();
+ pad = tok.nextToken();
+ try
+ {
+ result = (CipherSpi) Engine.getInstance(SERVICE, transformation,
+ provider);
+ return new Cipher(result, provider, transformation);
+ }
+ catch (Exception e)
+ {
+ msg = e.getMessage();
+ }
+ try
+ {
+ result = (CipherSpi) Engine.getInstance(SERVICE, alg + '/' + mode,
+ provider);
+ result.engineSetPadding(pad);
+ return new Cipher(result, provider, transformation);
+ }
+ catch (Exception e)
+ {
+ if (e instanceof NoSuchPaddingException)
+ {
+ throw (NoSuchPaddingException) e;
+ }
+ msg = e.getMessage();
+ }
+ try
+ {
+ result = (CipherSpi) Engine.getInstance(SERVICE, alg + "//" + pad,
+ provider);
+ result.engineSetMode(mode);
+ return new Cipher(result, provider, transformation);
+ }
+ catch (Exception e)
+ {
+ msg = e.getMessage();
+ }
+ try
+ {
+ result = (CipherSpi) Engine.getInstance(SERVICE, alg, provider);
+ result.engineSetMode(mode);
+ result.engineSetPadding(pad);
+ return new Cipher(result, provider, transformation);
+ }
+ catch (Exception e)
+ {
+ if (e instanceof NoSuchPaddingException)
+ {
+ throw (NoSuchPaddingException) e;
+ }
+ msg = e.getMessage();
+ }
+ }
+ throw new NoSuchAlgorithmException(transformation + ": " + msg);
+ }
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a cipher.
+ *
+ * @param cipherSpi The underlying implementation of the cipher.
+ * @param provider The provider of this cipher implementation.
+ * @param transformation The transformation this cipher performs.
+ */
+ protected
+ Cipher(CipherSpi cipherSpi, Provider provider, String transformation)
+ {
+ this.cipherSpi = cipherSpi;
+ this.provider = provider;
+ this.transformation = transformation;
+ state = INITIAL_STATE;
+ }
+
+ // Public instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the name that this cipher instance was created with; this is
+ * equivalent to the "transformation" argument given to any of the
+ * {@link #getInstance()} methods.
+ *
+ * @return The cipher name.
+ */
+ public final String getAlgorithm()
+ {
+ return transformation;
+ }
+
+ /**
+ * Return the size of blocks, in bytes, that this cipher processes.
+ *
+ * @return The block size.
+ */
+ public final int getBlockSize()
+ {
+ if (cipherSpi != null)
+ {
+ return cipherSpi.engineGetBlockSize();
+ }
+ return 1;
+ }
+
+ /**
+ * Return the currently-operating {@link ExemptionMechanism}.
+ *
+ * @return null, currently.
+ */
+ public final ExemptionMechanism getExemptionMechanism()
+ {
+ return null;
+ }
+
+ /**
+ * Return the <i>initialization vector</i> that this instance was
+ * initialized with.
+ *
+ * @return The IV.
+ */
+ public final byte[] getIV()
+ {
+ if (cipherSpi != null)
+ {
+ return cipherSpi.engineGetIV();
+ }
+ return null;
+ }
+
+ /**
+ * Return the {@link java.security.AlgorithmParameters} that this
+ * instance was initialized with.
+ *
+ * @return The parameters.
+ */
+ public final AlgorithmParameters getParameters()
+ {
+ if (cipherSpi != null) {
+ return cipherSpi.engineGetParameters();
+ }
+ return null;
+ }
+
+ /**
+ * Return this cipher's provider.
+ *
+ * @return The provider.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Finishes a multi-part transformation, and returns the final
+ * transformed bytes.
+ *
+ * @return The final transformed bytes.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized, or if a <tt>doFinal</tt> call has already
+ * been made.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input is not a multiple of this cipher's
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is
+ * decrypting and the padding bytes do not match this
+ * instance's padding scheme.
+ */
+ public final byte[] doFinal()
+ throws IllegalStateException, IllegalBlockSizeException, BadPaddingException
+ {
+ return doFinal(new byte[0], 0, 0);
+ }
+
+ /**
+ * Finishes a multi-part transformation or does an entire
+ * transformation on the input, and returns the transformed bytes.
+ *
+ * @param input The final input bytes.
+ * @return The final transformed bytes.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized, or if a <tt>doFinal</tt> call has already
+ * been made.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input is not a multiple of this cipher's
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is
+ * decrypting and the padding bytes do not match this
+ * instance's padding scheme.
+ */
+ public final byte[] doFinal(byte[] input)
+ throws IllegalStateException, IllegalBlockSizeException, BadPaddingException
+ {
+ return doFinal(input, 0, input.length);
+ }
+
+ /**
+ * Finishes a multi-part transformation or does an entire
+ * transformation on the input, and returns the transformed bytes.
+ *
+ * @param input The final input bytes.
+ * @param inputOffset The index in the input bytes to start.
+ * @param inputLength The number of bytes to read from the input.
+ * @return The final transformed bytes.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized, or if a <tt>doFinal</tt> call has already
+ * been made.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input is not a multiple of this cipher's
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is
+ * decrypting and the padding bytes do not match this
+ * instance's padding scheme.
+ */
+ public final byte[] doFinal(byte[] input, int inputOffset, int inputLength)
+ throws IllegalStateException, IllegalBlockSizeException, BadPaddingException
+ {
+ if (cipherSpi == null)
+ {
+ byte[] b = new byte[inputLength];
+ System.arraycopy(input, inputOffset, b, 0, inputLength);
+ return b;
+ }
+ if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
+ {
+ throw new IllegalStateException("neither encrypting nor decrypting");
+ }
+ state = INITIAL_STATE;
+ return cipherSpi.engineDoFinal(input, inputOffset, inputLength);
+ }
+
+ /**
+ * Finishes a multi-part transformation and stores the transformed
+ * bytes into the given array.
+ *
+ * @param output The destination for the transformed bytes.
+ * @param outputOffset The offset in <tt>output</tt> to start storing
+ * bytes.
+ * @return The number of bytes placed into the output array.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized, or if a <tt>doFinal</tt> call has already
+ * been made.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input is not a multiple of this cipher's
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is
+ * decrypting and the padding bytes do not match this
+ * instance's padding scheme.
+ * @throws javax.crypto.ShortBufferException If the output array is
+ * not large enough to hold the transformed bytes.
+ */
+ public final int doFinal(byte[] output, int outputOffset)
+ throws IllegalStateException, IllegalBlockSizeException, BadPaddingException,
+ ShortBufferException
+ {
+ if (cipherSpi == null)
+ {
+ return 0;
+ }
+ if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
+ {
+ throw new IllegalStateException("neither encrypting nor decrypting");
+ }
+ state = INITIAL_STATE;
+ return cipherSpi.engineDoFinal(new byte[0], 0, 0, output, outputOffset);
+ }
+
+ /**
+ * Finishes a multi-part transformation or transforms a portion of a
+ * byte array, and stores the result in the given byte array.
+ *
+ * @param input The input bytes.
+ * @param inputOffset The index in <tt>input</tt> to start.
+ * @param inputLength The number of bytes to transform.
+ * @param output The output buffer.
+ * @param outputOffset The index in <tt>output</tt> to start.
+ * @return The number of bytes placed into the output array.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized, or if a <tt>doFinal</tt> call has already
+ * been made.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input is not a multiple of this cipher's
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is
+ * decrypting and the padding bytes do not match this
+ * instance's padding scheme.
+ * @throws javax.crypto.ShortBufferException If the output array is
+ * not large enough to hold the transformed bytes.
+ */
+ public final int doFinal(byte[] input, int inputOffset, int inputLength,
+ byte[] output, int outputOffset)
+ throws IllegalStateException, IllegalBlockSizeException, BadPaddingException,
+ ShortBufferException
+ {
+ if (cipherSpi == null)
+ {
+ if (inputLength > output.length - outputOffset)
+ {
+ throw new ShortBufferException();
+ }
+ System.arraycopy(input, inputOffset, output, outputOffset, inputLength);
+ return inputLength;
+ }
+ if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
+ {
+ throw new IllegalStateException("neither encrypting nor decrypting");
+ }
+ state = INITIAL_STATE;
+ return cipherSpi.engineDoFinal(input, inputOffset, inputLength,
+ output, outputOffset);
+ }
+
+ public final int doFinal(byte[] input, int inputOffset, int inputLength,
+ byte[] output)
+ throws IllegalStateException, IllegalBlockSizeException, BadPaddingException,
+ ShortBufferException
+ {
+ return doFinal(input, inputOffset, inputLength, output, 0);
+ }
+
+ /**
+ * Returns the size an output buffer needs to be if this cipher is
+ * updated with a number of bytes.
+ *
+ * @param inputLength The input length.
+ * @return The output length given this input length.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized, or if a <tt>doFinal</tt> call has already
+ * been made.
+ */
+ public final int getOutputSize(int inputLength) throws IllegalStateException
+ {
+ if (cipherSpi == null)
+ {
+ return inputLength;
+ }
+ if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
+ {
+ throw new IllegalStateException("neither encrypting nor decrypting");
+ }
+ return cipherSpi.engineGetOutputSize(inputLength);
+ }
+
+ /**
+ * <p>Initialize this cipher with the public key from the given
+ * certificate.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>As per the Java 1.4 specification, if <code>cert</code> is an
+ * instance of an {@link java.security.cert.X509Certificate} and its
+ * <i>key usage</i> extension field is incompatible with
+ * <code>opmode</code> then an {@link
+ * java.security.InvalidKeyException} is thrown.</p>
+ *
+ * <p>If this cipher requires any random bytes (for example for an
+ * initilization vector) than the {@link java.security.SecureRandom}
+ * with the highest priority is used as the source of these bytes.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param certificate The certificate.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the certificate's public key, or if the
+ * public key cannot be used as described above.
+ */
+ public final void init(int opmode, Certificate certificate)
+ throws InvalidKeyException
+ {
+ init(opmode, certificate, new SecureRandom());
+ }
+
+ /**
+ * <p>Initialize this cipher with the supplied key.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>If this cipher requires any random bytes (for example for an
+ * initilization vector) than the {@link java.security.SecureRandom}
+ * with the highest priority is used as the source of these bytes.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param key The key.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the given key.
+ */
+ public final void init(int opmode, Key key) throws InvalidKeyException
+ {
+ state = opmode;
+ if (cipherSpi != null)
+ {
+ cipherSpi.engineInit(opmode, key, new SecureRandom());
+ }
+ }
+
+ /**
+ * <p>Initialize this cipher with the public key from the given
+ * certificate and the specified source of randomness.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>As per the Java 1.4 specification, if <code>cert</code> is an
+ * instance of an {@link java.security.cert.X509Certificate} and its
+ * <i>key usage</i> extension field is incompatible with
+ * <code>opmode</code> then an {@link
+ * java.security.InvalidKeyException} is thrown.</p>
+ *
+ * <p>If this cipher requires any random bytes (for example for an
+ * initilization vector) than the {@link java.security.SecureRandom}
+ * with the highest priority is used as the source of these bytes.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param certificate The certificate.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the certificate's public key, or if the
+ * public key cannot be used as described above.
+ */
+ public final void
+ init(int opmode, Certificate certificate, SecureRandom random)
+ throws InvalidKeyException
+ {
+ if (certificate instanceof X509Certificate)
+ {
+ boolean[] keyInfo = ((X509Certificate) certificate).getKeyUsage();
+ if (keyInfo != null)
+ {
+ switch (opmode)
+ {
+ case DECRYPT_MODE:
+ if (!keyInfo[3])
+ {
+ throw new InvalidKeyException(
+ "the certificate's key cannot be used for transforming data");
+ }
+ if (keyInfo[7])
+ {
+ throw new InvalidKeyException(
+ "the certificate's key can only be used for encryption");
+ }
+ break;
+
+ case ENCRYPT_MODE:
+ if (!keyInfo[3])
+ {
+ throw new InvalidKeyException(
+ "the certificate's key cannot be used for transforming data");
+ }
+ if (keyInfo[8])
+ {
+ throw new InvalidKeyException(
+ "the certificate's key can only be used for decryption");
+ }
+ break;
+
+ case UNWRAP_MODE:
+ if (!keyInfo[2] || keyInfo[7])
+ {
+ throw new InvalidKeyException(
+ "the certificate's key cannot be used for key unwrapping");
+ }
+ break;
+
+ case WRAP_MODE:
+ if (!keyInfo[2] || keyInfo[8])
+ {
+ throw new InvalidKeyException(
+ "the certificate's key cannot be used for key wrapping");
+ }
+ break;
+ }
+ }
+ }
+ init(opmode, certificate.getPublicKey(), random);
+ }
+
+ /**
+ * <p>Initialize this cipher with the supplied key and source of
+ * randomness.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param key The key.
+ * @param random The source of randomness to use.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the given key.
+ */
+ public final void init(int opmode, Key key, SecureRandom random)
+ throws InvalidKeyException
+ {
+ state = opmode;
+ if (cipherSpi != null)
+ {
+ cipherSpi.engineInit(opmode, key, random);
+ }
+ }
+
+ /**
+ * <p>Initialize this cipher with the supplied key and parameters.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>If this cipher requires any random bytes (for example for an
+ * initilization vector) then the {@link java.security.SecureRandom}
+ * with the highest priority is used as the source of these bytes.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param key The key.
+ * @param params The algorithm parameters to initialize this instance
+ * with.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the given key.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inappropriate for this cipher.
+ */
+ public final void init(int opmode, Key key, AlgorithmParameters params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException
+ {
+ init(opmode, key, params, new SecureRandom());
+ }
+
+ /**
+ * <p>Initialize this cipher with the supplied key and parameters.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>If this cipher requires any random bytes (for example for an
+ * initilization vector) then the {@link java.security.SecureRandom}
+ * with the highest priority is used as the source of these bytes.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param key The key.
+ * @param params The algorithm parameters to initialize this instance
+ * with.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the given key.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inappropriate for this cipher.
+ */
+ public final void init(int opmode, Key key, AlgorithmParameterSpec params)
+ throws InvalidKeyException, InvalidAlgorithmParameterException
+ {
+ init(opmode, key, params, new SecureRandom());
+ }
+
+ /**
+ * <p>Initialize this cipher with the supplied key, parameters, and
+ * source of randomness.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param key The key.
+ * @param params The algorithm parameters to initialize this instance
+ * with.
+ * @param random The source of randomness to use.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the given key.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inappropriate for this cipher.
+ */
+ public final void init(int opmode, Key key, AlgorithmParameters params,
+ SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException
+ {
+ state = opmode;
+ if (cipherSpi != null)
+ {
+ cipherSpi.engineInit(opmode, key, params, random);
+ }
+ }
+
+ /**
+ * <p>Initialize this cipher with the supplied key, parameters, and
+ * source of randomness.</p>
+ *
+ * <p>The cipher will be initialized for encryption, decryption, key
+ * wrapping, or key unwrapping, depending upon whether the
+ * <code>opmode</code> argument is {@link #ENCRYPT_MODE}, {@link
+ * #DECRYPT_MODE}, {@link #WRAP_MODE}, or {@link #UNWRAP_MODE},
+ * respectively.</p>
+ *
+ * <p>A call to any of the <code>init</code> methods overrides the
+ * state of the instance, and is equivalent to creating a new instance
+ * and calling its <code>init</code> method.</p>
+ *
+ * @param opmode The operation mode to use.
+ * @param key The key.
+ * @param params The algorithm parameters to initialize this instance
+ * with.
+ * @param random The source of randomness to use.
+ * @throws java.security.InvalidKeyException If the underlying cipher
+ * instance rejects the given key.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inappropriate for this cipher.
+ */
+ public final void init(int opmode, Key key, AlgorithmParameterSpec params,
+ SecureRandom random)
+ throws InvalidKeyException, InvalidAlgorithmParameterException
+ {
+ state = opmode;
+ if (cipherSpi != null)
+ {
+ cipherSpi.engineInit(opmode, key, params, random);
+ }
+ }
+
+ /**
+ * Unwrap a previously-wrapped key.
+ *
+ * @param wrappedKey The wrapped key.
+ * @param wrappedKeyAlgorithm The algorithm with which the key was
+ * wrapped.
+ * @param wrappedKeyType The type of key (public, private, or
+ * secret) that this wrapped key respresents.
+ * @return The unwrapped key.
+ * @throws java.lang.IllegalStateException If this instance has not be
+ * initialized for unwrapping.
+ * @throws java.security.InvalidKeyException If <code>wrappedKey</code>
+ * is not a wrapped key, if the algorithm cannot unwrap this
+ * key, or if the unwrapped key's type differs from the
+ * specified type.
+ * @throws java.security.NoSuchAlgorithmException If
+ * <code>wrappedKeyAlgorithm</code> is not a valid algorithm
+ * name.
+ */
+ public final Key unwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
+ int wrappedKeyType)
+ throws IllegalStateException, InvalidKeyException, NoSuchAlgorithmException
+ {
+ if (cipherSpi == null)
+ {
+ return null;
+ }
+ if (state != UNWRAP_MODE)
+ {
+ throw new IllegalStateException("instance is not for unwrapping");
+ }
+ return cipherSpi.engineUnwrap(wrappedKey, wrappedKeyAlgorithm,
+ wrappedKeyType);
+ }
+
+ /**
+ * Continue a multi-part transformation on an entire byte array,
+ * returning the transformed bytes.
+ *
+ * @param input The input bytes.
+ * @return The transformed bytes.
+ * @throws java.lang.IllegalStateException If this cipher was not
+ * initialized for encryption or decryption.
+ */
+ public final byte[] update(byte[] input) throws IllegalStateException
+ {
+ return update(input, 0, input.length);
+ }
+
+ /**
+ * Continue a multi-part transformation on part of a byte array,
+ * returning the transformed bytes.
+ *
+ * @param input The input bytes.
+ * @param inputOffset The index in the input to start.
+ * @param inputLength The number of bytes to transform.
+ * @return The transformed bytes.
+ * @throws java.lang.IllegalStateException If this cipher was not
+ * initialized for encryption or decryption.
+ */
+ public final byte[] update(byte[] input, int inputOffset, int inputLength)
+ throws IllegalStateException
+ {
+ if (cipherSpi == null)
+ {
+ byte[] b = new byte[inputLength];
+ System.arraycopy(input, inputOffset, b, 0, inputLength);
+ return b;
+ }
+ if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
+ {
+ throw new IllegalStateException(
+ "cipher is not for encrypting or decrypting");
+ }
+ return cipherSpi.engineUpdate(input, inputOffset, inputLength);
+ }
+
+ /**
+ * Continue a multi-part transformation on part of a byte array,
+ * placing the transformed bytes into the given array.
+ *
+ * @param input The input bytes.
+ * @param inputOffset The index in the input to start.
+ * @param inputLength The number of bytes to transform.
+ * @param output The output byte array.
+ * @return The number of transformed bytes.
+ * @throws java.lang.IllegalStateException If this cipher was not
+ * initialized for encryption or decryption.
+ * @throws javax.security.ShortBufferException If there is not enough
+ * room in the output array to hold the transformed bytes.
+ */
+ public final int update(byte[] input, int inputOffset, int inputLength,
+ byte[] output)
+ throws IllegalStateException, ShortBufferException
+ {
+ return update(input, inputOffset, inputLength, output, 0);
+ }
+
+ /**
+ * Continue a multi-part transformation on part of a byte array,
+ * placing the transformed bytes into the given array.
+ *
+ * @param input The input bytes.
+ * @param inputOffset The index in the input to start.
+ * @param inputLength The number of bytes to transform.
+ * @param output The output byte array.
+ * @param outputOffset The index in the output array to start.
+ * @return The number of transformed bytes.
+ * @throws java.lang.IllegalStateException If this cipher was not
+ * initialized for encryption or decryption.
+ * @throws javax.security.ShortBufferException If there is not enough
+ * room in the output array to hold the transformed bytes.
+ */
+ public final int update(byte[] input, int inputOffset, int inputLength,
+ byte[] output, int outputOffset)
+ throws IllegalStateException, ShortBufferException
+ {
+ if (cipherSpi == null)
+ {
+ if (inputLength > output.length - outputOffset)
+ {
+ throw new ShortBufferException();
+ }
+ System.arraycopy(input, inputOffset, output, outputOffset, inputLength);
+ return inputLength;
+ }
+ if (state != ENCRYPT_MODE && state != DECRYPT_MODE)
+ {
+ throw new IllegalStateException(
+ "cipher is not for encrypting or decrypting");
+ }
+ return cipherSpi.engineUpdate(input, inputOffset, inputLength,
+ output, outputOffset);
+ }
+
+ /**
+ * Wrap a key.
+ *
+ * @param key The key to wrap.
+ * @return The wrapped key.
+ * @throws java.lang.IllegalStateException If this instance was not
+ * initialized for key wrapping.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the key is not a multiple of the block size.
+ * @throws java.security.InvalidKeyException If this instance cannot
+ * wrap this key.
+ */
+ public final byte[] wrap(Key key)
+ throws IllegalStateException, IllegalBlockSizeException, InvalidKeyException
+ {
+ if (cipherSpi == null)
+ {
+ return null;
+ }
+ if (state != WRAP_MODE)
+ {
+ throw new IllegalStateException("instance is not for key wrapping");
+ }
+ return cipherSpi.engineWrap(key);
+ }
+}
diff --git a/libjava/javax/crypto/CipherInputStream.java b/libjava/javax/crypto/CipherInputStream.java
new file mode 100644
index 00000000000..c01cb47ac4c
--- /dev/null
+++ b/libjava/javax/crypto/CipherInputStream.java
@@ -0,0 +1,383 @@
+/* CipherInputStream.java -- Filters input through a cipher.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * This is an {@link java.io.InputStream} that filters its data
+ * through a {@link Cipher} before returning it. The <code>Cipher</code>
+ * argument must have been initialized before it is passed to the
+ * constructor.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class CipherInputStream extends FilterInputStream
+{
+
+ // Constants and variables.
+ // ------------------------------------------------------------------------
+
+ /**
+ * The underlying {@link Cipher} instance.
+ */
+ private Cipher cipher;
+
+ /**
+ * Data that has been transformed but not read.
+ */
+ private byte[] outBuffer;
+
+ /**
+ * The offset into {@link #outBuffer} where valid data starts.
+ */
+ private int outOffset;
+
+ /**
+ * The number of valid bytes in the {@link #outBuffer}.
+ */
+ private int outLength;
+
+ /**
+ * Byte buffer that is filled with raw data from the underlying input
+ * stream.
+ */
+ private byte[][] inBuffer;
+
+ /**
+ * The amount of bytes in inBuffer[0] that may be input to the cipher.
+ */
+ private int inLength;
+
+ /**
+ * We set this when the cipher block size is 1, meaning that we can
+ * transform any amount of data.
+ */
+ private boolean isStream;
+
+ private static final int VIRGIN = 0; // I am born.
+ private static final int LIVING = 1; // I am nailed to the hull.
+ private static final int DYING = 2; // I am eaten by sharks.
+ private static final int DEAD = 3;
+ private int state;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates a new input stream with a source input stream and cipher.
+ *
+ * @param in The underlying input stream.
+ * @param cipher The cipher to filter data through.
+ */
+ public CipherInputStream(InputStream in, Cipher cipher)
+ {
+ this(in);
+ this.cipher = cipher;
+ if (!(isStream = cipher.getBlockSize() == 1))
+ {
+ inBuffer = new byte[2][];
+ inBuffer[0] = new byte[cipher.getBlockSize()];
+ inBuffer[1] = new byte[cipher.getBlockSize()];
+ inLength = 0;
+ outBuffer = new byte[cipher.getBlockSize()];
+ outOffset = outLength = 0;
+ state = VIRGIN;
+ }
+ }
+
+ /**
+ * Creates a new input stream without a cipher. This constructor is
+ * <code>protected</code> because this class does not work without an
+ * underlying cipher.
+ *
+ * @param in The underlying input stream.
+ */
+ protected CipherInputStream(InputStream in)
+ {
+ super(in);
+ }
+
+ // Instance methods overriding java.io.FilterInputStream.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns the number of bytes available without blocking. The value
+ * returned by this method is never greater than the underlying
+ * cipher's block size.
+ *
+ * @return The number of bytes immediately available.
+ * @throws java.io.IOException If an I/O exception occurs.
+ */
+ public int available() throws IOException
+ {
+ if (isStream)
+ return super.available();
+ return outLength - outOffset;
+ }
+
+ /**
+ * Close this input stream. This method merely calls the {@link
+ * java.io.InputStream#close()} method of the underlying input stream.
+ *
+ * @throws java.io.IOException If an I/O exception occurs.
+ */
+ public void close() throws IOException
+ {
+ super.close();
+ }
+
+ /**
+ * Read a single byte from this input stream; returns -1 on the
+ * end-of-file.
+ *
+ * @return The byte read, or -1 if there are no more bytes.
+ * @throws java.io.IOExcpetion If an I/O exception occurs.
+ */
+ public int read() throws IOException
+ {
+ if (isStream)
+ {
+ byte[] buf = new byte[1];
+ int in = super.read();
+ if (in == -1)
+ return -1;
+ buf[0] = (byte) in;
+ try
+ {
+ cipher.update(buf, 0, 1, buf, 0);
+ }
+ catch (ShortBufferException shouldNotHappen)
+ {
+ throw new IOException(shouldNotHappen.getMessage());
+ }
+ return buf[0] & 0xFF;
+ }
+ if (state == DEAD) return -1;
+ if (available() == 0) nextBlock();
+ if (state == DEAD) return -1;
+ return outBuffer[outOffset++] & 0xFF;
+ }
+
+ /**
+ * Read bytes into an array, returning the number of bytes read or -1
+ * on the end-of-file.
+ *
+ * @param buf The byte array to read into.
+ * @param off The offset in <code>buf</code> to start.
+ * @param len The maximum number of bytes to read.
+ * @return The number of bytes read, or -1 on the end-of-file.
+ * @throws java.io.IOException If an I/O exception occurs.
+ */
+ public int read(byte[] buf, int off, int len) throws IOException
+ {
+ if (isStream)
+ {
+ len = super.read(buf, off, len);
+ try
+ {
+ cipher.update(buf, off, len, buf, off);
+ }
+ catch (ShortBufferException shouldNotHappen)
+ {
+ throw new IOException(shouldNotHappen.getMessage());
+ }
+ return len;
+ }
+
+ int count = 0;
+ while (count < len)
+ {
+ if (available() == 0)
+ nextBlock();
+ if (state == DEAD)
+ {
+ if (count > 0) return count;
+ else return -1;
+ }
+ int l = Math.min(available(), len - count);
+ System.arraycopy(outBuffer, outOffset, buf, count+off, l);
+ count += l;
+ outOffset = outLength = 0;
+ }
+ return count;
+ }
+
+ /**
+ * Read bytes into an array, returning the number of bytes read or -1
+ * on the end-of-file.
+ *
+ * @param buf The byte arry to read into.
+ * @return The number of bytes read, or -1 on the end-of-file.
+ * @throws java.io.IOException If an I/O exception occurs.
+ */
+ public int read(byte[] buf) throws IOException
+ {
+ return read(buf, 0, buf.length);
+ }
+
+ /**
+ * Skip a number of bytes. This class only supports skipping as many
+ * bytes as are returned by {@link #available()}, which is the number
+ * of transformed bytes currently in this class's internal buffer.
+ *
+ * @param bytes The number of bytes to skip.
+ * @return The number of bytes skipped.
+ */
+ public long skip(long bytes) throws IOException
+ {
+ if (isStream)
+ {
+ return super.skip(bytes);
+ }
+ long ret = 0;
+ if (bytes > 0 && available() > 0)
+ {
+ ret = available();
+ outOffset = outLength = 0;
+ }
+ return ret;
+ }
+
+ /**
+ * Returns whether or not this input stream supports the {@link
+ * #mark(long)} and {@link #reset()} methods; this input stream does
+ * not, however, and invariably returns <code>false</code>.
+ *
+ * @return <code>false</code>
+ */
+ public boolean markSupported()
+ {
+ return false;
+ }
+
+ /**
+ * Set the mark. This method is unsupported and is empty.
+ *
+ * @param mark Is ignored.
+ */
+ public void mark(long mark)
+ {
+ }
+
+ /**
+ * Reset to the mark. This method is unsupported and is empty.
+ */
+ public void reset() throws IOException
+ {
+ throw new IOException("reset not supported");
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private void nextBlock() throws IOException
+ {
+ byte[] temp = inBuffer[0];
+ inBuffer[0] = inBuffer[1];
+ inBuffer[1] = temp;
+ int count = 0;
+ boolean eof = false;
+
+ if (state == VIRGIN || state == LIVING)
+ {
+ do
+ {
+ int l = in.read(inBuffer[1], count, inBuffer[1].length - count);
+ if (l == -1)
+ {
+ eof = true;
+ break;
+ }
+ count += l;
+ }
+ while (count < inBuffer[1].length);
+ }
+
+ try
+ {
+ switch (state)
+ {
+ case VIRGIN:
+ state = LIVING;
+ nextBlock();
+ break;
+ case LIVING:
+ if (eof)
+ {
+ if (count > 0)
+ {
+ outOffset = cipher.update(inBuffer[0], 0, inLength, outBuffer, 0);
+ state = DYING;
+ }
+ else
+ {
+ outOffset = cipher.doFinal(inBuffer[0], 0, inLength, outBuffer, 0);
+ state = DEAD;
+ }
+ }
+ else
+ {
+ outOffset = cipher.update(inBuffer[0], 0, inLength, outBuffer, 0);
+ }
+ break;
+ case DYING:
+ outOffset = cipher.doFinal(inBuffer[0], 0, inLength, outBuffer, 0);
+ state = DEAD;
+ break;
+ case DEAD:
+ }
+ }
+ catch (ShortBufferException sbe)
+ {
+ throw new IOException(sbe.toString());
+ }
+ catch (BadPaddingException bpe)
+ {
+ throw new IOException(bpe.toString());
+ }
+ catch (IllegalBlockSizeException ibse)
+ {
+ throw new IOException(ibse.toString());
+ }
+ inLength = count;
+ }
+}
diff --git a/libjava/javax/crypto/CipherOutputStream.java b/libjava/javax/crypto/CipherOutputStream.java
new file mode 100644
index 00000000000..7eb09c1d08c
--- /dev/null
+++ b/libjava/javax/crypto/CipherOutputStream.java
@@ -0,0 +1,268 @@
+/* CipherOutputStream.java -- Filters output through a cipher.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.io.FilterOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+/**
+ * A filtered output stream that transforms data written to it with a
+ * {@link Cipher} before sending it to the underlying output stream.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class CipherOutputStream extends FilterOutputStream
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ /** The underlying cipher. */
+ private Cipher cipher;
+
+ private byte[][] inBuffer;
+
+ private int inLength;
+
+ private byte[] outBuffer;
+
+ private static final int FIRST_TIME = 0;
+ private static final int SECOND_TIME = 1;
+ private static final int SEASONED = 2;
+ private int state;
+
+ /** True if the cipher is a stream cipher (blockSize == 1) */
+ private boolean isStream;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new cipher output stream. The cipher argument must have
+ * already been initialized.
+ *
+ * @param out The sink for transformed data.
+ * @param cipher The cipher to transform data with.
+ */
+ public CipherOutputStream(OutputStream out, Cipher cipher)
+ {
+ super(out);
+ if (cipher != null)
+ {
+ this.cipher = cipher;
+ if (!(isStream = cipher.getBlockSize() == 1))
+ {
+ inBuffer = new byte[2][];
+ inBuffer[0] = new byte[cipher.getBlockSize()];
+ inBuffer[1] = new byte[cipher.getBlockSize()];
+ inLength = 0;
+ state = FIRST_TIME;
+ }
+ }
+ else
+ this.cipher = new NullCipher();
+ }
+
+ /**
+ * Create a cipher output stream with no cipher.
+ *
+ * @param out The sink for transformed data.
+ */
+ protected CipherOutputStream(OutputStream out)
+ {
+ super(out);
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Close this output stream, and the sink output stream.
+ *
+ * <p>This method will first invoke the {@link Cipher#doFinal()}
+ * method of the underlying {@link Cipher}, and writes the output of
+ * that method to the sink output stream.
+ *
+ * @throws java.io.IOException If an I/O error occurs, or if an error
+ * is caused by finalizing the transformation.
+ */
+ public void close() throws IOException
+ {
+ try
+ {
+ int len;
+ if (state != FIRST_TIME)
+ {
+ len = cipher.update(inBuffer[0], 0, inBuffer[0].length, outBuffer);
+ out.write(outBuffer, 0, len);
+ }
+ len = cipher.doFinal(inBuffer[0], 0, inLength, outBuffer);
+ out.write(outBuffer, 0, len);
+ }
+ catch (javax.crypto.IllegalBlockSizeException ibse)
+ {
+ throw new IOException(ibse.toString());
+ }
+ catch (javax.crypto.BadPaddingException bpe)
+ {
+ throw new IOException(bpe.toString());
+ }
+ catch (ShortBufferException sbe)
+ {
+ throw new IOException(sbe.toString());
+ }
+ out.flush();
+ out.close();
+ }
+
+ /**
+ * Flush any pending output.
+ *
+ * @throws java.io.IOException If an I/O error occurs.
+ */
+ public void flush() throws IOException
+ {
+ out.flush();
+ }
+
+ /**
+ * Write a single byte to the output stream.
+ *
+ * @param b The next byte.
+ * @throws java.io.IOException If an I/O error occurs, or if the
+ * underlying cipher is not in the correct state to transform
+ * data.
+ */
+ public void write(int b) throws IOException
+ {
+ if (isStream)
+ {
+ byte[] buf = new byte[] { (byte) b };
+ try
+ {
+ cipher.update(buf, 0, 1, buf, 0);
+ }
+ catch (ShortBufferException sbe)
+ {
+ throw new IOException(sbe.toString());
+ }
+ out.write(buf);
+ return;
+ }
+ inBuffer[1][inLength++] = (byte) b;
+ if (inLength == inBuffer[1].length)
+ process();
+ }
+
+ /**
+ * Write a byte array to the output stream.
+ *
+ * @param buf The next bytes.
+ * @throws java.io.IOException If an I/O error occurs, or if the
+ * underlying cipher is not in the correct state to transform
+ * data.
+ */
+ public void write(byte[] buf) throws IOException
+ {
+ write(buf, 0, buf.length);
+ }
+
+ /**
+ * Write a portion of a byte array to the output stream.
+ *
+ * @param buf The next bytes.
+ * @param off The offset in the byte array to start.
+ * @param len The number of bytes to write.
+ * @throws java.io.IOException If an I/O error occurs, or if the
+ * underlying cipher is not in the correct state to transform
+ * data.
+ */
+ public void write(byte[] buf, int off, int len) throws IOException
+ {
+ if (isStream)
+ {
+ out.write(cipher.update(buf, off, len));
+ return;
+ }
+ int count = 0;
+ while (count < len)
+ {
+ int l = Math.min(inBuffer[1].length - inLength, len - count);
+ System.arraycopy(buf, off+count, inBuffer[1], inLength, l);
+ count += l;
+ inLength += l;
+ if (inLength == inBuffer[1].length)
+ process();
+ }
+ }
+
+ // Own method.
+ // -------------------------------------------------------------------------
+
+ private void process() throws IOException
+ {
+ if (state == SECOND_TIME)
+ {
+ state = SEASONED;
+ }
+ else
+ {
+ byte[] temp = inBuffer[0];
+ inBuffer[0] = inBuffer[1];
+ inBuffer[1] = temp;
+ }
+ if (state == FIRST_TIME)
+ {
+ inLength = 0;
+ state = SECOND_TIME;
+ return;
+ }
+ try
+ {
+ cipher.update(inBuffer[0], 0, inBuffer[0].length, outBuffer);
+ }
+ catch (ShortBufferException sbe)
+ {
+ throw new IOException(sbe.toString());
+ }
+ out.write(outBuffer);
+ inLength = 0;
+ }
+}
diff --git a/libjava/javax/crypto/CipherSpi.java b/libjava/javax/crypto/CipherSpi.java
new file mode 100644
index 00000000000..06ea534f4f6
--- /dev/null
+++ b/libjava/javax/crypto/CipherSpi.java
@@ -0,0 +1,398 @@
+/* CipherSpi.java -- The cipher service provider interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * <p>This class represents the <i>Service Provider Interface</i>
+ * (<b>SPI</b>) for cryptographic ciphers.</p>
+ *
+ * <p>Providers of cryptographic ciphers must subclass this for every
+ * cipher they implement, implementing the abstract methods as
+ * appropriate, then provide an entry that points to the subclass in
+ * their implementation of {@link java.security.Provider}.</p>
+ *
+ * <p>CipherSpi objects are instantiated along with {@link Cipher}s when
+ * the {@link Cipher#getInstance(java.lang.String)} methods are invoked.
+ * Particular ciphers are referenced by a <i>transformation</i>, which
+ * is a String consisting of the cipher's name or the ciper's name
+ * followed by a mode and a padding. Transformations all follow the
+ * general form:</p>
+ *
+ * <ul>
+ * <li><i>algorithm</i>, or</li>
+ * <li><i>algorithm</i>/<i>mode</i>/<i>padding</i>
+ * </ul>
+ *
+ * <p>Cipher names in the master {@link java.security.Provider} class
+ * may be:</p>
+ *
+ * <ol>
+ * <li>The algorithm's name, which uses a pluggable mode and padding:
+ * <code>Cipher.<i>algorithm</i></code></li>
+ * <li>The algorithm's name and the mode, which uses pluggable padding:
+ * <code>Cipher.<i>algorithm</i>/<i>mode</i></code></li>
+ * <li>The algorithm's name and the padding, which uses a pluggable
+ * mode: <code>Cipher.<i>algorithm</i>//<i>padding</i></code></li>
+ * <li>The algorihtm's name, the mode, and the padding:
+ * <code>Cipher.<i>algorithm</i>/<i>mode</i>/<i>padding</i></code></li>
+ * </ol>
+ *
+ * <p>When any {@link Cipher#getInstance(java.lang.String)} method is
+ * invoked, the following happens if the transformation is simply
+ * <i>algorithm</i>:</p>
+ *
+ * <ol>
+ * <li>If the provider defines a <code>CipherSpi</code> implementation
+ * for "<i>algorithm</i>", return it. Otherwise throw a {@link
+ * java.security.NoSuchAlgorithmException}.</li>
+ * </ol>
+ *
+ * <p>If the transformation is of the form
+ * <i>algorithm</i>/<i>mode</i>/<i>padding</i>:</p>
+ *
+ * <ol>
+ * <li>If the provider defines a <code>CipherSpi</code> subclass for
+ * "<i>algorithm</i>/<i>mode</i>/<i>padding</i>", return it. Otherwise
+ * go to step 2.</li>
+ *
+ * <li>If the provider defines a <code>CipherSpi</code> subclass for
+ * "<i>algorithm</i>/<i>mode</i>", instatiate it, call {@link
+ * #engineSetPadding(java.lang.String)} for the padding name, and return
+ * it. Otherwise go to step 3.</li>
+ *
+ * <li>If the provider defines a <code>CipherSpi</code> subclass for
+ * "<i>algorithm</i>//<i>padding</i>", instatiate it, call {@link
+ * #engineSetMode(java.lang.String)} for the mode name, and return
+ * it. Otherwise go to step 4.</li>
+ *
+ * <li>If the provider defines a <code>CipherSpi</code> subclass for
+ * "<i>algorithm</i>", instatiate it, call {@link
+ * #engineSetMode(java.lang.String)} for the mode name, call {@link
+ * #engineSetPadding(java.lang.String)} for the padding name, and return
+ * it. Otherwise throw a {@link java.security.NoSuchAlgorithmException}.</li>
+ * </ol>
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public abstract class CipherSpi
+{
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new CipherSpi.
+ */
+ public CipherSpi()
+ {
+ }
+
+ // Abstract methods to be implemented by providers.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Finishes a multi-part transformation or transforms a portion of a
+ * byte array, and returns the transformed bytes.
+ *
+ * @param input The input bytes.
+ * @param inputOffset The index in the input at which to start.
+ * @param inputLength The number of bytes to transform.
+ * @return The transformed bytes in a new array.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input size is not a multiple of the
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is being
+ * used for decryption and the padding is not appropriate for
+ * this instance's padding scheme.
+ */
+ protected abstract byte[]
+ engineDoFinal(byte[] input, int inputOffset, int inputLength)
+ throws IllegalBlockSizeException, BadPaddingException;
+
+ /**
+ * Finishes a multi-part transformation or transforms a portion of a
+ * byte array, and stores the transformed bytes in the supplied array.
+ *
+ * @param input The input bytes.
+ * @param inputOffset The index in the input at which to start.
+ * @param inputLength The number of bytes to transform.
+ * @param output The output byte array.
+ * @param outputOffset The index in the output array at which to start.
+ * @return The number of transformed bytes stored in the output array.
+ * @throws javax.crypto.IllegalBlockSizeException If this instance has
+ * no padding and the input size is not a multiple of the
+ * block size.
+ * @throws javax.crypto.BadPaddingException If this instance is being
+ * used for decryption and the padding is not appropriate for
+ * this instance's padding scheme.
+ * @throws javax.crypto.ShortBufferException If there is not enough
+ * space in the output array for the transformed bytes.
+ */
+ protected abstract int
+ engineDoFinal(byte[] input, int inputOffset, int inputLength,
+ byte[] output, int outputOffset)
+ throws IllegalBlockSizeException, BadPaddingException, ShortBufferException;
+
+ /**
+ * Returns the block size of the underlying cipher.
+ *
+ * @return The block size.
+ */
+ protected abstract int engineGetBlockSize();
+
+ /**
+ * Returns the initializaiton vector this cipher was initialized with,
+ * if any.
+ *
+ * @return The IV, or null if this cipher uses no IV or if this
+ * instance has not been initialized yet.
+ */
+ protected abstract byte[] engineGetIV();
+
+ /**
+ * <p>Return the length of the given key in bits.</p>
+ *
+ * <p>For compatibility this method is not declared
+ * <code>abstract</code>, and the default implementation will throw an
+ * {@link java.lang.UnsupportedOperationException}. Concrete
+ * subclasses should override this method to return the correct
+ * value.</p>
+ *
+ * @param key The key to get the size for.
+ * @return The size of the key, in bits.
+ * @throws java.security.InvalidKeyException If the key's length
+ * cannot be determined by this implementation.
+ */
+ protected int engineGetKeySize(Key key) throws InvalidKeyException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * <p>Returns the size, in bytes, an output buffer must be for a call
+ * to {@link #engineUpdate(byte[],int,int,byte[],int)} or {@link
+ * #engineDoFinal(byte[],int,int,byte[],int)} to succeed.</p>
+ *
+ * <p>The actual output length may be smaller than the value returned
+ * by this method, as it considers the padding length as well. The
+ * length considered is the argument plus the length of any buffered,
+ * unprocessed bytes.</p>
+ *
+ * @param inputLength The input length, in bytes.
+ * @return The size an output buffer must be.
+ */
+ protected abstract int engineGetOutputSize(int inputLength);
+
+ /**
+ * Returns the parameters that this cipher is using. This may be the
+ * parameters used to initialize this cipher, or it may be parameters
+ * that have been initialized with random values.
+ *
+ * @return This cipher's parameters, or <code>null</code> if this
+ * cipher does not use parameters.
+ */
+ protected abstract AlgorithmParameters engineGetParameters();
+
+ /**
+ * Initializes this cipher with an operation mode, key, and source of
+ * randomness. If this cipher requires any other initializing data,
+ * for example an initialization vector, then it should generate it
+ * from the provided source of randomness.
+ *
+ * @param opmode The operation mode, one of {@link
+ * Cipher#DECRYPT_MODE}, {@link Cipher#ENCRYPT_MODE}, {@link
+ * Cipher#UNWRAP_MODE}, or {@link Cipher#WRAP_MODE}.
+ * @param key The key to initialize this cipher with.
+ * @param random The source of random bytes to use.
+ * @throws java.security.InvalidKeyException If the given key is not
+ * acceptable for this implementation.
+ */
+ protected abstract void engineInit(int opmode, Key key, SecureRandom random)
+ throws InvalidKeyException;
+
+ /**
+ * Initializes this cipher with an operation mode, key, parameters,
+ * and source of randomness. If this cipher requires any other
+ * initializing data, for example an initialization vector, then it should
+ * generate it from the provided source of randomness.
+ *
+ * @param opmode The operation mode, one of {@link
+ * Cipher#DECRYPT_MODE}, {@link Cipher#ENCRYPT_MODE}, {@link
+ * Cipher#UNWRAP_MODE}, or {@link Cipher#WRAP_MODE}.
+ * @param key The key to initialize this cipher with.
+ * @param params The algorithm parameters to initialize with.
+ * @param random The source of random bytes to use.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * given parameters are not appropriate for this
+ * implementation.
+ * @throws java.security.InvalidKeyException If the given key is not
+ * acceptable for this implementation.
+ */
+ protected abstract void
+ engineInit(int opmode, Key key, AlgorithmParameters params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException, InvalidKeyException;
+
+ /**
+ * Initializes this cipher with an operation mode, key, parameters,
+ * and source of randomness. If this cipher requires any other
+ * initializing data, for example an initialization vector, then it should
+ * generate it from the provided source of randomness.
+ *
+ * @param opmode The operation mode, one of {@link
+ * Cipher#DECRYPT_MODE}, {@link Cipher#ENCRYPT_MODE}, {@link
+ * Cipher#UNWRAP_MODE}, or {@link Cipher#WRAP_MODE}.
+ * @param key The key to initialize this cipher with.
+ * @param params The algorithm parameters to initialize with.
+ * @param random The source of random bytes to use.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * given parameters are not appropriate for this
+ * implementation.
+ * @throws java.security.InvalidKeyException If the given key is not
+ * acceptable for this implementation.
+ */
+ protected abstract void
+ engineInit(int opmode, Key key, AlgorithmParameterSpec params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException, InvalidKeyException;
+
+ /**
+ * Set the mode in which this cipher is to run.
+ *
+ * @param mode The name of the mode to use.
+ * @throws java.security.NoSuchAlgorithmException If the mode is
+ * not supported by this cipher's provider.
+ */
+ protected abstract void engineSetMode(String mode)
+ throws NoSuchAlgorithmException;
+
+ /**
+ * Set the method with which the input is to be padded.
+ *
+ * @param padding The name of the padding to use.
+ * @throws javax.crypto.NoSuchPaddingException If the padding is not
+ * supported by this cipher's provider.
+ */
+ protected abstract void engineSetPadding(String padding)
+ throws NoSuchPaddingException;
+
+ /**
+ * <p>Unwraps a previously-wrapped key.</p>
+ *
+ * <p>For compatibility this method is not declared
+ * <code>abstract</code>, and the default implementation will throw an
+ * {@link java.lang.UnsupportedOperationException}.</p>
+ *
+ * @param wrappedKey The wrapped key.
+ * @param wrappedKeyAlgorithm The name of the algorithm used to wrap
+ * this key.
+ * @param wrappedKeyType The type of wrapped key; one of
+ * {@link Cipher#PRIVATE_KEY},
+ * {@link Cipher#PUBLIC_KEY}, or
+ * {@link Cipher#SECRET_KEY}.
+ * @return The unwrapped key.
+ * @throws java.security.InvalidKeyException If the key cannot be
+ * unwrapped, or if <code>wrappedKeyType</code> is an
+ * inappropriate type for the unwrapped key.
+ * @throws java.security.NoSuchAlgorithmException If the
+ * <code>wrappedKeyAlgorithm</code> is unknown.
+ */
+ protected Key engineUnwrap(byte[] wrappedKey, String wrappedKeyAlgorithm,
+ int wrappedKeyType)
+ throws InvalidKeyException, NoSuchAlgorithmException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Continue with a multi-part transformation, returning a new array of
+ * the transformed bytes.
+ *
+ * @param input The next input bytes.
+ * @param inputOffset The index in the input array from which to start.
+ * @param inputLength The number of bytes to input.
+ * @return The transformed bytes.
+ */
+ protected abstract byte[]
+ engineUpdate(byte[] input, int inputOffset, int inputLength);
+
+ /**
+ * Continue with a multi-part transformation, storing the transformed
+ * bytes into the specified array.
+ *
+ * @param input The next input bytes.
+ * @param inputOffset The index in the input from which to start.
+ * @param inputLength The number of bytes to input.
+ * @param output The output buffer.
+ * @param outputOffset The index in the output array from which to start.
+ * @return The transformed bytes.
+ * @throws javax.crypto.ShortBufferException If there is not enough
+ * space in the output array to store the transformed bytes.
+ */
+ protected abstract int
+ engineUpdate(byte[] input, int inputOffset, int inputLength,
+ byte[] output, int outputOffset)
+ throws ShortBufferException;
+
+ /**
+ * <p>Wrap a key.</p>
+ *
+ * <p>For compatibility this method is not declared
+ * <code>abstract</code>, and the default implementation will throw an
+ * {@link java.lang.UnsupportedOperationException}.</p>
+ *
+ * @param key The key to wrap.
+ * @return The wrapped key.
+ * @throws java.security.InvalidKeyException If the key cannot be
+ * wrapped.
+ */
+ protected byte[] engineWrap(Key key) throws InvalidKeyException, IllegalBlockSizeException
+ {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/libjava/javax/crypto/EncryptedPrivateKeyInfo.java b/libjava/javax/crypto/EncryptedPrivateKeyInfo.java
new file mode 100644
index 00000000000..b64fbd6af5c
--- /dev/null
+++ b/libjava/javax/crypto/EncryptedPrivateKeyInfo.java
@@ -0,0 +1,284 @@
+/* EncryptedPrivateKeyInfo.java -- As in PKCS #8.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import gnu.java.security.OID;
+import gnu.java.security.der.DER;
+import gnu.java.security.der.DERReader;
+import gnu.java.security.der.DERValue;
+
+import java.io.IOException;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import java.security.AlgorithmParameters;
+import java.security.NoSuchAlgorithmException;
+import java.security.spec.InvalidKeySpecException;
+import java.security.spec.PKCS8EncodedKeySpec;
+
+/**
+ * An implementation of the <code>EncryptedPrivateKeyInfo</code> ASN.1
+ * type as specified in <a
+ * href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-8/">PKCS #8 -
+ * Private-Key Information Syntax Standard</a>.
+ *
+ * <p>The ASN.1 type <code>EncryptedPrivateKeyInfo</code> is:
+ *
+ * <blockquote>
+ * <pre>EncryptedPrivateKeyInfo ::= SEQUENCE {
+ * encryptionAlgorithm EncryptionAlgorithmIdentifier,
+ * encryptedData EncryptedData }
+ *
+ * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier
+ *
+ * EncrytpedData ::= OCTET STRING
+ *
+ * AlgorithmIdentifier ::= SEQUENCE {
+ * algorithm OBJECT IDENTIFIER,
+ * parameters ANY DEFINED BY algorithm OPTIONAL }</pre>
+ * </blockquote>
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see java.security.spec.PKCS8EncodedKeySpec
+ */
+public class EncryptedPrivateKeyInfo
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ /** The encrypted data. */
+ private byte[] encryptedData;
+
+ /** The encoded, encrypted key. */
+ private byte[] encoded;
+
+ /** The OID of the encryption algorithm. */
+ private OID algOid;
+
+ /** The encryption algorithm's parameters. */
+ private AlgorithmParameters params;
+
+ /** The encoded ASN.1 algorithm parameters. */
+ private byte[] encodedParams;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new <code>EncryptedPrivateKeyInfo</code> object from raw
+ * encrypted data and the parameters used for encryption.
+ *
+ * <p>The <code>encryptedData</code> array is cloned.
+ *
+ * @param params The encryption algorithm parameters.
+ * @param encryptedData The encrypted key data.
+ * @throws java.lang.IllegalArgumentException If the
+ * <code>encryptedData</code> array is empty (zero-length).
+ * @throws java.security.NoSuchAlgorithmException If the algorithm
+ * specified in the parameters is not supported.
+ * @throws java.lang.NullPointerException If <code>encryptedData</code>
+ * is null.
+ */
+ public EncryptedPrivateKeyInfo(AlgorithmParameters params,
+ byte[] encryptedData)
+ throws IllegalArgumentException, NoSuchAlgorithmException
+ {
+ if (encryptedData.length == 0)
+ {
+ throw new IllegalArgumentException("0-length encryptedData");
+ }
+ this.params = params;
+ algOid = new OID(params.getAlgorithm());
+ this.encryptedData = (byte[]) encryptedData.clone();
+ }
+
+ /**
+ * Create a new <code>EncryptedPrivateKeyInfo</code> from an encoded
+ * representation, parsing the ASN.1 sequence.
+ *
+ * @param encoded The encoded info.
+ * @throws java.io.IOException If parsing the encoded data fails.
+ * @throws java.lang.NullPointerException If <code>encoded</code> is
+ * null.
+ */
+ public EncryptedPrivateKeyInfo(byte[] encoded)
+ throws IOException
+ {
+ this.encoded = (byte[]) encoded.clone();
+ decode();
+ }
+
+ /**
+ * Create a new <code>EncryptedPrivateKeyInfo</code> from the cipher
+ * name and the encrytpedData.
+ *
+ * <p>The <code>encryptedData</code> array is cloned.
+ *
+ * @param algName The name of the algorithm (as an object identifier).
+ * @param encryptedData The encrypted key data.
+ * @throws java.lang.IllegalArgumentException If the
+ * <code>encryptedData</code> array is empty (zero-length).
+ * @throws java.security.NoSuchAlgorithmException If algName is not
+ * the name of a supported algorithm.
+ * @throws java.lang.NullPointerException If <code>encryptedData</code>
+ * is null.
+ */
+ public EncryptedPrivateKeyInfo(String algName, byte[] encryptedData)
+ throws IllegalArgumentException, NoSuchAlgorithmException,
+ NullPointerException
+ {
+ if (encryptedData.length == 0)
+ {
+ throw new IllegalArgumentException("0-length encryptedData");
+ }
+ this.algOid = new OID(algName);
+ this.encryptedData = (byte[]) encryptedData.clone();
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return the name of the cipher used to encrypt this key.
+ *
+ * @return The algorithm name.
+ */
+ public String getAlgName()
+ {
+ return algOid.toString();
+ }
+
+ public AlgorithmParameters getAlgParameters()
+ {
+ if (params == null && encodedParams != null)
+ {
+ try
+ {
+ params = AlgorithmParameters.getInstance(getAlgName());
+ params.init(encodedParams);
+ }
+ catch (NoSuchAlgorithmException ignore)
+ {
+ }
+ catch (IOException ignore)
+ {
+ }
+ }
+ return params;
+ }
+
+ public synchronized byte[] getEncoded() throws IOException
+ {
+ if (encoded == null) encode();
+ return (byte[]) encoded.clone();
+ }
+
+ public byte[] getEncryptedData()
+ {
+ return encryptedData;
+ }
+
+ public PKCS8EncodedKeySpec getKeySpec(Cipher cipher)
+ throws InvalidKeySpecException
+ {
+ try
+ {
+ return new PKCS8EncodedKeySpec(cipher.doFinal(encryptedData));
+ }
+ catch (Exception x)
+ {
+ throw new InvalidKeySpecException(x.toString());
+ }
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private void decode() throws IOException
+ {
+ DERReader der = new DERReader(encoded);
+ DERValue val = der.read();
+ if (val.getTag() != DER.SEQUENCE)
+ throw new IOException("malformed EncryptedPrivateKeyInfo");
+ val = der.read();
+ if (val.getTag() != DER.SEQUENCE)
+ throw new IOException("malformed AlgorithmIdentifier");
+ int algpLen = val.getLength();
+ DERValue oid = der.read();
+ if (oid.getTag() != DER.OBJECT_IDENTIFIER)
+ throw new IOException("malformed AlgorithmIdentifier");
+ algOid = (OID) oid.getValue();
+ if (algpLen == 0)
+ {
+ val = der.read();
+ if (val.getTag() != 0)
+ {
+ encodedParams = val.getEncoded();
+ der.read();
+ }
+ }
+ else if (oid.getEncodedLength() < val.getLength())
+ {
+ val = der.read();
+ encodedParams = val.getEncoded();
+ }
+ val = der.read();
+ if (val.getTag() != DER.OCTET_STRING)
+ throw new IOException("malformed AlgorithmIdentifier");
+ encryptedData = (byte[]) val.getValue();
+ }
+
+ private void encode() throws IOException
+ {
+ List algId = new ArrayList(2);
+ algId.add(new DERValue(DER.OBJECT_IDENTIFIER, algOid));
+ getAlgParameters();
+ if (params != null)
+ {
+ algId.add(DERReader.read(params.getEncoded()));
+ }
+ List epki = new ArrayList(2);
+ epki.add(new DERValue(DER.CONSTRUCTED|DER.SEQUENCE, algId));
+ epki.add(new DERValue(DER.OCTET_STRING, encryptedData));
+ encoded = new DERValue(DER.CONSTRUCTED|DER.SEQUENCE, epki).getEncoded();
+ }
+}
diff --git a/libjava/javax/crypto/ExemptionMechanism.java b/libjava/javax/crypto/ExemptionMechanism.java
new file mode 100644
index 00000000000..7fa658e9e37
--- /dev/null
+++ b/libjava/javax/crypto/ExemptionMechanism.java
@@ -0,0 +1,226 @@
+/* ExemptionMechanism.java -- Generic crypto-weakening mechanism.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.Security;
+import java.security.spec.AlgorithmParameterSpec;
+
+import gnu.java.security.Engine;
+
+/**
+ * An exemption mechanism, which will conditionally allow cryptography
+ * where it is not normally allowed, implements things such as <i>key
+ * recovery</i>, <i>key weakening</i>, or <i>key escrow</i>.
+ *
+ * <p><b>Implementation note</b>: this class is present for
+ * API-compatibility only; it is not actually used anywhere in this library
+ * and this library does not, in general, support crypto weakening.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class ExemptionMechanism
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ private static final String SERVICE = "ExemptionMechanism";
+ private ExemptionMechanismSpi emSpi;
+ private Provider provider;
+ private String mechanism;
+ private boolean virgin;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ protected ExemptionMechanism(ExemptionMechanismSpi emSpi, Provider provider,
+ String mechanism)
+ {
+ this.emSpi = emSpi;
+ this.provider = provider;
+ this.mechanism = mechanism;
+ virgin = true;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ public static final ExemptionMechanism getInstance(String mechanism)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ String msg = "";
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(mechanism, provs[i]);
+ }
+ catch (NoSuchAlgorithmException nsae)
+ {
+ msg = nsae.getMessage();
+ }
+ }
+ throw new NoSuchAlgorithmException(msg);
+ }
+
+ public static final ExemptionMechanism getInstance(String mechanism,
+ String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(mechanism, p);
+ }
+
+ public static final ExemptionMechanism getInstance(String mechanism,
+ Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ try
+ {
+ return new ExemptionMechanism((ExemptionMechanismSpi)
+ Engine.getInstance(SERVICE, mechanism, provider),
+ provider, mechanism);
+ }
+ catch (InvocationTargetException ite)
+ {
+ if (ite.getCause() instanceof NoSuchAlgorithmException)
+ throw (NoSuchAlgorithmException) ite.getCause();
+ else
+ throw new NoSuchAlgorithmException(mechanism);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(mechanism);
+ }
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ public final byte[] genExemptionBlob()
+ throws IllegalStateException, ExemptionMechanismException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return emSpi.engineGenExemptionBlob();
+ }
+
+ public final int genExemptionBlob(byte[] output)
+ throws IllegalStateException, ExemptionMechanismException,
+ ShortBufferException
+ {
+ return genExemptionBlob(output, 0);
+ }
+
+ public final int genExemptionBlob(byte[] output, int outputOffset)
+ throws IllegalStateException, ExemptionMechanismException,
+ ShortBufferException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return emSpi.engineGenExemptionBlob(output, outputOffset);
+ }
+
+ public final String getName()
+ {
+ return mechanism;
+ }
+
+ public final int getOutputSize(int inputLength) throws IllegalStateException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return emSpi.engineGetOutputSize(inputLength);
+ }
+
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ public final void init(Key key)
+ throws ExemptionMechanismException, InvalidKeyException
+ {
+ emSpi.engineInit(key);
+ virgin = false;
+ }
+
+ public final void init(Key key, AlgorithmParameters params)
+ throws ExemptionMechanismException, InvalidAlgorithmParameterException,
+ InvalidKeyException
+ {
+ emSpi.engineInit(key, params);
+ virgin = false;
+ }
+
+ public final void init(Key key, AlgorithmParameterSpec params)
+ throws ExemptionMechanismException, InvalidAlgorithmParameterException,
+ InvalidKeyException
+ {
+ emSpi.engineInit(key, params);
+ virgin = false;
+ }
+
+ public final boolean isCryptoAllowed(Key key)
+ throws ExemptionMechanismException
+ {
+ return true;
+ }
+}
diff --git a/libjava/javax/crypto/ExemptionMechanismException.java b/libjava/javax/crypto/ExemptionMechanismException.java
new file mode 100644
index 00000000000..42e1c5e9b77
--- /dev/null
+++ b/libjava/javax/crypto/ExemptionMechanismException.java
@@ -0,0 +1,81 @@
+/* ExemptionMechanismException -- An error in an exemption mechanism.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License along
+with GNU Classpath; if not, write to the
+
+ Free Software Foundation, Inc.,
+ 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307
+ USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+
+package javax.crypto;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * Signals a general exception in an {@link ExemptionMechanism}.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class ExemptionMechanismException extends GeneralSecurityException
+{
+
+ // Constant.
+ // ------------------------------------------------------------------------
+
+ /** Compatible with JDK1.4. */
+ private static final long serialVersionUID = 1572699429277957109L;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new exception with no detail message.
+ */
+ public ExemptionMechanismException()
+ {
+ super();
+ }
+
+ /**
+ * Create a new exception with a detail message.
+ *
+ * @param message The detail message.
+ */
+ public ExemptionMechanismException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/crypto/ExemptionMechanismSpi.java b/libjava/javax/crypto/ExemptionMechanismSpi.java
new file mode 100644
index 00000000000..78997ee0704
--- /dev/null
+++ b/libjava/javax/crypto/ExemptionMechanismSpi.java
@@ -0,0 +1,149 @@
+/* ExemptionMechanismSpi.java -- Exemption mechanism service provider interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * The <i>Service Provider Interface</i> (<b>SPI</b>) for the {@link
+ * ExemptionMechanism} class.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public abstract class ExemptionMechanismSpi
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new exemption mechanism SPI.
+ */
+ public ExemptionMechanismSpi()
+ {
+ }
+
+ // Abstract instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return a key blob for the key that this mechanism was initialized
+ * with.
+ *
+ * @return The key blob.
+ * @throws javax.crypto.ExemptionMechanismException If generating the
+ * blob fails.
+ */
+ protected abstract byte[] engineGenExemptionBlob()
+ throws ExemptionMechanismException;
+
+ /**
+ * Generate a key blob for the key that this mechanism was initialized
+ * with, storing it into the given byte array.
+ *
+ * @param output The destination for the key blob.
+ * @param outputOffset The index in the output array to start.
+ * @return The size of the key blob.
+ * @throws javax.crypto.ExemptionMechanismException If generating the
+ * blob fails.
+ * @throws javax.crypto.ShortBufferException If the output array is
+ * not large enough for the key blob.
+ */
+ protected abstract int engineGenExemptionBlob(byte[] output, int outputOffset)
+ throws ExemptionMechanismException, ShortBufferException;
+
+ /**
+ * Get the size of the output blob given an input key size. The actual
+ * blob may be shorter than the value returned by this method. Both
+ * values are in bytes.
+ *
+ * @param inputLength The input size.
+ * @return The output size.
+ */
+ protected abstract int engineGetOutputSize(int inputLength);
+
+ /**
+ * Initialize this mechanism with a key.
+ *
+ * @param key The key.
+ * @throws javax.crypto.ExemptionMechanismException If generating the
+ * blob fails.
+ * @throws java.security.InvalidKeyException If the supplied key
+ * cannot be used.
+ */
+ protected abstract void engineInit(Key key)
+ throws ExemptionMechanismException, InvalidKeyException;
+
+ /**
+ * Initialize this mechanism with a key and parameters.
+ *
+ * @param key The key.
+ * @param params The parameters.
+ * @throws javax.crypto.ExemptionMechanismException If generating the
+ * blob fails.
+ * @throws java.security.InvalidAlgorithmParameterExceptin If the
+ * supplied parameters are inappropriate.
+ * @throws java.security.InvalidKeyException If the supplied key
+ * cannot be used.
+ */
+ protected abstract void engineInit(Key key, AlgorithmParameters params)
+ throws ExemptionMechanismException, InvalidAlgorithmParameterException,
+ InvalidKeyException;
+
+ /**
+ * Initialize this mechanism with a key and parameters.
+ *
+ * @param key The key.
+ * @param params The parameters.
+ * @throws javax.crypto.ExemptionMechanismException If generating the
+ * blob fails.
+ * @throws java.security.InvalidAlgorithmParameterExceptin If the
+ * supplied parameters are inappropriate.
+ * @throws java.security.InvalidKeyException If the supplied key
+ * cannot be used.
+ */
+ protected abstract void engineInit(Key key, AlgorithmParameterSpec params)
+ throws ExemptionMechanismException, InvalidAlgorithmParameterException,
+ InvalidKeyException;
+}
diff --git a/libjava/javax/crypto/IllegalBlockSizeException.java b/libjava/javax/crypto/IllegalBlockSizeException.java
new file mode 100644
index 00000000000..1e442833c76
--- /dev/null
+++ b/libjava/javax/crypto/IllegalBlockSizeException.java
@@ -0,0 +1,71 @@
+/* IllegalBlockSizeException.java -- Signals illegal block sizes.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * This exception is thrown when finishing encryption without padding or
+ * decryption and the input is not a multiple of the cipher's block
+ * size.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class IllegalBlockSizeException extends GeneralSecurityException
+{
+
+ // Constant.
+ // ------------------------------------------------------------------------
+
+ /** Serialization constant. */
+ private static final long serialVersionUID = -1965144811953540392L;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ public IllegalBlockSizeException()
+ {
+ super();
+ }
+
+ public IllegalBlockSizeException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/crypto/KeyAgreement.java b/libjava/javax/crypto/KeyAgreement.java
new file mode 100644
index 00000000000..6f6ed34e04f
--- /dev/null
+++ b/libjava/javax/crypto/KeyAgreement.java
@@ -0,0 +1,373 @@
+/* KeyAgreement.java -- Engine for key agreement methods.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.spec.AlgorithmParameterSpec;
+
+import gnu.java.security.Engine;
+
+/**
+ * Key agreement is a method in which two or more parties may agree on a
+ * secret key for symmetric cryptography or message authentication
+ * without transmitting any secrets in the clear. Key agreement
+ * algorithms typically use a public/private <i>key pair</i>, and the
+ * public key (along with some additional information) is sent across
+ * untrusted networks.
+ *
+ * <p>The most common form of key agreement used today is the
+ * <i>Diffie-Hellman key exchange algorithm</i>, described in <a
+ * href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/">PKCS #3 -
+ * Diffie Hellman Key Agreement Standard</a>.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see KeyGenerator
+ * @see SecretKey
+ */
+public class KeyAgreement
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ private static final String SERVICE = "KeyAgreement";
+
+ /** The underlying key agreement implementation. */
+ private KeyAgreementSpi kaSpi;
+
+ /** The provider of this implementation. */
+ private Provider provider;
+
+ /** The name of this instance's algorithm. */
+ private String algorithm;
+
+ /** Singnals whether or not this instance has been initialized. */
+ private boolean virgin;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ protected KeyAgreement(KeyAgreementSpi kaSpi, Provider provider,
+ String algorithm)
+ {
+ this.kaSpi = kaSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ virgin = true;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get an implementation of an algorithm from the first provider that
+ * implements it.
+ *
+ * @param algorithm The name of the algorithm to get.
+ * @return The proper KeyAgreement instacne, if found.
+ * @throws java.security.NoSuchAlgorithmException If the specified
+ * algorithm is not implemented by any installed provider.
+ */
+ public static final KeyAgreement getInstance(String algorithm)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ String msg = algorithm;
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(algorithm, provs[i]);
+ }
+ catch (NoSuchAlgorithmException nsae)
+ {
+ msg = nsae.getMessage();
+ }
+ }
+ throw new NoSuchAlgorithmException(msg);
+ }
+
+ /**
+ * Get an implementation of an algorithm from a named provider.
+ *
+ * @param algorithm The name of the algorithm to get.
+ * @param provider The name of the provider from which to get the
+ * implementation.
+ * @return The proper KeyAgreement instance, if found.
+ * @throws java.security.NoSuchAlgorithmException If the named provider
+ * does not implement the algorithm.
+ * @throws java.security.NoSuchProviderException If the named provider
+ * does not exist.
+ */
+ public static final KeyAgreement getInstance(String algorithm,
+ String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(algorithm, p);
+ }
+
+ /**
+ * Get an implementation of an algorithm from a specific provider.
+ *
+ * @param algorithm The name of the algorithm to get.
+ * @param provider The provider from which to get the implementation.
+ * @return The proper KeyAgreement instance, if found.
+ * @throws java.security.NoSuchAlgorithmException If this provider
+ * does not implement the algorithm.
+ */
+ public static final KeyAgreement getInstance(String algorithm,
+ Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ try
+ {
+ return new KeyAgreement((KeyAgreementSpi)
+ Engine.getInstance(SERVICE, algorithm, provider),
+ provider, algorithm);
+ }
+ catch (InvocationTargetException ite)
+ {
+ if (ite.getCause() == null)
+ throw new NoSuchAlgorithmException(algorithm);
+ if (ite.getCause() instanceof NoSuchAlgorithmException)
+ throw (NoSuchAlgorithmException) ite.getCause();
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Do a phase in the key agreement. The number of times this method is
+ * called depends upon the algorithm and the number of parties
+ * involved, but must be called at least once with the
+ * <code>lastPhase</code> flag set to <code>true</code>.
+ *
+ * @param key The key for this phase.
+ * @param lastPhase Should be <code>true</code> if this will be the
+ * last phase before generating the shared secret.
+ * @return The intermediate result, or <code>null</code> if there is
+ * no intermediate result.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized.
+ * @throws java.security.InvalidKeyException If the key is
+ * inappropriate for this algorithm.
+ */
+ public final Key doPhase(Key key, boolean lastPhase)
+ throws IllegalStateException, InvalidKeyException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return kaSpi.engineDoPhase(key, lastPhase);
+ }
+
+ /**
+ * Generate the shared secret in a new byte array.
+ *
+ * @return The shared secret.
+ * @throws java.lang.IllegalStateException If this instnace has not
+ * been initialized, or if not enough calls to
+ * <code>doPhase</code> have been made.
+ */
+ public final byte[] generateSecret() throws IllegalStateException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return kaSpi.engineGenerateSecret();
+ }
+
+ /**
+ * Generate the shared secret and store it into the supplied array.
+ *
+ * @param sharedSecret The array in which to store the secret.
+ * @param offset The index in <code>sharedSecret</code> to start
+ * storing data.
+ * @return The length of the shared secret, in bytes.
+ * @throws java.lang.IllegalStateException If this instnace has not
+ * been initialized, or if not enough calls to
+ * <code>doPhase</code> have been made.
+ * @throws javax.crypto.ShortBufferException If the supplied array is
+ * not large enough to store the result.
+ */
+ public final int generateSecret(byte[] sharedSecret, int offset)
+ throws IllegalStateException, ShortBufferException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return kaSpi.engineGenerateSecret(sharedSecret, offset);
+ }
+
+ /**
+ * Generate the shared secret and return it as an appropriate {@link
+ * SecretKey}.
+ *
+ * @param algorithm The secret key's algorithm.
+ * @return The shared secret as a secret key.
+ * @throws java.lang.IllegalStateException If this instnace has not
+ * been initialized, or if not enough calls to
+ * <code>doPhase</code> have been made.
+ * @throws java.security.InvalidKeyException If the shared secret
+ * cannot be used to make a {@link SecretKey}.
+ * @throws java.security.NoSuchAlgorithmException If the specified
+ * algorithm does not exist.
+ */
+ public final SecretKey generateSecret(String algorithm)
+ throws IllegalStateException, InvalidKeyException, NoSuchAlgorithmException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ return kaSpi.engineGenerateSecret(algorithm);
+ }
+
+ /**
+ * Return the name of this key-agreement algorithm.
+ *
+ * @return The algorithm name.
+ */
+ public final String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Return the provider of the underlying implementation.
+ *
+ * @return The provider.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Initialize this key agreement with a key. This method will use the
+ * highest-priority {@link java.security.SecureRandom} as its source
+ * of randomness.
+ *
+ * @param key The key, usually the user's private key.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * not appropriate.
+ */
+ public final void init(Key key) throws InvalidKeyException
+ {
+ init(key, new SecureRandom());
+ }
+
+ /**
+ * Initialize this key agreement with a key and a source of
+ * randomness.
+ *
+ * @param key The key, usually the user's private key.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * not appropriate.
+ */
+ public final void init(Key key, SecureRandom random)
+ throws InvalidKeyException
+ {
+ kaSpi.engineInit(key, random);
+ virgin = false; // w00t!
+ }
+
+ /**
+ * Initialize this key agreement with a key and parameters. This
+ * method will use the highest-priority {@link
+ * java.security.SecureRandom} as its source of randomness.
+ *
+ * @param key The key, usually the user's private key.
+ * @param params The algorithm parameters.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are not appropriate.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * not appropriate.
+ */
+ public final void init(Key key, AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException, InvalidKeyException
+ {
+ init(key, params, new SecureRandom());
+ }
+
+ /**
+ * Initialize this key agreement with a key, parameters, and source of
+ * randomness.
+ *
+ * @param key The key, usually the user's private key.
+ * @param params The algorithm parameters.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are not appropriate.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * not appropriate.
+ */
+ public final void init(Key key, AlgorithmParameterSpec params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException, InvalidKeyException
+ {
+ kaSpi.engineInit(key, params, random);
+ virgin = false; // w00t!
+ }
+}
diff --git a/libjava/javax/crypto/KeyAgreementSpi.java b/libjava/javax/crypto/KeyAgreementSpi.java
new file mode 100644
index 00000000000..231f112794b
--- /dev/null
+++ b/libjava/javax/crypto/KeyAgreementSpi.java
@@ -0,0 +1,160 @@
+/* KeyAgreementSpi.java -- The key agreement service provider interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * This is the <i>Service Provider Interface</i> (<b>SPI</b>) for the
+ * {@link javax.crypto.KeyAgreement} class.
+ *
+ * <p>Providers wishing to implement a key agreement algorithm must
+ * subclass this and provide an appropriate implementation for all the
+ * abstract methods below, and provide an appropriate entry in the
+ * master {@link java.security.Provider} class (the service name for key
+ * agreement algorithms is <code>"KeyAgreement"</code>).
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see KeyAgreement
+ * @see SecretKey
+ */
+public abstract class KeyAgreementSpi
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new KeyAgreementSpi instance.
+ */
+ public KeyAgreementSpi()
+ {
+ }
+
+ // Abstract instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Do a phase in the key agreement.
+ *
+ * @param key The key to use for this phase.
+ * @param lastPhase <code>true</code> if this call should be the last
+ * phase.
+ * @return The intermediate result, or <code>null</code> if there is
+ * no intermediate result.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * not appropriate.
+ */
+ protected abstract Key engineDoPhase(Key key, boolean lastPhase)
+ throws IllegalStateException, InvalidKeyException;
+
+ /**
+ * Generate the shared secret in a new byte array.
+ *
+ * @return The shared secret in a new byte array.
+ * @throws java.lang.IllegalStateException If this key agreement is
+ * not ready to generate the secret.
+ */
+ protected abstract byte[] engineGenerateSecret()
+ throws IllegalStateException;
+
+ /**
+ * Generate the shared secret, storing it into the specified array.
+ *
+ * @param sharedSecret The byte array in which to store the secret.
+ * @param offset The offset into the byte array to start.
+ * @return The size of the shared secret.
+ * @throws java.lang.IllegalStateException If this key agreement is
+ * not ready to generate the secret.
+ * @throws javax.crypto.ShortBufferException If there is not enough
+ * space in the supplied array for the shared secret.
+ */
+ protected abstract int engineGenerateSecret(byte[] sharedSecret, int offset)
+ throws IllegalStateException, ShortBufferException;
+
+ /**
+ * Generate the shared secret and return it as a {@link SecretKey}.
+ *
+ * @param algorithm The algorithm with which to generate the secret key.
+ * @return The shared secret as a secret key.
+ * @throws java.lang.IllegalStateException If this key agreement is
+ * not ready to generate the secret.
+ * @throws java.security.InvalidKeyException If the shared secret
+ * cannot be made into a {@link SecretKey}.
+ * @throws java.security.NoSuchAlgorithmException If
+ * <code>algorithm</code> cannot be found.
+ */
+ protected abstract SecretKey engineGenerateSecret(String algorithm)
+ throws IllegalStateException, InvalidKeyException, NoSuchAlgorithmException;
+
+ /**
+ * Initialize this key agreement with a key, parameters, and source of
+ * randomness.
+ *
+ * @param key The key to initialize with, usually a private key.
+ * @param params The parameters to initialize with.
+ * @param random The source of randomness to use.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inappropriate.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * inappropriate.
+ */
+ protected abstract void engineInit(Key key, AlgorithmParameterSpec params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException, InvalidKeyException;
+
+ /**
+ * Initialize this key agreement with a key and source of randomness.
+ *
+ * @param key The key to initialize with, usually a private key.
+ * @param random The source of randomness to use.
+ * @throws java.security.InvalidKeyException If the supplied key is
+ * inappropriate.
+ */
+ protected abstract void engineInit(Key key, SecureRandom random)
+ throws InvalidKeyException;
+}
diff --git a/libjava/javax/crypto/KeyGenerator.java b/libjava/javax/crypto/KeyGenerator.java
new file mode 100644
index 00000000000..35753b036de
--- /dev/null
+++ b/libjava/javax/crypto/KeyGenerator.java
@@ -0,0 +1,284 @@
+/* KeyGenerator.java -- Interface to a symmetric key generator.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.spec.AlgorithmParameterSpec;
+
+import gnu.java.security.Engine;
+
+/**
+ * A generic producer of keys for symmetric cryptography. The keys
+ * returned may be simple wrappers around byte arrays, or, if the
+ * target cipher requires them, more complex objects.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see Cipher
+ * @see Mac
+ */
+public class KeyGenerator
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ private static final String SERVICE = "KeyGenerator";
+
+ /** The underlying generator implementation. */
+ private KeyGeneratorSpi kgSpi;
+
+ /** The provider of the implementation. */
+ private Provider provider;
+
+ /** The name of the algorithm. */
+ private String algorithm;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new key generator.
+ *
+ * @param kgSpi The underlying generator.
+ * @param provider The provider of this implementation.
+ * @param algorithm The algorithm's name.
+ */
+ protected KeyGenerator(KeyGeneratorSpi kgSpi, Provider provider,
+ String algorithm)
+ {
+ this.kgSpi = kgSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new key generator, returning the first available
+ * implementation.
+ *
+ * @param algorithm The generator algorithm name.
+ * @throws java.security.NoSuchAlgorithmException If the specified
+ * algorithm does not exist.
+ */
+ public static final KeyGenerator getInstance(String algorithm)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ String msg = algorithm;
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(algorithm, provs[i]);
+ }
+ catch (NoSuchAlgorithmException nsae)
+ {
+ msg = nsae.getMessage();
+ }
+ }
+ throw new NoSuchAlgorithmException(msg);
+ }
+
+ /**
+ * Create a new key generator from the named provider.
+ *
+ * @param algorithm The generator algorithm name.
+ * @param provider The name of the provider to use.
+ * @return An appropriate key generator, if found.
+ * @throws java.security.NoSuchAlgorithmException If the specified
+ * algorithm is not implemented by the named provider.
+ * @throws java.security.NoSuchProviderException If the named provider
+ * does not exist.
+ */
+ public static final KeyGenerator getInstance(String algorithm, String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(algorithm, p);
+ }
+
+ /**
+ * Create a new key generator from the supplied provider.
+ *
+ * @param algorithm The generator algorithm name.
+ * @param provider The provider to use.
+ * @return An appropriate key generator, if found.
+ * @throws java.security.NoSuchAlgorithmException If the specified
+ * algorithm is not implemented by the provider.
+ */
+ public static final KeyGenerator getInstance(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ try
+ {
+ return new KeyGenerator((KeyGeneratorSpi)
+ Engine.getInstance(SERVICE, algorithm, provider),
+ provider, algorithm);
+ }
+ catch (InvocationTargetException ite)
+ {
+ if (ite.getCause() == null)
+ throw new NoSuchAlgorithmException(algorithm);
+ if (ite.getCause() instanceof NoSuchAlgorithmException)
+ throw (NoSuchAlgorithmException) ite.getCause();
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Generate a key.
+ *
+ * @return The new key.
+ */
+ public final SecretKey generateKey()
+ {
+ return kgSpi.engineGenerateKey();
+ }
+
+ /**
+ * Return the name of this key generator.
+ *
+ * @return The algorithm name.
+ */
+ public final String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Return the provider of the underlying implementation.
+ *
+ * @return The provider.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Initialize this key generator with a set of parameters; the
+ * highest-priority {@link java.security.SecureRandom} implementation
+ * will be used.
+ *
+ * @param params The algorithm parameters.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inapproprate.
+ */
+ public final void init(AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException
+ {
+ init(params, new SecureRandom());
+ }
+
+ /**
+ * Initialize this key generator with a set of parameters and a source
+ * of randomness.
+ *
+ * @param params The algorithm parameters.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * supplied parameters are inapproprate.
+ */
+ public final void init(AlgorithmParameterSpec params, SecureRandom random)
+ throws InvalidAlgorithmParameterException
+ {
+ kgSpi.engineInit(params, random);
+ }
+
+ /**
+ * Initialize this key generator with a key size (in bits); the
+ * highest-priority {@link java.security.SecureRandom} implementation
+ * will be used.
+ *
+ * @param keySize The target key size, in bits.
+ * @throws java.security.InvalidParameterException If the
+ * key size is unsupported.
+ */
+ public final void init(int keySize)
+ {
+ init(keySize, new SecureRandom());
+ }
+
+ /**
+ * Initialize this key generator with a key size (in bits) and a
+ * source of randomness.
+ *
+ * @param keySize The target key size, in bits.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * key size is unsupported.
+ */
+ public final void init(int keySize, SecureRandom random)
+ {
+ kgSpi.engineInit(keySize, random);
+ }
+
+ /**
+ * Initialize this key generator with a source of randomness. The
+ * implementation-specific default parameters (such as key size) will
+ * be used.
+ *
+ * @param random The source of randomness.
+ */
+ public final void init(SecureRandom random)
+ {
+ kgSpi.engineInit(random);
+ }
+}
diff --git a/libjava/javax/crypto/KeyGeneratorSpi.java b/libjava/javax/crypto/KeyGeneratorSpi.java
new file mode 100644
index 00000000000..fcf229b955c
--- /dev/null
+++ b/libjava/javax/crypto/KeyGeneratorSpi.java
@@ -0,0 +1,112 @@
+/* KeyGeneratorSpi.java -- The key generator service provider interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * The <i>Service Provider Interface</i> (<b>SPI</b>) for the {@link
+ * KeyGenerator} class.
+ *
+ * <p>Providers wishing to implement a key generator must subclass this
+ * and provide an appropriate implementation for all the abstract
+ * methods below, and provide an appropriate entry in the master {@link
+ * java.security.Provider} class (the service name for key generators is
+ * <code>"KeyGenerator"</code>).
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see KeyGenerator
+ */
+public abstract class KeyGeneratorSpi
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /** Create a new key generator SPI. */
+ public KeyGeneratorSpi()
+ {
+ }
+
+ // Abstract instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Generate a key, returning it as a {@link SecretKey}.
+ *
+ * @return The generated key.
+ */
+ protected abstract SecretKey engineGenerateKey();
+
+ /**
+ * Initialize this key generator with parameters and a source of
+ * randomness.
+ *
+ * @param params The parameters.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * parameters are inappropriate for this instance.
+ */
+ protected abstract void engineInit(AlgorithmParameterSpec params,
+ SecureRandom random)
+ throws InvalidAlgorithmParameterException;
+
+ /**
+ * Initialize this key generator with a key size (in bits) and a
+ * source of randomness.
+ *
+ * @param keySize The target key size, in bits.
+ * @param random The source of randomness.
+ * @throws java.security.InvalidParameterException If the
+ * key size is illogical or unsupported.
+ */
+ protected abstract void engineInit(int keySize, SecureRandom random);
+
+ /**
+ * Initialize this key generator with a source of randomness; the
+ * implementation should use reasonable default parameters (such as
+ * generated key size).
+ *
+ * @param random The source of randomness.
+ */
+ protected abstract void engineInit(SecureRandom random);
+}
diff --git a/libjava/javax/crypto/Mac.java b/libjava/javax/crypto/Mac.java
new file mode 100644
index 00000000000..55f5be61b17
--- /dev/null
+++ b/libjava/javax/crypto/Mac.java
@@ -0,0 +1,414 @@
+/* Mac.java -- The message authentication code interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.Security;
+import java.security.spec.AlgorithmParameterSpec;
+
+import gnu.java.security.Engine;
+
+/**
+ * This class implements a "message authentication code" (MAC), a method
+ * to ensure the integrity of data transmitted between two parties who
+ * share a common secret key.
+ *
+ * <p>The best way to describe a MAC is as a <i>keyed one-way hash
+ * function</i>, which looks like:
+ *
+ * <blockquote><p><code>D = MAC(K, M)</code></blockquote>
+ *
+ * <p>where <code>K</code> is the key, <code>M</code> is the message,
+ * and <code>D</code> is the resulting digest. One party will usually
+ * send the concatenation <code>M || D</code> to the other party, who
+ * will then verify <code>D</code> by computing <code>D'</code> in a
+ * similar fashion. If <code>D == D'</code>, then the message is assumed
+ * to be authentic.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class Mac implements Cloneable
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ private static final String SERVICE = "Mac";
+
+ /** The underlying MAC implementation. */
+ private MacSpi macSpi;
+
+ /** The provider we got our implementation from. */
+ private Provider provider;
+
+ /** The name of the algorithm. */
+ private String algorithm;
+
+ /** Whether or not we've been initialized. */
+ private boolean virgin;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates a new Mac instance.
+ *
+ * @param macSpi The underlying MAC implementation.
+ * @param provider The provider of this implementation.
+ * @param algorithm The name of this MAC algorithm.
+ */
+ protected Mac(MacSpi macSpi, Provider provider, String algorithm)
+ {
+ this.macSpi = macSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ virgin = true;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get an instance of the named algorithm from the first provider with
+ * an appropriate implementation.
+ *
+ * @param algorithm The name of the algorithm.
+ * @return An appropriate Mac instance, if the specified algorithm
+ * is implemented by a provider.
+ * @throws java.security.NoSuchAlgorithmException If no implementation
+ * of the named algorithm is installed.
+ */
+ public static final Mac getInstance(String algorithm)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ String msg = "";
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(algorithm, provs[i]);
+ }
+ catch (NoSuchAlgorithmException nsae)
+ {
+ msg = nsae.getMessage();
+ }
+ }
+ throw new NoSuchAlgorithmException(msg);
+ }
+
+ /**
+ * Get an instance of the named algorithm from the named provider.
+ *
+ * @param algorithm The name of the algorithm.
+ * @param provider The name of the provider.
+ * @return An appropriate Mac instance, if the specified algorithm is
+ * implemented by the named provider.
+ * @throws java.security.NoSuchAlgorithmException If the named provider
+ * has no implementation of the algorithm.
+ * @throws java.security.NoSuchProviderException If the named provider
+ * does not exist.
+ */
+ public static final Mac getInstance(String algorithm, String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(algorithm, p);
+ }
+
+ /**
+ * Get an instance of the named algorithm from a provider.
+ *
+ * @param algorithm The name of the algorithm.
+ * @param provider The provider.
+ * @return An appropriate Mac instance, if the specified algorithm is
+ * implemented by the provider.
+ * @throws java.security.NoSuchAlgorithmException If the provider
+ * has no implementation of the algorithm.
+ */
+ public static final Mac getInstance(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ try
+ {
+ return new Mac((MacSpi) Engine.getInstance(SERVICE, algorithm, provider),
+ provider, algorithm);
+ }
+ catch (InvocationTargetException ite)
+ {
+ if (ite.getCause() == null)
+ throw new NoSuchAlgorithmException(algorithm);
+ if (ite.getCause() instanceof NoSuchAlgorithmException)
+ throw (NoSuchAlgorithmException) ite.getCause();
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Finishes the computation of a MAC and returns the digest.
+ *
+ * <p>After this method succeeds, it may be used again as just after a
+ * call to <code>init</code>, and can compute another MAC using the
+ * same key and parameters.
+ *
+ * @return The message authentication code.
+ * @throws java.lang.IllegalStateException If this instnace has not
+ * been initialized.
+ */
+ public final byte[] doFinal() throws IllegalStateException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ byte[] digest = macSpi.engineDoFinal();
+ reset();
+ return digest;
+ }
+
+ /**
+ * Finishes the computation of a MAC with a final byte array (or
+ * computes a MAC over those bytes only) and returns the digest.
+ *
+ * <p>After this method succeeds, it may be used again as just after a
+ * call to <code>init</code>, and can compute another MAC using the
+ * same key and parameters.
+ *
+ * @param input The bytes to add.
+ * @return The message authentication code.
+ * @throws java.lang.IllegalStateException If this instnace has not
+ * been initialized.
+ */
+ public final byte[] doFinal(byte[] input) throws IllegalStateException
+ {
+ update(input);
+ byte[] digest = macSpi.engineDoFinal();
+ reset();
+ return digest;
+ }
+
+ /**
+ * Finishes the computation of a MAC and places the result into the
+ * given array.
+ *
+ * <p>After this method succeeds, it may be used again as just after a
+ * call to <code>init</code>, and can compute another MAC using the
+ * same key and parameters.
+ *
+ * @param output The destination for the result.
+ * @param outOffset The index in the output array to start.
+ * @return The message authentication code.
+ * @throws java.lang.IllegalStateException If this instnace has not
+ * been initialized.
+ * @throws javax.crypto.ShortBufferException If <code>output</code> is
+ * not large enough to hold the result.
+ */
+ public final void doFinal(byte[] output, int outOffset)
+ throws IllegalStateException, ShortBufferException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ if (output.length - outOffset < getMacLength())
+ {
+ throw new ShortBufferException();
+ }
+ byte[] mac = macSpi.engineDoFinal();
+ System.arraycopy(mac, 0, output, outOffset, getMacLength());
+ reset();
+ }
+
+ /**
+ * Returns the name of this MAC algorithm.
+ *
+ * @return The MAC name.
+ */
+ public final String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Get the size of the MAC. This is the size of the array returned by
+ * {@link #doFinal()} and {@link #doFinal(byte[])}, and the minimum
+ * number of bytes that must be available in the byte array passed to
+ * {@link #doFinal(byte[],int)}.
+ *
+ * @return The MAC length.
+ */
+ public int getMacLength()
+ {
+ return macSpi.engineGetMacLength();
+ }
+
+ /**
+ * Get the provider of the underlying implementation.
+ *
+ * @return The provider.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Initialize this MAC with a key and no parameters.
+ *
+ * @param key The key to initialize this instance with.
+ * @throws java.security.InvalidKeyException If the key is
+ * unacceptable.
+ */
+ public final void init(Key key) throws InvalidKeyException
+ {
+ try
+ {
+ init(key, null);
+ }
+ catch (InvalidAlgorithmParameterException iape)
+ {
+ throw new IllegalArgumentException(algorithm + " needs parameters");
+ }
+ }
+
+ /**
+ * Initialize this MAC with a key and parameters.
+ *
+ * @param key The key to initialize this instance with.
+ * @param params The algorithm-specific parameters.
+ * @throws java.security.InvalidAlgorithmParameterException If the
+ * algorithm parameters are unacceptable.
+ * @throws java.security.InvalidKeyException If the key is
+ * unacceptable.
+ */
+ public final void init(Key key, AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException, InvalidKeyException
+ {
+ macSpi.engineInit(key, params);
+ virgin = false; // w00t!
+ }
+
+ /**
+ * Reset this instance. A call to this method returns this instance
+ * back to the state it was in just after it was initialized.
+ */
+ public final void reset()
+ {
+ macSpi.engineReset();
+ }
+
+ /**
+ * Update the computation with a single byte.
+ *
+ * @param input The next byte.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized.
+ */
+ public final void update(byte input) throws IllegalStateException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ macSpi.engineUpdate(input);
+ }
+
+ /**
+ * Update the computation with a byte array.
+ *
+ * @param input The next bytes.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized.
+ */
+ public final void update(byte[] input) throws IllegalStateException
+ {
+ update(input, 0, input.length);
+ }
+
+ /**
+ * Update the computation with a portion of a byte array.
+ *
+ * @param input The next bytes.
+ * @param offset The index in <code>input</code> to start.
+ * @param length The number of bytes to update.
+ * @throws java.lang.IllegalStateException If this instance has not
+ * been initialized.
+ */
+ public final void update(byte[] input, int offset, int length)
+ throws IllegalStateException
+ {
+ if (virgin)
+ {
+ throw new IllegalStateException("not initialized");
+ }
+ macSpi.engineUpdate(input, offset, length);
+ }
+
+ /**
+ * Clone this instance, if the underlying implementation supports it.
+ *
+ * @return A clone of this instance.
+ * @throws java.lang.CloneNotSupportedException If the underlying
+ * implementation is not cloneable.
+ */
+ public Object clone() throws CloneNotSupportedException
+ {
+ Mac result = new Mac((MacSpi) macSpi.clone(), provider, algorithm);
+ result.virgin = virgin;
+ return result;
+ }
+}
diff --git a/libjava/javax/crypto/MacSpi.java b/libjava/javax/crypto/MacSpi.java
new file mode 100644
index 00000000000..4d63b6a8efc
--- /dev/null
+++ b/libjava/javax/crypto/MacSpi.java
@@ -0,0 +1,145 @@
+/* MacSpi.java -- The MAC service provider interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * This is the <i>Service Provider Interface</i> (<b>SPI</b>) for the
+ * {@link Mac} class.
+ *
+ * <p>Providers wishing to implement a Mac must subclass this class and
+ * provide appropriate implementations of all its abstract methods,
+ * then provide an entry pointing to this implementation in the master
+ * {@link java.security.Provider} class.
+ *
+ * <p>Implemetations may optionally implement the {@link
+ * java.lang.Cloneable} interface.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public abstract class MacSpi
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new MacSpi instance.
+ */
+ public MacSpi()
+ {
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns a clone of this instance if cloning is supported.
+ *
+ * @return A clone of this instance.
+ * @throws java.lang.CloneNotSupportedException If this instance does
+ * not support cloneing.
+ */
+ public Object clone() throws CloneNotSupportedException
+ {
+ return super.clone();
+ }
+
+ // Abstract instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Finalize the computation of this MAC and return the result as a
+ * byte array.
+ *
+ * @return The MAC.
+ */
+ protected abstract byte[] engineDoFinal();
+
+ /**
+ * Return the total length, in bytes, of the computed MAC (the length
+ * of the byte array returned by {@link #doFinal()}.
+ *
+ * @return The MAC length.
+ */
+ protected abstract int engineGetMacLength();
+
+ /**
+ * Initialize (or re-initialize) this instance.
+ *
+ * @param key The key to use.
+ * @param params The parameters to use.
+ * @throws java.security.InvalidAlgorithmParameterException If this
+ * instance rejects the specified parameters.
+ * @throws java.security.InvalidKeyException If this instance rejects
+ * the specified key.
+ */
+ protected abstract void engineInit(Key key, AlgorithmParameterSpec params)
+ throws InvalidAlgorithmParameterException, InvalidKeyException;
+
+ /**
+ * Reset this instance. After this method succeeds, the state of this
+ * instance should be the same as it was before any data was input
+ * (possibly after a call to {@link
+ * #init(java.security.Key,java.security.spec.AlgorithmParameterSpec)},
+ * possibly not).
+ */
+ protected abstract void engineReset();
+
+ /**
+ * Update this MAC with a single byte.
+ *
+ * @param input The next byte.
+ */
+ protected abstract void engineUpdate(byte input);
+
+ /**
+ * Update this MAC with a portion of a byte array.
+ *
+ * @param input The next bytes.
+ * @param offset The index in <code>input</code> at which to start.
+ * @param length The number of bytes to update.
+ */
+ protected abstract void engineUpdate(byte[] input, int offset, int length);
+}
diff --git a/libjava/javax/crypto/NoSuchPaddingException.java b/libjava/javax/crypto/NoSuchPaddingException.java
new file mode 100644
index 00000000000..3acd7ae68f6
--- /dev/null
+++ b/libjava/javax/crypto/NoSuchPaddingException.java
@@ -0,0 +1,71 @@
+/* NoSuchPaddingException.java -- Signals an unknown padding scheme.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * This exception is thrown when a particular padding scheme is
+ * requested but is not available.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class NoSuchPaddingException extends GeneralSecurityException
+{
+
+ // Constant.
+ // ------------------------------------------------------------------------
+
+ /** Serialization constant. */
+ private static final long serialVersionUID = -4572885201200175466L;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ public NoSuchPaddingException()
+ {
+ super();
+ }
+
+ public NoSuchPaddingException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/crypto/NullCipher.java b/libjava/javax/crypto/NullCipher.java
new file mode 100644
index 00000000000..95f3a8e8f2d
--- /dev/null
+++ b/libjava/javax/crypto/NullCipher.java
@@ -0,0 +1,62 @@
+/* NullCipher.java -- The identity cipher.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+/**
+ * Trivial subclass of Cipher that implements the <i>identity
+ * transformation</i>, where the input is always copied to the output
+ * unchanged. Null ciphers can be instantiated with the public
+ * constructor.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class NullCipher extends Cipher
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new identity cipher.
+ */
+ public NullCipher()
+ {
+ super(new NullCipherImpl(), null, "NULL");
+ }
+}
diff --git a/libjava/javax/crypto/NullCipherImpl.java b/libjava/javax/crypto/NullCipherImpl.java
new file mode 100644
index 00000000000..b203d24bf78
--- /dev/null
+++ b/libjava/javax/crypto/NullCipherImpl.java
@@ -0,0 +1,127 @@
+/* NullCipherImpl.java -- implementation of NullCipher.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.AlgorithmParameters;
+import java.security.Key;
+import java.security.SecureRandom;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * Implementation of the identity cipher.
+ */
+final class NullCipherImpl extends CipherSpi
+{
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ NullCipherImpl()
+ {
+ super();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ protected void engineSetMode(String mode) { }
+ protected void engineSetPadding(String padding) { }
+
+ protected int engineGetBlockSize()
+ {
+ return 1;
+ }
+
+ protected int engineGetOutputSize(int inputLen)
+ {
+ return inputLen;
+ }
+
+ protected byte[] engineGetIV()
+ {
+ return null;
+ }
+
+ protected AlgorithmParameters engineGetParameters()
+ {
+ return null;
+ }
+
+ protected void engineInit(int mode, Key key, SecureRandom random) { }
+ protected void engineInit(int mode, Key key, AlgorithmParameterSpec spec, SecureRandom random) { }
+ protected void engineInit(int mode, Key key, AlgorithmParameters params, SecureRandom random) { }
+
+ protected byte[] engineUpdate(byte[] input, int inputOffset, int inputLen)
+ {
+ if (input == null)
+ return new byte[0];
+ if (inputOffset < 0 || inputLen < 0 || inputOffset + inputLen > input.length)
+ throw new ArrayIndexOutOfBoundsException();
+ byte[] output = new byte[inputLen];
+ System.arraycopy(input, inputOffset, output, 0, inputLen);
+ return output;
+ }
+
+ protected int engineUpdate(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset)
+ throws ShortBufferException
+ {
+ if (input == null)
+ return 0;
+ if (inputOffset < 0 || inputLen < 0 || inputOffset + inputLen > input.length
+ || outputOffset < 0)
+ throw new ArrayIndexOutOfBoundsException();
+ if (output.length - outputOffset < inputLen)
+ throw new ShortBufferException();
+ System.arraycopy(input, inputOffset, output, outputOffset, inputLen);
+ return inputLen;
+ }
+
+ protected byte[] engineDoFinal(byte[] input, int inputOffset, int inputLen)
+ {
+ return engineUpdate(input, inputOffset, inputLen);
+ }
+
+ protected int engineDoFinal(byte[] input, int inputOffset, int inputLen,
+ byte[] output, int outputOffset)
+ throws ShortBufferException
+ {
+ return engineUpdate(input, inputOffset, inputLen, output, outputOffset);
+ }
+}
diff --git a/libjava/javax/crypto/SealedObject.java b/libjava/javax/crypto/SealedObject.java
new file mode 100644
index 00000000000..9bbbe29be01
--- /dev/null
+++ b/libjava/javax/crypto/SealedObject.java
@@ -0,0 +1,355 @@
+/* SealedObject.java -- An encrypted Serializable object.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+import java.security.AlgorithmParameters;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.InvalidKeyException;
+import java.security.Key;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+
+/**
+ * This class allows any {@link java.io.Serializable} object to be
+ * stored in an encrypted form.
+ *
+ * <p>When the sealed object is ready to be unsealed (and deserialized)
+ * the caller may use either
+ *
+ * <ol>
+ * <li>{@link #getObject(javax.crypto.Cipher)}, which uses an
+ * already-initialized {@link javax.crypto.Cipher}.<br>
+ * <br>
+ * or,</li>
+ *
+ * <li>{@link #getObject(java.security.Key)} or {@link
+ * #getObject(java.security.Key,java.lang.String)}, which will
+ * initialize a new cipher instance with the {@link #encodedParams} that
+ * were stored with this sealed object (this is so parameters, such as
+ * the IV, don't need to be known by the one unsealing the object).</li>
+ * </ol>
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class SealedObject implements Serializable
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ /** The encoded algorithm parameters. */
+ protected byte[] encodedParams;
+
+ /** The serialized, encrypted object. */
+ private byte[] encryptedContent;
+
+ /** The algorithm used to seal the object. */
+ private String sealAlg;
+
+ /** The parameter type. */
+ private String paramsAlg;
+
+ /** The cipher that decrypts when this object is unsealed. */
+ private transient Cipher sealCipher;
+
+ /** Compatible with JDK1.4. */
+ private static final long serialVersionUID = 4482838265551344752L;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new sealed object from a {@link java.io.Serializable}
+ * object and a cipher.
+ *
+ * @param object The object to seal.
+ * @param cipher The cipher to encrypt with.
+ * @throws java.io.IOException If serializing the object fails.
+ * @throws javax.crypto.IllegalBlockSizeException If the cipher has no
+ * padding and the size of the serialized representation of the
+ * object is not a multiple of the cipher's block size.
+ */
+ public SealedObject(Serializable object, Cipher cipher)
+ throws IOException, IllegalBlockSizeException
+ {
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ ObjectOutputStream oos = new ObjectOutputStream(baos);
+ oos.writeObject(object);
+ oos.flush();
+ try
+ {
+ encryptedContent = cipher.doFinal(baos.toByteArray());
+ }
+ catch (IllegalStateException ise)
+ {
+ throw new IOException("cipher not in proper state");
+ }
+ catch (BadPaddingException bpe)
+ {
+ throw new IOException(
+ "encrypting but got javax.crypto.BadPaddingException");
+ }
+ sealAlg = cipher.getAlgorithm();
+ encodedParams = cipher.getParameters().getEncoded();
+ paramsAlg = cipher.getParameters().getAlgorithm();
+ }
+
+ /**
+ * Create a new sealed object from another sealed object.
+ *
+ * @param so The other sealed object.
+ */
+ protected SealedObject(SealedObject so)
+ {
+ this.encodedParams = (byte[]) so.encodedParams.clone();
+ this.encryptedContent = (byte[]) so.encryptedContent.clone();
+ this.sealAlg = so.sealAlg;
+ this.paramsAlg = so.paramsAlg;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the name of the algorithm used to seal this object.
+ *
+ * @return The algorithm's name.
+ */
+ public final String getAlgorithm()
+ {
+ return sealAlg;
+ }
+
+ /**
+ * Unseal and deserialize this sealed object with a specified (already
+ * initialized) cipher.
+ *
+ * @param cipher The cipher to decrypt with.
+ * @return The original object.
+ * @throws java.io.IOException If reading fails.
+ * @throws java.lang.ClassNotFoundException If deserialization fails.
+ * @throws javax.crypto.IllegalBlockSizeException If the cipher has no
+ * padding and the encrypted data is not a multiple of the
+ * cipher's block size.
+ * @throws javax.crypto.BadPaddingException If the padding bytes are
+ * incorrect.
+ */
+ public final Object getObject(Cipher cipher)
+ throws IOException, ClassNotFoundException, IllegalBlockSizeException,
+ BadPaddingException
+ {
+ sealCipher = cipher;
+ return unseal();
+ }
+
+ /**
+ * Unseal and deserialize this sealed object with the specified key.
+ *
+ * @param key The key to decrypt with.
+ * @return The original object.
+ * @throws java.io.IOException If reading fails.
+ * @throws java.lang.ClassNotFoundException If deserialization fails.
+ * @throws java.security.InvalidKeyException If the supplied key
+ * cannot be used to unseal this object.
+ * @throws java.security.NoSuchAlgorithmException If the algorithm
+ * used to originally seal this object is not available.
+ */
+ public final Object getObject(Key key)
+ throws IOException, ClassNotFoundException, InvalidKeyException,
+ NoSuchAlgorithmException
+ {
+ try
+ {
+ if (sealCipher == null)
+ sealCipher = Cipher.getInstance(sealAlg);
+ }
+ catch (NoSuchPaddingException nspe)
+ {
+ throw new NoSuchAlgorithmException(nspe.getMessage());
+ }
+ AlgorithmParameters params = null;
+ if (encodedParams != null)
+ {
+ params = AlgorithmParameters.getInstance(paramsAlg);
+ params.init(encodedParams);
+ }
+ try
+ {
+ sealCipher.init(Cipher.DECRYPT_MODE, key, params);
+ return unseal();
+ }
+ catch (InvalidAlgorithmParameterException iape)
+ {
+ throw new IOException("bad parameters");
+ }
+ catch (IllegalBlockSizeException ibse)
+ {
+ throw new IOException("illegal block size");
+ }
+ catch (BadPaddingException bpe)
+ {
+ throw new IOException("bad padding");
+ }
+ }
+
+ /**
+ * Unseal and deserialize this sealed object with the specified key,
+ * using a cipher from the named provider.
+ *
+ * @param key The key to decrypt with.
+ * @param provider The name of the provider to use.
+ * @return The original object.
+ * @throws java.io.IOException If reading fails.
+ * @throws java.lang.ClassNotFoundException If deserialization fails.
+ * @throws java.security.InvalidKeyException If the supplied key
+ * cannot be used to unseal this object.
+ * @throws java.security.NoSuchAlgorithmException If the algorithm
+ * used to originally seal this object is not available from
+ * the named provider.
+ * @throws java.security.NoSuchProviderException If the named provider
+ * does not exist.
+ */
+ public final Object getObject(Key key, String provider)
+ throws IOException, ClassNotFoundException, InvalidKeyException,
+ NoSuchAlgorithmException, NoSuchProviderException
+ {
+ try
+ {
+ sealCipher = Cipher.getInstance(sealAlg, provider);
+ }
+ catch (NoSuchPaddingException nspe)
+ {
+ throw new NoSuchAlgorithmException(nspe.getMessage());
+ }
+ AlgorithmParameters params = null;
+ if (encodedParams != null)
+ {
+ params = AlgorithmParameters.getInstance(paramsAlg, provider);
+ params.init(encodedParams);
+ }
+ try
+ {
+ sealCipher.init(Cipher.DECRYPT_MODE, key, params);
+ return unseal();
+ }
+ catch (InvalidAlgorithmParameterException iape)
+ {
+ throw new IOException("bad parameters");
+ }
+ catch (IllegalBlockSizeException ibse)
+ {
+ throw new IOException("illegal block size");
+ }
+ catch (BadPaddingException bpe)
+ {
+ throw new IOException("bad padding");
+ }
+ }
+
+ // Own methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Deserialize this object.
+ *
+ * @param ois The input stream.
+ * @throws java.io.IOException If reading fails.
+ * @throws java.lang.ClassNotFoundException If reading fails.
+ */
+ private void readObject(ObjectInputStream ois)
+ throws IOException, ClassNotFoundException
+ {
+ encodedParams = (byte[]) ois.readObject();
+ encryptedContent = (byte[]) ois.readObject();
+ sealAlg = (String) ois.readObject();
+ paramsAlg = (String) ois.readObject();
+ }
+
+ /**
+ * Serialize this object.
+ *
+ * @param oos The output stream.
+ * @throws java.io.IOException If writing fails.
+ */
+ private void writeObject(ObjectOutputStream oos)
+ throws IOException
+ {
+ oos.writeObject(encodedParams);
+ oos.writeObject(encryptedContent);
+ oos.writeObject(sealAlg);
+ oos.writeObject(paramsAlg);
+ }
+
+ /**
+ * Unseal this object, returning it.
+ *
+ * @return The unsealed, deserialized Object.
+ * @throws java.io.IOException If reading fails.
+ * @throws java.io.ClassNotFoundException If reading fails.
+ * @throws javax.crypto.IllegalBlockSizeException If the cipher has no
+ * padding and the encrypted data is not a multiple of the
+ * cipher's block size.
+ * @throws javax.crypto.BadPaddingException If the padding bytes are
+ * incorrect.
+ */
+ private Object unseal()
+ throws IOException, ClassNotFoundException, IllegalBlockSizeException,
+ BadPaddingException
+ {
+ ByteArrayInputStream bais = null;
+ try
+ {
+ bais = new ByteArrayInputStream(sealCipher.doFinal(encryptedContent));
+ }
+ catch (IllegalStateException ise)
+ {
+ throw new IOException("cipher not initialized");
+ }
+ ObjectInputStream ois = new ObjectInputStream(bais);
+ return ois.readObject();
+ }
+}
diff --git a/libjava/javax/crypto/SecretKey.java b/libjava/javax/crypto/SecretKey.java
new file mode 100644
index 00000000000..85529b94de2
--- /dev/null
+++ b/libjava/javax/crypto/SecretKey.java
@@ -0,0 +1,67 @@
+/* SecretKey.java -- A key for symmetric cryptography.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is a part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2 of the License, or (at
+your option) any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License along
+with GNU Classpath; if not, write to the
+
+ Free Software Foundation, Inc.,
+ 59 Temple Place, Suite 330,
+ Boston, MA 02111-1307
+ USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under terms
+of your choice, provided that you also meet, for each linked independent
+module, the terms and conditions of the license of that module. An
+independent module is a module which is not derived from or based on
+this library. If you modify this library, you may extend this exception
+to your version of the library, but you are not obligated to do so. If
+you do not wish to do so, delete this exception statement from your
+version. */
+
+
+package javax.crypto;
+
+import java.security.Key;
+
+/**
+ * A secret key for symmetric cryptography.
+ *
+ * <p>This interface defines no new methods over {@link
+ * java.security.Key}, but rather is intended to be a <i>marker
+ * interface</i> and to provide type safety for secret keys.</p>
+ *
+ * <p>The format of secret keys should be <code>RAW</code>, as returned
+ * by {@link java.security.Key#getFormat()}.</p>
+ *
+ * <p>Concrete implementations of this interface should override the
+ * {@link java.lang.Object#equals} and {@link java.lang.Object#hashCode}
+ * methods of {@link java.lang.Object} to use the actual key data rather
+ * than the identity-based default methods.</p>
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @see javax.crypto.SecretKeyFactory
+ * @see javax.crypto.Cipher
+ */
+public interface SecretKey extends Key
+{
+}
diff --git a/libjava/javax/crypto/SecretKeyFactory.java b/libjava/javax/crypto/SecretKeyFactory.java
new file mode 100644
index 00000000000..92f18ec6659
--- /dev/null
+++ b/libjava/javax/crypto/SecretKeyFactory.java
@@ -0,0 +1,249 @@
+/* SecretKeyFactory.java -- Factory for creating secret keys.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+import java.security.spec.KeySpec;
+import java.security.spec.InvalidKeySpecException;
+
+import gnu.java.security.Engine;
+
+/**
+ * A secret key factory translates {@link SecretKey} objects to and from
+ * {@link java.security.spec.KeySpec} objects, and can translate between
+ * different vendors' representations of {@link SecretKey} objects (for
+ * security or semantics; whichever applies).
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see SecretKey
+ */
+public class SecretKeyFactory
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ private static final String SERVICE = "SecretKeyFactory";
+
+ /** The underlying factory implementation. */
+ private SecretKeyFactorySpi skfSpi;
+
+ /** The provider of the implementation. */
+ private Provider provider;
+
+ /** The name of the algorithm. */
+ private String algorithm;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new secret key factory.
+ *
+ * @param skfSpi The underlying factory implementation.
+ * @param provider The provider.
+ * @param algorithm The algorithm name.
+ */
+ protected SecretKeyFactory(SecretKeyFactorySpi skfSpi, Provider provider,
+ String algorithm)
+ {
+ this.skfSpi = skfSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new secret key factory from the first appropriate
+ * instance.
+ *
+ * @param algorithm The algorithm name.
+ * @return The appropriate key factory, if found.
+ * @throws java.security.NoSuchAlgorithmException If no provider
+ * implements the specified algorithm.
+ */
+ public static final SecretKeyFactory getInstance(String algorithm)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(algorithm, provs[i]);
+ }
+ catch (NoSuchAlgorithmException nsae)
+ {
+ }
+ }
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+
+ /**
+ * Create a new secret key factory from the named provider.
+ *
+ * @param algorithm The algorithm name.
+ * @param provider The provider name.
+ * @return The appropriate key factory, if found.
+ * @throws java.security.NoSuchAlgorithmException If the named
+ * provider does not implement the algorithm.
+ * @throws java.security.NoSuchProviderException If the named provider
+ * does not exist.
+ */
+ public static final SecretKeyFactory getInstance(String algorithm,
+ String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(algorithm, p);
+ }
+
+ /**
+ * Create a new secret key factory from the specified provider.
+ *
+ * @param algorithm The algorithm name.
+ * @param provider The provider.
+ * @return The appropriate key factory, if found.
+ * @throws java.security.NoSuchAlgorithmException If the provider
+ * does not implement the algorithm.
+ */
+ public static final SecretKeyFactory getInstance(String algorithm,
+ Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ try
+ {
+ return new SecretKeyFactory((SecretKeyFactorySpi)
+ Engine.getInstance(SERVICE, algorithm, provider),
+ provider, algorithm);
+ }
+ catch (InvocationTargetException ite)
+ {
+ if (ite.getCause() == null)
+ throw new NoSuchAlgorithmException(algorithm);
+ if (ite.getCause() instanceof NoSuchAlgorithmException)
+ throw (NoSuchAlgorithmException) ite.getCause();
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Generate a secret key from a key specification, if possible.
+ *
+ * @param keySpec The key specification.
+ * @return The secret key.
+ * @throws java.security.InvalidKeySpecException If the key specification
+ * cannot be transformed into a secret key.
+ */
+ public final SecretKey generateSecret(KeySpec keySpec)
+ throws InvalidKeySpecException
+ {
+ return skfSpi.engineGenerateSecret(keySpec);
+ }
+
+ /**
+ * Get the algorithm name.
+ *
+ * @return The algorithm name.
+ */
+ public final String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Get the key specification from a secret key.
+ *
+ * @param key The secret key.
+ * @param keySpec The target key specification class.
+ * @return The key specification.
+ * @throws java.security.spec.InvalidKeySpecException If the secret key cannot
+ * be transformed into the specified key specification.
+ */
+ public final KeySpec getKeySpec(SecretKey key, Class keySpec)
+ throws InvalidKeySpecException
+ {
+ return skfSpi.engineGetKeySpec(key, keySpec);
+ }
+
+ /**
+ * Get the provider of this implementation.
+ *
+ * @return The provider.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Translate a secret key into another form.
+ *
+ * @param key The key to translate.
+ * @return The translated key.
+ * @throws java.security.InvalidKeyException If the argument cannot be
+ * translated.
+ */
+ public final SecretKey translateKey(SecretKey key)
+ throws InvalidKeyException
+ {
+ return skfSpi.engineTranslateKey(key);
+ }
+}
diff --git a/libjava/javax/crypto/SecretKeyFactorySpi.java b/libjava/javax/crypto/SecretKeyFactorySpi.java
new file mode 100644
index 00000000000..7b4763dff41
--- /dev/null
+++ b/libjava/javax/crypto/SecretKeyFactorySpi.java
@@ -0,0 +1,108 @@
+/* SecretKeyFactorySpi.java -- Secret key factory service provider interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.InvalidKeyException;
+import java.security.spec.KeySpec;
+import java.security.spec.InvalidKeySpecException;
+
+/**
+ * The <i>Service Provider Interface</i> (<b>SPI</b>) for the {@link
+ * SecretKeyFactory} class.
+ *
+ * <p>Providers wishing to implement a secret key factory must
+ * subclass this and provide an appropriate implementation for all the
+ * abstract methods below, and provide an appropriate entry in the
+ * master {@link java.security.Provider} class (the service name for
+ * secret key factories is <code>"SecretKeyFactory"</code>).
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see SecretKeyFactory
+ */
+public abstract class SecretKeyFactorySpi
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new secret key factory SPI.
+ */
+ public SecretKeyFactorySpi()
+ {
+ }
+
+ // Abstract instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Translate a {@link java.security.KeySpec} into a {@link SecretKey}.
+ *
+ * @param keySpec The key specification.
+ * @return The secret key.
+ * @throws java.security.spec.InvalidKeySpecException If the key specification
+ * cannot be translated into a secret key.
+ */
+ protected abstract SecretKey engineGenerateSecret(KeySpec keySpec)
+ throws InvalidKeySpecException;
+
+ /**
+ * Translate a {@link SecretKey} into a {@link java.security.KeySpec}.
+ *
+ * @param key The secret key.
+ * @param keySpec The desired key specification class.
+ * @return The key specification.
+ * @throws java.security.spec.InvalidKeySpecException If the secret key cannot
+ * be translated into the desired key specification.
+ */
+ protected abstract KeySpec engineGetKeySpec(SecretKey key, Class keySpec)
+ throws InvalidKeySpecException;
+
+ /**
+ * Translate a secret key into a different representation.
+ *
+ * @param key The secret key to translate.
+ * @return The translated key.
+ * @throws java.security.InvalidKeyException If the specified secret
+ * key cannot be translated.
+ */
+ protected abstract SecretKey engineTranslateKey(SecretKey key)
+ throws InvalidKeyException;
+}
diff --git a/libjava/javax/crypto/ShortBufferException.java b/libjava/javax/crypto/ShortBufferException.java
new file mode 100644
index 00000000000..5b5bf5437e5
--- /dev/null
+++ b/libjava/javax/crypto/ShortBufferException.java
@@ -0,0 +1,70 @@
+/* ShortBufferException.java -- Signals a short output buffer.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * This exception is thrown on an attempt to transform bytes into a
+ * buffer that is too short to contain the data.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class ShortBufferException extends GeneralSecurityException
+{
+
+ // Constant.
+ // ------------------------------------------------------------------------
+
+ /** Serialization constant. */
+ private static final long serialVersionUID = 8427718640832943747L;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ public ShortBufferException()
+ {
+ super();
+ }
+
+ public ShortBufferException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/crypto/interfaces/DHKey.java b/libjava/javax/crypto/interfaces/DHKey.java
new file mode 100644
index 00000000000..d5d827946df
--- /dev/null
+++ b/libjava/javax/crypto/interfaces/DHKey.java
@@ -0,0 +1,61 @@
+/* DHKey.java -- General interface for a Diffie-Hellman key.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.interfaces;
+
+import javax.crypto.spec.DHParameterSpec;
+
+/**
+ * This interface marks public/private keys in the Diffie-Hellman key
+ * exchange algorithm. Implementations of Diffie-Hellman keys should
+ * implement this interface, and applications can safely cast keys that
+ * are known to be Diffie-Hellman keys to this interface.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public interface DHKey
+{
+ /**
+ * Returns the Diffie-Hellman parameters for this key, which includes
+ * the generator and the prime.
+ *
+ * @return The Diffie-Hellman parameters.
+ */
+ DHParameterSpec getParams();
+}
diff --git a/libjava/javax/crypto/interfaces/DHPrivateKey.java b/libjava/javax/crypto/interfaces/DHPrivateKey.java
new file mode 100644
index 00000000000..63b9c15c416
--- /dev/null
+++ b/libjava/javax/crypto/interfaces/DHPrivateKey.java
@@ -0,0 +1,70 @@
+/* DHPrivateKey.java -- A Diffie-Hellman private key.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.interfaces;
+
+import java.math.BigInteger;
+import java.security.PrivateKey;
+
+/**
+ * This interface marks a private key in the Diffie-Hellman key exchange
+ * algorithm. It should be treated with as much care as any {@link
+ * java.security.PrivateKey}.
+ *
+ * <p>Implementations of Diffie-Hellman private keys should implement
+ * this interface. Applications that know a particular key is a
+ * Diffie-Hellman private key can safely cast it to this interface.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see DHKey
+ * @see DHPublicKey
+ */
+public interface DHPrivateKey extends DHKey, PrivateKey
+{
+
+ /** Compatible with JDK1.4. */
+ static final long serialVersionUID = 2211791113380396553L;
+
+ /**
+ * Returns the private value <i>x</i>.
+ *
+ * @return The private value <i>x</i>.
+ */
+ BigInteger getX();
+}
diff --git a/libjava/javax/crypto/interfaces/DHPublicKey.java b/libjava/javax/crypto/interfaces/DHPublicKey.java
new file mode 100644
index 00000000000..5e0b35bf008
--- /dev/null
+++ b/libjava/javax/crypto/interfaces/DHPublicKey.java
@@ -0,0 +1,69 @@
+/* DHPublicKey.java -- A Diffie-Hellman public key.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.interfaces;
+
+import java.math.BigInteger;
+import java.security.PublicKey;
+
+/**
+ * This interface marks a public key in the Diffie-Hellman key-exchange
+ * algorithm.
+ *
+ * <p>Implementations of Diffie-Hellman public keys should implement
+ * this interface. Applications that know that a particular key is a
+ * Diffie-Hellman public key it can be safely cast to this interface.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see DHKey
+ * @see DHPrivateKey
+ */
+public interface DHPublicKey extends DHKey, PublicKey
+{
+
+ /** Compatible with JDK1.4. */
+ static final long serialVersionUID = -6628103563352519193L;
+
+ /**
+ * Get the public value <i>y</i>.
+ *
+ * @return The public value <i>y</i>.
+ */
+ BigInteger getY();
+}
diff --git a/libjava/javax/crypto/interfaces/PBEKey.java b/libjava/javax/crypto/interfaces/PBEKey.java
new file mode 100644
index 00000000000..53349189849
--- /dev/null
+++ b/libjava/javax/crypto/interfaces/PBEKey.java
@@ -0,0 +1,91 @@
+/* PBEKey.java -- A key derived from a password.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.interfaces;
+
+import javax.crypto.SecretKey;
+
+/**
+ * Interface to a password-derived key for password-based encryption
+ * (PBE). Applications working with a {@link javax.crypto.SecretKey}
+ * that is known to be a password-based key can safely cast such keys to
+ * this interface.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public interface PBEKey extends SecretKey
+{
+
+ /** Compatible with JDK1.4. */
+ static final long serialVersionUID = -1430015993304333921L;
+
+ /**
+ * Retruns the iteration count, or 0 if not specified.
+ *
+ * @return The iteration count.
+ */
+ int getIterationCount();
+
+ /**
+ * Returns a copy of the password as a character array. It is the
+ * caller's responsibility to zero-out the password when it is no
+ * longer in use.
+ *
+ * <p>Although it is not specified in the documentation,
+ * implementations should not copy or clone the password array, but
+ * rather return the reference to the array itself, so the caller has
+ * the ability to erase the password.
+ *
+ * @return The password.
+ */
+ char[] getPassword();
+
+ /**
+ * Returns a copy of the salt. It is the caller's responsibility to
+ * zero-out the salt when it is no longer in use.
+ *
+ * <p>Although it is not specified in the documentation,
+ * implementations should not copy or clone the salt array, but
+ * rather return the reference to the array itself, so the caller has
+ * the ability to erase the salt.
+ *
+ * @return The salt.
+ */
+ byte[] getSalt();
+}
diff --git a/libjava/javax/crypto/spec/DESKeySpec.java b/libjava/javax/crypto/spec/DESKeySpec.java
new file mode 100644
index 00000000000..7423c969b63
--- /dev/null
+++ b/libjava/javax/crypto/spec/DESKeySpec.java
@@ -0,0 +1,220 @@
+/* DESKeySpec -- Keys for DES.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.InvalidKeyException;
+import java.security.spec.KeySpec;
+
+/**
+ * This class is a transparent wrapper for DES keys, which are arrays
+ * of 8 bytes.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class DESKeySpec implements KeySpec
+{
+
+ // Constants.
+ // ------------------------------------------------------------------------
+
+ /**
+ * The length of a DES key, in bytes.
+ */
+ public static final int DES_KEY_LEN = 8;
+
+ /**
+ * The key bytes.
+ */
+ private byte[] key;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new DES key spec, copying the first 8 bytes from the
+ * byte array.
+ *
+ * @param key The key bytes.
+ * @throws java.security.InvalidKeyException If there are less than 8
+ * bytes in the array.
+ */
+ public DESKeySpec(byte[] key) throws InvalidKeyException
+ {
+ this(key, 0);
+ }
+
+ /**
+ * Create a new DES key spec, starting at <code>offset</code> in
+ * the byte array. The first 8 bytes starting at <code>offset</code>
+ * are copied.
+ *
+ * @param key The key bytes.
+ * @param offset The offset into the byte array at which to begin.
+ * @throws java.security.InvalidKeyException If there are less than 8
+ * bytes starting at <code>offset</code>.
+ */
+ public DESKeySpec(byte[] key, int offset) throws InvalidKeyException
+ {
+ if (key.length - offset < DES_KEY_LEN)
+ {
+ throw new InvalidKeyException("DES keys must be 8 bytes long");
+ }
+ this.key = new byte[DES_KEY_LEN];
+ System.arraycopy(key, offset, this.key, 0, DES_KEY_LEN);
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns whether or not the given key is <i>parity adjusted</i>;
+ * i.e. every byte in the key has an odd number of "1" bits.
+ *
+ * @param key The key bytes, considered between <code>[offset,
+ * offset+7]</code>
+ * @param offset The offset into the byte array at which to begin.
+ * @return True if all bytes have an odd number of "1" bits.
+ * @throws java.security.InvalidKeyException If there are not enough
+ * bytes in the array.
+ */
+ public static boolean isParityAdjusted(byte[] key, int offset)
+ throws InvalidKeyException
+ {
+ if (key.length - offset < DES_KEY_LEN)
+ {
+ throw new InvalidKeyException("DES keys must be 8 bytes long");
+ }
+ boolean parity = false;
+ boolean oddbits = false;
+ for (int i = 0; i < DES_KEY_LEN; i++)
+ {
+ oddbits = false;
+ for (int j = 0; j < 8; j++)
+ {
+ oddbits ^= (key[i+offset] & 1 << j) != 0;
+ }
+ parity &= oddbits;
+ }
+ return parity;
+ }
+
+ /**
+ * One-half of the weak and semiweak DES keys (the other half are the
+ * complements of these).
+ */
+ private static final byte[][] WEAK_KEYS = new byte[][] {
+ { 0, 0, 0, 0, 0, 0, 0, 0 }, // 0000 0000 0000 0000
+ { -1, -1, -1, -1, 0, 0, 0, 0 }, // ffff ffff 0000 0000
+ { 1, 1, 1, 1, 1, 1, 1, 1 }, // 0101 0101 0101 0101
+ { 31, 31, 31, 31, 14, 14, 14, 14 }, // 1f1f 1f1f 0e0e 0e0e
+ { 1, -2, 1, -2, 1, -2, 1, -2 }, // 01fe 01fe 01fe 01fe
+ { 31, -32, 31, -32, -32, 31, -32, 31 }, // 1fe0 1fe0 0e1f 0e1f
+ { 1, -32, 1, -32, 1, -15, 1, -15 }, // 01e0 01e0 01f1 01f1
+ { 31, -2, 31, -2, 14, -2, 14, -2 }, // 1ffe 1ffe 0efe 0efe
+ { 1, 31, 1, 31, 1, 14, 1, 14 }, // 011f 011f 010e 010e
+ { -32, -2, -32, -2, -15, -2, -15, -2 }, // e0fe e0fe f1fe f1fe
+ };
+
+ /**
+ * Tests if the bytes between <code>[offset, offset+7]</code>
+ * constitute a weak or semi-weak DES key.
+ *
+ * @param key The key bytes to check.
+ * @param offset The offset in the byte array to start.
+ * @return true If the key bytes are a weak key.
+ */
+ public static boolean isWeak(byte[] key, int offset)
+ throws InvalidKeyException
+ {
+ if (key.length - offset < DES_KEY_LEN)
+ {
+ throw new InvalidKeyException("DES keys must be 8 bytes long");
+ }
+ for (int i = 0; i < WEAK_KEYS.length; i++)
+ {
+ if (equalsOrComplementEquals(key, offset, WEAK_KEYS[i]))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * This method returns true if the first 8 bytes starting at
+ * <code>off</code> in <code>a</code> equal the first 8 bytes in
+ * <code>b</code>, or equal the <i>complement</i> of the first 8 bytes
+ * in <code>b</code>.
+ *
+ * @param a The first byte array.
+ * @param off The index into the first byte array.
+ * @param b The second byte array.
+ * @return <code>a == b || a == ~b</code>
+ */
+ private static boolean equalsOrComplementEquals(byte[] a, int off, byte[] b)
+ {
+ boolean result = true;
+ for (int i = 0; i < DES_KEY_LEN; i++)
+ {
+ result &= a[off+i] == b[i];
+ }
+ if (result) return true;
+ result = true;
+ for (int i = 0; i < DES_KEY_LEN; i++)
+ {
+ result &= a[off+i] == (~b[i]);
+ }
+ return result;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return the key as a byte array. This method does not copy the byte
+ * array.
+ *
+ * @return The key bytes.
+ */
+ public byte[] getKey()
+ {
+ return key;
+ }
+}
diff --git a/libjava/javax/crypto/spec/DESedeKeySpec.java b/libjava/javax/crypto/spec/DESedeKeySpec.java
new file mode 100644
index 00000000000..d455163bcee
--- /dev/null
+++ b/libjava/javax/crypto/spec/DESedeKeySpec.java
@@ -0,0 +1,151 @@
+/* DESedeKeySpec.java -- Keys for triple-DES.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.InvalidKeyException;
+import java.security.spec.KeySpec;
+
+/**
+ * This class is a transparent wrapper for DES-EDE (Triple-DES) keys,
+ * which are arrays of 24 bytes.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class DESedeKeySpec implements KeySpec
+{
+
+ // Constants.
+ // ------------------------------------------------------------------------
+
+ /**
+ * The length of a triple-DES key, in bytes.
+ */
+ public static final int DES_EDE_KEY_LEN = 24;
+
+ /**
+ * The key bytes.
+ */
+ private byte[] key;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new DES-EDE key spec, copying the first 24 bytes from the
+ * byte array.
+ *
+ * @param key The key bytes.
+ * @throws java.security.InvalidKeyException If there are less than 24
+ * bytes in the array.
+ */
+ public DESedeKeySpec(byte[] key) throws InvalidKeyException
+ {
+ this(key, 0);
+ }
+
+ /**
+ * Create a new DES-EDE key spec, starting at <code>offset</code> in
+ * the byte array. The first 24 bytes starting at <code>offset</code>
+ * are copied.
+ *
+ * @param key The key bytes.
+ * @param offset The offset into the byte array at which to begin.
+ * @throws java.security.InvalidKeyException If there are less than 24
+ * bytes starting at <code>offset</code>.
+ */
+ public DESedeKeySpec(byte[] key, int offset) throws InvalidKeyException
+ {
+ if (key.length - offset < DES_EDE_KEY_LEN)
+ {
+ throw new InvalidKeyException("DES-EDE keys must be 24 bytes long");
+ }
+ this.key = new byte[DES_EDE_KEY_LEN];
+ System.arraycopy(key, offset, this.key, 0, DES_EDE_KEY_LEN);
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns whether or not the given key is <i>parity adjusted</i>;
+ * i.e. every byte in the key has an odd number of "1" bits.
+ *
+ * @param key The key bytes, considered between <code>[offset,
+ * offset+23]</code>
+ * @param offset The offset into the byte array at which to begin.
+ * @return True if all bytes have an odd number of "1" bits.
+ * @throws java.security.InvalidKeyException If there are not enough
+ * bytes in the array.
+ */
+ public static boolean isParityAdjusted(byte[] key, int offset)
+ throws InvalidKeyException
+ {
+ if (key.length - offset < DES_EDE_KEY_LEN)
+ {
+ throw new InvalidKeyException("DES-EDE keys must be 24 bytes long");
+ }
+ boolean parity = false;
+ boolean oddbits = false;
+ for (int i = 0; i < DES_EDE_KEY_LEN; i++)
+ {
+ oddbits = false;
+ for (int j = 0; j < 8; j++)
+ {
+ oddbits ^= (key[i+offset] & 1 << j) != 0;
+ }
+ parity &= oddbits;
+ }
+ return parity;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return the key as a byte array. This method does not copy the byte
+ * array.
+ *
+ * @return The key bytes.
+ */
+ public byte[] getKey()
+ {
+ return key;
+ }
+}
diff --git a/libjava/javax/crypto/spec/DHGenParameterSpec.java b/libjava/javax/crypto/spec/DHGenParameterSpec.java
new file mode 100644
index 00000000000..67392a50f1b
--- /dev/null
+++ b/libjava/javax/crypto/spec/DHGenParameterSpec.java
@@ -0,0 +1,100 @@
+/* DHGenParameterSpec.java -- Diffie-Hellman parameter generator spec.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * This class represents the parameters needed for generating
+ * Diffie-Hellman parameters.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see DHParameterSpec
+ */
+public class DHGenParameterSpec implements AlgorithmParameterSpec
+{
+
+ // Variables.
+ // ------------------------------------------------------------------------
+
+ /** The length of the prime, in bits. */
+ private int primeSize;
+
+ /** The length of the exponent, in bits. */
+ private int exponentSize;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new Diffie-Hellman parameter generator spec.
+ *
+ * @param primeSize The size of the prime, in bits.
+ * @param exponentSize The size of the exponent, in bits.
+ */
+ public DHGenParameterSpec(int primeSize, int exponentSize)
+ {
+ this.primeSize = primeSize;
+ this.exponentSize = exponentSize;
+ }
+
+ // Intance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the size of the exponent, in bits.
+ *
+ * @return The exponent size.
+ */
+ public int getExponentSize()
+ {
+ return exponentSize;
+ }
+
+ /**
+ * Get the size of the prime, in bits.
+ *
+ * @return The prime size.
+ */
+ public int getPrimeSize()
+ {
+ return primeSize;
+ }
+}
diff --git a/libjava/javax/crypto/spec/DHParameterSpec.java b/libjava/javax/crypto/spec/DHParameterSpec.java
new file mode 100644
index 00000000000..e66f632e882
--- /dev/null
+++ b/libjava/javax/crypto/spec/DHParameterSpec.java
@@ -0,0 +1,135 @@
+/* DHParameterSpec.java -- Parameters for Diffie-Hellman keys.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.math.BigInteger;
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * The base set of parameters necessary to perform Diffie-Hellman key
+ * exchange. Each party in the key exchange shares these parameters.
+ *
+ * <p>Each set of parameters consists of a <i>base generator</i>
+ * <code>g</code>, a <i>prime modulus</i> <code>p</code>, and an
+ * optional length, in bits, of the private exponent.
+ *
+ * <p>See <a href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-3/">PKCS
+ * #3 - Diffie-Hellman Key Agreement Standard</a> for more information.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see javax.crypto.KeyAgreement
+ */
+public class DHParameterSpec implements AlgorithmParameterSpec
+{
+
+ // Variables.
+ // ------------------------------------------------------------------------
+
+ /** The base generator g. */
+ private BigInteger g;
+
+ /** The prime modulus p. */
+ private BigInteger p;
+
+ /** The length, in bits, of the private exponent. */
+ private int l;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new set of Diffie-Hellman parameters.
+ *
+ * @param p The prime modulus.
+ * @param g The base generator.
+ */
+ public DHParameterSpec(BigInteger p, BigInteger g)
+ {
+ this(p, g, 0);
+ }
+
+ /**
+ * Create a new set of Diffie-Hellman parameters.
+ *
+ * @param p The prime modulus.
+ * @param g The base generator.
+ * @param l The size of the private exponent, in bits.
+ */
+ public DHParameterSpec(BigInteger p, BigInteger g, int l)
+ {
+ this.p = p;
+ this.g = g;
+ this.l = l;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the base generator, <i>g</i>.
+ *
+ * @return The base generator <i>g</i>.
+ */
+ public BigInteger getG()
+ {
+ return g;
+ }
+
+ /**
+ * Get the length of the private exponent, in bits.
+ *
+ * @return The length of the private exponent, in bits, or 0 if this
+ * has not been explicitly set.
+ */
+ public int getL()
+ {
+ return l;
+ }
+
+ /**
+ * Get the prime modulus, <i>p</i>.
+ *
+ * @return The prime modulus, <i>p</i>.
+ */
+ public BigInteger getP()
+ {
+ return p;
+ }
+}
diff --git a/libjava/javax/crypto/spec/DHPrivateKeySpec.java b/libjava/javax/crypto/spec/DHPrivateKeySpec.java
new file mode 100644
index 00000000000..8a4a790a16c
--- /dev/null
+++ b/libjava/javax/crypto/spec/DHPrivateKeySpec.java
@@ -0,0 +1,115 @@
+/* DHPrivateKeySpec.java -- Wrapper for Diffie-Hellman private keys.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.math.BigInteger;
+import java.security.spec.KeySpec;
+
+/**
+ * A wrapper for Diffie-Hellman private key data.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see DHPublicKeySpec
+ */
+public class DHPrivateKeySpec implements KeySpec
+{
+
+ // Variables.
+ // ------------------------------------------------------------------------
+
+ /** The base generator. */
+ private BigInteger g;
+
+ /** The prime modulus. */
+ private BigInteger p;
+
+ /** The private exponent. */
+ private BigInteger x;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new Diffie-Hellman private key spec.
+ *
+ * @param x The private exponent.
+ * @param p The prime modulus.
+ * @param g The base generator.
+ */
+ public DHPrivateKeySpec(BigInteger x, BigInteger p, BigInteger g)
+ {
+ this.x = x;
+ this.p = p;
+ this.g = g;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the base generator.
+ *
+ * @return The base generator.
+ */
+ public BigInteger getG()
+ {
+ return g;
+ }
+
+ /**
+ * Get the prime modulus.
+ *
+ * @return The prime modulus.
+ */
+ public BigInteger getP()
+ {
+ return p;
+ }
+
+ /**
+ * Get the private exponent.
+ *
+ * @return The private exponent.
+ */
+ public BigInteger getX()
+ {
+ return x;
+ }
+}
diff --git a/libjava/javax/crypto/spec/DHPublicKeySpec.java b/libjava/javax/crypto/spec/DHPublicKeySpec.java
new file mode 100644
index 00000000000..723dfefa404
--- /dev/null
+++ b/libjava/javax/crypto/spec/DHPublicKeySpec.java
@@ -0,0 +1,115 @@
+/* DHPublicKeySpec.java -- Wrapper for Diffie-Hellman public keys.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.math.BigInteger;
+import java.security.spec.KeySpec;
+
+/**
+ * A wrapper for Diffie-Hellman public key data.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see DHPrivateKeySpec
+ */
+public class DHPublicKeySpec implements KeySpec
+{
+
+ // Variables.
+ // ------------------------------------------------------------------------
+
+ /** The base generator. */
+ private BigInteger g;
+
+ /** The prime modulus. */
+ private BigInteger p;
+
+ /** The public value. */
+ private BigInteger y;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new Diffie-Hellman public key spec.
+ *
+ * @param y The public value.
+ * @param p The prime modulus.
+ * @param g The base generator.
+ */
+ public DHPublicKeySpec(BigInteger y, BigInteger p, BigInteger g)
+ {
+ this.y = y;
+ this.p = p;
+ this.g = g;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the base generator.
+ *
+ * @return The base generator.
+ */
+ public BigInteger getG()
+ {
+ return g;
+ }
+
+ /**
+ * Get the prime modulus.
+ *
+ * @return The prime modulus.
+ */
+ public BigInteger getP()
+ {
+ return p;
+ }
+
+ /**
+ * Get the public value.
+ *
+ * @return The public value.
+ */
+ public BigInteger getY()
+ {
+ return y;
+ }
+}
diff --git a/libjava/javax/crypto/spec/IvParameterSpec.java b/libjava/javax/crypto/spec/IvParameterSpec.java
new file mode 100644
index 00000000000..1c09c76659f
--- /dev/null
+++ b/libjava/javax/crypto/spec/IvParameterSpec.java
@@ -0,0 +1,96 @@
+/* IvParameterSpec.java -- A simple wrapper for initialization vectors.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * A wrapper for an initialization vector. An initialization vector is
+ * necessary for any cipher in any <i>feedback mode</i>, e.g. CBC.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ */
+public class IvParameterSpec implements AlgorithmParameterSpec
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ /** The IV. */
+ private byte[] iv;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new initialization vector spec from an entire byte array.
+ *
+ * @param iv The IV bytes.
+ */
+ public IvParameterSpec(byte[] iv)
+ {
+ this(iv, 0, iv.length);
+ }
+
+ /**
+ * Create a new initialization vector spec from part of a byte array.
+ *
+ * @param iv The IV bytes.
+ * @param off The offset into the IV bytes.
+ * @param len The number of IV bytes.
+ */
+ public IvParameterSpec(byte[] iv, int off, int len)
+ {
+ this.iv = new byte[len];
+ System.arraycopy(iv, off, this.iv, 0, len);
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns the IV. This method does not copy the byte array.
+ *
+ * @return The IV.
+ */
+ public byte[] getIV()
+ {
+ return iv;
+ }
+}
diff --git a/libjava/javax/crypto/spec/PBEKeySpec.java b/libjava/javax/crypto/spec/PBEKeySpec.java
new file mode 100644
index 00000000000..7a8c224cc64
--- /dev/null
+++ b/libjava/javax/crypto/spec/PBEKeySpec.java
@@ -0,0 +1,176 @@
+/* PBEKeySpec.java -- Wrapper for password-based keys.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.KeySpec;
+
+/**
+ * A wrapper for a password-based key, used for password-based
+ * encryption (PBE).
+ *
+ * <p>Examples of password-based encryption algorithms include:
+ *
+ * <ul>
+ * <li><a href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-5/">PKCS #5
+ * - Password-Based Cryptography Standard</a></li>
+ * <li><a href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-12/">PKCS
+ * #12 - Personal Information Exchange Syntax Standard</a></li>
+ * </ul>
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ * @see javax.crypto.SecretKeyFactory
+ * @see PBEParameterSpec
+ */
+public class PBEKeySpec implements KeySpec
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ /** The iteration count. */
+ private int iterationCount;
+
+ /** The generated key length. */
+ private int keyLength;
+
+ /** The password. */
+ private char[] password;
+
+ /** The salt. */
+ private byte[] salt;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new PBE key spec with just a password.
+ *
+ * @param password The password char array.
+ */
+ public PBEKeySpec(char[] password)
+ {
+ this(password, null, 0, 0);
+ }
+
+ /**
+ * Create a PBE key spec with a password, salt, and iteration count.
+ *
+ * @param password The password char array.
+ * @param salt The salt bytes.
+ * @param iterationCount The iteration count.
+ */
+ public PBEKeySpec(char[] password, byte[] salt, int iterationCount)
+ {
+ this(password, salt, iterationCount, 0);
+ }
+
+ /**
+ * Create a PBE key spec with a password, salt, iteration count, and
+ * key length.
+ *
+ * @param password The password char array.
+ * @param salt The salt bytes.
+ * @param iterationCount The iteration count.
+ * @param keyLength The generated key length.
+ */
+ public PBEKeySpec(char[] password, byte[] salt, int iterationCount,
+ int keyLength)
+ {
+ this.password = password;
+ this.salt = salt;
+ this.iterationCount = iterationCount;
+ this.keyLength = keyLength;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Clear the password array by filling it with null characters.
+ */
+ public final void clearPassword()
+ {
+ if (password == null) return;
+ for (int i = 0; i < password.length; i++)
+ {
+ password[i] = '\u0000';
+ }
+ }
+
+ /**
+ * Get the iteration count, or 0 if it has not been specified.
+ *
+ * @return The iteration count, or 0 if it has not been specified.
+ */
+ public final int getIterationCount()
+ {
+ return iterationCount;
+ }
+
+ /**
+ * Get the generated key length, or 0 if it has not been specified.
+ *
+ * @return The key length, or 0 if it has not been specified.
+ */
+ public final int getKeyLength()
+ {
+ return keyLength;
+ }
+
+ /**
+ * Get the password character array.
+ *
+ * @return The password.
+ */
+ public final char[] getPassword()
+ {
+ return password;
+ }
+
+ /**
+ * Get the salt bytes.
+ *
+ * @return The salt.
+ */
+ public final byte[] getSalt()
+ {
+ return salt;
+ }
+}
diff --git a/libjava/javax/crypto/spec/PBEParameterSpec.java b/libjava/javax/crypto/spec/PBEParameterSpec.java
new file mode 100644
index 00000000000..f45c866c9d8
--- /dev/null
+++ b/libjava/javax/crypto/spec/PBEParameterSpec.java
@@ -0,0 +1,100 @@
+/* PBEParameterSpec.java -- A wrapper for PBE parameters.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * A wrapper for the parameters used in <a
+ * href="http://www.rsasecurity.com/rsalabs/pkcs/pkcs-5/">PKCS #5 -
+ * Password-Based Cryptography Standard</a>.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class PBEParameterSpec implements AlgorithmParameterSpec
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ /** The iteration count. */
+ private int iterationCount;
+
+ /** The salt. */
+ private byte[] salt;
+
+ // Constructor.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Creates a new password-based encryption parameter specification.
+ *
+ * @param salt The salt.
+ * @param iterationCount The iteration count.
+ */
+ public PBEParameterSpec(byte[] salt, int iterationCount)
+ {
+ this.salt = salt;
+ this.iterationCount = iterationCount;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the iteration count.
+ *
+ * @return The iteration count.
+ */
+ public int getIterationCount()
+ {
+ return iterationCount;
+ }
+
+ /**
+ * Get the salt.
+ *
+ * @return The salt.
+ */
+ public byte[] getSalt()
+ {
+ return salt;
+ }
+}
diff --git a/libjava/javax/crypto/spec/RC2ParameterSpec.java b/libjava/javax/crypto/spec/RC2ParameterSpec.java
new file mode 100644
index 00000000000..ec9cde71cf1
--- /dev/null
+++ b/libjava/javax/crypto/spec/RC2ParameterSpec.java
@@ -0,0 +1,166 @@
+/* RC2ParameterSpec.java -- Wrapper for RC2 parameters.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * A wrapper for parameters for the <a
+ * href="http://www.rsasecurity.com/rsalabs/faq/3-6-2.html">RC2</a>
+ * block cipher ("RC" means either "Rivest Cipher" or "Ron's Code",
+ * depending upon who you ask and when).
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class RC2ParameterSpec implements AlgorithmParameterSpec
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ /** The length of an RC2 IV, in bytes. */
+ private static final int RC2_IV_LENGTH = 8;
+
+ /** The effective key length, in bits. */
+ private int effectiveKeyBits;
+
+ /** The initialization vector. */
+ private byte[] iv;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create RC2 parameters without an IV.
+ *
+ * @param effectiveKeyBits The number of effective key bits.
+ */
+ public RC2ParameterSpec(int effectiveKeyBits)
+ {
+ this.effectiveKeyBits = effectiveKeyBits;
+ }
+
+ /**
+ * Create RC2 parameters with an IV.
+ *
+ * @param effectiveKeyBits The number of effective key bits.
+ * @param iv The IV; the first eight bytes of this array
+ * are used.
+ */
+ public RC2ParameterSpec(int effectiveKeyBits, byte[] iv)
+ {
+ this(effectiveKeyBits, iv, 0);
+ }
+
+ /**
+ * Create RC2 parameters with an IV.
+ *
+ * @param effectiveKeyBits The number of effective key bits.
+ * @param iv The IV; the first eight bytes of this array
+ * after <code>offset</code> are used.
+ * @param offset From whence to start in the array.
+ */
+ public RC2ParameterSpec(int effectiveKeyBits, byte[] iv, int offset)
+ {
+ if (iv.length - offset < RC2_IV_LENGTH)
+ {
+ throw new IllegalArgumentException("IV too short");
+ }
+ this.effectiveKeyBits = effectiveKeyBits;
+ this.iv = new byte[RC2_IV_LENGTH];
+ System.arraycopy(iv, offset, this.iv, 0, RC2_IV_LENGTH);
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Get the number of effective key bits.
+ *
+ * @return The numer of effective key bits.
+ */
+ public int getEffectiveKeyBits()
+ {
+ return effectiveKeyBits;
+ }
+
+ /**
+ * Return the initialization vector, or <code>null</code> if none was
+ * specified.
+ *
+ * @return The IV, or null.
+ */
+ public byte[] getIV()
+ {
+ return iv;
+ }
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ byte[] oiv = ((RC2ParameterSpec) o).getIV();
+ if (iv != oiv)
+ {
+ if (iv == null || oiv == null) return false;
+ if (iv.length != oiv.length) return false;
+ for (int i = 0; i < iv.length; i++)
+ {
+ if (iv[i] != oiv[i])
+ {
+ return false;
+ }
+ }
+ }
+ return effectiveKeyBits == ((RC2ParameterSpec) o).getEffectiveKeyBits();
+ }
+
+ public int hashCode()
+ {
+ int code = effectiveKeyBits;
+ if (iv != null)
+ {
+ for (int i = 0; i < RC2_IV_LENGTH; i++)
+ {
+ code += iv[i];
+ }
+ }
+ return code;
+ }
+}
diff --git a/libjava/javax/crypto/spec/RC5ParameterSpec.java b/libjava/javax/crypto/spec/RC5ParameterSpec.java
new file mode 100644
index 00000000000..e7549dd63fe
--- /dev/null
+++ b/libjava/javax/crypto/spec/RC5ParameterSpec.java
@@ -0,0 +1,202 @@
+/* RC5ParameterSpec.java -- parameters for RC5.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.AlgorithmParameterSpec;
+
+/**
+ * A wrapper for parameters to the <a
+ * href="http://www.rsasecurity.com/rsalabs/faq/3-6-4.html">RC5</a>
+ * block cipher.
+ *
+ * @author Casey Marshall (csm@gnu.org)
+ * @since 1.4
+ */
+public class RC5ParameterSpec implements AlgorithmParameterSpec
+{
+
+ // Fields.
+ // ------------------------------------------------------------------------
+
+ /** The IV. */
+ private byte[] iv;
+
+ /** The number of rounds. */
+ private int rounds;
+
+ /** The version number. */
+ private int version;
+
+ /** The word size, in bits. */
+ private int wordSize;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create RC5 parameters without an IV.
+ *
+ * @param version The version number.
+ * @param rounds The number of rounds.
+ * @param wordSize The size of a word, in bits.
+ */
+ public RC5ParameterSpec(int version, int rounds, int wordSize)
+ {
+ this.version = version;
+ this.rounds = rounds;
+ this.wordSize = wordSize;
+ }
+
+ /**
+ * Create RC5 parameters with an IV. The bytes in <code>iv</code> in
+ * the range <code>[0, 2*(wordSize/8)-1]</code> are used.
+ *
+ * @param version The version number.
+ * @param rounds The number of rounds.
+ * @param wordSize The size of a word, in bits.
+ * @param iv The IV data.
+ */
+ public RC5ParameterSpec(int version, int rounds, int wordSize, byte[] iv)
+ {
+ this(version, rounds, wordSize, iv, 0);
+ }
+
+ /**
+ * Create RC5 parameters with an IV. The bytes in <code>iv</code> in
+ * the range <code>[off, off+2*(wordSize/8)-1]</code> are used.
+ *
+ * @param version The version number.
+ * @param rounds The number of rounds.
+ * @param wordSize The size of a word, in bits.
+ * @param iv The IV data.
+ * @param off From where in the array the IV starts.
+ */
+ public
+ RC5ParameterSpec(int version, int rounds, int wordSize, byte[] iv, int off)
+ {
+ this(version, rounds, wordSize);
+ int ivLength = 2 * (wordSize / 8);
+ if (off < 0)
+ throw new IllegalArgumentException();
+ if (iv.length - off < ivLength)
+ {
+ throw new IllegalArgumentException("IV too short");
+ }
+ this.iv = new byte[ivLength];
+ System.arraycopy(iv, off, this.iv, 0, ivLength);
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return the initializaiton vector, or <code>null</code> if none was
+ * specified.
+ *
+ * @return The IV, or null.
+ */
+ public byte[] getIV()
+ {
+ return iv;
+ }
+
+ /**
+ * Get the number of rounds.
+ *
+ * @return The number of rounds.
+ */
+ public int getRounds()
+ {
+ return rounds;
+ }
+
+ /**
+ * Get the version number.
+ *
+ * @return The version number.
+ */
+ public int getVersion()
+ {
+ return version;
+ }
+
+ /**
+ * Get the word size, in bits.
+ *
+ * @return The word size, in bits.
+ */
+ public int getWordSize()
+ {
+ return wordSize;
+ }
+
+ public boolean equals(Object o)
+ {
+ if (this == o) return true;
+ byte[] oiv = ((RC5ParameterSpec) o).getIV();
+ if (iv != oiv)
+ {
+ if (iv == null || oiv == null) return false;
+ if (iv.length != oiv.length) return false;
+ for (int i = 0; i < iv.length; i++)
+ {
+ if (iv[i] != oiv[i])
+ {
+ return false;
+ }
+ }
+ }
+ return rounds == ((RC5ParameterSpec) o).getRounds()
+ && version == ((RC5ParameterSpec) o).getVersion()
+ && wordSize == ((RC5ParameterSpec) o).getWordSize();
+ }
+
+ public int hashCode()
+ {
+ int code = rounds + version + wordSize;
+ if (iv != null)
+ {
+ for (int i = 0; i < iv.length; i++)
+ {
+ code += iv[i];
+ }
+ }
+ return code;
+ }
+}
diff --git a/libjava/javax/crypto/spec/SecretKeySpec.java b/libjava/javax/crypto/spec/SecretKeySpec.java
new file mode 100644
index 00000000000..6d9f4b8feb2
--- /dev/null
+++ b/libjava/javax/crypto/spec/SecretKeySpec.java
@@ -0,0 +1,154 @@
+/* SecretKeySpec.java -- Wrapper for secret keys.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.crypto.spec;
+
+import java.security.spec.KeySpec;
+import javax.crypto.SecretKey;
+
+/**
+ * This is a simple wrapper around a raw byte array, for ciphers that do
+ * not require any key parameters other than the bytes themselves.
+ *
+ * <p>Since this class implements {@link javax.crypto.SecretKey}, which
+ * in turn extends {@link java.security.Key}, so instances of this class
+ * may be passed directly to the <code>init()</code> methods of {@link
+ * javax.crypto.Cipher}.
+ *
+ * @see javax.crypto.SecretKey
+ * @see javax.crypto.SecretKeyFactory
+ */
+public class SecretKeySpec implements KeySpec, SecretKey
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------------
+
+ /** Compatible with JDK1.4. */
+ private static final long serialVersionUID = 6577238317307289933L;
+
+ /** The key bytes. */
+ private byte[] key;
+
+ /** The algorithm's name. */
+ private String algorithm;
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create a new secret key spec from an entire byte array.
+ *
+ * @param key The key material.
+ * @param algorithm The name of the algorithm using this key.
+ */
+ public SecretKeySpec(byte[] key, String algorithm)
+ {
+ this(key, 0, key.length, algorithm);
+ }
+
+ /**
+ * Create a new secret key spec from part of a byte array.
+ *
+ * @param key The key material.
+ * @param off The offset at which key material begins.
+ * @param len The length of key material.
+ * @param algorithm The name of the algorithm using this key.
+ */
+ public SecretKeySpec(byte[] key, int off, int len, String algorithm)
+ {
+ this.key = new byte[len];
+ this.algorithm = algorithm;
+ System.arraycopy(key, off, this.key, 0, len);
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Return the name of the algorithm associated with this secret key.
+ *
+ * @return The algorithm's name.
+ */
+ public String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Return the key as a byte array.
+ *
+ * @return The key material.
+ */
+ public byte[] getEncoded()
+ {
+ return key;
+ }
+
+ /**
+ * This key's format, which is always "RAW".
+ *
+ * @return "RAW"
+ */
+ public String getFormat()
+ {
+ return "RAW";
+ }
+
+ public boolean equals(Object o)
+ {
+ byte[] okey = ((SecretKeySpec) o).getEncoded();
+ if (key.length != okey.length) return false;
+ for (int i = 0; i < key.length; i++)
+ {
+ if (key[i] != okey[i])
+ return false;
+ }
+ return algorithm.equals(((SecretKeySpec) o).getAlgorithm());
+ }
+
+ public int hashCode()
+ {
+ int code = 0;
+ for (int i = 0; i < key.length; i++)
+ {
+ code ^= (key[i] & 0xff) << (i << 3 & 31);
+ }
+ return code ^ algorithm.hashCode();
+ }
+}
diff --git a/libjava/javax/net/ServerSocketFactory.java b/libjava/javax/net/ServerSocketFactory.java
new file mode 100644
index 00000000000..d20c7fbe9f2
--- /dev/null
+++ b/libjava/javax/net/ServerSocketFactory.java
@@ -0,0 +1,122 @@
+/* ServerSocketFactory.java -- factory for server sockets.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net;
+
+import java.io.IOException;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+
+import java.security.Security;
+
+/**
+ * A factory for server sockets. The purpose of this class is to serve
+ * as the superclass of server socket factories that produce server
+ * sockets of a particular type, such as <i>Secure Socket Layer</i>
+ * (<b>SSL</b>) server sockets.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public abstract class ServerSocketFactory
+{
+
+ // Constructors.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Default 0-argument constructor.
+ */
+ protected ServerSocketFactory()
+ {
+ super();
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Returns the default server socket factory. The type of factory
+ * returned may depend upon the installation.
+ *
+ * @return The default server socket factory.
+ */
+ public static synchronized ServerSocketFactory getDefault()
+ {
+ try
+ {
+ String s = Security.getProperty("gnu.defaultServerSocketFactory");
+ if (s != null)
+ {
+ Class c = Class.forName(s);
+ return (ServerSocketFactory) c.newInstance();
+ }
+ }
+ catch (Exception e)
+ {
+ }
+ return new VanillaServerSocketFactory();
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------------
+
+ /**
+ * Create an unbound server socket.
+ *
+ * @return The new server socket.
+ * @throws IOException If a networking error occurs.
+ */
+ public ServerSocket createServerSocket() throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Create a server socket bound to the given port.
+ *
+ * @param port The port to bind the server socket to.
+ * @return A server socket bound to <i>port</i>.
+ * @throws IOException If a networking error occurs.
+ */
+ public abstract ServerSocket createServerSocket(int port) throws IOException;
+
+ public abstract ServerSocket createServerSocket(int port, int backlog) throws IOException;
+
+ public abstract ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddress) throws IOException;
+}
diff --git a/libjava/javax/net/SocketFactory.java b/libjava/javax/net/SocketFactory.java
new file mode 100644
index 00000000000..9e236d2dfe3
--- /dev/null
+++ b/libjava/javax/net/SocketFactory.java
@@ -0,0 +1,157 @@
+/* SocketFactory.java -- factory for client sockets.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net;
+
+import java.io.IOException;
+
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+import java.security.Security;
+
+/**
+ * A factory for client sockets. The purpose of this class is to serve
+ * as the superclass of server socket factories that produce client
+ * sockets of a particular type, such as <i>Secure Socket Layer</i>
+ * (<b>SSL</b>) sockets.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public abstract class SocketFactory
+{
+
+ // Constructor.
+ // -------------------------------------------------------------------
+
+ /**
+ * Default 0-arguments constructor.
+ */
+ protected SocketFactory()
+ {
+ super();
+ }
+
+ // Class methods.
+ // -------------------------------------------------------------------
+
+ /**
+ * Returns the default socket factory. The type of factory
+ * returned may depend upon the installation.
+ *
+ * @return The default socket factory.
+ */
+ public static synchronized SocketFactory getDefault()
+ {
+ try
+ {
+ String s = Security.getProperty("gnu.defaultSocketFactory");
+ if (s != null)
+ {
+ Class c = Class.forName(s);
+ return (SocketFactory) c.newInstance();
+ }
+ }
+ catch (Exception e)
+ {
+ }
+ return new VanillaSocketFactory();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------
+
+ /**
+ * Returns an unbound client socket.
+ *
+ * @return The new, unbound socket.
+ */
+ public Socket createSocket() throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * Creates a socket connected to a given host on a given port.
+ *
+ * @param host The hostname to connect to.
+ * @param port The port on <i>host</i> to connect to.
+ * @return A socket connected to <i>host</i> on <i>port</i>.
+ * @throws IOException If a network error occurs.
+ * @throws UnknownHostException If <i>host</i> cannot be resolved.
+ */
+ public abstract Socket createSocket(String host, int port) throws IOException, UnknownHostException;
+
+ /**
+ * Creates a socket connected to a given host on a given port,
+ * connecting locally to the interface with the given address and port.
+ *
+ * @param host The hostname to connect to.
+ * @param port The port on <i>host</i> to connect to.
+ * @param localHost The address of the local interface to bind to.
+ * @param localPort The local port to bind to.
+ * @return A socket connected to <i>host</i> on <i>port</i>.
+ * @throws IOException If a network error occurs.
+ * @throws UnknownHostException If <i>host</i> cannot be resolved.
+ */
+ public abstract Socket createSocket(String host, int port, InetAddress localHost, int localPort) throws IOException, UnknownHostException;
+
+ /**
+ * Creates a socket connected to a given host on a given port.
+ *
+ * @param host The host address to connect to.
+ * @param port The port on <i>host</i> to connect to.
+ * @return A socket connected to <i>host</i> on <i>port</i>.
+ * @throws IOException If a network error occurs.
+ */
+ public abstract Socket createSocket(InetAddress host, int port) throws IOException;
+
+ /**
+ * Creates a socket connected to a given host on a given port,
+ * connecting locally to the interface with the given address and port.
+ *
+ * @param host The host address to connect to.
+ * @param port The port on <i>host</i> to connect to.
+ * @param localHost The address of the local interface to bind to.
+ * @param localPort The local port to bind to.
+ * @return A socket connected to <i>host</i> on <i>port</i>.
+ * @throws IOException If a network error occurs.
+ */
+ public abstract Socket createSocket(InetAddress hast, int port, InetAddress localHost, int localPort) throws IOException;
+}
diff --git a/libjava/javax/net/VanillaServerSocketFactory.java b/libjava/javax/net/VanillaServerSocketFactory.java
new file mode 100644
index 00000000000..e52ecba9ee3
--- /dev/null
+++ b/libjava/javax/net/VanillaServerSocketFactory.java
@@ -0,0 +1,82 @@
+/* VanillaServerSocketFactory.java -- trivial socket factory.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net;
+
+import java.io.IOException;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+
+/**
+ * A trivial server socket factory.
+ */
+class VanillaServerSocketFactory extends ServerSocketFactory
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ VanillaServerSocketFactory()
+ {
+ super();
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------
+
+ public ServerSocket createServerSocket() throws IOException
+ {
+ return new ServerSocket();
+ }
+
+ public ServerSocket createServerSocket(int port) throws IOException
+ {
+ return new ServerSocket(port);
+ }
+
+ public ServerSocket createServerSocket(int port, int backlog) throws IOException
+ {
+ return new ServerSocket(port, backlog);
+ }
+
+ public ServerSocket createServerSocket(int port, int backlog, InetAddress bindAddress) throws IOException
+ {
+ return new ServerSocket(port, backlog, bindAddress);
+ }
+}
diff --git a/libjava/javax/net/VanillaSocketFactory.java b/libjava/javax/net/VanillaSocketFactory.java
new file mode 100644
index 00000000000..ace84929378
--- /dev/null
+++ b/libjava/javax/net/VanillaSocketFactory.java
@@ -0,0 +1,88 @@
+/* VanillaSocketFactory.java -- trivial socket factory.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net;
+
+import java.io.IOException;
+
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+/**
+ * A trivial client socket factory.
+ */
+class VanillaSocketFactory extends SocketFactory
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ VanillaSocketFactory()
+ {
+ super();
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------
+
+ public Socket createSocket() throws IOException
+ {
+ return new Socket();
+ }
+
+ public Socket createSocket(String host, int port) throws IOException, UnknownHostException
+ {
+ return new Socket(host, port);
+ }
+
+ public Socket createSocket(String host, int port, InetAddress localAddr, int localPort) throws IOException, UnknownHostException
+ {
+ return new Socket(host, port, localAddr, localPort);
+ }
+
+ public Socket createSocket(InetAddress address, int port) throws IOException
+ {
+ return new Socket(address, port);
+ }
+
+ public Socket createSocket(InetAddress address, int port, InetAddress localAddr, int localPort) throws IOException
+ {
+ return new Socket(address, port, localAddr, localPort);
+ }
+}
diff --git a/libjava/javax/net/ssl/HandshakeCompletedEvent.java b/libjava/javax/net/ssl/HandshakeCompletedEvent.java
new file mode 100644
index 00000000000..6171ebc48e7
--- /dev/null
+++ b/libjava/javax/net/ssl/HandshakeCompletedEvent.java
@@ -0,0 +1,152 @@
+/* HandshakeCompletedEvent.java -- SSL handshake completed.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.cert.Certificate;
+import javax.security.cert.X509Certificate;
+
+/**
+ * An event raised by a SSLSocket and passed to the {@link
+ * HandshakeCompletedListener#handshakeCompleted(HandshakeCompletedEvent)}
+ * method of all registered listeners when a SSL handshake in a SSL
+ * protocol is completed.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public class HandshakeCompletedEvent extends java.util.EventObject
+{
+
+ // Fields.
+ // -------------------------------------------------------------------
+
+ /** Serialization constant. */
+ private static final long serialVersionUID = 7914963744257769778L;
+
+ /** The session. */
+ private transient final SSLSession session;
+
+ // Constructor.
+ // -------------------------------------------------------------------
+
+ /**
+ * Creates a new handshake completed event.
+ *
+ * @param socket The socket (also the source) creating this event.
+ * @param session The associated session object.
+ * @throws NullPointerException If <i>session</i> is null.
+ */
+ public HandshakeCompletedEvent(SSLSocket socket, SSLSession session)
+ {
+ super(socket);
+ if (session == null)
+ throw new NullPointerException();
+ this.session = session;
+ }
+
+ // Instance methods.
+ // --------------------------------------------------------------------
+
+ /**
+ * Returns the name of the cipher that was negotiated in this
+ * connection.
+ *
+ * @return The negotiated cipher name.
+ */
+ public String getCipherSuite()
+ {
+ if (session != null)
+ return session.getCipherSuite();
+ return null;
+ }
+
+ /**
+ * Returns the local certificates being used in this connection.
+ *
+ * @return The local certificates.
+ */
+ public Certificate[] getLocalCertificates()
+ {
+ if (session != null)
+ return session.getLocalCertificates();
+ return null;
+ }
+
+ /**
+ * Returns the peer's certificates being used in this connection.
+ *
+ * @return The peer's certificates.
+ * @throws SSLPeerUnverifiedException If the peer has not been
+ * verified.
+ */
+ public Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException
+ {
+ if (session != null)
+ return session.getPeerCertificates();
+ return null;
+ }
+
+ public X509Certificate[] getPeerCertificateChain() throws SSLPeerUnverifiedException
+ {
+ if (session != null)
+ return session.getPeerCertificateChain();
+ return null;
+ }
+
+ /**
+ * Returns the SSL session object associated with this connection.
+ *
+ * @return The session object.
+ */
+ public SSLSession getSession()
+ {
+ return session;
+ }
+
+ /**
+ * Returns the socket over which this connection is being
+ * negotiated. This method is equivalent to the {@link
+ * java.util.EventObject#getSource()} method.
+ *
+ * @return The socket.
+ */
+ public SSLSocket getSocket()
+ {
+ return (SSLSocket) getSource();
+ }
+}
diff --git a/libjava/javax/net/ssl/HandshakeCompletedListener.java b/libjava/javax/net/ssl/HandshakeCompletedListener.java
new file mode 100644
index 00000000000..5b79bf973d8
--- /dev/null
+++ b/libjava/javax/net/ssl/HandshakeCompletedListener.java
@@ -0,0 +1,57 @@
+/* HandshakeCompletedListener.java -- listens for handshake events.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * An event listener that waits to be notified of {@link
+ * HandshakeCompletedEvent} objects created when handshake phase of
+ * the SSL protocol is completed for a particular connection.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public interface HandshakeCompletedListener extends java.util.EventListener
+{
+
+ /**
+ * Called when the handshake phase of the SSL protocol completes.
+ *
+ * @param event The event describing the new connection.
+ */
+ void handshakeCompleted(HandshakeCompletedEvent event);
+}
diff --git a/libjava/javax/net/ssl/HostnameVerifier.java b/libjava/javax/net/ssl/HostnameVerifier.java
new file mode 100644
index 00000000000..a45648effb3
--- /dev/null
+++ b/libjava/javax/net/ssl/HostnameVerifier.java
@@ -0,0 +1,64 @@
+/* HostnameVerifier.java -- verifies disparate hostnames.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * The interface for classes that perform hostname verification for cases
+ * when the hostname used to begin the connection (such as in a URL)
+ * does not match the hostname used in the SSL handshake.
+ * Implementations of this interface should provide an implementation
+ * of the {@link #verify(java.lang.String,javax.net.ssl.SSLSession)}
+ * method that accepts or rejects hostnames as appropriate.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public interface HostnameVerifier
+{
+
+ /**
+ * Verifies a hostname given a particular SSL session. This method
+ * should return <code>true</code> if the hostname is an accepted
+ * alias for the hostname negotiated in the SSL handshake.
+ *
+ * @param hostname The hostname in question.
+ * @param session The current SSL session.
+ * @return <code>true</code> if the hostname is acceptable.
+ */
+ boolean verify(String hostname, SSLSession session);
+}
diff --git a/libjava/javax/net/ssl/HttpsURLConnection.java b/libjava/javax/net/ssl/HttpsURLConnection.java
new file mode 100644
index 00000000000..a7b86c184b4
--- /dev/null
+++ b/libjava/javax/net/ssl/HttpsURLConnection.java
@@ -0,0 +1,256 @@
+/* HttpsURLConnection.java -- an HTTPS connection.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.URL;
+import java.security.cert.Certificate;
+
+/**
+ * A URL connection that connects via the <i>Secure Socket Layer</i>
+ * (<b>SSL</b>) for HTTPS connections.
+ *
+ * <p>This class may be used in the same way as {@link
+ * HttpURLConnection}, and it will transparently negotiate the SSL
+ * connection.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public abstract class HttpsURLConnection extends HttpURLConnection
+{
+
+ // Fields.
+ // ------------------------------------------------------------------
+
+ /** The default verifier. */
+ private static HostnameVerifier defaultVerifier;
+
+ /** The default factory. */
+ private static SSLSocketFactory defaultFactory;
+
+ /**
+ * The hostname verifier used for this connection.
+ */
+ protected HostnameVerifier hostnameVerifier;
+
+ /**
+ * This connection's socket factory.
+ */
+ private SSLSocketFactory factory;
+
+ // Static initializer.
+ // ------------------------------------------------------------------
+
+ static {
+ defaultVerifier = new TrivialHostnameVerifier();
+ try
+ {
+ defaultFactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
+ }
+ catch (Throwable t)
+ {
+ t.printStackTrace();
+ }
+ }
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ /**
+ * Creates a new HTTPS URL connection.
+ *
+ * @param url The URL of the connection being established.
+ * @throws IOException If the connection cannot be established.
+ */
+ protected HttpsURLConnection(URL url) throws IOException
+ {
+ super(url);
+ hostnameVerifier = defaultVerifier;
+ factory = defaultFactory;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------
+
+ /**
+ * Returns the default hostname verifier used in all new
+ * connections.
+ *
+ * @return The default hostname verifier.
+ */
+ public static HostnameVerifier getDefaultHostnameVerifier()
+ {
+ return defaultVerifier;
+ }
+
+ /**
+ * Sets the default hostname verifier to be used in all new
+ * connections.
+ *
+ * @param newDefault The new default hostname verifier.
+ * @throws IllegalArgumentException If <i>newDefault</i> is null.
+ * @throws SecurityException If there is a security manager
+ * currently installed and the caller does not have the {@link
+ * SSLPermission} "setHostnameVerifier".
+ */
+ public static void setDefaultHostnameVerifier(HostnameVerifier newDefault)
+ {
+ if (newDefault == null)
+ throw new IllegalArgumentException("default verifier cannot be null");
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission(new SSLPermission("setHostnameVerifier"));
+ defaultVerifier = newDefault;
+ }
+
+ /**
+ * Returns the default SSL socket factory used in all new
+ * connections.
+ *
+ * @return The default SSL socket factory.
+ */
+ public static SSLSocketFactory getDefaultSSLSocketFactory()
+ {
+ return defaultFactory;
+ }
+
+ /**
+ * Sets the default SSL socket factory to be used in all new
+ * connections.
+ *
+ * @param newDefault The new socket factory.
+ * @throws IllegalArgumentException If <i>newDefault</i> is null.
+ * @throws SecurityException If there is a security manager
+ * installed and a call to {@link
+ * SecurityManager#checkSetFactory()} fails.
+ */
+ public static void setDefaultSSLSocketFactory(SSLSocketFactory newDefault)
+ {
+ if (newDefault == null)
+ throw new IllegalArgumentException("default factory cannot be null");
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkSetFactory();
+ defaultFactory = newDefault;
+ }
+
+ // Instance methods.
+ // ------------------------------------------------------------------
+
+ /**
+ * Returns the current hostname verifier for this instance.
+ *
+ * @return The hostname verifier.
+ */
+ public HostnameVerifier getHostnameVerifier()
+ {
+ return hostnameVerifier;
+ }
+
+ /**
+ * Sets the hostname verifier for this instance.
+ *
+ * @param hostnameVerifier The new verifier.
+ * @throws IllegalArgumentException If <i>hostnameVerifier</i> is
+ * null.
+ */
+ public void setHostnameVerifier(HostnameVerifier hostnameVerifier)
+ {
+ if (hostnameVerifier == null)
+ throw new IllegalArgumentException("verifier cannot be null");
+ this.hostnameVerifier = hostnameVerifier;
+ }
+
+ /**
+ * Returns the current SSL socket factory for this instance.
+ *
+ * @return The current SSL socket factory.
+ */
+ public SSLSocketFactory getSSLSocketFactory()
+ {
+ return factory;
+ }
+
+ /**
+ * Sets the SSL socket factory for this instance.
+ *
+ * @param factory The new factory.
+ * @throws IllegalArgumentException If <i>factory</i> is null.
+ */
+ public void setSSLSocketFactory(SSLSocketFactory factory)
+ {
+ if (factory == null)
+ throw new IllegalArgumentException("factory cannot be null");
+ this.factory = factory;
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------
+
+ /**
+ * Returns the cipher name negotiated for this connection.
+ *
+ * @return The cipher name.
+ * @throws IllegalStateException If the connection has not yet been
+ * established.
+ */
+ public abstract String getCipherSuite();
+
+ /**
+ * Returns the certificates used on the local side in this
+ * connection.
+ *
+ * @return The local certificates.
+ * @throws IllegalStateException If the connection has not yet been
+ * established.
+ */
+ public abstract Certificate[] getLocalCertificates();
+
+ /**
+ * Returns the certificates sent by the other party.
+ *
+ * @return The peer's certificates.
+ * @throws IllegalStateException If the connection has not yet been
+ * established.
+ * @throws SSLPeerUnverifiedException If the peer could not be
+ * verified.
+ */
+ public abstract Certificate[] getServerCertificates() throws SSLPeerUnverifiedException;
+}
diff --git a/libjava/javax/net/ssl/KeyManager.java b/libjava/javax/net/ssl/KeyManager.java
new file mode 100644
index 00000000000..083f3f592ed
--- /dev/null
+++ b/libjava/javax/net/ssl/KeyManager.java
@@ -0,0 +1,51 @@
+/* KeyManager.java -- marker interface for key manager classes.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * A marker interface for objects that serve as key managers in SSL
+ * communications. Key managers typically keep track of the public
+ * certificates and private keys when authenticating the local host to
+ * remote host, and thus is typically used in SSL servers.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public interface KeyManager
+{
+}
diff --git a/libjava/javax/net/ssl/KeyManagerFactory.java b/libjava/javax/net/ssl/KeyManagerFactory.java
new file mode 100644
index 00000000000..a166f60aa43
--- /dev/null
+++ b/libjava/javax/net/ssl/KeyManagerFactory.java
@@ -0,0 +1,281 @@
+/* KeyManagerFactory.java -- factory for key managers.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.AccessController;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivilegedAction;
+import java.security.Provider;
+import java.security.Security;
+import java.security.UnrecoverableKeyException;
+
+import gnu.java.security.Engine;
+
+/**
+ * A class that creates key manager implementations based on a
+ * requested algorithm.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public class KeyManagerFactory
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------
+
+ /** The service name for key manager factories. */
+ private static final String KEY_MANAGER_FACTORY = "KeyManagerFactory";
+
+ /** The system default trust manager algorithm. */
+ private static final String DEFAULT_ALGORITHM = "JessieX509";
+
+ /** The underlying engine. */
+ private final KeyManagerFactorySpi kmfSpi;
+
+ /** The provider of this implementation. */
+ private final Provider provider;
+
+ /** The name of this algorithm. */
+ private final String algorithm;
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ /**
+ * Create a new key manager factory.
+ *
+ * @param kmfSpi The underlying engine.
+ * @param provider The engine's provider.
+ * @param algorithm The name of this algorithm.
+ */
+ protected KeyManagerFactory(KeyManagerFactorySpi kmfSpi,
+ Provider provider, String algorithm)
+ {
+ this.kmfSpi = kmfSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------
+
+ /**
+ * Get the default algorithm name. This value may be specified at
+ * run-time via the security property
+ * "ssl.KeyManagerFactory.algorithm". If this property is
+ * not specified, this method returns "JessieX509".
+ *
+ * @return The default key manager factory algorithm's name.
+ */
+ public static final String getDefaultAlgorithm()
+ {
+ String alg = null;
+ try
+ {
+ alg = (String) AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ public Object run()
+ {
+ return Security.getProperty("ssl.KeyManagerFactory.algorithm");
+ }
+ }
+ );
+ }
+ catch (SecurityException se)
+ {
+ }
+ if (alg == null)
+ alg = DEFAULT_ALGORITHM;
+ return alg;
+ }
+
+ /**
+ * Get an instance of the named key manager factory, from the first
+ * provider that implements it.
+ *
+ * @param algorithm The type of key manager factory to get.
+ * @return An appropriate implementation of that algoritm.
+ * @throws NoSuchAlgorithmException If no provider implements the
+ * requested algorithm.
+ */
+ public static final KeyManagerFactory getInstance(String algorithm)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(algorithm, provs[i]);
+ }
+ catch (NoSuchAlgorithmException ignore)
+ {
+ }
+ }
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+
+ /**
+ * Get an instance of the named key manager factory, from the named
+ * provider.
+ *
+ * @param algorithm The type of key manager factory to get.
+ * @param provider The name of the provider to get the
+ * implementation from.
+ * @return An appropriate implementation of that algorithm.
+ * @throws NoSuchAlgorithmException If the provider does not
+ * implement the requested algorithm.
+ * @throws NoSuchProviderException If the named provider does not
+ * exist.
+ */
+ public static final KeyManagerFactory getInstance(String algorithm, String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ if (provider == null)
+ throw new IllegalArgumentException("provider is null");
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ throw new NoSuchProviderException(provider);
+ return getInstance(algorithm, p);
+ }
+
+ /**
+ * Get an instance of the named key manager factory, from the given
+ * provider.
+ *
+ * @param algorithm The type of key manager factory to get.
+ * @param provider The provider to get the implementation from.
+ * @return An appropriate implementation of that algorithm.
+ * @throws NoSuchAlgorithmException If the provider does not
+ * implement the requested algorithm.
+ * @throws IllegalArgumentException If <i>provider</i> is null.
+ */
+ public static final KeyManagerFactory getInstance(String algorithm, Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ if (provider == null)
+ throw new IllegalArgumentException("provider is null");
+ try
+ {
+ return new KeyManagerFactory((KeyManagerFactorySpi)
+ Engine.getInstance(KEY_MANAGER_FACTORY, algorithm, provider),
+ provider, algorithm);
+ }
+ catch (InvocationTargetException ite)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------
+
+ /**
+ * Returns the name of this key manager factory algorithm.
+ *
+ * @return The name of this key manager factory algorithm.
+ */
+ public final String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Get an array of key managers appropriate for this algorithm, with
+ * the most preferred manager first.
+ *
+ * @return The array of key managers.
+ */
+ public final KeyManager[] getKeyManagers()
+ {
+ return kmfSpi.engineGetKeyManagers();
+ }
+
+ /**
+ * Returns the provider of this implementation.
+ *
+ * @return The provider of this implementation.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Initialize this instance with an implementation-dependent
+ * parameter object.
+ *
+ * @param params The parameters to initialize with.
+ * @throws InvalidAlgorithmParameterException If the specified
+ * parameters are inappropriate.
+ */
+ public final void init(ManagerFactoryParameters params)
+ throws InvalidAlgorithmParameterException
+ {
+ kmfSpi.engineInit(params);
+ }
+
+ /**
+ * Initialize this instance with a key store and a password for
+ * private key entries.
+ *
+ * @param store The key store to read.
+ * @param passwd The password protecting private keys in the store.
+ * @throws KeyStoreException If an error occurs reading the keys.
+ * @throws NoSuchAlgorithmException If an algorithm (such as a
+ * certificate algorithm) is not available.
+ * @throws UnrecoverableKeyException If the password is incorrect.
+ */
+ public final void init(KeyStore store, char[] passwd)
+ throws KeyStoreException, NoSuchAlgorithmException, UnrecoverableKeyException
+ {
+ kmfSpi.engineInit(store, passwd);
+ }
+}
diff --git a/libjava/javax/net/ssl/KeyManagerFactorySpi.java b/libjava/javax/net/ssl/KeyManagerFactorySpi.java
new file mode 100644
index 00000000000..3ed978f356c
--- /dev/null
+++ b/libjava/javax/net/ssl/KeyManagerFactorySpi.java
@@ -0,0 +1,102 @@
+/* KeyManagerFactorySpi.java -- SPI for key manager factories.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+
+/**
+ * The <i>Service Provider Interface</i> (<b>SPI</b>) for key manager
+ * factories.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public abstract class KeyManagerFactorySpi
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ public KeyManagerFactorySpi()
+ {
+ super();
+ }
+
+ // Abstract methods.
+ // ------------------------------------------------------------------
+
+ /**
+ * Engine method for retrieving this factory's key managers.
+ *
+ * @return The key managers.
+ */
+ protected abstract KeyManager[] engineGetKeyManagers();
+
+ /**
+ * Engine method for initializing this factory with some
+ * algorithm-specific parameters.
+ *
+ * @param params The factory parameters.
+ * @throws InvalidAlgorithmParameterException If the supplied parameters
+ * are inappropriate for this instance.
+ */
+ protected abstract void engineInit(ManagerFactoryParameters params)
+ throws InvalidAlgorithmParameterException;
+
+ /**
+ * Engine method for initializing this factory with a key store and a
+ * password for private keys. Either parameter may be <code>null</code>,
+ * in which case some default parameters (possibly derived from system
+ * properties) should be used.
+ *
+ * @param store The key store.
+ * @param passwd The private key password.
+ * @throws KeyStoreException If the key store cannot be accessed.
+ * @throws NoSuchAlgorithmException If some of the data from the key
+ * store cannot be retrieved.
+ * @throws UnrecoverableKeyException If a private key cannot be retrieved,
+ * likely from a wrong password.
+ */
+ protected abstract void engineInit(KeyStore store, char[] passwd)
+ throws KeyStoreException, NoSuchAlgorithmException,
+ UnrecoverableKeyException;
+}
diff --git a/libjava/javax/net/ssl/ManagerFactoryParameters.java b/libjava/javax/net/ssl/ManagerFactoryParameters.java
new file mode 100644
index 00000000000..6d3e008dea9
--- /dev/null
+++ b/libjava/javax/net/ssl/ManagerFactoryParameters.java
@@ -0,0 +1,50 @@
+/* ManagerFactoryParameters.java -- marker interface for manager parameters.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * A marker interface for classes that serve as key or trust manager
+ * parameters, used to initialize instances of {@link
+ * KeyManagerFactory} or {@link TrustManagerFactory}.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public interface ManagerFactoryParameters
+{
+}
diff --git a/libjava/javax/net/ssl/SSLContext.java b/libjava/javax/net/ssl/SSLContext.java
new file mode 100644
index 00000000000..45e01c3c7be
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLContext.java
@@ -0,0 +1,269 @@
+/* SSLContext.java -- an SSL protocol context.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.KeyManagementException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.Provider;
+import java.security.SecureRandom;
+import java.security.Security;
+
+import gnu.java.security.Engine;
+
+/**
+ * A "meta-factory" for protocol-specific socket and server socket
+ * factories. This class serves as a clearinghouse for socket
+ * factories and cached session contexts for a particular protocol,
+ * such as SSLv3.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public class SSLContext
+{
+
+ // Constants and fields.
+ // ------------------------------------------------------------------
+
+ /** Service name for SSL contexts. */
+ private static final String SSL_CONTEXT = "SSLContext";
+
+ /** The underlying engine. */
+ private final SSLContextSpi ctxSpi;
+
+ /** The provider of the engine class. */
+ private final Provider provider;
+
+ /** The protocal name. */
+ private final String protocol;
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ /**
+ * Create a new SSL context.
+ *
+ * @param ctxSpi The context engine.
+ * @param provider The provider of the implementation.
+ * @param protocol The name of the SSL protocol.
+ */
+ protected SSLContext(SSLContextSpi ctxSpi, Provider provider,
+ String protocol)
+ {
+ this.ctxSpi = ctxSpi;
+ this.provider = provider;
+ this.protocol = protocol;
+ }
+
+ // Class methods.
+ // ------------------------------------------------------------------
+
+ /**
+ * Get an instance of a context for the specified protocol from the
+ * first provider that implements it.
+ *
+ * @param protocol The name of the protocol to get a context for.
+ * @return The new context.
+ * @throws NoSuchAlgorithm If no provider implements the given
+ * protocol.
+ */
+ public static final SSLContext getInstance(String protocol)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(protocol, provs[i]);
+ }
+ catch (NoSuchAlgorithmException ignore)
+ {
+ }
+ }
+ throw new NoSuchAlgorithmException(protocol);
+ }
+
+ /**
+ * Get an instance of a context for the specified protocol from the
+ * named provider.
+ *
+ * @param protocol The name of the protocol to get a context for.
+ * @param provider The name of the provider to get the
+ * implementation from.
+ * @return The new context.
+ * @throws NoSuchAlgorithmException If the provider does not
+ * implement the given protocol.
+ * @throws NoSuchProviderException If the named provider does not
+ * exist.
+ * @throws IllegalArgumentException If <i>provider</i> is null.
+ */
+ public static final SSLContext getInstance(String protocol,
+ String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ if (provider == null)
+ {
+ throw new IllegalArgumentException();
+ }
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(protocol, p);
+ }
+
+ /**
+ * Get an instance of a context for the specified protocol from the
+ * specified provider.
+ *
+ * @param protocol The name of the protocol to get a context for.
+ * @param provider The name of the provider to get the
+ * implementation from.
+ * @return The new context.
+ * @throws NoSuchAlgorithmException If the provider does not
+ * implement the given protocol.
+ * @throws IllegalArgumentException If <i>provider</i> is null.
+ */
+ public static final SSLContext getInstance(String protocol,
+ Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ try
+ {
+ return new SSLContext((SSLContextSpi)
+ Engine.getInstance(SSL_CONTEXT, protocol, provider),
+ provider, protocol);
+ }
+ catch (InvocationTargetException ite)
+ {
+ ite.printStackTrace();
+ throw new NoSuchAlgorithmException();
+ }
+ catch (ClassCastException cce)
+ {
+ cce.printStackTrace();
+ throw new NoSuchAlgorithmException();
+ }
+ }
+
+ // Instance methods.
+ // -----------------------------------------------------------------
+
+ /**
+ * Returns the set of SSL contexts available for client connections.
+ *
+ * @return The set of SSL contexts available for client connections.
+ */
+ public final SSLSessionContext getClientSessionContext()
+ {
+ return ctxSpi.engineGetClientSessionContext();
+ }
+
+ /**
+ * Returns the protocol name of this context.
+ *
+ * @return The protocol name of this context.
+ */
+ public final String getProtocol()
+ {
+ return protocol;
+ }
+
+ /**
+ * Returns the provider of this implementation.
+ *
+ * @return The provider of this implementation.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Returns the set of SSL contexts available for server connections.
+ *
+ * @return The set of SSL contexts available for server connections.
+ */
+ public final SSLSessionContext getServerSessionContext()
+ {
+ return ctxSpi.engineGetServerSessionContext();
+ }
+
+ /**
+ * Returns the factory for server SSL sockets.
+ *
+ * @return The factory for server SSL sockets.
+ */
+ public final SSLServerSocketFactory getServerSocketFactory()
+ {
+ return ctxSpi.engineGetServerSocketFactory();
+ }
+
+ /**
+ * Returns the factory for client SSL sockets.
+ *
+ * @return The factory for client SSL sockets.
+ */
+ public final SSLSocketFactory getSocketFactory()
+ {
+ return ctxSpi.engineGetSocketFactory();
+ }
+
+ /**
+ * Initializes this context and prepares it for producing socket
+ * factories. All of the parameters are optional; default values are
+ * used if left unspecified.
+ *
+ * @param keyManagers The set of key managers to use.
+ * @param trustManagers The set of trust managers to use.
+ * @param random A source of random bits to use.
+ * @throws KeyManagementException If initialization fails.
+ */
+ public final void init(KeyManager[] keyManagers,
+ TrustManager[] trustManagers,
+ SecureRandom random)
+ throws KeyManagementException
+ {
+ ctxSpi.engineInit(keyManagers, trustManagers, random);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLContextSpi.java b/libjava/javax/net/ssl/SSLContextSpi.java
new file mode 100644
index 00000000000..ecac1cbc5af
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLContextSpi.java
@@ -0,0 +1,109 @@
+/* SSLContextSpi.java -- SPI for SSL contexts.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.KeyManagementException;
+import java.security.SecureRandom;
+
+/**
+ * The <i>Service Provider Interface</i> (<b>SPI</b>) for SSLContext
+ * objects.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public abstract class SSLContextSpi
+{
+
+ // Constructor.
+ // -------------------------------------------------------------------
+
+ /**
+ * Create a new SSLContextSpi.
+ */
+ public SSLContextSpi()
+ {
+ super();
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------
+
+ /**
+ * Returns the set of SSL sessions available for client connections.
+ *
+ * @return The set of SSL sessions available for client connections.
+ */
+ protected abstract SSLSessionContext engineGetClientSessionContext();
+
+ /**
+ * Returns the set of SSL sessions available for server connections.
+ *
+ * @return The set of SSL sessions available for server connections.
+ */
+ protected abstract SSLSessionContext engineGetServerSessionContext();
+
+ /**
+ * Returns the SSL server socket factory.
+ *
+ * @return The SSL server socket factory.
+ */
+ protected abstract SSLServerSocketFactory engineGetServerSocketFactory();
+
+ /**
+ * Returns the SSL client socket factory.
+ *
+ * @return The SSL client socket factory.
+ */
+ protected abstract SSLSocketFactory engineGetSocketFactory();
+
+ /**
+ * Initialize this context with key and trust managers, and a source
+ * of randomness. All of the parameters are optional.
+ *
+ * @param keyManagers The set of key managers.
+ * @param trustManagers The set of trust managers.
+ * @param random The source of randomness.
+ * @throws KeyManagementException If this context cannot be
+ * initialized with these parameters.
+ */
+ protected abstract void engineInit(KeyManager[] keyManagers,
+ TrustManager[] trustManagers,
+ SecureRandom random)
+ throws KeyManagementException;
+}
diff --git a/libjava/javax/net/ssl/SSLException.java b/libjava/javax/net/ssl/SSLException.java
new file mode 100644
index 00000000000..0a33b458fa5
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLException.java
@@ -0,0 +1,59 @@
+/* SSLException.java -- generic SSL exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.io.IOException;
+
+/**
+ * The superclass of all possible SSL exceptions. Usually, a specific
+ * exception is thrown instead of this exception.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public class SSLException extends IOException
+{
+
+ // Constructor.
+ // ------------------------------------------------------------------
+
+ public SSLException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLHandshakeException.java b/libjava/javax/net/ssl/SSLHandshakeException.java
new file mode 100644
index 00000000000..c0f2c5cbb8f
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLHandshakeException.java
@@ -0,0 +1,51 @@
+/* SSLHandshakeException.java -- exception in SSL handshake.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * An exception that signals an error in the SSL handshake phase.
+ */
+public class SSLHandshakeException extends SSLException
+{
+
+ public SSLHandshakeException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLKeyException.java b/libjava/javax/net/ssl/SSLKeyException.java
new file mode 100644
index 00000000000..c60cac19fe6
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLKeyException.java
@@ -0,0 +1,52 @@
+/* SSLKeyException.java -- exception in using a key in SSL.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * An exception signaling a problem using a public or private key in
+ * an SSL communication.
+ */
+public class SSLKeyException extends SSLException
+{
+
+ public SSLKeyException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLPeerUnverifiedException.java b/libjava/javax/net/ssl/SSLPeerUnverifiedException.java
new file mode 100644
index 00000000000..1b3acbc2497
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLPeerUnverifiedException.java
@@ -0,0 +1,51 @@
+/* SSLPeerUnverifiedException.java -- unverified peer exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * An exception thrown when the remote peer could not be verified.
+ */
+public class SSLPeerUnverifiedException extends SSLException
+{
+
+ public SSLPeerUnverifiedException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLPermission.java b/libjava/javax/net/ssl/SSLPermission.java
new file mode 100644
index 00000000000..3771eaf9828
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLPermission.java
@@ -0,0 +1,66 @@
+/* SSLPermission.java -- SSL permission class.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.BasicPermission;
+
+/**
+ * A permission used for accessing SSL classes.
+ */
+public class SSLPermission extends BasicPermission
+{
+
+ // Constant.
+ // -------------------------------------------------------------------------
+
+ private static final long serialVersionUID = -3456898025505876775L;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public SSLPermission(String name)
+ {
+ super(name);
+ }
+
+ public SSLPermission(String name, String actions)
+ {
+ super(name, actions);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLProtocolException.java b/libjava/javax/net/ssl/SSLProtocolException.java
new file mode 100644
index 00000000000..16a1457ab3e
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLProtocolException.java
@@ -0,0 +1,53 @@
+/* SSLProtocolException.java -- exception in SSL protocol.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * An exception thrown when a fatal protocol error is encountered. This
+ * exception usually indicates some serious problem with the local or
+ * remote SSL implementation.
+ */
+public class SSLProtocolException extends SSLException
+{
+
+ public SSLProtocolException(String message)
+ {
+ super(message);
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLServerSocket.java b/libjava/javax/net/ssl/SSLServerSocket.java
new file mode 100644
index 00000000000..fee99f48e4b
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLServerSocket.java
@@ -0,0 +1,188 @@
+/* SSLServerSocket.java -- a server socket for SSL connections.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.io.IOException;
+
+import java.net.InetAddress;
+import java.net.ServerSocket;
+
+/**
+ * A server socket that allows clients to connect via the SSL protocol.
+ */
+public abstract class SSLServerSocket extends ServerSocket
+{
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ protected SSLServerSocket() throws IOException
+ {
+ super();
+ //super(0);
+ //throw new UnsupportedOperationException("1.4 socket methods not enabled");
+ }
+
+ protected SSLServerSocket(int port) throws IOException
+ {
+ super(port);
+ }
+
+ protected SSLServerSocket(int port, int backlog) throws IOException
+ {
+ super(port, backlog);
+ }
+
+ protected SSLServerSocket(int port, int backlog, InetAddress bindAddress)
+ throws IOException
+ {
+ super(port, backlog, bindAddress);
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the list of cihper suites that are currently enabled in this
+ * server socket. Sockets accepted by this server socket will only have
+ * these suites enabled.
+ *
+ * @return The enabled cipher suites.
+ */
+ public abstract String[] getEnabledCipherSuites();
+
+ /**
+ * Sets the list enabled cipher suites.
+ *
+ * @param suites The cipher suites to enable.
+ */
+ public abstract void setEnabledCipherSuites(String[] suites);
+
+ /**
+ * Returns the list of enabled protocols, such as "SSLv3" and "TLSv1".
+ *
+ * @return The enabled protocols.
+ */
+ public abstract String[] getEnabledProtocols();
+
+ /**
+ * Sets the list of enabled protocols.
+ *
+ * @param protocols The list of protocols to enable.
+ */
+ public abstract void setEnabledProtocols(String[] protocols);
+
+ /**
+ * Returns whether or not sessions will be created, i.e., whether or not
+ * this server socket will allow SSL session resumption.
+ *
+ * @return True if sessions will be created.
+ */
+ public abstract boolean getEnableSessionCreation();
+
+ /**
+ * Sets whether or not sessions will be created.
+ *
+ * @param enabled The new enabled value.
+ */
+ public abstract void setEnableSessionCreation(boolean enabled);
+
+ /**
+ * Returns whether or not this server socket will require clients to
+ * authenticate themselves, such as through a certificate.
+ *
+ * @return True if clients must authenticate themselves.
+ */
+ public abstract boolean getNeedClientAuth();
+
+ /**
+ * Enabled or disables the requirement that clients authenticate themselves.
+ * When this is set to <code>true</code>, connections will be rejected if
+ * connecting clients do not provide proper authentication.
+ *
+ * @param needAuth The new need auth value.
+ */
+ public abstract void setNeedClientAuth(boolean needAuth);
+
+ /**
+ * Returns whether or not sockets accepted by this server socket will do
+ * their handshake as the client-side. The default is false.
+ *
+ * @return True if client mode will be used.
+ */
+ public abstract boolean getUseClientMode();
+
+ /**
+ * Sets whether or not sockets accepted by this server socket will be
+ * created in client mode.
+ *
+ * @param clientMode The new client mode value.
+ */
+ public abstract void setUseClientMode(boolean clientMode);
+
+ /**
+ * Returns whether or not this socket will ask for, but not require, that
+ * connecting clients authenticate themselves. Clients that do not
+ * provide authentication they will still be allowed to connect.
+ *
+ * @return True if this server socket wants client authentication.
+ */
+ public abstract boolean getWantClientAuth();
+
+ /**
+ * Sets whether or not this server socket will want client authentication.
+ *
+ * @param wantAuth The new want auth value.
+ */
+ public abstract void setWantClientAuth(boolean wantAuth);
+
+ /**
+ * Returns a list of cipher suites that this server socket supports.
+ *
+ * @return The list of supported suites.
+ */
+ public abstract String[] getSupportedCipherSuites();
+
+ /**
+ * Returns a list of SSL protocols supported by this server socket.
+ *
+ * @return The list of supported protocols.
+ */
+ public abstract String[] getSupportedProtocols();
+}
diff --git a/libjava/javax/net/ssl/SSLServerSocketFactory.java b/libjava/javax/net/ssl/SSLServerSocketFactory.java
new file mode 100644
index 00000000000..ef82d146294
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLServerSocketFactory.java
@@ -0,0 +1,172 @@
+/* SSLServerSocketFactory.java -- factory for SSL server sockets.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.KeyStore;
+import java.security.Security;
+import javax.net.ServerSocketFactory;
+
+/**
+ * A server socket factory for <i>Secure Socket Layer</i> (<b>SSL</b>)
+ * server sockets.
+ */
+public abstract class SSLServerSocketFactory extends ServerSocketFactory
+{
+
+ // Field.
+ // -------------------------------------------------------------------------
+
+ private static SSLContext context;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ protected SSLServerSocketFactory()
+ {
+ super();
+ }
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns a default implementation of a SSL server socket factory.
+ *
+ * <p>To control the class that gets returned by this method, set the
+ * security property "ssl.ServerSocketFactory.provider" to the class
+ * name of a concrete implementation of this class. If not set, a
+ * system-dependent implementation will be used.</p>
+ *
+ * <p>The implementation returned is created by the first implementation
+ * of the {@link SSLContext} class found, which is initialized with
+ * default parameters. To control the key and trust manager factory
+ * algorithms used as defaults, set the security properties
+ * "ssl.keyManagerFactory.algorithm" and "ssl.trustManagerFactory.algorithm"
+ * to the appropriate names.</p>
+ *
+ * <p>Using this method is not recommended. Instead, use the methods of
+ * {@link SSLContext}, which provide much better control over the
+ * creation of server socket factories.</p>
+ *
+ * @return The default server socket factory.
+ * @throws RuntimeException If no default can be created.
+ */
+ public static synchronized ServerSocketFactory getDefault()
+ {
+ try
+ {
+ String s = Security.getProperty("ssl.ServerSocketFactory.provider");
+ ClassLoader cl = ClassLoader.getSystemClassLoader();
+ if (s != null && cl != null)
+ {
+ return (ServerSocketFactory) cl.loadClass(s).newInstance();
+ }
+ }
+ catch (Exception e)
+ {
+ }
+ if (context == null)
+ {
+ KeyManager[] km = null;
+ TrustManager[] tm = null;
+
+ // 1. Determine which algorithms to use for the key and trust
+ // manager factories.
+ String kmAlg = KeyManagerFactory.getDefaultAlgorithm();
+ String tmAlg = TrustManagerFactory.getDefaultAlgorithm();
+ // 2. Try to initialize the factories with default parameters.
+ try
+ {
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmAlg);
+ kmf.init(null, null);
+ km = kmf.getKeyManagers();
+ }
+ catch (Exception ex)
+ {
+ }
+ try
+ {
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlg);
+ tmf.init((KeyStore) null);
+ tm = tmf.getTrustManagers();
+ }
+ catch (Exception ex)
+ {
+ }
+
+ // 3. Create and initialize a context.
+ try
+ {
+ context = SSLContext.getInstance("SSLv3");
+ context.init(km, tm, null);
+ }
+ catch (Exception ex)
+ {
+ throw new RuntimeException("error instantiating default server socket factory: "
+ + ex.toString());
+ }
+ }
+ try
+ {
+ return context.getServerSocketFactory();
+ }
+ catch (Exception e)
+ {
+ }
+ throw new RuntimeException("no SSLSocketFactory implementation available");
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the list of cipher suites that will be enabled in server sockets
+ * created by this factory.
+ *
+ * @return The default cipher suites.
+ */
+ public abstract String[] getDefaultCipherSuites();
+
+ /**
+ * Returns the list of all cipher suites supported by this factory.
+ *
+ * @return The list of supported cipher suites.
+ */
+ public abstract String[] getSupportedCipherSuites();
+}
diff --git a/libjava/javax/net/ssl/SSLSession.java b/libjava/javax/net/ssl/SSLSession.java
new file mode 100644
index 00000000000..14797f083a7
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLSession.java
@@ -0,0 +1,168 @@
+/* SSLSession.java -- an SSL session.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.cert.Certificate;
+import javax.security.cert.X509Certificate;
+
+/**
+ * An SSL session is a mechanism through which connections can be established
+ * by re-using previously negotiated handshakes.
+ */
+public interface SSLSession
+{
+
+ /**
+ * Returns this session's cihper suite.
+ *
+ * @return The cipher suite.
+ */
+ String getCipherSuite();
+
+ /**
+ * Returns the time in milliseconds since midnight GMT, 1 January 1970, that
+ * this session was created.
+ *
+ * @return The creation time.
+ */
+ long getCreationTime();
+
+ /**
+ * Returns this session's unique identifier, a arbitrary byte array of up
+ * to 32 bytes.
+ *
+ * @return The session identifier.
+ */
+ byte[] getId();
+
+ /**
+ * Returns the last time this session was accessed.
+ *
+ * @return The lest time this session was accessed.
+ */
+ long getLastAccessedTime();
+
+ /**
+ * Returns the chain of certificates that the local side used in the
+ * handshake, or null if none were used.
+ *
+ * @return The local certificate chain.
+ */
+ Certificate[] getLocalCertificates();
+
+ /**
+ * Returns the chain of certificates that the remote side used in
+ * the handshake, or null if none were used.
+ *
+ * @return The peer's certificate chain.
+ * @throws SSLPeerUnverifiedException If the identity of the peer has
+ * not been verified.
+ */
+ Certificate[] getPeerCertificates() throws SSLPeerUnverifiedException;
+
+ /**
+ * Returns the chain of certificates that the remote side used in
+ * the handshake, or null if none were used.
+ *
+ * @return The peer's certificate chain.
+ * @throws SSLPeerUnverifiedException If the identity of the peer has
+ * not been verified.
+ */
+ X509Certificate[] getPeerCertificateChain()
+ throws SSLPeerUnverifiedException;
+
+ /**
+ * Returns the remote host's name.
+ *
+ * @return The name of the remote host.
+ */
+ String getPeerHost();
+
+ /**
+ * Returns the protocol this session uses.
+ *
+ * @return The protocol.
+ */
+ String getProtocol();
+
+ /**
+ * Returns this session's session context object.
+ *
+ * @return The session context.
+ * @throws SecurityException If the caller does not have the
+ * {@link SSLPermission} "getSessionContext".
+ */
+ SSLSessionContext getSessionContext();
+
+ /**
+ * Returns the names of all values bound to this session.
+ *
+ * @return The list of bound names.
+ */
+ String[] getValueNames();
+
+ /**
+ * Returns the object bound to the given name.
+ *
+ * @param name The name of the value to get.
+ * @return The object bound by that name, or null.
+ */
+ Object getValue(String name);
+
+ /**
+ * Invalidates this session, ensuring that it will not be continued by
+ * another socket.
+ */
+ void invalidate();
+
+ /**
+ * Binds a value to this session, with the given name.
+ *
+ * @param name The name to bind the object with.
+ * @param value The value to bind.
+ */
+ void putValue(String name, Object value);
+
+ /**
+ * Un-binds a value.
+ *
+ * @param name The name of the value to un-bind.
+ */
+ void removeValue(String name);
+}
diff --git a/libjava/javax/net/ssl/SSLSessionBindingEvent.java b/libjava/javax/net/ssl/SSLSessionBindingEvent.java
new file mode 100644
index 00000000000..e0d27efa657
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLSessionBindingEvent.java
@@ -0,0 +1,94 @@
+/* SSLSessionBindingEvent.java -- SSL binding event.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.util.EventObject;
+
+/**
+ * An event raised by {@link SSLSession} objects when objects are bound to
+ * them.
+ */
+public class SSLSessionBindingEvent extends EventObject
+{
+
+ // Fields.
+ // -------------------------------------------------------------------
+
+ private static final long serialVersionUID = 3989172637106345L;
+
+ private final String name;
+
+ // Constructor.
+ // -------------------------------------------------------------------
+
+ /**
+ * Creates a new binding event.
+ *
+ * @param session The session being bound to.
+ * @param name The name the object was bound under.
+ */
+ public SSLSessionBindingEvent(SSLSession session, String name)
+ {
+ super(session);
+ this.name = name;
+ }
+
+ // Instance methods.
+ // --------------------------------------------------------------------
+
+ /**
+ * Returns the name the object was bound under.
+ *
+ * @return The name.
+ */
+ public String getName()
+ {
+ return name;
+ }
+
+ /**
+ * Returns the session that the object was bound to.
+ *
+ * @return The session.
+ */
+ public SSLSession getSession()
+ {
+ return (SSLSession) getSource();
+ }
+}
diff --git a/libjava/javax/net/ssl/SSLSessionBindingListener.java b/libjava/javax/net/ssl/SSLSessionBindingListener.java
new file mode 100644
index 00000000000..2e2432d4aab
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLSessionBindingListener.java
@@ -0,0 +1,65 @@
+/* SSLSessionBindingListener.java -- listener for SSL bindings.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.util.EventListener;
+
+/**
+ * An event listener interface that should be notified when it is bound or
+ * unbound to a {@link SSLSession}.
+ */
+public interface SSLSessionBindingListener extends EventListener
+{
+
+ /**
+ * This method is called of all objects when they are bound to an SSL
+ * session.
+ *
+ * @param event The binding event.
+ */
+ void valueBound(SSLSessionBindingEvent event);
+
+ /**
+ * This method is called of all objects when they are unbound to an SSL
+ * session.
+ *
+ * @param event The binding event.
+ */
+ void valueUnbound(SSLSessionBindingEvent event);
+}
diff --git a/libjava/javax/net/ssl/SSLSessionContext.java b/libjava/javax/net/ssl/SSLSessionContext.java
new file mode 100644
index 00000000000..0cbdeed9d1e
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLSessionContext.java
@@ -0,0 +1,103 @@
+/* SSLSessionContext.java -- collection of SSL sessions.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.util.Enumeration;
+
+/**
+ * A collection of saved SSL sessions, with thier corresponding session
+ * IDs.
+ *
+ * @author Casey Marshall (rsdio@metastatic.org)
+ */
+public interface SSLSessionContext
+{
+
+ /**
+ * Returns an enumeration of all saved session IDs. Every element in
+ * the returned enumeration is a byte array.
+ *
+ * @return The session IDs.
+ */
+ Enumeration getIds();
+
+ /**
+ * Gets the session specified by its ID, or <code>null</code> if there
+ * is no session, or if it has expired.
+ *
+ * @param sessionId The ID of the session to get.
+ * @return The session, or <code>null</code>.
+ */
+ SSLSession getSession(byte[] sessionId);
+
+ /**
+ * Returns the maximum number of sessions that may be cached by this
+ * session context.
+ *
+ * @return The maximum number of sessions that may be cached.
+ */
+ int getSessionCacheSize();
+
+ /**
+ * Returns the period of time (in seconds) that a session may be cached
+ * for before becoming invalid.
+ *
+ * @return The time a session may be valid.
+ */
+ int getSessionTimeout();
+
+ /**
+ * Sets the maximum number of sessions that may be cached by this
+ * session context. A cache size of 0 means no limit.
+ *
+ * @param size The new cache size.
+ * @throws IllegalArgumentException If <code>size</code> is negative.
+ */
+ void setSessionCacheSize(int size);
+
+ /**
+ * Sets the period of time (in seconds) that a session may be cached
+ * for before becoming invalid. A timeout of 0 means that sessions
+ * never expire.
+ *
+ * @param seconds The new timeout.
+ * @throws IllegalArgumentException If <code>seconds</code> is negative.
+ */
+ void setSessionTimeout(int seconds);
+}
diff --git a/libjava/javax/net/ssl/SSLSocket.java b/libjava/javax/net/ssl/SSLSocket.java
new file mode 100644
index 00000000000..8b943b9d6f3
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLSocket.java
@@ -0,0 +1,229 @@
+/* SSLSocket.java -- an SSL client socket.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.net.UnknownHostException;
+
+/**
+ * A socket that communicates over the secure socket layer protocol.
+ */
+public abstract class SSLSocket extends Socket
+{
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ protected SSLSocket()
+ {
+ super();
+ }
+
+ protected SSLSocket(String host, int port)
+ throws IOException, UnknownHostException
+ {
+ super(host, port);
+ }
+
+ protected SSLSocket(InetAddress address, int port) throws IOException
+ {
+ super(address, port);
+ }
+
+ protected SSLSocket(String host, int port,
+ InetAddress localAddr, int localPort)
+ throws IOException, UnknownHostException
+ {
+ super(host, port, localAddr, localPort);
+ }
+
+ protected SSLSocket(InetAddress address, int port,
+ InetAddress localAddr, int localPort)
+ throws IOException
+ {
+ super(address, port, localAddr, localPort);
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Adds a handshake completed listener that wants to be notified when the
+ * SSL handshake completes.
+ *
+ * @param listener The listener to add.
+ */
+ public abstract void
+ addHandshakeCompletedListener(HandshakeCompletedListener listener);
+
+ /**
+ * Removes a handshake listener from this socket.
+ *
+ * @param listener The listener to remove.
+ */
+ public abstract void
+ removeHandshakeCompletedListener(HandshakeCompletedListener listener);
+
+ /**
+ * Returns the list of currently enabled cipher suites.
+ *
+ * @return The list of enabled cipher suites.
+ */
+ public abstract String[] getEnabledCipherSuites();
+
+ /**
+ * Sets the list of enabled cipher suites.
+ *
+ * @param suites The list of suites to enable.
+ */
+ public abstract void setEnabledCipherSuites(String[] suites);
+
+ /**
+ * Returns the list of enabled SSL protocols.
+ *
+ * @return The list of enabled protocols.
+ */
+ public abstract String[] getEnabledProtocols();
+
+ /**
+ * Sets the list of enabled SSL protocols.
+ *
+ * @param protocols The list of protocols to enable.
+ */
+ public abstract void setEnabledProtocols(String[] protocols);
+
+ /**
+ * Returns whether or not sessions will be created by this socket, and thus
+ * allow sessions to be continued later.
+ *
+ * @return Whether or not sessions will be created.
+ */
+ public abstract boolean getEnableSessionCreation();
+
+ /**
+ * Sets whether or not sessions will be created by this socket.
+ *
+ * @param enable The new value.
+ */
+ public abstract void setEnableSessionCreation(boolean enable);
+
+ /**
+ * Returns whether or not this socket will require connecting clients to
+ * authenticate themselves. This value only applies to sockets in server
+ * mode.
+ *
+ * @return Whether or not this socket requires client authentication.
+ */
+ public abstract boolean getNeedClientAuth();
+
+ /**
+ * Sets whether or not this socket will require connecting clients to
+ * authenticate themselves. This value only applies to sockets in server
+ * mode.
+ *
+ * @param needAuth The new need auth value.
+ */
+ public abstract void setNeedClientAuth(boolean needAuth);
+
+ /**
+ * Returns this socket's session object.
+ *
+ * @return The session.
+ */
+ public abstract SSLSession getSession();
+
+ /**
+ * Returns the list of cipher suites supported by this socket.
+ *
+ * @return The list of supported cipher suites.
+ */
+ public abstract String[] getSupportedCipherSuites();
+
+ /**
+ * Returns the list of protocols supported by this socket.
+ *
+ * @return The list of supported protocols.
+ */
+ public abstract String[] getSupportedProtocols();
+
+ /**
+ * Returns whether or not this socket will connect in client mode.
+ *
+ * @return True if this is a client socket.
+ */
+ public abstract boolean getUseClientMode();
+
+ /**
+ * Sets whether or not this socket will connect in client mode.
+ *
+ * @param clientMode The new value.
+ */
+ public abstract void setUseClientMode(boolean clientMode);
+
+ /**
+ * Returns whether or not this socket will request that connecting clients
+ * authenticate themselves. This value only applies to sockets in server
+ * mode.
+ *
+ * @return The want client auth value.
+ */
+ public abstract boolean getWantClientAuth();
+
+ /**
+ * Sets whether or not this socket will request that connecting clients
+ * authenticate themselves. This value only applies to sockets in server
+ * mode.
+ *
+ * @param wantAuth The new want auth value.
+ */
+ public abstract void setWantClientAuth(boolean wantAuth);
+
+ /**
+ * Explicitly begins the handshake, or, if the handshake has already
+ * completed, requests that the handshake be repeated.
+ *
+ * <p>The handshake will begin implicitly when any attempt to read or
+ * write to the socket is made.</p>
+ *
+ * @throws IOException If an I/O or SSL error occurs.
+ */
+ public abstract void startHandshake() throws IOException;
+}
diff --git a/libjava/javax/net/ssl/SSLSocketFactory.java b/libjava/javax/net/ssl/SSLSocketFactory.java
new file mode 100644
index 00000000000..181ab18a1d2
--- /dev/null
+++ b/libjava/javax/net/ssl/SSLSocketFactory.java
@@ -0,0 +1,192 @@
+/* SSLSocketFactory.java -- factory for SSL client sockets.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.io.IOException;
+import java.net.Socket;
+import java.security.AccessController;
+import java.security.KeyStore;
+import java.security.PrivilegedAction;
+import java.security.Security;
+import javax.net.SocketFactory;
+
+/**
+ * A socket factory for creating <i>Secure Socket Layer</i> (<b>SSL</b>)
+ * sockets.
+ */
+public abstract class SSLSocketFactory extends SocketFactory
+{
+
+ // Constants.
+ // -------------------------------------------------------------------------
+
+ private static SSLContext context;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public SSLSocketFactory()
+ {
+ super();
+ }
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns a default implementation of a SSL socket factory.
+ *
+ * <p>To control the class that gets returned by this method, set the
+ * security property "ssl.SocketFactory.provider" to the class
+ * name of a concrete implementation of this class. If not set, a
+ * system-dependent implementation will be used.</p>
+ *
+ * <p>The implementation returned is created by the first implementation
+ * of the {@link SSLContext} class found, which is initialized with
+ * default parameters. To control the key and trust manager factory
+ * algorithms used as defaults, set the security properties
+ * "ssl.keyManagerFactory.algorithm" and "ssl.trustManagerFactory.algorithm"
+ * to the appropriate names.</p>
+ *
+ * <p>Using this method is not recommended. Instead, use the methods of
+ * {@link SSLContext}, which provide much better control over the
+ * creation of socket factories.</p>
+ *
+ * @return The default socket factory.
+ * @throws RuntimeException If no default can be created.
+ */
+ public static synchronized SocketFactory getDefault()
+ {
+ try
+ {
+ String s = Security.getProperty("ssl.SocketFactory.provider");
+ ClassLoader cl = ClassLoader.getSystemClassLoader();
+ if (s != null && cl != null)
+ {
+ return (SocketFactory) cl.loadClass(s).newInstance();
+ }
+ }
+ catch (Exception e)
+ {
+ }
+ if (context == null)
+ {
+ KeyManager[] km = null;
+ TrustManager[] tm = null;
+
+ // 1. Determine which algorithms to use for the key and trust
+ // manager factories.
+ String kmAlg = KeyManagerFactory.getDefaultAlgorithm();
+ String tmAlg = TrustManagerFactory.getDefaultAlgorithm();
+
+ // 2. Try to initialize the factories with default parameters.
+ try
+ {
+ KeyManagerFactory kmf = KeyManagerFactory.getInstance(kmAlg);
+ kmf.init(null, null);
+ km = kmf.getKeyManagers();
+ }
+ catch (Exception ex)
+ {
+ }
+ try
+ {
+ TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmAlg);
+ tmf.init((KeyStore) null);
+ tm = tmf.getTrustManagers();
+ }
+ catch (Exception ex)
+ {
+ }
+
+ // 3. Create and initialize a context.
+ try
+ {
+ context = SSLContext.getInstance("SSLv3");
+ context.init(km, tm, null);
+ }
+ catch (Exception ex)
+ {
+ throw new RuntimeException("error instantiating default socket factory: "
+ + ex.toString());
+ }
+ }
+ try
+ {
+ return context.getSocketFactory();
+ }
+ catch (Exception e)
+ {
+ }
+ throw new RuntimeException("no SSLSocketFactory implementation available");
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Creates a SSL socket wrapped around an existing socket.
+ *
+ * @param socket The socket to wrap.
+ * @param host The host the socket is connected to.
+ * @param port The port the socket is connected to.
+ * @param autoClose Whether or not the wrapped socket should be closed
+ * automatically.
+ * @return The new SSL socket.
+ * @throws IOException If the socket could not be created.
+ */
+ public abstract Socket createSocket(Socket socket, String host,
+ int port, boolean autoClose)
+ throws IOException;
+
+ /**
+ * Returns the list of cipher suites that will be enabled in sockets
+ * created by this factory.
+ *
+ * @return The default cipher suites.
+ */
+ public abstract String[] getDefaultCipherSuites();
+
+ /**
+ * Returns the list of all cipher suites supported by this factory.
+ *
+ * @return The list of supported cipher suites.
+ */
+ public abstract String[] getSupportedCipherSuites();
+}
diff --git a/libjava/javax/net/ssl/TrivialHostnameVerifier.java b/libjava/javax/net/ssl/TrivialHostnameVerifier.java
new file mode 100644
index 00000000000..e4e2befc072
--- /dev/null
+++ b/libjava/javax/net/ssl/TrivialHostnameVerifier.java
@@ -0,0 +1,51 @@
+/* TrivialHostnameVerifier.java -- non-verifing verifier.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * A hostname verifier that always rejects mismatched hostnames.
+ */
+class TrivialHostnameVerifier implements HostnameVerifier
+{
+
+ public boolean verify(String hostname, SSLSession session)
+ {
+ return false;
+ }
+}
diff --git a/libjava/javax/net/ssl/TrustManager.java b/libjava/javax/net/ssl/TrustManager.java
new file mode 100644
index 00000000000..f90629ab40c
--- /dev/null
+++ b/libjava/javax/net/ssl/TrustManager.java
@@ -0,0 +1,47 @@
+/* TrustManager.java -- marker interface for trust managers.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+/**
+ * A marker interface for classes that establish the trust of remote
+ * hosts.
+ */
+public interface TrustManager
+{
+}
diff --git a/libjava/javax/net/ssl/TrustManagerFactory.java b/libjava/javax/net/ssl/TrustManagerFactory.java
new file mode 100644
index 00000000000..84059c89618
--- /dev/null
+++ b/libjava/javax/net/ssl/TrustManagerFactory.java
@@ -0,0 +1,279 @@
+/* TrustManagerFactory.java -- factory for trust managers.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.lang.reflect.InvocationTargetException;
+
+import java.security.AccessController;
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PrivilegedAction;
+import java.security.Provider;
+import java.security.Security;
+
+import gnu.java.security.Engine;
+
+/**
+ * A factory for creating trust manager objects.
+ */
+public class TrustManagerFactory
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ /** The service name for trust manager factories. */
+ private static final String TRUST_MANAGER_FACTORY = "TrustManagerFactory";
+
+ /** The system default trust manager algorithm. */
+ private static final String DEFAULT_ALGORITHM = "JessieX509";
+
+ /** The underlying engine class. */
+ private final TrustManagerFactorySpi tmfSpi;
+
+ /** The provider of the engine class. */
+ private final Provider provider;
+
+ /** The name of this trust manager algorithm. */
+ private final String algorithm;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Creates a new trust manager factory.
+ *
+ * @param tmfSpi The underlying engine class.
+ * @param provider The provider of the engine class.
+ * @param algorithm The trust manager algorithm name.
+ */
+ protected TrustManagerFactory(TrustManagerFactorySpi tmfSpi,
+ Provider provider, String algorithm)
+ {
+ this.tmfSpi = tmfSpi;
+ this.provider = provider;
+ this.algorithm = algorithm;
+ }
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns an instance of a trust manager factory for the given algorithm
+ * from the first provider that implements it.
+ *
+ * @param algorithm The name of the algorithm to get.
+ * @return The instance of the trust manager factory.
+ * @throws NoSuchAlgorithmException If no provider implements the given
+ * algorithm.
+ */
+ public static final TrustManagerFactory getInstance(String algorithm)
+ throws NoSuchAlgorithmException
+ {
+ Provider[] provs = Security.getProviders();
+ for (int i = 0; i < provs.length; i++)
+ {
+ try
+ {
+ return getInstance(algorithm, provs[i]);
+ }
+ catch (NoSuchAlgorithmException ignore)
+ {
+ }
+ }
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+
+ /**
+ * Returns an instance of a trust manager factory for the given algorithm
+ * from the named provider.
+ *
+ * @param algorithm The name of the algorithm to get.
+ * @param provider The name of the provider to get the instance from.
+ * @return The instance of the trust manager factory.
+ * @throws NoSuchAlgorithmException If the provider does not implement the
+ * given algorithm.
+ * @throws NoSuchProviderException If there is no such named provider.
+ * @throws IllegalArgumentException If the provider argument is null.
+ */
+ public static final TrustManagerFactory getInstance(String algorithm,
+ String provider)
+ throws NoSuchAlgorithmException, NoSuchProviderException
+ {
+ if (provider == null)
+ {
+ throw new IllegalArgumentException();
+ }
+ Provider p = Security.getProvider(provider);
+ if (p == null)
+ {
+ throw new NoSuchProviderException(provider);
+ }
+ return getInstance(algorithm, p);
+ }
+
+ /**
+ * Returns an instance of a trust manager factory for the given algorithm
+ * from the specified provider.
+ *
+ * @param algorithm The name of the algorithm to get.
+ * @param provider The provider to get the instance from.
+ * @return The instance of the trust manager factory.
+ * @throws NoSuchAlgorithmException If the provider does not implement the
+ * given algorithm.
+ * @throws IllegalArgumentException If the provider argument is null.
+ */
+ public static final TrustManagerFactory getInstance(String algorithm,
+ Provider provider)
+ throws NoSuchAlgorithmException
+ {
+ if (provider == null)
+ {
+ throw new IllegalArgumentException();
+ }
+ try
+ {
+ return new TrustManagerFactory((TrustManagerFactorySpi)
+ Engine.getInstance(TRUST_MANAGER_FACTORY, algorithm, provider),
+ provider, algorithm);
+ }
+ catch (InvocationTargetException ite)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ catch (ClassCastException cce)
+ {
+ throw new NoSuchAlgorithmException(algorithm);
+ }
+ }
+
+ /**
+ * Returns the default algorithm for trust manager factories. The value
+ * returned is either the value of the security property
+ * "ssl.TrustManagerFactory.algorithm" if it is set, or the value "JessieX509"
+ * if not.
+ *
+ * @return The default algorithm name.
+ * @see Security.getProperty(java.lang.String)
+ */
+ public static final String getDefaultAlgorithm()
+ {
+ String alg = null;
+ try
+ {
+ alg = (String) AccessController.doPrivileged(
+ new PrivilegedAction()
+ {
+ public Object run()
+ {
+ return Security.getProperty("ssl.TrustManagerFactory.algorithm");
+ }
+ }
+ );
+ }
+ catch (SecurityException se)
+ {
+ }
+ if (alg == null)
+ alg = DEFAULT_ALGORITHM;
+ return alg;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the name of this trust manager algorithm.
+ *
+ * @return The algorithm name.
+ */
+ public final String getAlgorithm()
+ {
+ return algorithm;
+ }
+
+ /**
+ * Returns the provider of the underlying implementation.
+ *
+ * @return The provider.
+ */
+ public final Provider getProvider()
+ {
+ return provider;
+ }
+
+ /**
+ * Returns the trust managers created by this factory.
+ *
+ * @return The trust managers.
+ */
+ public final TrustManager[] getTrustManagers()
+ {
+ return tmfSpi.engineGetTrustManagers();
+ }
+
+ /**
+ * Initialize this instance with some algorithm-specific parameters.
+ *
+ * @param params The parameters.
+ * @throws InvalidAlgorithmParameterException If the supplied parameters
+ * are inappropriate for this instance.
+ */
+ public final void init(ManagerFactoryParameters params)
+ throws InvalidAlgorithmParameterException
+ {
+ tmfSpi.engineInit(params);
+ }
+
+ /**
+ * Initialize this instance with a key store. The key store may be null,
+ * in which case a default will be used.
+ *
+ * @param store The key store.
+ * @throws KeyStoreException If there is a problem reading from the
+ * key store.
+ */
+ public final void init(KeyStore store) throws KeyStoreException
+ {
+ tmfSpi.engineInit(store);
+ }
+}
diff --git a/libjava/javax/net/ssl/TrustManagerFactorySpi.java b/libjava/javax/net/ssl/TrustManagerFactorySpi.java
new file mode 100644
index 00000000000..389e02325c4
--- /dev/null
+++ b/libjava/javax/net/ssl/TrustManagerFactorySpi.java
@@ -0,0 +1,88 @@
+/* TrustManagerFactorySpi.java -- SPI for trust manager factories.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+
+/**
+ * The <i>service provider interface</i> (<b>SPI</b>) for trust managers.
+ */
+public abstract class TrustManagerFactorySpi
+{
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public TrustManagerFactorySpi()
+ {
+ super();
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Engine method that returns the trust managers created by this factory.
+ *
+ * @return The trust managers.
+ */
+ protected abstract TrustManager[] engineGetTrustManagers();
+
+ /**
+ * Engine method that initializes this factory with some algorithm-specific
+ * parameters.
+ *
+ * @param params The parameters.
+ * @throws InvalidAlgorithmParameterException If the given parameters are
+ * inappropriate.
+ */
+ protected abstract void engineInit(ManagerFactoryParameters params)
+ throws InvalidAlgorithmParameterException;
+
+ /**
+ * Engine method that initializes this factory with a key store. The key
+ * store parameter may be null, in which case some default should be used.
+ *
+ * @param store The key store.
+ * @throws KeyStoreException If a problem occurs reading from the key store.
+ */
+ protected abstract void engineInit(KeyStore store) throws KeyStoreException;
+}
diff --git a/libjava/javax/net/ssl/X509KeyManager.java b/libjava/javax/net/ssl/X509KeyManager.java
new file mode 100644
index 00000000000..d5c00b62c97
--- /dev/null
+++ b/libjava/javax/net/ssl/X509KeyManager.java
@@ -0,0 +1,108 @@
+/* X509KeyManager.java -- X.509 key manager interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.net.Socket;
+
+import java.security.Principal;
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+
+/**
+ * A key manager for X.509 certificates and their associated private keys.
+ */
+public interface X509KeyManager extends KeyManager
+{
+
+ /**
+ * Choose an alias for client-side authentication.
+ *
+ * @param keyTypes A list of acceptable key types.
+ * @param issuers A list of acceptable certificate issuers.
+ * @param socket The connecting socket.
+ * @return The chosen alias.
+ */
+ String chooseClientAlias(String[] keyTypes, Principal[] issuers,
+ Socket socket);
+
+ /**
+ * Choose an alias for server-side authentication.
+ *
+ * @param keyType The desired certificate type.
+ * @param issuers A list of acceptable certificate issuers.
+ * @param socket The connecting socket.
+ * @return The chosen alias.
+ */
+ String chooseServerAlias(String keyType, Principal[] issuers,
+ Socket socket);
+
+ /**
+ * Gets the X.509 certificate chain associated with the given alias.
+ *
+ * @param alias The alias.
+ * @return The certificate chain.
+ */
+ X509Certificate[] getCertificateChain(String alias);
+
+ /**
+ * Returns all client aliases that support the given key type.
+ *
+ * @param keyType The desired key type.
+ * @param issuers A list of acceptable certificate issuers.
+ * @return The (possibly empty) list of aliases.
+ */
+ String[] getClientAliases(String keyType, Principal[] issuers);
+
+ /**
+ * Gets the private key associated with the given alias.
+ *
+ * @param alias The alias.
+ * @return The private key.
+ */
+ PrivateKey getPrivateKey(String alias);
+
+ /**
+ * Returns all server aliases that support the given key type.
+ *
+ * @param keyType The desired key type.
+ * @param issuers A list of acceptable certificate issuers.
+ * @return The (possibly empty) list of aliases.
+ */
+ String[] getServerAliases(String keyType, Principal[] issuers);
+}
diff --git a/libjava/javax/net/ssl/X509TrustManager.java b/libjava/javax/net/ssl/X509TrustManager.java
new file mode 100644
index 00000000000..b63e0a830b6
--- /dev/null
+++ b/libjava/javax/net/ssl/X509TrustManager.java
@@ -0,0 +1,76 @@
+/* X509TrustManager.java -- X.509 trust manager interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.net.ssl;
+
+import java.security.cert.CertificateException;
+import java.security.cert.X509Certificate;
+
+/**
+ * A trust manager for dealing with X.509 certificates.
+ */
+public interface X509TrustManager extends TrustManager
+{
+
+ /**
+ * Checks if a certificate chain sent by the client is trusted.
+ *
+ * @param chain The certificate chain to check.
+ * @param authType The authentication type.
+ * @throws CertificateException If the client's certificates are not trusted.
+ */
+ void checkClientTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException;
+
+ /**
+ * Checks if a certificate chain sent by the server is trusted.
+ *
+ * @param chain The certificate chain to check.
+ * @param authType The authentication type.
+ * @throws CertificateException If the server's certificates are not trusted.
+ */
+ void checkServerTrusted(X509Certificate[] chain, String authType)
+ throws CertificateException;
+
+ /**
+ * Returns the list of trusted issuer certificates currently in use.
+ *
+ * @return The list of trusted issuer certificates.
+ */
+ X509Certificate[] getAcceptedIssuers();
+}
diff --git a/libjava/javax/security/auth/AuthPermission.java b/libjava/javax/security/auth/AuthPermission.java
new file mode 100644
index 00000000000..b4ffa15a954
--- /dev/null
+++ b/libjava/javax/security/auth/AuthPermission.java
@@ -0,0 +1,146 @@
+/* AuthPermission.java -- permissions related to authentication.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+import java.security.BasicPermission;
+
+/**
+ * <p>A permission controlling access to authentication service. The
+ * <i>actions</i> field of auth permission objects is ignored; the whole
+ * of the permission is defined by the <i>target</i>.</p>
+ *
+ * <p>The authentication permission targets recognized are:</p>
+ *
+ * <dl>
+ * <dt><code>doAs</code></dt>
+ *
+ * <dd><p>Allows access to the {@link
+ * Subject#doAs(javax.security.auth.Subject java.security.PrivilegedAction)}
+ * methods.</p></dd>
+ *
+ * <dt><code>doAsPrivileged</code></dt>
+ *
+ * <dd><p>Allows access to the {@link
+ * Subject#doAsPrivileged(javax.security.auth.Subject,
+ * java.security.PrivilegedAction, java.security.AccessControlContext)}
+ * methods.</p></dd>
+ *
+ * <dt><code>getSubject</code></dt>
+ *
+ * <dd><p>Allows access to the {@link Subject} associated with a
+ * thread.</p></dd>
+ *
+ * <dt><code>getSubjectFromDomainCombiner</code></dt>
+ *
+ * <dd><p>Allows access to the {@link Subject} associated with a
+ * {@link SubjectDomainCombiner}.</p></dd>
+ *
+ * <dt><code>setReadOnly</code></dt>
+ *
+ * <dd><p>Allows a {@link Subject} to be marked as read-only.</p></dd>
+ *
+ * <dt><code>modifyPrincipals</code></dt>
+ *
+ * <dd><p>Allows the set of principals of a subject to be modified.</p></dd>
+ *
+ * <dt><code>modifyPublicCredentials</code></dt>
+ *
+ * <dd><p>Allows the set of public credentials of a subject to be
+ * modified.</p></dd>
+ *
+ * <dt><code>modifyPrivateCredentials</code></dt>
+ *
+ * <dd><p>Allows the set of private credentials of a subject to be
+ * modified.</p></dd>
+ *
+ * <dt><code>refreshCredential</code></dt>
+ *
+ * <dd><p>Allows a {@link Refreshable} credential to be refreshed.</p></dd>
+ *
+ * <dt><code>destroyCredential</code></dt>
+ *
+ * <dd><p>Allows a {@link Destroyable} credential to be destroyed.</p></dd>
+ *
+ * <dt><code>createLoginContext.<i>name</i></code></dt>
+ *
+ * <dd><p>Allows a {@link javax.security.auth.login.LoginContext} for the
+ * given <i>name</i>. <i>name</i> can also be a wildcard (<code>'*'</code>),
+ * which allows the creation of a context with any name.</p></dd>
+ *
+ * <dt><code>getLoginConfiguration</code></dt>
+ *
+ * <dd><p>Allows the system-wide login {@link
+ * javax.security.auth.login.Configuration} to be retrieved.</p></dd>
+ *
+ * <dt><code>setLoginConfiguration</code></dt>
+ *
+ * <dd><p>Allows the system-wide login {@link
+ * javax.security.auth.login.Configuration} to be set.</p></dd>
+ *
+ * <dt><code>refreshLoginConfiguration</code></dt>
+ *
+ * <dd><p>Allows the system-wide login {@link
+ * javax.security.auth.login.Configuration} to be refreshed.</p></dd>
+ * </dl>
+ */
+public final class AuthPermission extends BasicPermission
+{
+
+ /**
+ * Creates a new authentication permission for the given target name.
+ *
+ * @param name The target name.
+ */
+ public AuthPermission (String name)
+ {
+ super (name);
+ }
+
+ /**
+ * Creates a new authentication permission for the given target name.
+ * The actions list is not used by this class.
+ *
+ * @param name The target name.
+ * @param actions The action list.
+ */
+ public AuthPermission (String name, String actions)
+ {
+ super (name, actions);
+ }
+}
diff --git a/libjava/javax/security/auth/DestroyFailedException.java b/libjava/javax/security/auth/DestroyFailedException.java
new file mode 100644
index 00000000000..00bbd89667f
--- /dev/null
+++ b/libjava/javax/security/auth/DestroyFailedException.java
@@ -0,0 +1,67 @@
+/* DestroyFailedException.java -- signals an object could not be destroyed.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+/**
+ * An exception thrown when the {@link Destroyable#destroy()} method
+ * fails for a credential.
+ *
+ * @see Destroyable
+ */
+public class DestroyFailedException extends Exception
+{
+
+ /**
+ * Creates a new DestroyFailedException with no detail message.
+ */
+ public DestroyFailedException()
+ {
+ super();
+ }
+
+ /**
+ * Creates a new DestroyFailedException with a detail message.
+ *
+ * @param message The detail message.
+ */
+ public DestroyFailedException (String message)
+ {
+ super (message);
+ }
+}
diff --git a/libjava/javax/security/auth/Destroyable.java b/libjava/javax/security/auth/Destroyable.java
new file mode 100644
index 00000000000..484bece8de9
--- /dev/null
+++ b/libjava/javax/security/auth/Destroyable.java
@@ -0,0 +1,64 @@
+/* Destroyable.java -- an immutable object that may be destroyed.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+/**
+ * An interface for objects that are immutable but whose sensitive
+ * data may be wiped out.
+ */
+public interface Destroyable
+{
+
+ /**
+ * Destroy this object, clearing all sensitive fields appropriately.
+ *
+ * @throws DestroyFailedException If this object could not be
+ * destroyed.
+ * @throws SecurityException If the caller does not have permission
+ * to destroy this object.
+ */
+ void destroy() throws DestroyFailedException;
+
+ /**
+ * Tells whether or not this object has been destroyed.
+ *
+ * @return True if this object has been destroyed.
+ */
+ boolean isDestroyed();
+}
diff --git a/libjava/javax/security/auth/Policy.java b/libjava/javax/security/auth/Policy.java
new file mode 100644
index 00000000000..2234d85732b
--- /dev/null
+++ b/libjava/javax/security/auth/Policy.java
@@ -0,0 +1,79 @@
+/* Policy.java -- deprecated precursor to java.security.Policy.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+import java.security.CodeSource;
+import java.security.PermissionCollection;
+
+/**
+ * @deprecated The classes java.security.Policy and
+ * java.security.ProtectionDomain provide the functionality of this class.
+ */
+public abstract class Policy
+{
+
+ private static Policy policy;
+
+ protected Policy()
+ {
+ }
+
+ public static synchronized Policy getPolicy()
+ {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("getPolicy"));
+ }
+ return policy;
+ }
+
+ public static synchronized void setPolicy (Policy p)
+ {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("setPolicy"));
+ }
+ policy = p;
+ }
+
+ public abstract PermissionCollection getPermissions (Subject subject, CodeSource source);
+ public abstract void refresh();
+}
diff --git a/libjava/javax/security/auth/PrivateCredentialPermission.java b/libjava/javax/security/auth/PrivateCredentialPermission.java
new file mode 100644
index 00000000000..cc370ae17c7
--- /dev/null
+++ b/libjava/javax/security/auth/PrivateCredentialPermission.java
@@ -0,0 +1,326 @@
+/* PrivateCredentialPermission.java -- permissions governing private credentials.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+import java.io.Serializable;
+
+import java.security.Permission;
+import java.security.PermissionCollection;
+
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+/**
+ * A permission governing access to a private credential. The action of this
+ * permission is always "read" -- meaning that the private credential
+ * information can be read from an object.
+ *
+ * <p>The target of this permission is formatted as follows:</p>
+ *
+ * <p><code>CredentialClassName ( PrinicpalClassName PrincipalName )*</code></p>
+ *
+ * <p><i>CredentialClassName</i> is either the name of a private credential
+ * class name, or a wildcard character (<code>'*'</code>).
+ * <i>PrinicpalClassName</i> is the class name of a principal object, and
+ * <i>PrincipalName</i> is a string representing the principal, or the
+ * wildcard character.</p>
+ */
+public class PrivateCredentialPermission extends Permission
+ implements Serializable
+{
+ /**
+ * For compatability with Sun's JDK 1.4.2 rev. 5
+ */
+ private static final long serialVersionUID = 5284372143517237068L;
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial The credential class name.
+ */
+ private final String credentialClass;
+
+ /**
+ * @serial The principals, a set of CredOwner objects (an undocumented
+ * inner class of this class).
+ */
+ private final Set principals;
+
+ /**
+ * @serial Who knows?
+ */
+ private final boolean testing;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Create a new private credential permission.
+ *
+ * @param name The permission target name.
+ * @param actions The list of actions, which, for this class, must be
+ * <code>"read"</code>.
+ */
+ public PrivateCredentialPermission (final String name, String actions)
+ {
+ super(name);
+ actions = actions.trim().toLowerCase();
+ if (!"read".equals (actions))
+ {
+ throw new IllegalArgumentException("actions must be \"read\"");
+ }
+ StringTokenizer st = new StringTokenizer (name, " \"'");
+ principals = new HashSet();
+ if (st.countTokens() < 3 || (st.countTokens() & 1) == 0)
+ {
+ throw new IllegalArgumentException ("badly formed credential name");
+ }
+ credentialClass = st.nextToken();
+ while (st.hasMoreTokens())
+ {
+ principals.add (new CredOwner (st.nextToken(), st.nextToken()));
+ }
+ testing = false; // WTF ever.
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public boolean equals (Object o)
+ {
+ if (! (o instanceof PrivateCredentialPermission))
+ {
+ return false;
+ }
+ PrivateCredentialPermission that = (PrivateCredentialPermission) o;
+ if (!that.getActions().equals (getActions()))
+ {
+ return false;
+ }
+ if (!that.getCredentialClass().equals (getCredentialClass()))
+ {
+ return false;
+ }
+
+ final String[][] principals = getPrincipals();
+ final String[][] that_principals = that.getPrincipals();
+ if (that_principals == null)
+ {
+ return false;
+ }
+ if (that_principals.length != principals.length)
+ {
+ return false;
+ }
+ for (int i = 0; i < principals.length; i++)
+ {
+ if (!principals[i][0].equals (that_principals[i][0]) ||
+ !principals[i][1].equals (that_principals[i][1]))
+ {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns the actions this permission encompasses. For private credential
+ * permissions, this is always the string <code>"read"</code>.
+ *
+ * @return The list of actions.
+ */
+ public String getActions()
+ {
+ return "read";
+ }
+
+ /**
+ * Returns the credential class name that was embedded in this permission's
+ * target name.
+ *
+ * @return The credential class name.
+ */
+ public String getCredentialClass()
+ {
+ return credentialClass;
+ }
+
+ /**
+ * Returns the principal list that was embedded in this permission's target
+ * name.
+ *
+ * <p>Each element of the returned array is a pair; the first element is the
+ * principal class name, and the second is the principal name.
+ *
+ * @return The principal list.
+ */
+ public String[][] getPrincipals()
+ {
+ String[][] ret = new String[principals.size()][];
+ Iterator it = principals.iterator();
+ for (int i = 0; i < principals.size() && it.hasNext(); i++)
+ {
+ CredOwner co = (CredOwner) it.next();
+ ret[i] = new String[] { co.getPrincipalClass(), co.getPrincipalName() };
+ }
+ return ret;
+ }
+
+ public int hashCode()
+ {
+ return credentialClass.hashCode() + principals.hashCode();
+ }
+
+ /**
+ * Test if this permission implies another. This method returns true if:
+ *
+ * <ol>
+ * <li><i>p</i> is an instance of PrivateCredentialPermission</li>.
+ * <li>The credential class name of this instance matches that of <i>p</i>,
+ * and one of the principals of <i>p</i> is contained in the principals of
+ * this class. Thus,
+ * <ul>
+ * <li><code>[ * P "foo" ] implies [ C P "foo" ]</code></li>
+ * <li><code>[ C P1 "foo" ] implies [ C P1 "foo" P2 "bar" ]</code></li>
+ * <li><code>[ C P1 "*" ] implies [ C P1 "foo" ]</code></li>
+ * </ul>
+ * </ol>
+ *
+ * @param p The permission to check.
+ * @return True if this permission implies <i>p</i>.
+ */
+ public boolean implies (Permission p)
+ {
+ if (! (p instanceof PrivateCredentialPermission))
+ {
+ return false;
+ }
+ PrivateCredentialPermission that = (PrivateCredentialPermission) p;
+ if (!credentialClass.equals ("*")
+ && !credentialClass.equals (that.getCredentialClass()))
+ {
+ return false;
+ }
+ String[][] principals = getPrincipals();
+ String[][] that_principals = that.getPrincipals();
+ if (that_principals == null)
+ {
+ return false;
+ }
+ for (int i = 0; i < principals.length; i++)
+ {
+ for (int j = 0; j < that_principals.length; j++)
+ {
+ if (principals[i][0].equals (that_principals[j][0]) &&
+ (principals[i][1].equals ("*") ||
+ principals[i][1].equals (that_principals[j][1])))
+ {
+ return true;
+ }
+ }
+ }
+ return false;
+ }
+
+ /**
+ * This method is not necessary for this class, thus it always returns null.
+ *
+ * @return null.
+ */
+ public PermissionCollection newPermissionCollection()
+ {
+ return null;
+ }
+
+ // Inner class.
+ // -------------------------------------------------------------------------
+
+ /**
+ * An undocumented inner class present for serialization compatibility.
+ */
+ private static class CredOwner implements Serializable
+ {
+
+ // Fields.
+ // -----------------------------------------------------------------------
+
+ private final String principalClass;
+ private final String principalName;
+
+ // Constructor.
+ // -----------------------------------------------------------------------
+
+ CredOwner (final String principalClass, final String principalName)
+ {
+ this.principalClass = principalClass;
+ this.principalName = principalName;
+ }
+
+ // Instance methods.
+ // -----------------------------------------------------------------------
+
+ public boolean equals (Object o)
+ {
+ if (!(o instanceof CredOwner))
+ {
+ return false;
+ }
+ return principalClass.equals (((CredOwner) o).getPrincipalClass()) &&
+ principalName.equals (((CredOwner) o).getPrincipalName());
+ }
+
+ public int hashCode()
+ {
+ return principalClass.hashCode() + principalName.hashCode();
+ }
+
+ public String getPrincipalClass()
+ {
+ return principalClass;
+ }
+
+ public String getPrincipalName()
+ {
+ return principalName;
+ }
+ }
+}
diff --git a/libjava/javax/security/auth/RefreshFailedException.java b/libjava/javax/security/auth/RefreshFailedException.java
new file mode 100644
index 00000000000..5be9ab75ed6
--- /dev/null
+++ b/libjava/javax/security/auth/RefreshFailedException.java
@@ -0,0 +1,63 @@
+/* RefreshFailedException.java -- signals a failed refresh.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+/**
+ * A signal that a call to {@link Refreshable#refresh()} failed.
+ */
+public class RefreshFailedException extends Exception
+{
+
+ /**
+ * Create a new RefreshFailedException with no detail message.
+ */
+ public RefreshFailedException()
+ {
+ }
+
+ /**
+ * Create a new RefreshFailedException with a detail message.
+ *
+ * @param message The detail message.
+ */
+ public RefreshFailedException (String message)
+ {
+ super (message);
+ }
+}
diff --git a/libjava/javax/security/auth/Refreshable.java b/libjava/javax/security/auth/Refreshable.java
new file mode 100644
index 00000000000..b3ceded417a
--- /dev/null
+++ b/libjava/javax/security/auth/Refreshable.java
@@ -0,0 +1,65 @@
+/* Refreshable.java -- an object whose state may be refreshed.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+/**
+ * An object whose internal state may be <em>refreshed:</em> as in a
+ * credential object with a expiry date.
+ */
+public interface Refreshable
+{
+
+ /**
+ * Tells whether or not this object is current. Refreshable objects that
+ * are not current may need to be refreshed.
+ *
+ * @return Whether this object is current.
+ */
+ boolean isCurrent();
+
+ /**
+ * Refresh this object. The process involved in refreshing an object is
+ * per-implementation dependent.
+ *
+ * @throws RefreshFailedException If refreshing this object fails.
+ * @throws SecurityException If the caller does not have permission to
+ * refresh, or to take the steps involved in refreshing, this object.
+ */
+ void refresh() throws RefreshFailedException;
+}
diff --git a/libjava/javax/security/auth/Subject.java b/libjava/javax/security/auth/Subject.java
new file mode 100644
index 00000000000..264a41c0561
--- /dev/null
+++ b/libjava/javax/security/auth/Subject.java
@@ -0,0 +1,559 @@
+/* Subject.java -- a single entity in the system.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.io.Serializable;
+
+import java.security.AccessControlContext;
+import java.security.AccessController;
+import java.security.DomainCombiner;
+import java.security.Principal;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import java.util.AbstractSet;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.LinkedList;
+import java.util.Set;
+
+/**
+ *
+ */
+public final class Subject implements Serializable
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private static final long serialVersionUID = -8308522755600156056L;
+
+ /**
+ * @serial The set of principals. The type of this field is SecureSet, a
+ * private inner class.
+ */
+ private final Set principals;
+
+ /**
+ * @serial The read-only flag.
+ */
+ private boolean readOnly;
+
+ private transient final SecureSet pubCred;
+ private transient final SecureSet privCred;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public Subject()
+ {
+ principals = new SecureSet (this, SecureSet.PRINCIPALS);
+ pubCred = new SecureSet (this, SecureSet.PUBLIC_CREDENTIALS);
+ privCred = new SecureSet (this, SecureSet.PRIVATE_CREDENTIALS);
+ readOnly = false;
+ }
+
+ public Subject (final boolean readOnly, final Set principals,
+ final Set pubCred, final Set privCred)
+ {
+ if (principals == null || pubCred == null || privCred == null)
+ {
+ throw new NullPointerException();
+ }
+ this.principals = new SecureSet (this, SecureSet.PRINCIPALS, principals);
+ this.pubCred = new SecureSet (this, SecureSet.PUBLIC_CREDENTIALS, pubCred);
+ this.privCred = new SecureSet (this, SecureSet.PRIVATE_CREDENTIALS, privCred);
+ this.readOnly = readOnly;
+ }
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Returns the subject associated with the given {@link
+ * AccessControlContext}.</p>
+ *
+ * <p>All this method does is retrieve the Subject object from the supplied
+ * context's {@link DomainCombiner}, if any, and if it is an instance of
+ * a {@link SubjectDomainCombiner}.
+ *
+ * @param context The context to retrieve the subject from.
+ * @return The subject assoctiated with the context, or <code>null</code>
+ * if there is none.
+ * @throws NullPointerException If <i>subject</i> is null.
+ * @throws SecurityException If the caller does not have permission to get
+ * the subject (<code>"getSubject"</code> target of {@link AuthPermission}.
+ */
+ public static Subject getSubject (final AccessControlContext context)
+ {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("getSubject"));
+ }
+ DomainCombiner dc = context.getDomainCombiner();
+ if (!(dc instanceof SubjectDomainCombiner))
+ {
+ return null;
+ }
+ return ((SubjectDomainCombiner) dc).getSubject();
+ }
+
+ /**
+ * <p>Run a method as another subject. This method will obtain the current
+ * {@link AccessControlContext} for this thread, then creates another with
+ * a {@link SubjectDomainCombiner} with the given subject. The supplied
+ * action will then be run with the modified context.</p>
+ *
+ * @param subject The subject to run as.
+ * @param action The action to run.
+ * @return The value returned by the privileged action.
+ * @throws SecurityException If the caller is not allowed to run under a
+ * different identity (<code>"doAs"</code> target of {@link AuthPermission}.
+ */
+ public static Object doAs (final Subject subject, final PrivilegedAction action)
+ {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("doAs"));
+ }
+ AccessControlContext context =
+ new AccessControlContext (AccessController.getContext(),
+ new SubjectDomainCombiner (subject));
+ return AccessController.doPrivileged (action, context);
+ }
+
+ /**
+ * <p>Run a method as another subject. This method will obtain the current
+ * {@link AccessControlContext} for this thread, then creates another with
+ * a {@link SubjectDomainCombiner} with the given subject. The supplied
+ * action will then be run with the modified context.</p>
+ *
+ * @param subject The subject to run as.
+ * @param action The action to run.
+ * @return The value returned by the privileged action.
+ * @throws SecurityException If the caller is not allowed to run under a
+ * different identity (<code>"doAs"</code> target of {@link AuthPermission}.
+ * @throws PrivilegedActionException If the action throws an exception.
+ */
+ public static Object doAs (final Subject subject,
+ final PrivilegedExceptionAction action)
+ throws PrivilegedActionException
+ {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("doAs"));
+ }
+ AccessControlContext context =
+ new AccessControlContext (AccessController.getContext(),
+ new SubjectDomainCombiner(subject));
+ return AccessController.doPrivileged (action, context);
+ }
+
+ /**
+ * <p>Run a method as another subject. This method will create a new
+ * {@link AccessControlContext} derived from the given one, with a
+ * {@link SubjectDomainCombiner} with the given subject. The supplied
+ * action will then be run with the modified context.</p>
+ *
+ * @param subject The subject to run as.
+ * @param action The action to run.
+ * @param acc The context to use.
+ * @return The value returned by the privileged action.
+ * @throws SecurityException If the caller is not allowed to run under a
+ * different identity (<code>"doAsPrivileged"</code> target of {@link
+ * AuthPermission}.
+ */
+ public static Object doAsPrivileged (final Subject subject,
+ final PrivilegedAction action,
+ final AccessControlContext acc)
+ {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("doAsPrivileged"));
+ }
+ AccessControlContext context =
+ new AccessControlContext (acc, new SubjectDomainCombiner (subject));
+ return AccessController.doPrivileged (action, context);
+ }
+
+ /**
+ * <p>Run a method as another subject. This method will create a new
+ * {@link AccessControlContext} derived from the given one, with a
+ * {@link SubjectDomainCombiner} with the given subject. The supplied
+ * action will then be run with the modified context.</p>
+ *
+ * @param subject The subject to run as.
+ * @param action The action to run.
+ * @param acc The context to use.
+ * @return The value returned by the privileged action.
+ * @throws SecurityException If the caller is not allowed to run under a
+ * different identity (<code>"doAsPrivileged"</code> target of
+ * {@link AuthPermission}.
+ * @throws PrivilegedActionException If the action throws an exception.
+ */
+ public static Object doAsPrivileged (final Subject subject,
+ final PrivilegedExceptionAction action,
+ final AccessControlContext acc)
+ throws PrivilegedActionException
+ {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("doAsPrivileged"));
+ }
+ AccessControlContext context =
+ new AccessControlContext (acc, new SubjectDomainCombiner (subject));
+ return AccessController.doPrivileged (action, context);
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public boolean equals (Object o)
+ {
+ if (!(o instanceof Subject))
+ {
+ return false;
+ }
+ Subject that = (Subject) o;
+ return principals.containsAll (that.getPrincipals()) &&
+ pubCred.containsAll (that.getPublicCredentials()) &&
+ privCred.containsAll (that.getPrivateCredentials());
+ }
+
+ public Set getPrincipals()
+ {
+ return principals;
+ }
+
+ public Set getPrincipals(Class clazz)
+ {
+ HashSet result = new HashSet (principals.size());
+ for (Iterator it = principals.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (o != null && clazz.isAssignableFrom (o.getClass()))
+ {
+ result.add(o);
+ }
+ }
+ return Collections.unmodifiableSet (result);
+ }
+
+ public Set getPrivateCredentials()
+ {
+ return privCred;
+ }
+
+ public Set getPrivateCredentials (Class clazz)
+ {
+ HashSet result = new HashSet (privCred.size());
+ for (Iterator it = privCred.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (o != null && clazz.isAssignableFrom (o.getClass()))
+ {
+ result.add(o);
+ }
+ }
+ return Collections.unmodifiableSet (result);
+ }
+
+ public Set getPublicCredentials()
+ {
+ return pubCred;
+ }
+
+ public Set getPublicCredentials (Class clazz)
+ {
+ HashSet result = new HashSet (pubCred.size());
+ for (Iterator it = pubCred.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (o != null && clazz.isAssignableFrom (o.getClass()))
+ {
+ result.add(o);
+ }
+ }
+ return Collections.unmodifiableSet (result);
+ }
+
+ public int hashCode()
+ {
+ return principals.hashCode() + privCred.hashCode() + pubCred.hashCode();
+ }
+
+ /**
+ * <p>Returns whether or not this subject is read-only.</p>
+ *
+ * @return True is this subject is read-only.
+ */
+ public boolean isReadOnly()
+ {
+ return readOnly;
+ }
+
+ /**
+ * <p>Marks this subject as read-only.</p>
+ *
+ * @throws SecurityException If the caller does not have permission to
+ * set this subject as read-only (<code>"setReadOnly"</code> target of
+ * {@link AuthPermission}.
+ */
+ public void setReadOnly()
+ {
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("setReadOnly"));
+ }
+ readOnly = true;
+ }
+
+ public String toString()
+ {
+ return Subject.class.getName() + " [ principals=" + principals +
+ ", private credentials=" + privCred + ", public credentials=" +
+ pubCred + ", read-only=" + readOnly + " ]";
+ }
+
+ // Inner class.
+ // -------------------------------------------------------------------------
+
+ /**
+ * An undocumented inner class that is used for sets in the parent class.
+ */
+ private static class SecureSet extends AbstractSet implements Serializable
+ {
+
+ // Fields.
+ // -----------------------------------------------------------------------
+
+ private static final long serialVersionUID = 7911754171111800359L;
+
+ static final int PRINCIPALS = 0;
+ static final int PUBLIC_CREDENTIALS = 1;
+ static final int PRIVATE_CREDENTIALS = 2;
+
+ private final Subject subject;
+ private final LinkedList elements;
+ private transient final int type;
+
+ // Constructors.
+ // -----------------------------------------------------------------------
+
+ SecureSet (final Subject subject, final int type, final Collection elements)
+ {
+ this (subject, type);
+ for (Iterator it = elements.iterator(); it.hasNext(); )
+ {
+ Object o = it.next();
+ if (type == PRINCIPALS && !(o instanceof Principal))
+ {
+ throw new IllegalArgumentException(o+" is not a Principal");
+ }
+ if (!elements.contains (o))
+ {
+ elements.add (o);
+ }
+ }
+ }
+
+ SecureSet (final Subject subject, final int type)
+ {
+ this.subject = subject;
+ this.type = type;
+ this.elements = new LinkedList();
+ }
+
+ // Instance methods.
+ // -----------------------------------------------------------------------
+
+ public synchronized int size()
+ {
+ return elements.size();
+ }
+
+ public Iterator iterator()
+ {
+ return elements.iterator();
+ }
+
+ public synchronized boolean add(Object element)
+ {
+ if (subject.isReadOnly())
+ {
+ throw new IllegalStateException ("subject is read-only");
+ }
+ final SecurityManager sm = System.getSecurityManager();
+ switch (type)
+ {
+ case PRINCIPALS:
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("modifyPrincipals"));
+ }
+ if (!(element instanceof Principal))
+ {
+ throw new IllegalArgumentException ("element is not a Principal");
+ }
+ break;
+
+ case PUBLIC_CREDENTIALS:
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("modifyPublicCredentials"));
+ }
+ break;
+
+ case PRIVATE_CREDENTIALS:
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("modifyPrivateCredentials"));
+ }
+ break;
+
+ default:
+ throw new Error ("this statement should be unreachable");
+ }
+
+ if (elements.contains (element))
+ {
+ return false;
+ }
+
+ return elements.add (element);
+ }
+
+ public synchronized boolean remove (final Object element)
+ {
+ if (subject.isReadOnly())
+ {
+ throw new IllegalStateException ("subject is read-only");
+ }
+ final SecurityManager sm = System.getSecurityManager();
+ switch (type)
+ {
+ case PRINCIPALS:
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("modifyPrincipals"));
+ }
+ if (!(element instanceof Principal))
+ {
+ throw new IllegalArgumentException ("element is not a Principal");
+ }
+ break;
+
+ case PUBLIC_CREDENTIALS:
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("modifyPublicCredentials"));
+ }
+ break;
+
+ case PRIVATE_CREDENTIALS:
+ if (sm != null)
+ {
+ sm.checkPermission (new AuthPermission ("modifyPrivateCredentials"));
+ }
+ break;
+
+ default:
+ throw new Error("this statement should be unreachable");
+ }
+
+ return elements.remove(element);
+ }
+
+ public synchronized boolean contains (final Object element)
+ {
+ return elements.remove (element);
+ }
+
+ public boolean removeAll (final Collection c)
+ {
+ if (subject.isReadOnly())
+ {
+ throw new IllegalStateException ("subject is read-only");
+ }
+ return super.removeAll (c);
+ }
+
+ public boolean retainAll (final Collection c)
+ {
+ if (subject.isReadOnly())
+ {
+ throw new IllegalStateException ("subject is read-only");
+ }
+ return super.retainAll (c);
+ }
+
+ public void clear()
+ {
+ if (subject.isReadOnly())
+ {
+ throw new IllegalStateException ("subject is read-only");
+ }
+ elements.clear();
+ }
+
+ private synchronized void writeObject (ObjectOutputStream out)
+ throws IOException
+ {
+ throw new UnsupportedOperationException ("FIXME: determine serialization");
+ }
+
+ private void readObject (ObjectInputStream in)
+ throws ClassNotFoundException, IOException
+ {
+ throw new UnsupportedOperationException ("FIXME: determine serialization");
+ }
+ }
+}
diff --git a/libjava/javax/security/auth/SubjectDomainCombiner.java b/libjava/javax/security/auth/SubjectDomainCombiner.java
new file mode 100644
index 00000000000..194e1130a2a
--- /dev/null
+++ b/libjava/javax/security/auth/SubjectDomainCombiner.java
@@ -0,0 +1,96 @@
+/* SubjectDomainCombiner.java -- domain combiner for Subjects.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth;
+
+import java.security.DomainCombiner;
+import java.security.Principal;
+import java.security.ProtectionDomain;
+
+import java.util.LinkedList;
+
+public class SubjectDomainCombiner implements DomainCombiner
+{
+
+ // Field.
+ // -------------------------------------------------------------------------
+
+ private final Subject subject;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public SubjectDomainCombiner (final Subject subject)
+ {
+ this.subject = subject;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public ProtectionDomain[] combine (final ProtectionDomain[] current,
+ final ProtectionDomain[] assigned)
+ {
+ LinkedList domains = new LinkedList();
+ Principal[] principals =
+ (Principal[]) subject.getPrincipals().toArray (new Principal[0]);
+ if (current != null)
+ {
+ for (int i = 0; i < current.length; i++)
+ {
+ domains.add (new ProtectionDomain (current[i].getCodeSource(),
+ current[i].getPermissions(),
+ current[i].getClassLoader(),
+ principals));
+ }
+ }
+ if (assigned != null)
+ {
+ for (int i = 0; i < assigned.length; i++)
+ {
+ domains.add (assigned[i]);
+ }
+ }
+ return (ProtectionDomain[]) domains.toArray (new ProtectionDomain[domains.size()]);
+ }
+
+ public Subject getSubject()
+ {
+ return subject;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/Callback.java b/libjava/javax/security/auth/callback/Callback.java
new file mode 100644
index 00000000000..655ad3348ba
--- /dev/null
+++ b/libjava/javax/security/auth/callback/Callback.java
@@ -0,0 +1,65 @@
+/* Callback.java -- marker interface for callback classes
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+/**
+ * <p>Implementations of this interface are passed to a {@link CallbackHandler},
+ * allowing underlying security services the ability to interact with a calling
+ * application to retrieve specific authentication data such as usernames and
+ * passwords, or to display certain information, such as error and warning
+ * messages.</p>
+ *
+ * <p><code>Callback</code> implementations do not retrieve or display the
+ * information requested by underlying security services. <code>Callback</code>
+ * implementations simply provide the means to pass such requests to
+ * applications, and for applications, if appropriate, to return requested
+ * information back to the underlying security services.</p>
+ *
+ * @see CallbackHandler
+ * @see ChoiceCallback
+ * @see ConfirmationCallback
+ * @see LanguageCallback
+ * @see NameCallback
+ * @see PasswordCallback
+ * @see TextInputCallback
+ * @see TextOutputCallback
+ * @version $Revision: 1.1 $
+ */
+public interface Callback {
+}
diff --git a/libjava/javax/security/auth/callback/CallbackHandler.java b/libjava/javax/security/auth/callback/CallbackHandler.java
new file mode 100644
index 00000000000..289999c5ee1
--- /dev/null
+++ b/libjava/javax/security/auth/callback/CallbackHandler.java
@@ -0,0 +1,156 @@
+/* CallbackHandler.java -- base interface for callback handlers.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.IOException;
+
+/**
+ * <p>An application implements a <code>CallbackHandler</code> and passes it to
+ * underlying security services so that they may interact with the application
+ * to retrieve specific authentication data, such as usernames and passwords, or
+ * to display certain information, such as error and warning messages.</p>
+ *
+ * <p><code>CallbackHandler</code>s are implemented in an application-dependent
+ * fashion. For example, implementations for an application with a graphical
+ * user interface (GUI) may pop up windows to prompt for requested information
+ * or to display error messages. An implementation may also choose to obtain
+ * requested information from an alternate source without asking the end user.</p>
+ *
+ * <p>Underlying security services make requests for different types of
+ * information by passing individual Callbacks to the <code>CallbackHandler</code>.
+ * The <code>CallbackHandler</code> implementation decides how to retrieve and
+ * display information depending on the {@link Callback}s passed to it. For
+ * example, if the underlying service needs a username and password to
+ * authenticate a user, it uses a {@link NameCallback} and
+ * {@link PasswordCallback}. The <code>CallbackHandler</code> can then choose
+ * to prompt for a username and password serially, or to prompt for both in a
+ * single window.</p>
+ *
+ * <p>A default <code>CallbackHandler</code> class implementation may be
+ * specified in the <code>auth.login.defaultCallbackHandler</code> security
+ * property. The security property can be set in the Java security properties
+ * file located in the file named
+ * <code>&lt;JAVA_HOME>/lib/security/java.security</code>, where
+ * <code>&lt;JAVA_HOME></code> refers to the directory where the SDK was
+ * installed.</p>
+ *
+ * <p>If the security property is set to the fully qualified name of a
+ * <code>CallbackHandler</code> implementation class, then a
+ * <code>LoginContext</code>will load the specified <code>CallbackHandler</code>
+ * and pass it to the underlying <code>LoginModules</code>. The
+ * <code>LoginContext</code> only loads the default handler if one was not
+ * provided.</p>
+ *
+ * <p>All default handler implementations must provide a public zero-argument
+ * constructor.</p>
+ *
+ * @version $Revision: 1.1 $
+ */
+public interface CallbackHandler
+{
+
+ /**
+ * <p>Retrieve or display the information requested in the provided
+ * {@link Callback}s.</p>
+ *
+ * <p>The <code>handle()</code> method implementation checks the instance(s)
+ * of the {@link Callback} object(s) passed in to retrieve or display the
+ * requested information. The following example is provided to help
+ * demonstrate what an <code>handle()</code> method implementation might look
+ * like. This example code is for guidance only. Many details, including
+ * proper error handling, are left out for simplicity.</p>
+ *
+ * <pre>
+ *public void handle(Callback[] callbacks)
+ *throws IOException, UnsupportedCallbackException {
+ * for (int i = 0; i < callbacks.length; i++) {
+ * if (callbacks[i] instanceof TextOutputCallback) {
+ * // display the message according to the specified type
+ * TextOutputCallback toc = (TextOutputCallback)callbacks[i];
+ * switch (toc.getMessageType()) {
+ * case TextOutputCallback.INFORMATION:
+ * System.out.println(toc.getMessage());
+ * break;
+ * case TextOutputCallback.ERROR:
+ * System.out.println("ERROR: " + toc.getMessage());
+ * break;
+ * case TextOutputCallback.WARNING:
+ * System.out.println("WARNING: " + toc.getMessage());
+ * break;
+ * default:
+ * throw new IOException("Unsupported message type: "
+ * + toc.getMessageType());
+ * }
+ * } else if (callbacks[i] instanceof NameCallback) {
+ * // prompt the user for a username
+ * NameCallback nc = (NameCallback)callbacks[i];
+ * // ignore the provided defaultName
+ * System.err.print(nc.getPrompt());
+ * System.err.flush();
+ * nc.setName((new BufferedReader(
+ * new InputStreamReader(System.in))).readLine());
+ * } else if (callbacks[i] instanceof PasswordCallback) {
+ * // prompt the user for sensitive information
+ * PasswordCallback pc = (PasswordCallback)callbacks[i];
+ * System.err.print(pc.getPrompt());
+ * System.err.flush();
+ * pc.setPassword(readPassword(System.in));
+ * } else {
+ * throw new UnsupportedCallbackException(
+ * callbacks[i], "Unrecognized Callback");
+ * }
+ * }
+ *}
+ *
+ * // Reads user password from given input stream.
+ *private char[] readPassword(InputStream in) throws IOException {
+ * // insert code to read a user password from the input stream
+ *}
+ * </pre>
+ *
+ * @param callbacks an array of {@link Callback} objects provided by an
+ * underlying security service which contains the information requested to
+ * be retrieved or displayed.
+ * @throws IOException if an input or output error occurs.
+ * @throws UnsupportedCallbackException if the implementation of this method
+ * does not support one or more of the Callbacks specified in the
+ * <code>callbacks</code> parameter.
+ */
+ void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException;
+}
diff --git a/libjava/javax/security/auth/callback/ChoiceCallback.java b/libjava/javax/security/auth/callback/ChoiceCallback.java
new file mode 100644
index 00000000000..44b5ffcba5e
--- /dev/null
+++ b/libjava/javax/security/auth/callback/ChoiceCallback.java
@@ -0,0 +1,237 @@
+/* ChoiceCallback.java -- callback for a choice of values.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+
+/**
+ * Underlying security services instantiate and pass a
+ * <code>ChoiceCallback</code> to the <code>handle()</code> method of a
+ * {@link CallbackHandler} to display a list of choices and to retrieve the
+ * selected choice(s).
+ *
+ * @see CallbackHandler
+ * @version $Revision: 1.1 $
+ */
+public class ChoiceCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String prompt;
+
+ /**
+ * @serial the list of choices.
+ * @since 1.4
+ */
+ private String[] choices;
+
+ /**
+ * @serial the choice to be used as the default choice.
+ * @since 1.4
+ */
+ private int defaultChoice;
+
+ /**
+ * @serial whether multiple selections are allowed from the list of choices.
+ * @since 1.4
+ */
+ private boolean multipleSelectionsAllowed;
+
+ /**
+ * @serial the selected choices, represented as indexes into the choices list.
+ * @since 1.4
+ */
+ private int[] selections;
+
+ // Constructor(s)
+ //--------------------------------------------------------------------------
+
+ /**
+ * Construct a <code>ChoiceCallback</code> with a prompt, a list of choices,
+ * a default choice, and a boolean specifying whether or not multiple
+ * selections from the list of choices are allowed.
+ *
+ * @param prompt the prompt used to describe the list of choices.
+ * @param choices the list of choices.
+ * @param defaultChoice the choice to be used as the default choice when the
+ * list of choices are displayed. This value is represented as an index into
+ * the <code>choices</code> array.
+ * @param multipleSelectionsAllowed boolean specifying whether or not
+ * multiple selections can be made from the list of choices.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>,
+ * if <code>prompt</code> has a length of <code>0</code>, if <code>choices</code>
+ * is <code>null</code>, if <code>choices</code> has a length of <code>0</code>,
+ * if any element from <code>choices</code> is <code>null</code>, if any
+ * element from <code>choices</code> has a length of <code>0</code> or if
+ * <code>defaultChoice</code> does not fall within the array boundaries of
+ * <code>choices</code>.
+ */
+ public ChoiceCallback(String prompt, String[] choices, int defaultChoice,
+ boolean multipleSelectionsAllowed)
+ {
+ super();
+
+ setPrompt(prompt);
+ setChoices(choices);
+ if (defaultChoice < 0 || defaultChoice >= this.choices.length)
+ {
+ throw new IllegalArgumentException("default choice is out of bounds");
+ }
+ this.defaultChoice = defaultChoice;
+ this.multipleSelectionsAllowed = multipleSelectionsAllowed;
+ }
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Get the prompt.
+ *
+ * @return the prompt.
+ */
+ public String getPrompt()
+ {
+ return prompt;
+ }
+
+ /**
+ * Get the list of choices.
+ *
+ * @return the list of choices.
+ */
+ public String[] getChoices()
+ {
+ return choices;
+ }
+
+ /**
+ * Get the defaultChoice.
+ *
+ * @return the defaultChoice, represented as an index into the choices list.
+ */
+ public int getDefaultChoice()
+ {
+ return defaultChoice;
+ }
+
+ /**
+ * Get the boolean determining whether multiple selections from the choices
+ * list are allowed.
+ *
+ * @return whether multiple selections are allowed.
+ */
+ public boolean allowMultipleSelections()
+ {
+ return multipleSelectionsAllowed;
+ }
+
+ /**
+ * Set the selected choice.
+ *
+ * @param selection the selection represented as an index into the choices
+ * list.
+ * @see #getSelectedIndexes()
+ */
+ public void setSelectedIndex(int selection)
+ {
+ this.selections = new int[1];
+ this.selections[0] = selection;
+ }
+
+ /**
+ * Set the selected choices.
+ *
+ * @param selections the selections represented as indexes into the choices
+ * list.
+ * @throws UnsupportedOperationException if multiple selections are not
+ * allowed, as determined by <code>allowMultipleSelections</code>.
+ * @see #getSelectedIndexes()
+ */
+ public void setSelectedIndexes(int[] selections)
+ {
+ if (!multipleSelectionsAllowed)
+ {
+ throw new UnsupportedOperationException("not allowed");
+ }
+
+ this.selections = selections;
+ }
+
+ /**
+ * Get the selected choices.
+ *
+ * @return the selected choices, represented as indexes into the choices list.
+ * @see #setSelectedIndexes(int[])
+ */
+ public int[] getSelectedIndexes()
+ {
+ return selections;
+ }
+
+ private void setPrompt(String prompt) throws IllegalArgumentException
+ {
+ if ((prompt == null) || (prompt.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid prompt");
+ }
+ this.prompt = prompt;
+ }
+
+ private void setChoices(String[] choices) throws IllegalArgumentException
+ {
+ if (choices == null || choices.length == 0)
+ {
+ throw new IllegalArgumentException("invalid choices");
+ }
+ for (int i = 0; i < choices.length; i++)
+ {
+ if (choices[i] == null || choices[i].length() == 0)
+ {
+ throw new IllegalArgumentException("invalid choice at index #"+i);
+ }
+ }
+ this.choices = choices;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/ConfirmationCallback.java b/libjava/javax/security/auth/callback/ConfirmationCallback.java
new file mode 100644
index 00000000000..8abd393f52c
--- /dev/null
+++ b/libjava/javax/security/auth/callback/ConfirmationCallback.java
@@ -0,0 +1,506 @@
+/* ConfirmationCallback.java -- callback for confirmations.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+
+/**
+ * Underlying security services instantiate and pass a
+ * <code>ConfirmationCallback</code> to the <code>handle()</code> method of a
+ * {@link CallbackHandler} to ask for YES/NO, OK/CANCEL, YES/NO/CANCEL or other
+ * similar confirmations.
+ *
+ * @see CallbackHandler
+ * @version $Revision: 1.1 $
+ */
+public class ConfirmationCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Unspecified option type.</p>
+ *
+ * <p>The <code>getOptionType</code> method returns this value if this
+ * <code>ConfirmationCallback</code> was instantiated with <code>options</code>
+ * instead of an <code>optionType</code>.</p>
+ */
+ public static final int UNSPECIFIED_OPTION = -1;
+
+ /**
+ * <p>YES/NO confirmation option.</p>
+ *
+ * <p>An underlying security service specifies this as the <code>optionType</code>
+ * to a <code>ConfirmationCallback</code> constructor if it requires a
+ * confirmation which can be answered with either <code>YES</code> or
+ * <code>NO</code>.</p>
+ */
+ public static final int YES_NO_OPTION = 0;
+
+ /**
+ * <p>YES/NO/CANCEL confirmation confirmation option.</p>
+ *
+ * <p>An underlying security service specifies this as the <code>optionType</code>
+ * to a <code>ConfirmationCallback</code> constructor if it requires a
+ * confirmation which can be answered with either <code>YES</code>,
+ * <code>NO</code> or <code>CANCEL</code>.
+ */
+ public static final int YES_NO_CANCEL_OPTION = 1;
+
+ /**
+ * <p>OK/CANCEL confirmation confirmation option.</p>
+ *
+ * <p>An underlying security service specifies this as the <code>optionType</code>
+ * to a <code>ConfirmationCallback</code> constructor if it requires a
+ * confirmation which can be answered with either <code>OK</code> or
+ * <code>CANCEL</code>.</p>
+ */
+ public static final int OK_CANCEL_OPTION = 2;
+
+ /**
+ * <p>YES option.</p>
+ *
+ * <p>If an <code>optionType</code> was specified to this
+ * <code>ConfirmationCallback</code>, this option may be specified as a
+ * <code>defaultOption</code> or returned as the selected index.</p>
+ */
+ public static final int YES = 0;
+
+ /**
+ * <p>NO option.</p>
+ *
+ * <p>If an <code>optionType</code> was specified to this
+ * <code>ConfirmationCallback</code>, this option may be specified as a
+ * <code>defaultOption</code> or returned as the selected index.</p>
+ */
+ public static final int NO = 1;
+
+ /**
+ * <p>CANCEL option.</p>
+ *
+ * <p>If an <code>optionType</code> was specified to this
+ * <code>ConfirmationCallback</code>, this option may be specified as a
+ * <code>defaultOption</code> or returned as the selected index.</p>
+ */
+ public static final int CANCEL = 2;
+
+ /**
+ * <p>OK option.</p>
+ *
+ * <p>If an <code>optionType</code> was specified to this
+ * <code>ConfirmationCallback</code>, this option may be specified as a
+ * <code>defaultOption</code> or returned as the selected index.</p>
+ */
+ public static final int OK = 3;
+
+ /** INFORMATION message type. */
+ public static final int INFORMATION = 0;
+
+ /** WARNING message type. */
+ public static final int WARNING = 1;
+
+ /** ERROR message type. */
+ public static final int ERROR = 2;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String prompt;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private int messageType;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private int optionType;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private int defaultOption;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String[] options = null;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private int selection;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Construct a <code>ConfirmationCallback</code> with a message type, an
+ * option type and a default option.</p>
+ *
+ * <p>Underlying security services use this constructor if they require
+ * either a YES/NO, YES/NO/CANCEL or OK/CANCEL confirmation.</p>
+ *
+ * @param messageType the message type (INFORMATION, WARNING or ERROR).
+ * @param optionType the option type (YES_NO_OPTION, YES_NO_CANCEL_OPTION or
+ * OK_CANCEL_OPTION).
+ * @param defaultOption the default option from the provided optionType (YES,
+ * NO, CANCEL or OK).
+ * @throws IllegalArgumentException if <code>messageType</code> is not either
+ * <code>INFORMATION</code>, <code>WARNING</code>, or <code>ERROR</code>, if
+ * <code>optionType</code> is not either <code>YES_NO_OPTION</code>,
+ * <code>YES_NO_CANCEL_OPTION</code>, or <code>OK_CANCEL_OPTION</code>, or if
+ * <code>defaultOption</code> does not correspond to one of the options in
+ * <code>optionType</code>.
+ */
+ public ConfirmationCallback(int messageType, int optionType, int defaultOption)
+ throws IllegalArgumentException
+ {
+ super();
+
+ setMessageType(messageType);
+ setOptionType(optionType, defaultOption);
+ this.defaultOption = defaultOption;
+ }
+
+ /**
+ * <p>Construct a <code>ConfirmationCallback</code> with a message type, a
+ * list of options and a default option.</p>
+ *
+ * <p>Underlying security services use this constructor if they require a
+ * confirmation different from the available preset confirmations provided
+ * (for example, CONTINUE/ABORT or STOP/GO). The confirmation options are
+ * listed in the <code>options</code> array, and are displayed by the
+ * {@link CallbackHandler} implementation in a manner consistent with the
+ * way preset options are displayed.</p>
+ *
+ * @param messageType the message type (INFORMATION, WARNING or ERROR).
+ * @param options the list of confirmation options.
+ * @param defaultOption the default option, represented as an index into the
+ * <code>options</code> array.
+ * @throws IllegalArgumentException if <code>messageType</code> is not either
+ * <code>INFORMATION</code>, <code>WARNING</code>, or <code>ERROR</code>, if
+ * <code>options</code> is <code>null</code>, if <code>options</code> has a
+ * length of <code>0</code>, if any element from <code>options</code> is
+ * <code>null</code>, if any element from <code>options</code> has a length
+ * of <code>0</code>, or if <code>defaultOption</code> does not lie within
+ * the array boundaries of <code>options</code>.
+ */
+ public ConfirmationCallback(int messageType, String[] options, int defaultOption)
+ {
+ super();
+
+ setMessageType(messageType);
+ setOptions(options, defaultOption);
+ this.defaultOption = defaultOption;
+ }
+
+ /**
+ * <p>Construct a <code>ConfirmationCallback</code> with a prompt, message
+ * type, an option type and a default option.</p>
+ *
+ * <p>Underlying security services use this constructor if they require
+ * either a YES/NO, YES/NO/CANCEL or OK/CANCEL confirmation.</p>
+ *
+ * @param prompt the prompt used to describe the list of options.
+ * @param messageType the message type (INFORMATION, WARNING or ERROR).
+ * @param optionType the option type (YES_NO_OPTION, YES_NO_CANCEL_OPTION or
+ * OK_CANCEL_OPTION).
+ * @param defaultOption the default option from the provided optionType (YES,
+ * NO, CANCEL or OK).
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>,
+ * if <code>prompt</code> has a length of <code>0</code>, if
+ * <code>messageType</code> is not either <ode>INFORMATION</code>,
+ * <code>WARNING</code>, or <code>ERROR</code>, if <code>optionType</code> is
+ * not either <code>YES_NO_OPTION</code>, <code>YES_NO_CANCEL_OPTION</code>,
+ * or <code>OK_CANCEL_OPTION</code>, or if <code>defaultOption</code> does
+ * not correspond to one of the options in <code>optionType</code>.
+ */
+ public ConfirmationCallback(String prompt, int messageType, int optionType,
+ int defaultOption)
+ {
+ super();
+
+ setPrompt(prompt);
+ setMessageType(messageType);
+ setOptionType(optionType, defaultOption);
+ this.defaultOption = defaultOption;
+ }
+
+ /**
+ * <p>Construct a <code>ConfirmationCallback</code> with a prompt, message
+ * type, a list of options and a default option.</p>
+ *
+ * <p>Underlying security services use this constructor if they require a
+ * confirmation different from the available preset confirmations provided
+ * (for example, CONTINUE/ABORT or STOP/GO). The confirmation options are
+ * listed in the <code>options</code> array, and are displayed by the
+ * {@link CallbackHandler} implementation in a manner consistent with the
+ * way preset options are displayed.</p>
+ *
+ * @param prompt the prompt used to describe the list of options.
+ * @param messageType the message type (INFORMATION, WARNING or ERROR).
+ * @param options the list of confirmation options.
+ * @param defaultOption the default option, represented as an index into the
+ * <code>options</code> array.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>,
+ * if <code>prompt</code> has a length of <code>0</code>, if
+ * <code>messageType</code> is not either <ode>INFORMATION</code>,
+ * <code>WARNING</code>, or <code>ERROR</code>, if <code>options</code> is
+ * <code>null</code>, if <code>options</code> has a length of <code>0</code>,
+ * if any element from <code>options</code> is <code>null</code>, if any
+ * element from <code>options</code> has a length of <code>0</code>, or if
+ * <code>defaultOption</code> does not lie within the array boundaries of
+ * <code>options</code>.
+ */
+ public ConfirmationCallback(String prompt, int messageType, String[] options,
+ int defaultOption)
+ {
+ super();
+
+ setPrompt(prompt);
+ setMessageType(messageType);
+ setOptions(options, defaultOption);
+ this.defaultOption = defaultOption;
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Get the prompt.
+ *
+ * @return the prompt, or <code>null</code> if this
+ * <code>ConfirmationCallback</code> was instantiated without a prompt.
+ */
+ public String getPrompt()
+ {
+ return prompt;
+ }
+
+ /**
+ * Get the message type.
+ *
+ * @return the message type (INFORMATION, WARNING or ERROR).
+ */
+ public int getMessageType()
+ {
+ return messageType;
+ }
+
+ /**
+ * <p>Get the option type.</p>
+ *
+ * <p>If this method returns {@link #UNSPECIFIED_OPTION}, then this
+ * <code>ConfirmationCallback</code> was instantiated with <code>options</code>
+ * instead of an <code>optionType</code>. In this case, invoke the
+ * {@link #getOptions()} method to determine which confirmation options to
+ * display.</p>
+ *
+ * @return the option type (YES_NO_OPTION, YES_NO_CANCEL_OPTION or
+ * OK_CANCEL_OPTION), or UNSPECIFIED_OPTION if this
+ * <code>ConfirmationCallback</code> was instantiated with <code>options</code>
+ * instead of an <code>optionType</code>.
+ */
+ public int getOptionType()
+ {
+ if (options != null)
+ {
+ return UNSPECIFIED_OPTION;
+ }
+ return optionType;
+ }
+
+ /**
+ * Get the confirmation options.
+ *
+ * @return the list of confirmation options, or <code>null</code> if this
+ * <code>ConfirmationCallback</code> was instantiated with an
+ * <code>optionType</code> instead of <code>options</code>.
+ */
+ public String[] getOptions()
+ {
+ return options;
+ }
+
+ /**
+ * Get the default option.
+ *
+ * @return the default option, represented as <code>YES</code>, <code>NO</code>,
+ * <code>OK</code> or <code>CANCEL</code> if an <code>optionType</code> was
+ * specified to the constructor of this <code>ConfirmationCallback</code>.
+ * Otherwise, this method returns the default option as an index into the
+ * <code>options</code> array specified to the constructor of this
+ * <code>ConfirmationCallback</code>.
+ */
+ public int getDefaultOption()
+ {
+ return defaultOption;
+ }
+
+ /**
+ * Set the selected confirmation option.
+ *
+ * @param selection the selection represented as <code>YES</code>,
+ * <code>NO</code>, <code>OK</code> or <code>CANCEL</code> if an
+ * <code>optionType</code> was specified to the constructor of this
+ * <code>ConfirmationCallback</code>. Otherwise, the <code>selection</code>
+ * represents the index into the <code>options</code> array specified to the
+ * constructor of this <code>ConfirmationCallback</code>.
+ * @see #getSelectedIndex()
+ */
+ public void setSelectedIndex(int selection)
+ {
+ if (options != null)
+ {
+ setOptions(options, selection);
+ }
+ else
+ {
+ setOptionType(optionType, selection);
+ }
+ }
+
+ /**
+ * Get the selected confirmation option.
+ *
+ * @return the selected confirmation option represented as <code>YES</code>,
+ * <code>NO</code>, <code>OK</code> or <code>CANCEL</code> if an
+ * <code>optionType</code> was specified to the constructor of this
+ * <code>ConfirmationCallback</code>. Otherwise, this method returns the
+ * selected confirmation option as an index into the <code>options</code>
+ * array specified to the constructor of this <code>ConfirmationCallback</code>.
+ * @see #setSelectedIndex(int)
+ */
+ public int getSelectedIndex()
+ {
+ return this.selection;
+ }
+
+ private void setMessageType(int messageType) throws IllegalArgumentException
+ {
+ switch (messageType)
+ {
+ case INFORMATION:
+ case WARNING:
+ case ERROR: this.messageType = messageType; break;
+ default: throw new IllegalArgumentException("illegal message type");
+ }
+ }
+
+ private void setOptionType(int optionType, int selectedOption)
+ throws IllegalArgumentException
+ {
+ switch (optionType)
+ {
+ case YES_NO_OPTION:
+ this.optionType = optionType;
+ switch (selectedOption)
+ {
+ case YES:
+ case NO: this.selection = selectedOption; break;
+ default: throw new IllegalArgumentException("invalid option");
+ }
+ break;
+ case YES_NO_CANCEL_OPTION:
+ this.optionType = optionType;
+ switch (selectedOption)
+ {
+ case YES:
+ case NO:
+ case CANCEL: this.selection = selectedOption; break;
+ default: throw new IllegalArgumentException("invalid option");
+ }
+ break;
+ case OK_CANCEL_OPTION:
+ this.optionType = optionType;
+ switch (selectedOption)
+ {
+ case OK:
+ case CANCEL: this.selection = selectedOption; break;
+ default: throw new IllegalArgumentException("invalid option");
+ }
+ break;
+ default:
+ throw new IllegalArgumentException("illegal option type");
+ }
+ }
+
+ private void setOptions(String[] options, int selectedOption)
+ throws IllegalArgumentException
+ {
+ if ((selectedOption < 0) || (selectedOption > options.length - 1))
+ {
+ throw new IllegalArgumentException("invalid selection");
+ }
+ if ((options == null) || (options.length == 0))
+ {
+ throw new IllegalArgumentException("options is null or empty");
+ }
+ for (int i = 0; i < options.length; i++)
+ {
+ if ((options[i] == null) || (options[i].length() == 0))
+ {
+ throw new IllegalArgumentException("options[" + i + "] is null or empty");
+ }
+ }
+ this.options = options;
+ this.selection = selectedOption;
+ }
+
+ private void setPrompt(String prompt) throws IllegalArgumentException
+ {
+ if ((prompt == null) || (prompt.length() == 0))
+ {
+ throw new IllegalArgumentException("prompt is null or empty");
+ }
+ this.prompt = prompt;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/LanguageCallback.java b/libjava/javax/security/auth/callback/LanguageCallback.java
new file mode 100644
index 00000000000..71910632b48
--- /dev/null
+++ b/libjava/javax/security/auth/callback/LanguageCallback.java
@@ -0,0 +1,101 @@
+/* LanguageCallback.java -- callback for language choices.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+import java.util.Locale;
+
+/**
+ * Underlying security services instantiate and pass a <code>LanguageCallback</code>
+ * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve
+ * the {@link Locale} used for localizing text.
+ *
+ * @see CallbackHandler
+ * @version $Revision: 1.1 $
+ */
+public class LanguageCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private Locale locale;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /** Construct a <code>LanguageCallback</code>. */
+ public LanguageCallback()
+ {
+ super();
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Set the retrieved Locale.
+ *
+ * @param locale the retrieved Locale.
+ * @see #getLocale()
+ */
+ public void setLocale(Locale locale)
+ {
+ this.locale = locale;
+ }
+
+ /**
+ * Get the retrieved Locale.
+ *
+ * @return the retrieved Locale, or <code>null</code> if no Locale could be
+ * retrieved.
+ * @see #setLocale(Locale)
+ */
+ public Locale getLocale()
+ {
+ return locale;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/NameCallback.java b/libjava/javax/security/auth/callback/NameCallback.java
new file mode 100644
index 00000000000..c98edfdbea9
--- /dev/null
+++ b/libjava/javax/security/auth/callback/NameCallback.java
@@ -0,0 +1,179 @@
+/* NameCallback.java -- callback for user names.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+
+/**
+ * Underlying security services instantiate and pass a <code>NameCallback</code>
+ * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve
+ * name information.
+ *
+ * @see CallbackHandler
+ * @version $Revision: 1.1 $
+ */
+public class NameCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String prompt;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String defaultName;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String inputName;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Construct a <code>NameCallback</code> with a prompt.
+ *
+ * @param prompt the prompt used to request the name.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or if <code>prompt</code> has a length of <code>0</code>.
+ */
+ public NameCallback(String prompt)
+ {
+ super();
+
+ setPrompt(prompt);
+ }
+
+ /**
+ * Construct a <code>NameCallback</code> with a prompt and default name.
+ *
+ * @param prompt the prompt used to request the information.
+ * @param defaultName the name to be used as the default name displayed with
+ * the prompt.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or if <code>prompt</code> has a length of <code>0</code>, if
+ * <code>defaultName</code> is <code>null</code>, or if <code>defaultName</code>
+ * has a length of <code>0</code>.
+ */
+ public NameCallback(String prompt, String defaultName)
+ throws IllegalArgumentException
+ {
+ super();
+
+ setPrompt(prompt);
+ setDefaultName(defaultName);
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Get the prompt.
+ *
+ * @return the prompt.
+ */
+ public String getPrompt()
+ {
+ return prompt;
+ }
+
+ /**
+ * Get the default name.
+ *
+ * @return the default name, or <code>null</code> if this
+ * <code>NameCallback</code> was not instantiated with a
+ * <code>defaultName</code>.
+ */
+ public String getDefaultName()
+ {
+ return defaultName;
+ }
+
+ /**
+ * Set the retrieved name.
+ *
+ * @param name the retrieved name (which may be <code>null</code>).
+ * @see #getName()
+ */
+ public void setName(String name)
+ {
+ this.inputName = name;
+ }
+
+ /**
+ * Get the retrieved name.
+ *
+ * @return the retrieved name (which may be <code>null</code>)
+ * @see #setName(String)
+ */
+ public String getName()
+ {
+ return inputName;
+ }
+
+ private void setPrompt(String prompt) throws IllegalArgumentException
+ {
+ if ((prompt == null) || (prompt.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid prompt");
+ }
+ this.prompt = prompt;
+ }
+
+ private void setDefaultName(String defaultName) throws IllegalArgumentException
+ {
+ if ((defaultName == null) || (defaultName.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid default name");
+ }
+ this.defaultName = defaultName;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/PasswordCallback.java b/libjava/javax/security/auth/callback/PasswordCallback.java
new file mode 100644
index 00000000000..5620bc5cd79
--- /dev/null
+++ b/libjava/javax/security/auth/callback/PasswordCallback.java
@@ -0,0 +1,169 @@
+/* PasswordCallback.java -- callback for passwords.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+
+/**
+ * Underlying security services instantiate and pass a <code>PasswordCallback</code>
+ * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve
+ * password information.
+ *
+ * @see CallbackHandler,
+ * @version $Revision: 1.1 $
+ */
+public class PasswordCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String prompt;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private boolean echoOn;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private char[] inputPassword;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Construct a <code>PasswordCallback</code> with a prompt and a boolean
+ * specifying whether the password should be displayed as it is being typed.
+ *
+ * @param prompt the prompt used to request the password.
+ * @param echoOn <code>true</code> if the password should be displayed as it
+ * is being typed.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or if <code>prompt</code> has a length of <code>0</code>.
+ */
+ public PasswordCallback(String prompt, boolean echoOn)
+ {
+ super();
+
+ setPrompt(prompt);
+ this.echoOn = echoOn;
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Get the prompt.
+ *
+ * @return the prompt.
+ */
+ public String getPrompt()
+ {
+ return prompt;
+ }
+
+ /**
+ * Return whether the password should be displayed as it is being typed.
+ *
+ * @return the whether the password should be displayed as it is being typed.
+ */
+ public boolean isEchoOn()
+ {
+ return echoOn;
+ }
+
+ /**
+ * <p>Set the retrieved password.</p>
+ *
+ * <p>This method makes a copy of the input password before storing it.</p>
+ *
+ * @param password the retrieved password, which may be <code>null</code>.
+ * @see #getPassword()
+ */
+ public void setPassword(char[] password)
+ {
+ inputPassword = (password == null ? null : (char[]) password.clone());
+ }
+
+ /**
+ * <p>Get the retrieved password.</p>
+ *
+ * <p>This method returns a copy of the retrieved password.</p>
+ *
+ * @return the retrieved password, which may be <code>null</code>.
+ * @see #setPassword(char[])
+ */
+ public char[] getPassword()
+ {
+ return (inputPassword == null ? null : (char[]) inputPassword.clone());
+ }
+
+ /** Clear the retrieved password. */
+ public void clearPassword()
+ {
+ if (inputPassword != null)
+ {
+ for (int i = 0; i < inputPassword.length; i++)
+ {
+ inputPassword[i] = '\0';
+ }
+ inputPassword = null;
+ }
+ }
+
+ private void setPrompt(String prompt) throws IllegalArgumentException
+ {
+ if ((prompt == null) || (prompt.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid prompt");
+ }
+ this.prompt = prompt;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/TextInputCallback.java b/libjava/javax/security/auth/callback/TextInputCallback.java
new file mode 100644
index 00000000000..55c1aa2534d
--- /dev/null
+++ b/libjava/javax/security/auth/callback/TextInputCallback.java
@@ -0,0 +1,178 @@
+/* TextInputCallback.java -- callbacks for user input.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+
+/**
+ * Underlying security services instantiate and pass a <code>TextInputCallback</code>
+ * to the <code>handle()</code> method of a {@link CallbackHandler} to retrieve
+ * generic text information.
+ *
+ * @see CallbackHandler
+ * @version $Revision: 1.1 $
+ */
+public class TextInputCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String prompt;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String defaultText;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String inputText;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Construct a <code>TextInputCallback</code> with a prompt.
+ *
+ * @param prompt the prompt used to request the information.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or if <code>prompt</code> has a length of <code>0</code>.
+ */
+ public TextInputCallback(String prompt) throws IllegalArgumentException
+ {
+ super();
+
+ setPrompt(prompt);
+ }
+
+ /**
+ * Construct a <code>TextInputCallback</code> with a prompt and default
+ * input value.
+ *
+ * @param prompt the prompt used to request the information.
+ * @param defaultText the text to be used as the default text displayed with
+ * the prompt.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>,
+ * if <code>prompt</code> has a length of <code>0</code>, if
+ * <code>defaultText</code> is <code>null</code> or if <code>defaultText</code>
+ * has a length of <code>0</code>.
+ */
+ public TextInputCallback(String prompt, String defaultText)
+ throws IllegalArgumentException
+ {
+ super();
+
+ setPrompt(prompt);
+ setDefaultText(defaultText);
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Get the prompt.
+ *
+ * @return the prompt.
+ */
+ public String getPrompt()
+ {
+ return prompt;
+ }
+
+ /**
+ * Get the default text.
+ *
+ * @return the default text, or <code>null</code> if this
+ * <code>TextInputCallback</code> was not instantiated with
+ * <code>defaultText</code>.
+ */
+ public String getDefaultText()
+ {
+ return defaultText;
+ }
+
+ /**
+ * Set the retrieved text.
+ *
+ * @param text the retrieved text, which may be <code>null</code>.
+ */
+ public void setText(String text)
+ {
+ this.inputText = text;
+ }
+
+ /**
+ * Get the retrieved text.
+ *
+ * @return the retrieved text, which may be <code>null</code>.
+ */
+ public String getText()
+ {
+ return inputText;
+ }
+
+ private void setPrompt(String prompt) throws IllegalArgumentException
+ {
+ if ((prompt == null) || (prompt.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid prompt");
+ }
+ this.prompt = prompt;
+ }
+
+ private void setDefaultText(String defaultText) throws IllegalArgumentException
+ {
+ if ((defaultText == null) || (defaultText.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid default text");
+ }
+ this.defaultText = defaultText;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/TextOutputCallback.java b/libjava/javax/security/auth/callback/TextOutputCallback.java
new file mode 100644
index 00000000000..380a5ef60f0
--- /dev/null
+++ b/libjava/javax/security/auth/callback/TextOutputCallback.java
@@ -0,0 +1,141 @@
+/* TextOutputCallback.java -- callback for text output.
+ Copyright (C) 2003 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+import java.io.Serializable;
+
+/**
+ * <p>Underlying security services instantiate and pass a
+ * <code>TextOutputCallback</code> to the <code>handle()</code> method of a
+ * {@link CallbackHandler} to display information messages, warning messages and
+ * error messages.</p>
+ *
+ * @see CallbackHandler
+ * @version $Revision: 1.2 $
+ */
+public class TextOutputCallback implements Callback, Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /** Information message */
+ public static final int INFORMATION = 0;
+
+ /** Warning message */
+ public static final int WARNING = 1;
+
+ /** Error message */
+ public static final int ERROR = 2;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private int messageType;
+
+ /**
+ * @serial
+ * @since 1.4
+ */
+ private String message;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Construct a <code>TextOutputCallback</code> with a message type and
+ * message to be displayed.</p>
+ *
+ * @param messageType the message type (INFORMATION, WARNING or ERROR).
+ * @param message the message to be displayed.
+ * @throws IllegalArgumentException if <code>messageType</code> is not either
+ * <code>INFORMATION</code>, <code>WARNING</code> or <code>ERROR</code>, if
+ * <code>message</code> is <code>null</code>, or if <code>message</code> has
+ * a length of <code>0</code>.
+ */
+ public TextOutputCallback(int messageType, String message)
+ throws IllegalArgumentException
+ {
+ switch (messageType)
+ {
+ case INFORMATION:
+ case WARNING:
+ case ERROR: this.messageType = messageType; break;
+ default: throw new IllegalArgumentException("invalid message type");
+ }
+
+ setMessage(message);
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Returns the message's <code>messageType</code>.</p>
+ *
+ * @return the message type (INFORMATION, WARNING or ERROR).
+ */
+ public int getMessageType()
+ {
+ return messageType;
+ }
+
+ /**
+ * <p>Returns the <code>message</code> to be displayed.</p>
+ *
+ * @return the message to be displayed.
+ */
+ public String getMessage()
+ {
+ return message;
+ }
+
+ private void setMessage(String message) throws IllegalArgumentException
+ {
+ if ((message == null) || (message.length() == 0))
+ {
+ throw new IllegalArgumentException("invalid message");
+ }
+ this.message = message;
+ }
+}
diff --git a/libjava/javax/security/auth/callback/UnsupportedCallbackException.java b/libjava/javax/security/auth/callback/UnsupportedCallbackException.java
new file mode 100644
index 00000000000..215942c40b5
--- /dev/null
+++ b/libjava/javax/security/auth/callback/UnsupportedCallbackException.java
@@ -0,0 +1,102 @@
+/* UnsupportedCallbackException.java -- signals an unsupported callback type.
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.callback;
+
+/**
+ * Signals that a {@link CallbackHandler} does not recognize a particular
+ * {@link Callback}.
+ *
+ * @version $Revision: 1.1 $
+ */
+public class UnsupportedCallbackException extends Exception
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /** @serial */
+ private Callback callback;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Constructs an <code>UnsupportedCallbackException</code> with no detail
+ * message.
+ *
+ * @param callback the unrecognized {@link Callback}.
+ */
+ public UnsupportedCallbackException(Callback callback)
+ {
+ super();
+
+ this.callback = callback;
+ }
+
+ /**
+ * Constructs an <code>UnsupportedCallbackException</code> with the specified
+ * detail message. A detail message is a {@link String} that describes this
+ * particular exception.
+ *
+ * @param callback the unrecognized {@link Callback}.
+ * @param msg the detail message.
+ */
+ public UnsupportedCallbackException(Callback callback, String msg)
+ {
+ super(msg);
+
+ this.callback = callback;
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Get the unrecognized {@link Callback}.
+ *
+ * @return the unrecognized {@link Callback}.
+ */
+ public Callback getCallback()
+ {
+ return this.callback;
+ }
+}
diff --git a/libjava/javax/security/auth/login/AccountExpiredException.java b/libjava/javax/security/auth/login/AccountExpiredException.java
new file mode 100644
index 00000000000..e8e331347be
--- /dev/null
+++ b/libjava/javax/security/auth/login/AccountExpiredException.java
@@ -0,0 +1,64 @@
+/* AccountExpiredException.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+/**
+ * An exception that signals that an attempt was made to login to an account
+ * that has expired.
+ */
+public class AccountExpiredException extends LoginException
+{
+
+ // Constant.
+ // -------------------------------------------------------------------------
+
+ private static final long serialVersionUID = -6064064890162661560L;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public AccountExpiredException()
+ {
+ }
+
+ public AccountExpiredException (String message)
+ {
+ super (message);
+ }
+}
diff --git a/libjava/javax/security/auth/login/AppConfigurationEntry.java b/libjava/javax/security/auth/login/AppConfigurationEntry.java
new file mode 100644
index 00000000000..1879a68c1e8
--- /dev/null
+++ b/libjava/javax/security/auth/login/AppConfigurationEntry.java
@@ -0,0 +1,135 @@
+/* AppConfigurationEntry.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+public class AppConfigurationEntry
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private final String loginModuleName;
+ private final LoginModuleControlFlag controlFlag;
+ private final Map options;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public AppConfigurationEntry (final String loginModuleName,
+ final LoginModuleControlFlag controlFlag,
+ final Map options)
+ {
+ if (loginModuleName == null || loginModuleName.length() == 0)
+ throw new IllegalArgumentException ("module name cannot be null nor empty");
+ if (LoginModuleControlFlag.OPTIONAL != controlFlag &&
+ LoginModuleControlFlag.REQUIRED != controlFlag &&
+ LoginModuleControlFlag.REQUISITE != controlFlag &&
+ LoginModuleControlFlag.SUFFICIENT != controlFlag)
+ throw new IllegalArgumentException ("invalid controlFlag");
+ if (options == null)
+ throw new IllegalArgumentException ("options cannot be null");
+ this.loginModuleName = loginModuleName;
+ this.controlFlag = controlFlag;
+ this.options = Collections.unmodifiableMap (new HashMap (options));
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public LoginModuleControlFlag getControlFlag()
+ {
+ return controlFlag;
+ }
+
+ public String getLoginModuleName()
+ {
+ return loginModuleName;
+ }
+
+ public Map getOptions()
+ {
+ return options;
+ }
+
+ // Inner class.
+ // -------------------------------------------------------------------------
+
+ public static class LoginModuleControlFlag
+ {
+
+ // Constants.
+ // -----------------------------------------------------------------------
+
+ public static final LoginModuleControlFlag OPTIONAL = new LoginModuleControlFlag();
+ public static final LoginModuleControlFlag REQUIRED = new LoginModuleControlFlag();
+ public static final LoginModuleControlFlag REQUISITE = new LoginModuleControlFlag();
+ public static final LoginModuleControlFlag SUFFICIENT = new LoginModuleControlFlag();
+
+ // Constructor.
+ // -----------------------------------------------------------------------
+
+ private LoginModuleControlFlag()
+ {
+ }
+
+ // Instance methods.
+ // -----------------------------------------------------------------------
+
+ public String toString()
+ {
+ StringBuffer buf = new StringBuffer (LoginModuleControlFlag.class.getName());
+ buf.append ('.');
+ if (this == OPTIONAL)
+ buf.append ("OPTIONAL");
+ else if (this == REQUIRED)
+ buf.append ("REQUIRED");
+ else if (this == REQUISITE)
+ buf.append ("REQUISITE");
+ else if (this == SUFFICIENT)
+ buf.append ("SUFFICIENT");
+ else
+ buf.append ("HARVEY_THE_RABBIT");
+ return buf.toString();
+ }
+ }
+}
diff --git a/libjava/javax/security/auth/login/Configuration.java b/libjava/javax/security/auth/login/Configuration.java
new file mode 100644
index 00000000000..4a55013ca2b
--- /dev/null
+++ b/libjava/javax/security/auth/login/Configuration.java
@@ -0,0 +1,109 @@
+/* Configuration.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.Security;
+
+import javax.security.auth.AuthPermission;
+
+public abstract class Configuration
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private static Configuration config;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ protected Configuration()
+ {
+ }
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ public static synchronized Configuration getConfiguration()
+ {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission (new AuthPermission ("getLoginConfiguration"));
+ if (config == null)
+ {
+ String conf = (String) AccessController.doPrivileged
+ (new PrivilegedAction()
+ {
+ public Object run()
+ {
+ return Security.getProperty ("login.configuration.provider");
+ }
+ });
+ try
+ {
+ if (conf != null)
+ config = (Configuration) Class.forName (conf).newInstance();
+ else
+ config = new NullConfiguration();
+ }
+ catch (Exception x)
+ {
+ config = new NullConfiguration();
+ }
+ }
+ return config;
+ }
+
+ public static synchronized void setConfiguration (Configuration config)
+ {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ sm.checkPermission (new AuthPermission ("setLoginConfiguration"));
+ Configuration.config = config;
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ public abstract AppConfigurationEntry[] getAppConfigurationEntry (String applicationName);
+
+ public abstract void refresh();
+}
diff --git a/libjava/javax/security/auth/login/CredentialExpiredException.java b/libjava/javax/security/auth/login/CredentialExpiredException.java
new file mode 100644
index 00000000000..df643ba6990
--- /dev/null
+++ b/libjava/javax/security/auth/login/CredentialExpiredException.java
@@ -0,0 +1,64 @@
+/* CredentialExpiredException.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+/**
+ * An exception that signals an attempt to login with a credential that
+ * has expired.
+ */
+public class CredentialExpiredException extends LoginException
+{
+
+ // Constant.
+ // -------------------------------------------------------------------------
+
+ private static final long serialVersionUID = -5344739593859737937L;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public CredentialExpiredException()
+ {
+ }
+
+ public CredentialExpiredException (String message)
+ {
+ super (message);
+ }
+}
diff --git a/libjava/javax/security/auth/login/FailedLoginException.java b/libjava/javax/security/auth/login/FailedLoginException.java
new file mode 100644
index 00000000000..384ade08427
--- /dev/null
+++ b/libjava/javax/security/auth/login/FailedLoginException.java
@@ -0,0 +1,63 @@
+/* FailedLoginException.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+/**
+ * An exception that signals that an attempt to login was unsuccessful.
+ */
+public class FailedLoginException extends LoginException
+{
+
+ // Constant.
+ // -------------------------------------------------------------------------
+
+ private static final long serialVersionUID = 802556922354616286L;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public FailedLoginException()
+ {
+ }
+
+ public FailedLoginException (String message)
+ {
+ super (message);
+ }
+}
diff --git a/libjava/javax/security/auth/login/LoginContext.java b/libjava/javax/security/auth/login/LoginContext.java
new file mode 100644
index 00000000000..da88e841282
--- /dev/null
+++ b/libjava/javax/security/auth/login/LoginContext.java
@@ -0,0 +1,44 @@
+/* LoginContext.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+public class LoginContext
+{
+
+}
diff --git a/libjava/javax/security/auth/login/LoginException.java b/libjava/javax/security/auth/login/LoginException.java
new file mode 100644
index 00000000000..878120381b5
--- /dev/null
+++ b/libjava/javax/security/auth/login/LoginException.java
@@ -0,0 +1,65 @@
+/* LoginException.java
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+import java.security.GeneralSecurityException;
+
+/**
+ * A general exception during authentication and authorization.
+ */
+public class LoginException extends GeneralSecurityException
+{
+
+ // Constant.
+ // -------------------------------------------------------------------------
+
+ private static final long serialVersionUID = -4679091624035232488L;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public LoginException()
+ {
+ }
+
+ public LoginException (String message)
+ {
+ super (message);
+ }
+}
diff --git a/libjava/javax/security/auth/login/NullConfiguration.java b/libjava/javax/security/auth/login/NullConfiguration.java
new file mode 100644
index 00000000000..e1c99037f96
--- /dev/null
+++ b/libjava/javax/security/auth/login/NullConfiguration.java
@@ -0,0 +1,64 @@
+/* NullConfiguration.java -- no-op default login configuration.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.login;
+
+import javax.security.auth.AuthPermission;
+
+final class NullConfiguration extends Configuration
+{
+
+ // Contructor.
+ // -------------------------------------------------------------------------
+
+ NullConfiguration()
+ {
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public AppConfigurationEntry[] getAppConfigurationEntry (String applicationName)
+ {
+ return null;
+ }
+
+ public void refresh()
+ {
+ }
+}
diff --git a/libjava/javax/security/auth/x500/X500PrivateCredential.java b/libjava/javax/security/auth/x500/X500PrivateCredential.java
new file mode 100644
index 00000000000..fb3a5ef40b7
--- /dev/null
+++ b/libjava/javax/security/auth/x500/X500PrivateCredential.java
@@ -0,0 +1,148 @@
+/* X500PrivateCredential.java -- certificate and private key pair.
+ Copyright (C) 2003 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.auth.x500;
+
+import java.security.PrivateKey;
+import java.security.cert.X509Certificate;
+import javax.security.auth.Destroyable;
+
+/**
+ * A pairing of a {@link X509Certificate} and its corresponding {@link
+ * PrivateKey}, with an optional keystore alias.
+ */
+public final class X500PrivateCredential implements Destroyable
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private PrivateKey key;
+ private X509Certificate certificate;
+ private String alias;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Creates a new private credential with no associated keystore alias.
+ *
+ * @param certificate The X.509 certificate.
+ * @param key The private key.
+ * @throws IllegalArgumentException If either parameter is null.
+ */
+ public X500PrivateCredential (X509Certificate certificate, PrivateKey key)
+ {
+ if (certificate == null || key == null)
+ throw new IllegalArgumentException();
+ this.certificate = certificate;
+ this.key = key;
+ }
+
+ /**
+ * Creates a new private credential with a keystore alias.
+ *
+ * @param certificate The X.509 certificate.
+ * @param key The private key.
+ * @param alias The keystore alias for this credential.
+ * @throws IllegalArgumentException If any parameter is null.
+ */
+ public X500PrivateCredential (X509Certificate certificate, PrivateKey key,
+ String alias)
+ {
+ this (certificate, key);
+ if (alias == null)
+ throw new IllegalArgumentException();
+ this.alias = alias;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the certificate of this credential.
+ *
+ * @return The certificate of this credential.
+ */
+ public X509Certificate getCertificate()
+ {
+ return certificate;
+ }
+
+ /**
+ * Returns the private key of this credential.
+ *
+ * @return The private key of this credential.
+ */
+ public PrivateKey getPrivateKey()
+ {
+ return key;
+ }
+
+ /**
+ * Returns the keystore alias of this credential, or null if not present.
+ *
+ * @return The keystore alias, or null.
+ */
+ public String getAlias()
+ {
+ return alias;
+ }
+
+ /**
+ * Destroy the sensitive data of this credential, setting the certificate,
+ * private key, and keystore alias to null.
+ */
+ public void destroy()
+ {
+ certificate = null;
+ key = null;
+ alias = null;
+ }
+
+ /**
+ * Tells whether or not this credential has been destroyed, and that
+ * the certificate and private key fields are null.
+ *
+ * @return True if this object has been destroyed.
+ */
+ public boolean isDestroyed()
+ {
+ return certificate == null && key == null;
+ }
+}
diff --git a/libjava/javax/security/cert/Certificate.java b/libjava/javax/security/cert/Certificate.java
new file mode 100644
index 00000000000..8090817fcf4
--- /dev/null
+++ b/libjava/javax/security/cert/Certificate.java
@@ -0,0 +1,176 @@
+/* Certificate.java -- base class of public-key certificates.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PublicKey;
+import java.security.SignatureException;
+
+import java.util.Arrays;
+import java.util.zip.Adler32;
+
+/**
+ * <p>The base class for public-key certificates.</p>
+ *
+ * <p><b>This class is deprecated in favor of the {@link
+ * java.security.cert.Certificate} class. It should not be used in new
+ * applications.</b></p>
+ */
+public abstract class Certificate
+{
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ public Certificate()
+ {
+ super();
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Tests if this certificate equals another.</p>
+ *
+ * @param other The object to test.
+ * @return True if the certificates are equal.
+ */
+ public boolean equals(Object other)
+ {
+ if (other == null || !(other instanceof Certificate))
+ {
+ return false;
+ }
+ if (other == this)
+ {
+ return true;
+ }
+ try
+ {
+ return Arrays.equals(getEncoded(), ((Certificate) other).getEncoded());
+ }
+ catch (CertificateEncodingException cee)
+ {
+ return false;
+ }
+ }
+
+ /**
+ * <p>Computes a hash code for this certificate.</p>
+ *
+ * @return The hash code.
+ */
+ public int hashCode()
+ {
+ try
+ {
+ Adler32 csum = new Adler32();
+ csum.update(getEncoded());
+ return (int) csum.getValue();
+ }
+ catch (CertificateEncodingException cee)
+ {
+ return 0;
+ }
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Return the encoded form of this certificate.</p>
+ *
+ * @return The encoded form.
+ * @throws CertificateEncodingException If the certificate could not be
+ * encoded.
+ */
+ public abstract byte[] getEncoded() throws CertificateEncodingException;
+
+ /**
+ * <p>Verifies the signature of this certificate.</p>
+ *
+ * @param key The signer's public key.
+ * @throws CertificateException
+ * @throws NoSuchAlgorithmException If the algorithm used to sign the
+ * certificate is not available.
+ * @throws InvalidKeyException If the supplied key is not appropriate for the
+ * certificate's signature algorithm.
+ * @throws NoSuchProviderException
+ * @throws SignatureException If the signature could not be verified.
+ */
+ public abstract void verify(PublicKey key)
+ throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException;
+
+ /**
+ * <p>Verifies the signature of this certificate, using the specified security
+ * provider.</p>
+ *
+ * @param key The signer's public key.
+ * @param sigProvider The name of the signature provider.
+ * @throws CertificateException
+ * @throws NoSuchAlgorithmException If the algorithm used to sign the
+ * certificate is not available.
+ * @throws InvalidKeyException If the supplied key is not appropriate for the
+ * certificate's signature algorithm.
+ * @throws NoSuchProviderException If <i>sigProvider</i> is not the name of an
+ * installed provider.
+ * @throws SignatureException If the signature could not be verified.
+ */
+ public abstract void verify(PublicKey key, String sigProvider)
+ throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException;
+
+ /**
+ * <p>Returns a printable representation of this certificate.</p>
+ *
+ * @return The string.
+ */
+ public abstract String toString();
+
+ /**
+ * <p>Returns this certificate's public key.</p>
+ *
+ * @return The public key.
+ */
+ public abstract PublicKey getPublicKey();
+}
diff --git a/libjava/javax/security/cert/CertificateEncodingException.java b/libjava/javax/security/cert/CertificateEncodingException.java
new file mode 100644
index 00000000000..81c85dd9f2e
--- /dev/null
+++ b/libjava/javax/security/cert/CertificateEncodingException.java
@@ -0,0 +1,60 @@
+/* CertificateEncodingException.java -- certificate encoding exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+/**
+ * <p>Signals a problem when encoding certificates.</p>
+ *
+ * <p><b>This class is deprecated in favor of the {@link
+ * java.security.cert.CertificateEncodingException} class. It should not be used
+ * in new applications.</b></p>
+ */
+public class CertificateEncodingException extends CertificateException
+{
+
+ public CertificateEncodingException()
+ {
+ super();
+ }
+
+ public CertificateEncodingException(String msg)
+ {
+ super(msg);
+ }
+}
diff --git a/libjava/javax/security/cert/CertificateException.java b/libjava/javax/security/cert/CertificateException.java
new file mode 100644
index 00000000000..4e79a312057
--- /dev/null
+++ b/libjava/javax/security/cert/CertificateException.java
@@ -0,0 +1,60 @@
+/* CertificateException.java -- certificate exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+/**
+ * <p>Signals a generic problem with certificates.</p>
+ *
+ * <p><b>This class is deprecated in favor of the {@link
+ * java.security.cert.CertificateException} class. It should not be used in new
+ * applications.</b></p>
+ */
+public class CertificateException extends Exception
+{
+
+ public CertificateException()
+ {
+ super();
+ }
+
+ public CertificateException(String msg)
+ {
+ super(msg);
+ }
+}
diff --git a/libjava/javax/security/cert/CertificateExpiredException.java b/libjava/javax/security/cert/CertificateExpiredException.java
new file mode 100644
index 00000000000..53b0cc007ed
--- /dev/null
+++ b/libjava/javax/security/cert/CertificateExpiredException.java
@@ -0,0 +1,60 @@
+/* CertificateExpiredException.java -- certificate expired exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+/**
+ * <p>Signals that a certificate has expired.</p>
+ *
+ * <p><b>This class is deprecated in favor of the {@link
+ * java.security.cert.CertificateExpiredException} class. It should not be used
+ * in new applications.</b></p>
+ */
+public class CertificateExpiredException extends CertificateException
+{
+
+ public CertificateExpiredException()
+ {
+ super();
+ }
+
+ public CertificateExpiredException(String msg)
+ {
+ super(msg);
+ }
+}
diff --git a/libjava/javax/security/cert/CertificateNotYetValidException.java b/libjava/javax/security/cert/CertificateNotYetValidException.java
new file mode 100644
index 00000000000..56c8aeb7f53
--- /dev/null
+++ b/libjava/javax/security/cert/CertificateNotYetValidException.java
@@ -0,0 +1,60 @@
+/* CertificateNotYetValidException.java -- certificate not yet valid exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+/**
+ * <p>Signals that a certificate is not yet valid.</p>
+ *
+ * <p><b>This class is deprecated in favor of the {@link
+ * java.security.cert.CertificateNotYetValidException} class. It should not be
+ * used in new applications.</b></p>
+ */
+public class CertificateNotYetValidException extends CertificateException
+{
+
+ public CertificateNotYetValidException()
+ {
+ super();
+ }
+
+ public CertificateNotYetValidException(String msg)
+ {
+ super(msg);
+ }
+}
diff --git a/libjava/javax/security/cert/CertificateParsingException.java b/libjava/javax/security/cert/CertificateParsingException.java
new file mode 100644
index 00000000000..17012e2f1c9
--- /dev/null
+++ b/libjava/javax/security/cert/CertificateParsingException.java
@@ -0,0 +1,59 @@
+/* CertificateParsingException.java -- certificate parsing exception.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+/**
+ * <p>Signals a parsing error when decoding a certificate.</p>
+ *
+ * <p><b>This class is deprecated. It should not be used in new
+ * applications.</b></p>
+ */
+public class CertificateParsingException extends CertificateException
+{
+
+ public CertificateParsingException()
+ {
+ super();
+ }
+
+ public CertificateParsingException(String msg)
+ {
+ super(msg);
+ }
+}
diff --git a/libjava/javax/security/cert/X509CertBridge.java b/libjava/javax/security/cert/X509CertBridge.java
new file mode 100644
index 00000000000..1c075d6d52f
--- /dev/null
+++ b/libjava/javax/security/cert/X509CertBridge.java
@@ -0,0 +1,203 @@
+/* X509CertBridge.java -- bridge between JDK and JSSE cert APIs.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+import java.math.BigInteger;
+
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.NoSuchProviderException;
+import java.security.PublicKey;
+import java.security.Principal;
+import java.security.SignatureException;
+
+import java.util.Date;
+
+/**
+ * <p>An implementation of the {@link X509Certificate} class that delegates
+ * calls to a {@link java.security.cert.X509Certificate}.</p>
+ */
+final class X509CertBridge extends X509Certificate
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private java.security.cert.X509Certificate cert;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ X509CertBridge(java.security.cert.X509Certificate cert)
+ {
+ this.cert = cert;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ public byte[] getEncoded() throws CertificateEncodingException
+ {
+ try
+ {
+ return cert.getEncoded();
+ }
+ catch (java.security.cert.CertificateEncodingException cee)
+ {
+ throw new CertificateEncodingException(cee.getMessage());
+ }
+ }
+
+ public void verify(PublicKey key)
+ throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException
+ {
+ try
+ {
+ cert.verify(key);
+ }
+ catch (java.security.cert.CertificateException ce)
+ {
+ throw new CertificateException(ce.getMessage());
+ }
+ }
+
+ public void verify(PublicKey key, String sigProvider)
+ throws CertificateException, NoSuchAlgorithmException, InvalidKeyException,
+ NoSuchProviderException, SignatureException
+ {
+ try
+ {
+ cert.verify(key, sigProvider);
+ }
+ catch (java.security.cert.CertificateException ce)
+ {
+ throw new CertificateException(ce.getMessage());
+ }
+ }
+
+ public String toString()
+ {
+ return cert.toString();
+ }
+
+ public PublicKey getPublicKey()
+ {
+ return cert.getPublicKey();
+ }
+
+ public void checkValidity()
+ throws CertificateExpiredException, CertificateNotYetValidException
+ {
+ try
+ {
+ cert.checkValidity();
+ }
+ catch (java.security.cert.CertificateExpiredException cee)
+ {
+ throw new CertificateExpiredException(cee.getMessage());
+ }
+ catch (java.security.cert.CertificateNotYetValidException cnyve)
+ {
+ throw new CertificateNotYetValidException(cnyve.getMessage());
+ }
+ }
+
+ public void checkValidity(Date date)
+ throws CertificateExpiredException, CertificateNotYetValidException
+ {
+ try
+ {
+ cert.checkValidity(date);
+ }
+ catch (java.security.cert.CertificateExpiredException cee)
+ {
+ throw new CertificateExpiredException(cee.getMessage());
+ }
+ catch (java.security.cert.CertificateNotYetValidException cnyve)
+ {
+ throw new CertificateNotYetValidException(cnyve.getMessage());
+ }
+ }
+
+ public int getVersion()
+ {
+ return cert.getVersion();
+ }
+
+ public BigInteger getSerialNumber()
+ {
+ return cert.getSerialNumber();
+ }
+
+ public Principal getIssuerDN()
+ {
+ return cert.getIssuerDN();
+ }
+
+ public Principal getSubjectDN()
+ {
+ return cert.getSubjectDN();
+ }
+
+ public Date getNotBefore()
+ {
+ return cert.getNotBefore();
+ }
+
+ public Date getNotAfter()
+ {
+ return cert.getNotAfter();
+ }
+
+ public String getSigAlgName()
+ {
+ return cert.getSigAlgName();
+ }
+
+ public String getSigAlgOID()
+ {
+ return cert.getSigAlgOID();
+ }
+
+ public byte[] getSigAlgParams()
+ {
+ return cert.getSigAlgParams();
+ }
+}
diff --git a/libjava/javax/security/cert/X509Certificate.java b/libjava/javax/security/cert/X509Certificate.java
new file mode 100644
index 00000000000..2bf0b4e94b0
--- /dev/null
+++ b/libjava/javax/security/cert/X509Certificate.java
@@ -0,0 +1,191 @@
+/* X509Certificate.java -- base class of X.509 certificates.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.cert;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+
+import java.math.BigInteger;
+
+import java.security.NoSuchAlgorithmException;
+import java.security.Principal;
+import java.security.cert.CertificateFactory;
+
+import java.util.Date;
+
+/**
+ * <p>The base class of all X.509 certificates.</p>
+ *
+ * <p><b>This class is deprecated in favor of the {@link
+ * java.security.cert.X509Certificate} class. It should not be used in new
+ * applications.</b></p>
+ */
+public abstract class X509Certificate extends Certificate
+{
+
+ // Class methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Get an instance of X509Certificate for the given encoded bytes.</p>
+ *
+ * @param encoded The encoded certificate.
+ * @return An instance of X509Certificate.
+ * @throws CertificateException If the encoded certificate cannot be parsed.
+ */
+ public static X509Certificate getInstance(byte[] encoded)
+ throws CertificateException
+ {
+ return getInstance(new ByteArrayInputStream(encoded));
+ }
+
+ /**
+ * <p>Get an instance of X509Certificate for the given encoded stream.</p>
+ *
+ * @param encoded The encoded certificate stream..
+ * @return An instance of X509Certificate.
+ * @throws CertificateException If the encoded certificate cannot be parsed.
+ */
+ public static X509Certificate getInstance(InputStream encoded)
+ throws CertificateException
+ {
+ try
+ {
+ CertificateFactory cf = CertificateFactory.getInstance("X.509");
+ return new X509CertBridge((java.security.cert.X509Certificate)
+ cf.generateCertificate(encoded));
+ }
+ catch (java.security.cert.CertificateException ce)
+ {
+ throw new CertificateException(ce.getMessage());
+ }
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Check if this certificate is valid now.</p>
+ *
+ * @throws CertificateExpiredException If the certificate has expired.
+ * @throws CertificateNotYetValidException If the certificate is not yet valid.
+ * @see #checkValidity(java.util.Date)
+ */
+ public abstract void checkValidity()
+ throws CertificateExpiredException, CertificateNotYetValidException;
+
+ /**
+ * <p>Check if this certificate is valid for the given date.</p>
+ *
+ * @param date The date to check.
+ * @throws CertificateExpiredException If the certificate has expired.
+ * @throws CertificateNotYetValidException If the certificate is not yet valid.
+ */
+ public abstract void checkValidity(Date date)
+ throws CertificateExpiredException, CertificateNotYetValidException;
+
+ /**
+ * <p>Returns the X.509 version number.</p>
+ *
+ * @return The version number.
+ */
+ public abstract int getVersion();
+
+ /**
+ * <p>Returns this certificate's serial number.</p>
+ *
+ * @return The serial number.
+ */
+ public abstract BigInteger getSerialNumber();
+
+ /**
+ * <p>Returns the distinguished name of this certificate's issuer.</p>
+ *
+ * @return The issuer's distinguished name.
+ */
+ public abstract Principal getIssuerDN();
+
+ /**
+ * <p>Returns the distinguished name of this certificate's subject.</p>
+ *
+ * @return The subject's distinguished name.
+ */
+ public abstract Principal getSubjectDN();
+
+ /**
+ * <p>Returns the <i>not before</i> portion of this certificate's validity
+ * period.</p>
+ *
+ * @return The not before date.
+ */
+ public abstract Date getNotBefore();
+
+ /**
+ * <p>Returns the <i>not after</i> portion of this certificate's validity
+ * period.</p>
+ *
+ * @return The not after date.
+ */
+ public abstract Date getNotAfter();
+
+ /**
+ * <p>Returns the name of this certificate's signature algorithm.</p>
+ *
+ * @return The name of the signature algorithm.
+ */
+ public abstract String getSigAlgName();
+
+ /**
+ * <p>Returns the object identifier (OID) of this certificate's signature
+ * algorithm. The returned string is a sequence of integers separated by
+ * periods.</p>
+ *
+ * @return The signature OID.
+ */
+ public abstract String getSigAlgOID();
+
+ /**
+ * <p>Returns the signature parameters. The returned byte array contains the
+ * raw DER-encoded parameters.</p>
+ *
+ * @return The signature parameters.
+ */
+ public abstract byte[] getSigAlgParams();
+}
diff --git a/libjava/javax/security/sasl/AuthenticationException.java b/libjava/javax/security/sasl/AuthenticationException.java
new file mode 100644
index 00000000000..1af2eb30a15
--- /dev/null
+++ b/libjava/javax/security/sasl/AuthenticationException.java
@@ -0,0 +1,105 @@
+/* AuthenticationException.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpathis free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpathis distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+/**
+ * <p>This exception is thrown by a SASL mechanism implementation to indicate
+ * that the SASL exchange has failed due to reasons related to authentication,
+ * such as an invalid identity, passphrase, or key.</p>
+ *
+ * <p>Note that the lack of an <code>AuthenticationException</code> does not
+ * mean that the failure was not due to an authentication error. A SASL
+ * mechanism implementation might throw the more general {@link SaslException}
+ * instead of <code>AuthenticationException</code> if it is unable to determine
+ * the nature of the failure, or if does not want to disclose the nature of the
+ * failure, for example, due to security reasons.</p>
+ */
+public class AuthenticationException extends SaslException
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Constructs a new instance of <code>AuthenticationException</code>. The
+ * root exception and the detailed message are <code>null</code>.
+ */
+ public AuthenticationException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a new instance of <code>AuthenticationException</code> with a
+ * detailed message. The root exception is <code>null</code>.
+ *
+ * @param detail a possibly <code>null</code> string containing details of
+ * the exception.
+ * @see Throwable#getMessage()
+ */
+ public AuthenticationException(String detail)
+ {
+ super(detail);
+ }
+
+ /**
+ * Constructs a new instance of <code>AuthenticationException</code> with a
+ * detailed message and a root exception.
+ *
+ * @param detail a possibly <code>null</code> string containing details of
+ * the exception.
+ * @param ex a possibly <code>null</code> root exception that caused this
+ * exception.
+ * @see Throwable#getMessage()
+ * @see SaslException#getCause()
+ */
+ public AuthenticationException(String detail, Throwable ex)
+ {
+ super(detail, ex);
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+}
diff --git a/libjava/javax/security/sasl/AuthorizeCallback.java b/libjava/javax/security/sasl/AuthorizeCallback.java
new file mode 100644
index 00000000000..77fe78698ad
--- /dev/null
+++ b/libjava/javax/security/sasl/AuthorizeCallback.java
@@ -0,0 +1,171 @@
+/* AuthorizeCallback.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpathis free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpathis distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import javax.security.auth.callback.Callback;
+
+/**
+ * This callback is used by {@link SaslServer} to determine whether one entity
+ * (identified by an authenticated authentication ID) can act on behalf of
+ * another entity (identified by an authorization ID).
+ */
+public class AuthorizeCallback implements Callback
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /** @serial The (authenticated) authentication id to check. */
+ private String authenticationID = null;
+
+ /** @serial The authorization id to check. */
+ private String authorizationID = null;
+
+ /**
+ * @serial The id of the authorized entity. If null, the id of the authorized
+ * entity is authorizationID.
+ */
+ private String authorizedID = null;
+
+ /**
+ * @serial A flag indicating whether the authentication id is allowed to act
+ * on behalf of the authorization id.
+ */
+ private boolean authorized = false;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Constructs an instance of <code>AuthorizeCallback</code>.
+ *
+ * @param authnID the (authenticated) authentication ID.
+ * @param authzID the authorization ID.
+ */
+ public AuthorizeCallback(String authnID, String authzID)
+ {
+ super();
+
+ this.authenticationID = authnID;
+ this.authorizationID = authzID;
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the authentication ID to check.
+ *
+ * @return the authentication ID to check
+ */
+ public String getAuthenticationID()
+ {
+ return authenticationID;
+ }
+
+ /**
+ * Returns the authorization ID to check.
+ *
+ * @return the authorization ID to check.
+ */
+ public String getAuthorizationID()
+ {
+ return authorizationID;
+ }
+
+ /**
+ * Determines if the identity represented by authentication ID is allowed to
+ * act on behalf of the authorization ID.
+ *
+ * @return <code>true</code> if authorization is allowed; <code>false</code>
+ * otherwise.
+ * @see #setAuthorized(boolean)
+ * @see #getAuthorizedID()
+ */
+ public boolean isAuthorized()
+ {
+ return authorized;
+ }
+
+ /**
+ * Sets if authorization is allowed or not.
+ *
+ * @param authorized <code>true</code> if authorization is allowed;
+ * <code>false</code> otherwise.
+ * @see #isAuthorized()
+ * @see #setAuthorizedID(String)
+ */
+ public void setAuthorized(boolean authorized)
+ {
+ this.authorized = authorized;
+ }
+
+ /**
+ * Returns the ID of the authorized user.
+ *
+ * @return the ID of the authorized user. <code>null</code> means the
+ * authorization failed.
+ * @see #setAuthorized(boolean)
+ * @see #setAuthorizedID(String)
+ */
+ public String getAuthorizedID()
+ {
+ if (!authorized)
+ {
+ return null;
+ }
+ return (authorizedID != null ? authorizedID : authorizationID);
+ }
+
+ /**
+ * Sets the ID of the authorized entity. Called by handler only when the ID
+ * is different from {@link #getAuthorizationID()}. For example, the ID might
+ * need to be canonicalized for the environment in which it will be used.
+ *
+ * @see #setAuthorized(boolean)
+ * @see #getAuthorizedID()
+ */
+ public void setAuthorizedID(String id)
+ {
+ this.authorizedID = id;
+ }
+}
diff --git a/libjava/javax/security/sasl/RealmCallback.java b/libjava/javax/security/sasl/RealmCallback.java
new file mode 100644
index 00000000000..49bc08ae2ec
--- /dev/null
+++ b/libjava/javax/security/sasl/RealmCallback.java
@@ -0,0 +1,75 @@
+/* RealmCallback.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import javax.security.auth.callback.TextInputCallback;
+
+/**
+ * This callback is used by {@link SaslClient} and {@link SaslServer} to
+ * retrieve realm information.
+ */
+public class RealmCallback extends TextInputCallback
+{
+
+ /**
+ * Constructs a <code>RealmCallback</code> with a prompt.
+ *
+ * @param prompt the non-null prompt to use to request the realm information.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or empty.
+ */
+ public RealmCallback(String prompt)
+ {
+ super(prompt);
+ }
+
+ /**
+ * Constructs a <code>RealmCallback</code> with a prompt and default realm
+ * information.
+ *
+ * @param prompt the non-null prompt to use to request the realm information.
+ * @param defaultRealmInfo the non-null default realm information to use.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or empty, or if <code>defaultRealm</code> is empty or <code>null</code>.
+ */
+ public RealmCallback(String prompt, String defaultRealmInfo)
+ {
+ super(prompt, defaultRealmInfo);
+ }
+}
diff --git a/libjava/javax/security/sasl/RealmChoiceCallback.java b/libjava/javax/security/sasl/RealmChoiceCallback.java
new file mode 100644
index 00000000000..2e00407610f
--- /dev/null
+++ b/libjava/javax/security/sasl/RealmChoiceCallback.java
@@ -0,0 +1,71 @@
+/* RealmChoiceCallback.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import javax.security.auth.callback.ChoiceCallback;
+
+/**
+ * This callback is used by {@link SaslClient} and {@link SaslServer} to obtain
+ * a realm given a list of realm choices.
+ */
+public class RealmChoiceCallback extends ChoiceCallback
+{
+
+ /**
+ * Constructs a <code>RealmChoiceCallback</code> with a prompt, a list of
+ * choices and a default choice.
+ *
+ * @param prompt the non-null prompt to use to request the realm.
+ * @param choices the non-null list of realms to choose from.
+ * @param defaultChoice the choice to be used as the default when the list of
+ * choices is displayed. It is an index into the <code>choices</code> array.
+ * @param multiple <code>true</code> if multiple choices allowed;
+ * <code>false</code> otherwise.
+ * @throws IllegalArgumentException if <code>prompt</code> is <code>null</code>
+ * or empty, if <code>choices</code> has a length of <code>0</code>, if any
+ * element from <code>choices</code> is <code>null</code> or empty, or if
+ * <code>defaultChoice</code> does not fall within the array boundary of
+ * <code>choices</code>.
+ */
+ public RealmChoiceCallback(String prompt, String[] choices, int defaultChoice,
+ boolean multiple)
+ {
+ super(prompt, choices, defaultChoice, multiple);
+ }
+}
diff --git a/libjava/javax/security/sasl/Sasl.java b/libjava/javax/security/sasl/Sasl.java
new file mode 100644
index 00000000000..2174692f4b4
--- /dev/null
+++ b/libjava/javax/security/sasl/Sasl.java
@@ -0,0 +1,691 @@
+/* Sasl.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import java.util.Enumeration;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.Vector;
+import java.security.Security;
+import java.security.Provider;
+
+import javax.security.auth.callback.CallbackHandler;
+
+/**
+ * <p>A static class for creating SASL clients and servers.</p>
+ *
+ * <p>This class defines the policy of how to locate, load, and instantiate SASL
+ * clients and servers.</p>
+ *
+ * <p>For example, an application or library gets a SASL client instance by
+ * doing something like:</p>
+ *
+ * <pre>
+ *SaslClient sc =
+ * Sasl.createSaslClient(mechanisms, authorizationID, protocol,
+ * serverName, props, callbackHandler);
+ * </pre>
+ *
+ * <p>It can then proceed to use the instance to create an authenticated
+ * connection.</p>
+ *
+ * <p>Similarly, a server gets a SASL server instance by using code that looks
+ * as follows:</p>
+ *
+ * <pre>
+ *SaslServer ss =
+ * Sasl.createSaslServer(mechanism, protocol, serverName, props,
+ * callbackHandler);
+ * </pre>
+ */
+public class Sasl
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>The name of a property that specifies the quality-of-protection to use.
+ * The property contains a comma-separated, ordered list of quality-of-
+ * protection values that the client or server is willing to support. A qop
+ * value is one of:</p>
+ *
+ * <ul>
+ * <li><code>"auth"</code> - authentication only,</li>
+ * <li><code>"auth-int"</code> - authentication plus integrity
+ * protection,</li>
+ * <li><code>"auth-conf"</code> - authentication plus integrity and
+ * confidentiality protection.</li>
+ * </ul>
+ *
+ * <p>The order of the list specifies the preference order of the client or
+ * server.</p>
+ *
+ * <p>If this property is absent, the default qop is <code>"auth"</code>.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.qop"</code>.</p>
+ */
+ public static final String QOP = "javax.security.sasl.qop";
+
+ /**
+ * <p>The name of a property that specifies the cipher strength to use. The
+ * property contains a comma-separated, ordered list of cipher strength
+ * values that the client or server is willing to support. A strength value
+ * is one of:</p>
+ *
+ * <ul>
+ * <li><code>"low"</code>,</li>
+ * <li><code>"medium"</code>,</li>
+ * <li><code>"high"</code>.</li>
+ * </ul>
+ *
+ * <p>The order of the list specifies the preference order of the client or
+ * server. An implementation should allow configuration of the meaning of
+ * these values. An application may use the Java Cryptography Extension (JCE)
+ * with JCE-aware mechanisms to control the selection of cipher suites that
+ * match the strength values.</p>
+ *
+ * <p>If this property is absent, the default strength is
+ * <code>"high,medium,low"</code>.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.strength"</code>.
+ * </p>
+ */
+ public static final String STRENGTH = "javax.security.sasl.strength";
+
+ /**
+ * <p>The name of a property that specifies whether the server must authenticate
+ * to the client. The property contains <code>"true"</code> if the server
+ * must authenticate the to client; <code>"false"</code> otherwise. The
+ * default is <code>"false"</code>.</p>
+ *
+ * <p>The value of this constant is
+ * <code>"javax.security.sasl.server.authentication"</code>.</p>
+ */
+ public static final String SERVER_AUTH = "javax.security.sasl.server.authentication";
+
+ /**
+ * <p>The name of a property that specifies the maximum size of the receive
+ * buffer in bytes of {@link SaslClient}/{@link SaslServer}. The property
+ * contains the string representation of an integer.</p>
+ *
+ * <p>If this property is absent, the default size is defined by the
+ * mechanism.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.maxbuffer"</code>.
+ * </p>
+ */
+ public static final String MAX_BUFFER = "javax.security.sasl.maxbuffer";
+
+ /**
+ * <p>The name of a property that specifies the maximum size of the raw send
+ * buffer in bytes of {@link SaslClient}/{@link SaslServer}. The property
+ * contains the string representation of an integer. The value of this
+ * property is negotiated between the client and server during the
+ * authentication exchange.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.rawsendsize"</code>.
+ * </p>
+ */
+ public static final String RAW_SEND_SIZE = "javax.security.sasl.rawsendsize";
+
+ /**
+ * <p>The name of a property that specifies whether mechanisms susceptible
+ * to simple plain passive attacks (e.g., "PLAIN") are not permitted. The
+ * property contains <code>"true"</code> if such mechanisms are not
+ * permitted; <code>"false"</code> if such mechanisms are permitted. The
+ * default is <code>"false"</code>.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.policy.noplaintext"</code>.
+ * </p>
+ */
+ public static final String POLICY_NOPLAINTEXT = "javax.security.sasl.policy.noplaintext";
+
+ /**
+ * <p>The name of a property that specifies whether mechanisms susceptible to
+ * active (non-dictionary) attacks are not permitted. The property contains
+ * <code>"true"</code> if mechanisms susceptible to active attacks are not
+ * permitted; <code>"false"</code> if such mechanisms are permitted. The
+ * default is <code>"false"</code>.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.policy.noactive"</code>.
+ * </p>
+ */
+ public static final String POLICY_NOACTIVE = "javax.security.sasl.policy.noactive";
+
+ /**
+ * <p>The name of a property that specifies whether mechanisms susceptible to
+ * passive dictionary attacks are not permitted. The property contains
+ * <code>"true"</code> if mechanisms susceptible to dictionary attacks are
+ * not permitted; <code>"false"</code> if such mechanisms are permitted. The
+ * default is <code>"false"</code>.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.policy.nodictionary"</code>.
+ * </p>
+ */
+ public static final String POLICY_NODICTIONARY = "javax.security.sasl.policy.nodictionary";
+
+ /**
+ * <p>The name of a property that specifies whether mechanisms that accept
+ * anonymous login are not permitted. The property contains <code>"true"</code>
+ * if mechanisms that accept anonymous login are not permitted; <code>"false"
+ * </code> if such mechanisms are permitted. The default is <code>"false"</code>.
+ * </p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.policy.noanonymous"</code>.
+ * </p>
+ */
+ public static final String POLICY_NOANONYMOUS = "javax.security.sasl.policy.noanonymous";
+
+ /**
+ * The name of a property that specifies whether mechanisms that implement
+ * forward secrecy between sessions are required. Forward secrecy means that
+ * breaking into one session will not automatically provide information for
+ * breaking into future sessions. The property contains <code>"true"</code>
+ * if mechanisms that implement forward secrecy between sessions are
+ * required; <code>"false"</code> if such mechanisms are not required. The
+ * default is <code>"false"</code>.</p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.policy.forward"</code>.
+ * </p>
+ */
+ public static final String POLICY_FORWARD_SECRECY = "javax.security.sasl.policy.forward";
+
+ /**
+ * The name of a property that specifies whether mechanisms that pass client
+ * credentials are required. The property contains <code>"true"</code> if
+ * mechanisms that pass client credentials are required; <code>"false"</code>
+ * if such mechanisms are not required. The default is <code>"false"</code>.
+ * </p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.policy.credentials"</code>.
+ * </p>
+ */
+ public static final String POLICY_PASS_CREDENTIALS = "javax.security.sasl.policy.credentials";
+
+ /**
+ * <p>The name of a property that specifies whether to reuse previously
+ * authenticated session information. The property contains <code>"true"</code>
+ * if the mechanism implementation may attempt to reuse previously
+ * authenticated session information; it contains <code>"false"</code> if the
+ * implementation must not reuse previously authenticated session information.
+ * A setting of <code>"true"</code> serves only as a hint; it does not
+ * necessarily entail actual reuse because reuse might not be possible due to
+ * a number of reasons, including, but not limited to, lack of mechanism
+ * support for reuse, expiration of reusable information, and the peer's
+ * refusal to support reuse. The property's default value is <code>"false"</code>.
+ * </p>
+ *
+ * <p>The value of this constant is <code>"javax.security.sasl.reuse"</code>.
+ * Note that all other parameters and properties required to create a SASL
+ * client/server instance must be provided regardless of whether this
+ * property has been supplied. That is, you cannot supply any less
+ * information in anticipation of reuse. Mechanism implementations that
+ * support reuse might allow customization of its implementation for factors
+ * such as cache size, timeouts, and criteria for reuseability. Such
+ * customizations are implementation-dependent.</p>
+ */
+ public static final String REUSE = "javax.security.sasl.reuse";
+
+ private static final String CLIENT_FACTORY_SVC = "SaslClientFactory.";
+ private static final String SERVER_FACTORY_SVC = "SaslServerFactory.";
+ private static final String ALIAS = "Alg.Alias.";
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ private Sasl()
+ {
+ super();
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Creates a {@link SaslClient} for the specified mechanism.</p>
+ *
+ * <p>This method uses the JCA Security Provider Framework, described in the
+ * "Java Cryptography Architecture API Specification &amp; Reference", for
+ * locating and selecting a {@link SaslClient} implementation.</p>
+ *
+ * <p>First, it obtains an ordered list of {@link SaslClientFactory}
+ * instances from the registered security providers for the
+ * <code>"SaslClientFactory"</code> service and the specified mechanism. It
+ * then invokes <code>createSaslClient()</code> on each factory instance on
+ * the list until one produces a non-null {@link SaslClient} instance. It
+ * returns the non-null {@link SaslClient} instance, or <code>null</code> if
+ * the search fails to produce a non-null {@link SaslClient} instance.</p>
+ *
+ * <p>A security provider for <code>SaslClientFactory</code> registers with
+ * the JCA Security Provider Framework keys of the form:</p>
+ *
+ * <pre>
+ * SaslClientFactory.mechanism_name
+ * </pre>
+ *
+ * <p>and values that are class names of implementations of {@link
+ * SaslClientFactory}.</p>
+ *
+ * <p>For example, a provider that contains a factory class,
+ * <code>com.wiz.sasl.digest.ClientFactory</code>, that supports the
+ * <code>"DIGEST-MD5"</code> mechanism would register the following entry
+ * with the JCA:</p>
+ *
+ * <pre>
+ * SaslClientFactory.DIGEST-MD5 com.wiz.sasl.digest.ClientFactory
+ * </pre>
+ *
+ * <p>See the "Java Cryptography Architecture API Specification &amp;
+ * Reference" for information about how to install and configure security
+ * service providers.</p>
+ *
+ * @param mechanisms the non-null list of mechanism names to try. Each is the
+ * IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
+ * @param authorizationID the possibly <code>null</code> protocol-dependent
+ * identification to be used for authorization. If <code>null</code> or
+ * empty, the server derives an authorization ID from the client's
+ * authentication credentials. When the SASL authentication completes
+ * successfully, the specified entity is granted access.
+ * @param protocol the non-null string name of the protocol for which the
+ * authentication is being performed (e.g. "ldap").
+ * @param serverName the non-null fully-qualified host name of the server to
+ * authenticate to.
+ * @param props the possibly null set of properties used to select the SASL
+ * mechanism and to configure the authentication exchange of the selected
+ * mechanism. For example, if props contains the {@link Sasl#POLICY_NOPLAINTEXT}
+ * property with the value <code>"true"</code>, then the selected SASL
+ * mechanism must not be susceptible to simple plain passive attacks. In
+ * addition to the standard properties declared in this class, other,
+ * possibly mechanism-specific, properties can be included. Properties not
+ * relevant to the selected mechanism are ignored.
+ * @param cbh the possibly <code>null</code> callback handler to used by the
+ * SASL mechanisms to get further information from the application/library to
+ * complete the authentication. For example, a SASL mechanism might require
+ * the authentication ID, password and realm from the caller. The
+ * authentication ID is requested by using a
+ * {@link javax.security.auth.callback.NameCallback}. The password is
+ * requested by using a {@link javax.security.auth.callback.PasswordCallback}.
+ * The realm is requested by using a {@link RealmChoiceCallback} if there is
+ * a list of realms to choose from, and by using a {@link RealmCallback} if
+ * the realm must be entered.
+ * @return a possibly <code>null</code> {@link SaslClient} created using the
+ * parameters supplied. If <code>null</code>, the method could not find a
+ * {@link SaslClientFactory} that will produce one.
+ * @throws SaslException if a {@link SaslClient} cannot be created because
+ * of an error.
+ */
+ public static SaslClient createSaslClient(String[] mechanisms,
+ String authorizationID,
+ String protocol,
+ String serverName, Map props,
+ CallbackHandler cbh)
+ throws SaslException
+ {
+ if (mechanisms == null)
+ {
+ return null;
+ }
+ Provider[] providers = Security.getProviders();
+ if (providers == null || providers.length == 0)
+ {
+ return null;
+ }
+
+ SaslClient result = null;
+ SaslClientFactory factory = null;
+ String m, clazz = null, upper, alias;
+ int j;
+ Provider p;
+ for (int i = 0; i < mechanisms.length; i++)
+ {
+ m = mechanisms[i];
+ if (m == null)
+ continue;
+ for (j = 0; j < providers.length; j++)
+ {
+ p = providers[j];
+ if (p != null)
+ {
+ // try the name as is
+ clazz = p.getProperty(CLIENT_FACTORY_SVC + m);
+ if (clazz == null) // try all uppercase
+ {
+ upper = m.toUpperCase();
+ clazz = p.getProperty(CLIENT_FACTORY_SVC + upper);
+ if (clazz == null) // try if it's an alias
+ {
+ alias = p.getProperty(ALIAS + CLIENT_FACTORY_SVC + m);
+ if (alias == null) // try all-uppercase alias name
+ {
+ alias = p.getProperty(ALIAS + CLIENT_FACTORY_SVC + upper);
+ if (alias == null) // spit the dummy
+ continue;
+ }
+ clazz = p.getProperty(CLIENT_FACTORY_SVC + alias);
+ }
+ }
+ if (clazz == null)
+ continue;
+ else
+ clazz = clazz.trim();
+ }
+
+ try
+ {
+ result = null;
+ factory = (SaslClientFactory) Class.forName(clazz).newInstance();
+ result = factory.createSaslClient(mechanisms, authorizationID,
+ protocol, serverName, props, cbh);
+ }
+ catch (ClassCastException ignored) // ignore instantiation exceptions
+ {
+ }
+ catch (ClassNotFoundException ignored)
+ {
+ }
+ catch (InstantiationException ignored)
+ {
+ }
+ catch (IllegalAccessException ignored)
+ {
+ }
+ if (result != null)
+ return result;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Gets an enumeration of known factories for producing a {@link SaslClient}
+ * instance. This method uses the same sources for locating factories as
+ * <code>createSaslClient()</code>.
+ *
+ * @return a non-null {@link Enumeration} of known factories for producing a
+ * {@link SaslClient} instance.
+ * @see #createSaslClient(String[],String,String,String,Map,CallbackHandler)
+ */
+ public static Enumeration getSaslClientFactories()
+ {
+ Vector result = new Vector();
+ HashSet names = new HashSet();
+ Provider[] providers = Security.getProviders();
+ Iterator it;
+ if (providers == null)
+ {
+ Provider p;
+ String key;
+ for (int i = 0; i < providers.length; i++)
+ {
+ p = providers[i];
+ for (it = p.keySet().iterator(); it.hasNext(); )
+ {
+ key = (String) it.next();
+ // add key's binding (a) it is a class of a client factory,
+ // and (b) the key does not include blanks
+ if (key.startsWith(CLIENT_FACTORY_SVC) && key.indexOf(" ") == -1)
+ {
+ names.add(p.getProperty(key));
+ break;
+ }
+ }
+ }
+ }
+ // we have the factory class names in names; instantiate and enumerate
+ String c;
+ for (it = names.iterator(); it.hasNext(); )
+ {
+ c = (String) it.next();
+ try
+ {
+ SaslClientFactory f = (SaslClientFactory) Class.forName(c).newInstance();
+ if (f != null)
+ result.add(f);
+ } catch (ClassCastException ignored) { // ignore instantiation exceptions
+ } catch (ClassNotFoundException ignored) {
+ } catch (InstantiationException ignored) {
+ } catch (IllegalAccessException ignored) {
+ }
+ }
+
+ return result.elements();
+ }
+
+ /**
+ * <p>Creates a {@link SaslServer} for the specified mechanism.</p>
+ *
+ * <p>This method uses the JCA Security Provider Framework, described in the
+ * "Java Cryptography Architecture API Specification &amp; Reference", for
+ * locating and selecting a SaslServer implementation.</p>
+ *
+ * <p>First, it obtains an ordered list of {@link SaslServerFactory}
+ * instances from the registered security providers for the
+ * <code>"SaslServerFactory"</code> service and the specified mechanism. It
+ * then invokes <code>createSaslServer()</code> on each factory instance on
+ * the list until one produces a non-null {@link SaslServer} instance. It
+ * returns the non-null {@link SaslServer} instance, or <code>null</code> if
+ * the search fails to produce a non-null {@link SaslServer} instance.</p>
+ *
+ * <p>A security provider for {@link SaslServerFactory} registers with the
+ * JCA Security Provider Framework keys of the form:</p>
+ *
+ * <pre>
+ * SaslServerFactory.mechanism_name
+ * </pre>
+ *
+ * <p>and values that are class names of implementations of {@link
+ * SaslServerFactory}.</p>
+ *
+ * <p>For example, a provider that contains a factory class,
+ * <code>com.wiz.sasl.digest.ServerFactory</code>, that supports the
+ * <code>"DIGEST-MD5"</code> mechanism would register the following entry
+ * with the JCA:</p>
+ *
+ * <pre>
+ * SaslServerFactory.DIGEST-MD5 com.wiz.sasl.digest.ServerFactory
+ * </pre></p>
+ *
+ * <p>See the "Java Cryptography Architecture API Specification &amp;
+ * Reference" for information about how to install and configure security
+ * service providers.</p>
+ *
+ * @param mechanism the non-null mechanism name. It must be an
+ * IANA-registered name of a SASL mechanism. (e.g. "GSSAPI", "CRAM-MD5").
+ * @param protocol the non-null string name of the protocol for which the
+ * authentication is being performed (e.g. "ldap").
+ * @param serverName the non-null fully qualified host name of the server.
+ * @param props the possibly <code>null</code> set of properties used to
+ * select the SASL mechanism and to configure the authentication exchange of
+ * the selected mechanism. For example, if props contains the {@link
+ * Sasl#POLICY_NOPLAINTEXT} property with the value <code>"true"</code>, then
+ * the selected SASL mechanism must not be susceptible to simple plain
+ * passive attacks. In addition to the standard properties declared in this
+ * class, other, possibly mechanism-specific, properties can be included.
+ * Properties not relevant to the selected mechanism are ignored.
+ * @param cbh the possibly <code>null</code> callback handler to used by the
+ * SASL mechanisms to get further information from the application/library to
+ * complete the authentication. For example, a SASL mechanism might require
+ * the authentication ID, password and realm from the caller. The
+ * authentication ID is requested by using a
+ * {@link javax.security.auth.callback.NameCallback}. The password is
+ * requested by using a {@link javax.security.auth.callback.PasswordCallback}.
+ * The realm is requested by using a {@link RealmChoiceCallback} if there is
+ * a list of realms to choose from, and by using a {@link RealmCallback} if
+ * the realm must be entered.
+ * @return a possibly <code>null</code> {@link SaslServer} created using the
+ * parameters supplied. If <code>null</code>, the method cannot find a
+ * {@link SaslServerFactory} instance that will produce one.
+ * @throws SaslException if a {@link SaslServer} instance cannot be created
+ * because of an error.
+ */
+ public static SaslServer createSaslServer(String mechanism, String protocol,
+ String serverName,
+ Map props, CallbackHandler cbh)
+ throws SaslException
+ {
+ if (mechanism == null)
+ return null;
+ Provider[] providers = Security.getProviders();
+ if (providers == null || providers.length == 0)
+ return null;
+
+ SaslServer result = null;
+ SaslServerFactory factory = null;
+ String clazz = null, upper, alias = null;
+ int j;
+ Provider p;
+ for (j = 0; j < providers.length; j++)
+ {
+ p = providers[j];
+ if (p != null)
+ {
+ // try the name as is
+ clazz = p.getProperty(SERVER_FACTORY_SVC + mechanism);
+ if (clazz == null) // try all uppercase
+ {
+ upper = mechanism.toUpperCase();
+ clazz = p.getProperty(SERVER_FACTORY_SVC + upper);
+ if (clazz == null) // try if it's an alias
+ {
+ alias = p.getProperty(ALIAS + SERVER_FACTORY_SVC + mechanism);
+ if (alias == null) // try all-uppercase alias name
+ {
+ alias = p.getProperty(ALIAS + SERVER_FACTORY_SVC + upper);
+ if (alias == null) // spit the dummy
+ continue;
+ }
+ }
+ clazz = p.getProperty(SERVER_FACTORY_SVC + alias);
+ }
+ }
+ if (clazz == null)
+ continue;
+ else
+ clazz = clazz.trim();
+
+ try
+ {
+ result = null;
+ factory = (SaslServerFactory) Class.forName(clazz).newInstance();
+ result =
+ factory.createSaslServer(mechanism, protocol, serverName, props, cbh);
+ }
+ catch (ClassCastException ignored) // ignore instantiation exceptions
+ {
+ }
+ catch (ClassNotFoundException ignored)
+ {
+ }
+ catch (InstantiationException ignored)
+ {
+ }
+ catch (IllegalAccessException ignored)
+ {
+ }
+ if (result != null)
+ return result;
+ }
+ return null;
+ }
+
+ /**
+ * Gets an enumeration of known factories for producing a {@link SaslServer}
+ * instance. This method uses the same sources for locating factories as
+ * <code>createSaslServer()</code>.
+ *
+ * @return a non-null {@link Enumeration} of known factories for producing a
+ * {@link SaslServer} instance.
+ * @see #createSaslServer(String,String,String,Map,CallbackHandler)
+ */
+ public static Enumeration getSaslServerFactories()
+ {
+ Vector result = new Vector();
+ HashSet names = new HashSet();
+ Provider[] providers = Security.getProviders();
+ Iterator it;
+ if (providers == null)
+ {
+ Provider p;
+ String key;
+ for (int i = 0; i < providers.length; i++)
+ {
+ p = providers[i];
+ for (it = p.keySet().iterator(); it.hasNext(); )
+ {
+ key = (String) it.next();
+ // add key's binding (a) it is a class of a server factory,
+ // and (b) the key does not include blanks
+ if (key.startsWith(SERVER_FACTORY_SVC) && key.indexOf(" ") == -1)
+ {
+ names.add(p.getProperty(key));
+ break;
+ }
+ }
+ }
+ }
+ // we have the factory class names in names; instantiate and enumerate
+ String c;
+ for (it = names.iterator(); it.hasNext(); )
+ {
+ c = (String) it.next();
+ try
+ {
+ SaslServerFactory f = (SaslServerFactory) Class.forName(c).newInstance();
+ if (f != null)
+ result.add(f);
+ }
+ catch (ClassCastException ignored) // ignore instantiation exceptions
+ {
+ }
+ catch (ClassNotFoundException ignored)
+ {
+ }
+ catch (InstantiationException ignored)
+ {
+ }
+ catch (IllegalAccessException ignored)
+ {
+ }
+ }
+
+ return result.elements();
+ }
+}
diff --git a/libjava/javax/security/sasl/SaslClient.java b/libjava/javax/security/sasl/SaslClient.java
new file mode 100644
index 00000000000..ca95ced2554
--- /dev/null
+++ b/libjava/javax/security/sasl/SaslClient.java
@@ -0,0 +1,231 @@
+/* SaslClient.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpathis free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpathis distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+/**
+ * <p>Performs SASL authentication as a client.</p>
+ *
+ * <p>A protocol library such as one for LDAP gets an instance of this class in
+ * order to perform authentication defined by a specific SASL mechanism.
+ * Invoking methods on the <code>SaslClient</code> instance process challenges
+ * and create responses according to the SASL mechanism implemented by the
+ * <code>SaslClient</code>. As the authentication proceeds, the instance
+ * encapsulates the state of a SASL client's authentication exchange.</p>
+ *
+ * <p>Here's an example of how an LDAP library might use a <code>SaslClient</code>.
+ * It first gets an instance of a SaslClient:</p>
+ * <pre>
+ *SaslClient sc =
+ * Sasl.createSaslClient(mechanisms, authorizationID, protocol,
+ * serverName, props, callbackHandler);
+ * </pre>
+ *
+ * <p>It can then proceed to use the client for authentication. For example, an
+ * LDAP library might use the client as follows:</p>
+ * <pre>
+ * // Get initial response and send to server
+ *byte[] response = sc.hasInitialResponse()
+ * ? sc.evaluateChallenge(new byte[0]) : null;
+ *LdapResult res = ldap.sendBindRequest(dn, sc.getName(), response);
+ *while (!sc.isComplete()
+ * && ((res.status == SASL_BIND_IN_PROGRESS) || (res.status == SUCCESS))) {
+ * response = sc.evaluateChallenge( res.getBytes() );
+ * if (res.status == SUCCESS) {
+ * // we're done; don't expect to send another BIND
+ * if ( response != null ) {
+ * throw new SaslException(
+ * "Protocol error: attempting to send response after completion");
+ * }
+ * break;
+ * }
+ * res = ldap.sendBindRequest(dn, sc.getName(), response);
+ *}
+ *if (sc.isComplete() && (res.status == SUCCESS) ) {
+ * String qop = (String)sc.getNegotiatedProperty(Sasl.QOP);
+ * if ((qop != null)
+ * && (qop.equalsIgnoreCase("auth-int")
+ * || qop.equalsIgnoreCase("auth-conf"))) {
+ * // Use SaslClient.wrap() and SaslClient.unwrap() for future
+ * // communication with server
+ * ldap.in = new SecureInputStream(sc, ldap.in);
+ * ldap.out = new SecureOutputStream(sc, ldap.out);
+ * }
+ *}
+ * </pre>
+ *
+ * <p>If the mechanism has an initial response, the library invokes
+ * {@link #evaluateChallenge(byte[])} with an empty challenge to get the initial
+ * response. Protocols such as IMAP4, which do not include an initial response
+ * with their first authentication command to the server, initiate the
+ * authentication without first calling {@link #hasInitialResponse()} or
+ * {@link #evaluateChallenge(byte[])}. When the server responds to the command,
+ * it sends an initial challenge. For a SASL mechanism in which the client sends
+ * data first, the server should have issued a challenge with no data. This will
+ * then result in a call (on the client) to {@link #evaluateChallenge(byte[])}
+ * with an empty challenge.</p>
+ *
+ * @see Sasl
+ * @see SaslClientFactory
+ * @version $Revision: 1.1 $
+ */
+public interface SaslClient
+{
+
+ /**
+ * Returns the IANA-registered mechanism name of this SASL client. (e.g.
+ * "CRAM-MD5", "GSSAPI").
+ *
+ * @return a non-null string representing the IANA-registered mechanism name.
+ */
+ String getMechanismName();
+
+ /**
+ * Determines if this mechanism has an optional initial response. If
+ * <code>true</code>, caller should call {@link #evaluateChallenge(byte[])}
+ * with an empty array to get the initial response.
+ *
+ * @return <code>true</code> if this mechanism has an initial response.
+ */
+ boolean hasInitialResponse();
+
+ /**
+ * Evaluates the challenge data and generates a response. If a challenge is
+ * received from the server during the authentication process, this method is
+ * called to prepare an appropriate next response to submit to the server.
+ *
+ * @param challenge the non-null challenge sent from the server. The
+ * challenge array may have zero length.
+ * @return the possibly <code>null</code> reponse to send to the server. It
+ * is <code>null</code> if the challenge accompanied a "SUCCESS" status and
+ * the challenge only contains data for the client to update its state and no
+ * response needs to be sent to the server. The response is a zero-length
+ * byte array if the client is to send a response with no data.
+ * @throws SaslException if an error occurred while processing the challenge
+ * or generating a response.
+ */
+ byte[] evaluateChallenge(byte[] challenge) throws SaslException;
+
+ /**
+ * Determines if the authentication exchange has completed. This method may
+ * be called at any time, but typically, it will not be called until the
+ * caller has received indication from the server (in a protocol-specific
+ * manner) that the exchange has completed.
+ *
+ * @return <code>true</code> if the authentication exchange has completed;
+ * <code>false</code> otherwise.
+ */
+ boolean isComplete();
+
+ /**
+ * <p>Unwraps a byte array received from the server. This method can be
+ * called only after the authentication exchange has completed (i.e., when
+ * {@link #isComplete()} returns <code>true</code>) and only if the
+ * authentication exchange has negotiated integrity and/or privacy as the
+ * quality of protection; otherwise, an {@link IllegalStateException} is
+ * thrown.</p>
+ *
+ * <p><code>incoming</code> is the contents of the SASL buffer as defined in
+ * RFC 2222 without the leading four octet field that represents the length.
+ * <code>offset</code> and <code>len</code> specify the portion of incoming
+ * to use.</p>
+ *
+ * @param incoming a non-null byte array containing the encoded bytes from
+ * the server.
+ * @param offset the starting position at <code>incoming</code> of the bytes
+ * to use.
+ * @param len the number of bytes from <code>incoming</code> to use.
+ * @return a non-null byte array containing the decoded bytes.
+ * @throws SaslException if <code>incoming</code> cannot be successfully
+ * unwrapped.
+ * @throws IllegalStateException if the authentication exchange has not
+ * completed, or if the negotiated quality of protection has neither
+ * integrity nor privacy.
+ */
+ byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException;
+
+ /**
+ * <p>Wraps a byte array to be sent to the server. This method can be called
+ * only after the authentication exchange has completed (i.e., when
+ * {@link #isComplete()} returns <code>true</code>) and only if the
+ * authentication exchange has negotiated integrity and/or privacy as the
+ * quality of protection; otherwise, an {@link IllegalStateException} is
+ * thrown.</p>
+ *
+ * <p>The result of this method will make up the contents of the SASL buffer
+ * as defined in RFC 2222 without the leading four octet field that
+ * represents the length. <code>offset</code> and <code>len</code> specify
+ * the portion of <code>outgoing</code> to use.</p>
+ *
+ * @param outgoing a non-null byte array containing the bytes to encode.
+ * @param offset the starting position at <code>outgoing</code> of the bytes
+ * to use.
+ * @param len the number of bytes from <code>outgoing</code> to use.
+ * @return a non-null byte array containing the encoded bytes.
+ * @throws SaslException if <code>outgoing</code> cannot be successfully
+ * wrapped.
+ * @throws IllegalStateException if the authentication exchange has not
+ * completed, or if the negotiated quality of protection has neither
+ * integrity nor privacy.
+ */
+ byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException;
+
+ /**
+ * Retrieves the negotiated property. This method can be called only after
+ * the authentication exchange has completed (i.e., when {@link #isComplete()}
+ * returns <code>true</code>); otherwise, an {@link IllegalStateException} is
+ * thrown.
+ *
+ * @param propName the non-null property name.
+ * @return the value of the negotiated property. If <code>null</code>, the
+ * property was not negotiated or is not applicable to this mechanism.
+ * @throws IllegalStateException if this authentication exchange has not
+ * completed.
+ */
+ Object getNegotiatedProperty(String propName) throws SaslException;
+
+ /**
+ * Disposes of any system resources or security-sensitive information the
+ * <code>SaslClient</code> might be using. Invoking this method invalidates
+ * the <code>SaslClient</code> instance. This method is idempotent.
+ *
+ * @throws SaslException if a problem was encountered while disposing of the
+ * resources.
+ */
+ void dispose() throws SaslException;
+}
diff --git a/libjava/javax/security/sasl/SaslClientFactory.java b/libjava/javax/security/sasl/SaslClientFactory.java
new file mode 100644
index 00000000000..b67c7a324f0
--- /dev/null
+++ b/libjava/javax/security/sasl/SaslClientFactory.java
@@ -0,0 +1,117 @@
+/* SaslClientFactory.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import java.util.Map;
+
+import javax.security.auth.callback.CallbackHandler;
+
+/**
+ * <p>An interface for creating instances of {@link SaslClient}. A class that
+ * implements this interface must be thread-safe and handle multiple
+ * simultaneous requests. It must also have a public constructor that accepts
+ * no arguments.</p>
+ *
+ * <p>This interface is not normally accessed directly by a client, which will
+ * use the {@link Sasl} static methods to create a client instance instead.
+ * However, a particular environment may provide and install a new or different
+ * <code>SaslClientFactory</code>.</p>
+ *
+ * @see SaslClient
+ * @see Sasl
+ * @version $Revision: 1.1 $
+ */
+public interface SaslClientFactory
+{
+
+ /**
+ * Creates a {@link SaslClient} using the parameters supplied.
+ *
+ * @param mechanisms the non-null list of mechanism names to try. Each is the
+ * IANA-registered name of a SASL mechanism (e.g. "GSSAPI", "CRAM-MD5").
+ * @param authorizationID the possibly null protocol-dependent identification
+ * to be used for authorization. If <code>null</code> or empty, the server
+ * derives an authorization ID from the client's authentication credentials.
+ * When the SASL authentication completes successfully, the specified entity
+ * is granted access.
+ * @param protocol the non-null string name of the protocol for which the
+ * authentication is being performed (e.g. "ldap").
+ * @param serverName the non-null fully qualified host name of the server to
+ * authenticate to.
+ * @param props the possibly <code>null</code> set of properties used to
+ * select the SASL mechanism and to configure the authentication exchange of
+ * the selected mechanism. See the {@link Sasl} class for a list of standard
+ * properties. Other, possibly mechanism-specific, properties can be included.
+ * Properties not relevant to the selected mechanism are ignored.
+ * @param cbh the possibly <code>null</code> callback handler to used by the
+ * SASL mechanisms to get further information from the application/library to
+ * complete the authentication. For example, a SASL mechanism might require
+ * the authentication ID, password and realm from the caller. The
+ * authentication ID is requested by using a
+ * {@link javax.security.auth.callback.NameCallback}. The password is
+ * requested by using a {@link javax.security.auth.callback.PasswordCallback}.
+ * The realm is requested by using a {@link RealmChoiceCallback} if there is
+ * a list of realms to choose from, and by using a {@link RealmCallback} if
+ * the realm must be entered.
+ * @return a possibly <code>null</code> {@link SaslClient} created using the
+ * parameters supplied. If <code>null</code>, this factory cannot produce a
+ * {@link SaslClient} using the parameters supplied.
+ * @throws SaslException if a {@link SaslClient} instance cannot be created
+ * because of an error.
+ */
+ SaslClient createSaslClient(String[] mechanisms, String authorizationID,
+ String protocol, String serverName, Map props,
+ CallbackHandler cbh)
+ throws SaslException;
+
+ /**
+ * Returns an array of names of mechanisms that match the specified mechanism
+ * selection policies.
+ *
+ * @param props the possibly <code>null</code> set of properties used to
+ * specify the security policy of the SASL mechanisms. For example, if props
+ * contains the {@link Sasl#POLICY_NOPLAINTEXT} property with the value
+ * <code>"true"</code>, then the factory must not return any SASL mechanisms
+ * that are susceptible to simple plain passive attacks. See the {@link Sasl}
+ * class for a complete list of policy properties. Non-policy related
+ * properties, if present in props, are ignored.
+ * @return a non-null array containing IANA-registered SASL mechanism names.
+ */
+ String[] getMechanismNames(Map props);
+}
diff --git a/libjava/javax/security/sasl/SaslException.java b/libjava/javax/security/sasl/SaslException.java
new file mode 100644
index 00000000000..9ff091d6374
--- /dev/null
+++ b/libjava/javax/security/sasl/SaslException.java
@@ -0,0 +1,185 @@
+/* SaslException.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import java.io.IOException;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.io.Serializable;
+
+/**
+ * This class represents an error that has occurred when using SASL.
+ *
+ * @version $Revision: 1.1 $
+ */
+public class SaslException extends IOException implements Serializable
+{
+
+ // Constants and variables
+ // -------------------------------------------------------------------------
+
+ /**
+ * @serial The possibly null root cause exception.
+ */
+ private Throwable _exception = null;
+
+ // Constructor(s)
+ // -------------------------------------------------------------------------
+
+ /**
+ * Constructs a new instance of <code>SaslException</code>. The root
+ * exception and the detailed message are null.
+ */
+ public SaslException()
+ {
+ super();
+ }
+
+ /**
+ * Constructs a new instance of <code>SaslException</code> with a detailed
+ * message. The <code>root</code> exception is <code>null</code>.
+ *
+ * @param detail a possibly null string containing details of the exception.
+ * @see Throwable#getMessage()
+ */
+ public SaslException(String detail)
+ {
+ super(detail);
+ }
+
+ /**
+ * Constructs a new instance of <code>SaslException</code> with a detailed
+ * message and a root exception. For example, a <code>SaslException</code>
+ * might result from a problem with the callback handler, which might throw a
+ * {@link javax.security.auth.callback.UnsupportedCallbackException} if it
+ * does not support the requested callback, or throw an {@link IOException}
+ * if it had problems obtaining data for the callback. The
+ * <code>SaslException</code>'s root exception would be then be the exception
+ * thrown by the callback handler.
+ *
+ * @param detail a possibly <code>null</code> string containing details of
+ * the exception.
+ * @param ex a possibly <code>null</code> root exception that caused this
+ * exception.
+ * @see Throwable#getMessage()
+ * @see #getCause()
+ */
+ public SaslException(String detail, Throwable ex)
+ {
+ super(detail);
+ _exception = ex;
+ }
+
+ // Class methods
+ // -------------------------------------------------------------------------
+
+ // Instance methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the cause of this throwable or <code>null</code> if the cause is
+ * nonexistent or unknown. The cause is the throwable that caused this
+ * exception to be thrown.
+ *
+ * @return the possibly <code>null</code> exception that caused this exception.
+ */
+ public Throwable getCause()
+ {
+ return _exception;
+ }
+
+ /**
+ * Prints this exception's stack trace to <code>System.err</code>. If this
+ * exception has a root exception; the stack trace of the root exception is
+ * also printed to <code>System.err</code>.
+ */
+ public void printStackTrace()
+ {
+ super.printStackTrace();
+ if (_exception != null)
+ _exception.printStackTrace();
+ }
+
+ /**
+ * Prints this exception's stack trace to a print stream. If this exception
+ * has a root exception; the stack trace of the root exception is also
+ * printed to the print stream.
+ *
+ * @param ps the non-null print stream to which to print.
+ */
+ public void printStackTrace(PrintStream ps)
+ {
+ super.printStackTrace(ps);
+ if (_exception != null)
+ _exception.printStackTrace(ps);
+ }
+
+ /**
+ * Prints this exception's stack trace to a print writer. If this exception
+ * has a root exception; the stack trace of the root exception is also
+ * printed to the print writer.
+ *
+ * @param pw the non-null print writer to use for output.
+ */
+ public void printStackTrace(PrintWriter pw)
+ {
+ super.printStackTrace(pw);
+ if (_exception != null)
+ _exception.printStackTrace(pw);
+ }
+
+ /**
+ * Returns the string representation of this exception. The string
+ * representation contains this exception's class name, its detailed
+ * messsage, and if it has a root exception, the string representation of the
+ * root exception. This string representation is meant for debugging and not
+ * meant to be interpreted programmatically.
+ *
+ * @return the non-null string representation of this exception.
+ * @see Throwable#getMessage()
+ */
+ public String toString()
+ {
+ StringBuffer sb = new StringBuffer(this.getClass().getName())
+ .append(": ").append(super.toString());
+ if (_exception != null)
+ sb.append("; caused by: ").append(_exception.toString());
+ return sb.toString();
+ }
+}
diff --git a/libjava/javax/security/sasl/SaslServer.java b/libjava/javax/security/sasl/SaslServer.java
new file mode 100644
index 00000000000..3f0d79d4412
--- /dev/null
+++ b/libjava/javax/security/sasl/SaslServer.java
@@ -0,0 +1,226 @@
+/* SasServer.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+/**
+ * <p>Performs SASL authentication as a server.</p>
+ *
+ * <p>A server such as an LDAP server gets an instance of this class in order to
+ * perform authentication defined by a specific SASL mechanism. Invoking methods
+ * on the <code>SaslServer</code> instance generates challenges corresponding to
+ * the SASL mechanism implemented by the <code>SaslServer</code> instance. As
+ * the authentication proceeds, the instance encapsulates the state of a SASL
+ * server's authentication exchange.</p>
+ *
+ * <p>Here's an example of how an LDAP server might use a <code>SaslServer</code>
+ * instance. It first gets an instance of a <code>SaslServer</code> for the SASL
+ * mechanism requested by the client:</p>
+ *
+ * <pre>
+ *SaslServer ss =
+ * Sasl.createSaslServer(mechanism, "ldap", myFQDN, props, callbackHandler);
+ * </pre>
+ *
+ * <p>It can then proceed to use the server for authentication. For example,
+ * suppose the LDAP server received an LDAP BIND request containing the name of
+ * the SASL mechanism and an (optional) initial response. It then might use the
+ * server as follows:</p>
+ *
+ * <pre>
+ *while (!ss.isComplete()) {
+ * try {
+ * byte[] challenge = ss.evaluateResponse(response);
+ * if (ss.isComplete()) {
+ * status = ldap.sendBindResponse(mechanism, challenge, SUCCESS);
+ * } else {
+ * status = ldap.sendBindResponse(mechanism, challenge, SASL_BIND_IN_PROGRESS);
+ * response = ldap.readBindRequest();
+ * }
+ * } catch (SaslException x) {
+ * status = ldap.sendErrorResponse(x);
+ * break;
+ * }
+ *}
+ *if (ss.isComplete() && (status == SUCCESS)) {
+ * String qop = (String) sc.getNegotiatedProperty(Sasl.QOP);
+ * if (qop != null
+ * && (qop.equalsIgnoreCase("auth-int")
+ * || qop.equalsIgnoreCase("auth-conf"))) {
+ * // Use SaslServer.wrap() and SaslServer.unwrap() for future
+ * // communication with client
+ * ldap.in = new SecureInputStream(ss, ldap.in);
+ * ldap.out = new SecureOutputStream(ss, ldap.out);
+ * }
+ *}
+ * </pre>
+ *
+ * @see Sasl
+ * @see SaslServerFactory
+ * @version $Revision: 1.1 $
+ */
+public interface SaslServer
+{
+
+ /**
+ * Returns the IANA-registered mechanism name of this SASL server (e.g.
+ * "CRAM-MD5", "GSSAPI").
+ *
+ * @return a non-null string representing the IANA-registered mechanism name.
+ */
+ String getMechanismName();
+
+ /**
+ * Evaluates the response data and generates a challenge. If a response is
+ * received from the client during the authentication process, this method is
+ * called to prepare an appropriate next challenge to submit to the client.
+ * The challenge is <code>null</code> if the authentication has succeeded and
+ * no more challenge data is to be sent to the client. It is non-null if the
+ * authentication must be continued by sending a challenge to the client, or
+ * if the authentication has succeeded but challenge data needs to be
+ * processed by the client. {@link #isComplete()} should be called after each
+ * call to <code>evaluateResponse()</code>,to determine if any further
+ * response is needed from the client.
+ *
+ * @param response the non-null (but possibly empty) response sent by the
+ * client.
+ * @return the possibly <code>null</code> challenge to send to the client.
+ * It is <code>null</code> if the authentication has succeeded and there is
+ * no more challenge data to be sent to the client.
+ * @throws SaslException if an error occurred while processing the response
+ * or generating a challenge.
+ */
+ byte[] evaluateResponse(byte[] response) throws SaslException;
+
+ /**
+ * Determines if the authentication exchange has completed. This method is
+ * typically called after each invocation of {@link #evaluateResponse(byte[])}
+ * to determine whether the authentication has completed successfully or
+ * should be continued.
+ *
+ * @return <code>true</code> if the authentication exchange has completed;
+ * <code>false</code> otherwise.
+ */
+ boolean isComplete();
+
+ /**
+ * Reports the authorization ID in effect for the client of this session This
+ * method can only be called if {@link #isComplete()} returns <code>true</code>.
+ *
+ * @return the authorization ID of the client.
+ * @throws IllegalStateException if this authentication session has not
+ * completed.
+ */
+ String getAuthorizationID();
+
+ /**
+ * <p>Unwraps a byte array received from the client. This method can be called
+ * only after the authentication exchange has completed (i.e., when
+ * {@link #isComplete()} returns <code>true</code>) and only if the
+ * authentication exchange has negotiated integrity and/or privacy as the
+ * quality of protection; otherwise, an {@link IllegalStateException} is
+ * thrown.</p>
+ *
+ * <p><code>incoming</code> is the contents of the SASL buffer as defined in
+ * RFC 2222 without the leading four octet field that represents the length.
+ * <code>offset</code> and <code>len</code> specify the portion of incoming
+ * to use.</p>
+ *
+ * @param incoming a non-null byte array containing the encoded bytes from
+ * the client.
+ * @param offset the starting position at <code>incoming</code> of the bytes
+ * to use.
+ * @param len the number of bytes from <code>incoming</code> to use.
+ * @return a non-null byte array containing the decoded bytes.
+ * @throws SaslException if <code>incoming</code> cannot be successfully
+ * unwrapped.
+ * @throws IllegalStateException if the authentication exchange has not
+ * completed, or if the negotiated quality of protection has neither
+ * integrity nor privacy.
+ */
+ byte[] unwrap(byte[] incoming, int offset, int len) throws SaslException;
+
+ /**
+ * <p>Wraps a byte array to be sent to the client. This method can be called
+ * only after the authentication exchange has completed (i.e., when
+ * {@link #isComplete()} returns <code>true</code>) and only if the
+ * authentication exchange has negotiated integrity and/or privacy as the
+ * quality of protection; otherwise, an {@link IllegalStateException} is
+ * thrown.</p>
+ *
+ * <p>The result of this method will make up the contents of the SASL buffer
+ * as defined in RFC 2222 without the leading four octet field that
+ * represents the length. <code>offset</code> and <code>len</code> specify
+ * the portion of <code>outgoing</code> to use.
+ *
+ * @param outgoing a non-null byte array containing the bytes to encode.
+ * @param offset the starting position at <code>outgoing</code> of the bytes
+ * to use.
+ * @param len the number of bytes from <code>outgoing</code> to use.
+ * @return a non-null byte array containing the encoded bytes.
+ * @throws SaslException if <code>outgoing</code> cannot be successfully
+ * wrapped.
+ * @throws IllegalStateException if the authentication exchange has not
+ * completed, or if the negotiated quality of protection has neither
+ * integrity nor privacy.
+ */
+ byte[] wrap(byte[] outgoing, int offset, int len) throws SaslException;
+
+ /**
+ * Retrieves the negotiated property. This method can be called only after
+ * the authentication exchange has completed (i.e., when
+ * {@link #isComplete()} returns <code>true</code>); otherwise, an
+ * {@link IllegalStateException} is thrown.
+ *
+ * @return the value of the negotiated property. If <code>null</code>, the
+ * property was not negotiated or is not applicable to this mechanism.
+ * @throws IllegalStateException if this authentication exchange has not
+ * completed.
+ */
+ Object getNegotiatedProperty(String propName) throws SaslException;
+
+ /**
+ * Disposes of any system resources or security-sensitive information the
+ * <code>SaslServer</code> might be using. Invoking this method invalidates
+ * the <code>SaslServer</code> instance. This method is idempotent.
+ *
+ * @throws SaslException if a problem was encountered while disposing of the
+ * resources.
+ */
+ void dispose() throws SaslException;
+}
diff --git a/libjava/javax/security/sasl/SaslServerFactory.java b/libjava/javax/security/sasl/SaslServerFactory.java
new file mode 100644
index 00000000000..b9387bbeed1
--- /dev/null
+++ b/libjava/javax/security/sasl/SaslServerFactory.java
@@ -0,0 +1,114 @@
+/* SaslServerFactory.java
+ Copyright (C) 2003, Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation Inc., 59 Temple Place - Suite 330, Boston, MA
+02111-1307 USA
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package javax.security.sasl;
+
+import java.util.Map;
+
+import javax.security.auth.callback.CallbackHandler;
+
+/**
+ * <p>An interface for creating instances of {@link SaslServer}. A class that
+ * implements this interface must be thread-safe and handle multiple
+ * simultaneous requests. It must also have a public constructor that accepts
+ * no arguments.</p>
+ *
+ * This interface is not normally accessed directly by a server, which will use
+ * the {@link Sasl} static methods to create a {@link SaslServer} instance
+ * instead. However, a particular environment may provide and install a new or
+ * different <code>SaslServerFactory</code>.</p>
+ *
+ * @see SaslServer
+ * @see Sasl
+ * @version $Revision: 1.1 $
+ */
+public interface SaslServerFactory
+{
+
+ /**
+ * Creates a {@link SaslServer} instance using the parameters supplied. It
+ * returns <code>null</code> if no {@link SaslServer} instance can be created
+ * using the parameters supplied. Throws {@link SaslException} if it cannot
+ * create a {@link SaslServer} because of an error.
+ *
+ * @param mechanism the non-null IANA-registered name of a SASL mechanism
+ * (e.g. "GSSAPI", "CRAM-MD5").
+ * @param protocol the non-null string name of the protocol for which the
+ * authentication is being performed (e.g. "ldap").
+ * @param serverName the non-null fully qualified host name of the server to
+ * authenticate to.
+ * @param props the possibly null set of properties used to select the SASL
+ * mechanism and to configure the authentication exchange of the selected
+ * mechanism. See the {@link Sasl} class for a list of standard properties.
+ * Other, possibly mechanism-specific, properties can be included. Properties
+ * not relevant to the selected mechanism are ignored.
+ * @param cbh the possibly null callback handler to used by the SASL
+ * mechanisms to get further information from the application/library to
+ * complete the authentication. For example, a SASL mechanism might require
+ * the authentication ID, password and realm from the caller. The
+ * authentication ID is requested by using a
+ * {@link javax.security.auth.callback.NameCallback}. The password is
+ * requested by using a {@link javax.security.auth.callback.PasswordCallback}.
+ * The realm is requested by using a {@link RealmChoiceCallback} if there is
+ * a list of realms to choose from, and by using a {@link RealmCallback} if
+ * the realm must be entered.
+ * @return a possibly null {@link SaslServer} created using the parameters
+ * supplied. If <code>null</code> is returned, it means that this factory
+ * cannot produce a {@link SaslServer} using the parameters supplied.
+ * @throws SaslException if a SaslServer instance cannot be created because
+ * of an error.
+ */
+ SaslServer createSaslServer(String mechanism, String protocol,
+ String serverName, Map props, CallbackHandler cbh)
+ throws SaslException;
+
+ /**
+ * Returns an array of names of mechanisms that match the specified mechanism
+ * selection policies.
+ *
+ * @param props the possibly <code>null</code> set of properties used to
+ * specify the security policy of the SASL mechanisms. For example, if props
+ * contains the {@link Sasl#POLICY_NOPLAINTEXT} property with the value
+ * <code>"true"</code>, then the factory must not return any SASL mechanisms
+ * that are susceptible to simple plain passive attacks. See the {@link Sasl}
+ * class for a complete list of policy properties. Non-policy related
+ * properties, if present in props, are ignored.
+ * @return a non-null array containing IANA-registered SASL mechanism names.
+ */
+ String[] getMechanismNames(Map props);
+}
diff --git a/libjava/org/ietf/jgss/ChannelBinding.java b/libjava/org/ietf/jgss/ChannelBinding.java
new file mode 100644
index 00000000000..9e966d54afb
--- /dev/null
+++ b/libjava/org/ietf/jgss/ChannelBinding.java
@@ -0,0 +1,215 @@
+/* ChannelBinding.java -- a channel binding in the GSS-API.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+import java.net.InetAddress;
+import java.util.Arrays;
+
+/**
+ * <p>The GSS-API accommodates the concept of caller-provided channel
+ * binding information. Channel bindings are used to strengthen the
+ * quality with which peer entity authentication is provided during
+ * context establishment. They enable the GSS-API callers to bind the
+ * establishment of the security context to relevant characteristics
+ * like addresses or to application specific data.</p>
+ *
+ * <p>The caller initiating the security context must determine the
+ * appropriate channel binding values to set in the {@link GSSContext}
+ * object. The acceptor must provide an identical binding in order to
+ * validate that received tokens possess correct channel-related
+ * characteristics.</p>
+ *
+ * <p>Use of channel bindings is optional in GSS-API. Since channel-binding
+ * information may be transmitted in context establishment tokens,
+ * applications should therefore not use confidential data as
+ * channel-binding components.</p>
+ */
+public class ChannelBinding
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private final byte[] appData;
+ private final InetAddress initAddr;
+ private final InetAddress acceptAddr;
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Create a ChannelBinding object with user supplied address information
+ * and data. <code>null</code> values can be used for any fields which the
+ * application does not want to specify.
+ *
+ * @param initAddr The address of the context initiator. <code>null</code>
+ * value can be supplied to indicate that the application
+ * does not want to set this value.
+ * @param acceptAddr The address of the context acceptor. <code>null</code>
+ * value can be supplied to indicate that the application
+ * does not want to set this value.
+ * @param appData Application supplied data to be used as part of the
+ * channel bindings. <code>null</code> value can be
+ * supplied to indicate that the application does not
+ * want to set this value.
+ */
+ public ChannelBinding(InetAddress initAddr, InetAddress acceptAddr,
+ byte[] appData)
+ {
+ this.appData = (appData != null) ? (byte[]) appData.clone() : null;
+ this.initAddr = initAddr;
+ this.acceptAddr = acceptAddr;
+ }
+
+ /**
+ * Creates a ChannelBinding object without any addressing information.
+ *
+ * @param appData Application supplied data to be used as part of the
+ * channel bindings.
+ */
+ public ChannelBinding(byte[] appData)
+ {
+ this(null, null, appData);
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the initiator's address for this channel binding.
+ * <code>null</code> is returned if the address has not been set.
+ *
+ * @return The initiator's address, or <code>null</code>.
+ */
+ public InetAddress getInitiatorAddress()
+ {
+ return initAddr;
+ }
+
+ /**
+ * Returns the acceptor's address for this channel binding.
+ * <code>null</code> is returned if the address has not been set.
+ *
+ * @return The acceptor's address, or <code>null</code>.
+ */
+ public InetAddress getAcceptorAddress()
+ {
+ return acceptAddr;
+ }
+
+ /**
+ * Returns application data being used as part of the ChannelBinding.
+ * <code>null</code> is returned if no application data has been
+ * specified for the channel binding.
+ *
+ * @return The application data, or <code>null</code>.
+ */
+ public byte[] getApplicationData()
+ {
+ if (appData != null)
+ return (byte[]) appData.clone();
+ return null;
+ }
+
+ /**
+ * Returns <code>true</code> if two channel bindings match.
+ *
+ * @param obj Another channel binding to compare with.
+ * @return True if this channel binding equals the other.
+ */
+ public boolean equals(Object obj)
+ {
+ if (!(obj instanceof ChannelBinding))
+ return false;
+ ChannelBinding cb = (ChannelBinding) obj;
+ boolean b1 = Arrays.equals(appData, cb.appData);
+ boolean b2 = (initAddr == null && cb.initAddr == null)
+ || (cb.initAddr != null && initAddr.equals(cb.initAddr));
+ boolean b3 = (acceptAddr == null && cb.acceptAddr == null)
+ || (cb.acceptAddr != null && acceptAddr.equals(cb.acceptAddr));
+ return b1 && b2 && b3;
+ }
+
+ /**
+ * Returns the hash code for this channel binding.
+ *
+ * @return The hash code.
+ */
+ public int hashCode()
+ {
+ int code = 0;
+ if (appData != null)
+ for (int i = 0; i < appData.length; i++)
+ code ^= appData[i] << ((8 * i) & 31);
+ if (initAddr != null)
+ code ^= initAddr.hashCode();
+ if (acceptAddr != null)
+ code ^= acceptAddr.hashCode();
+ return code;
+ }
+}
diff --git a/libjava/org/ietf/jgss/GSSContext.java b/libjava/org/ietf/jgss/GSSContext.java
new file mode 100644
index 00000000000..ab09c31c5c9
--- /dev/null
+++ b/libjava/org/ietf/jgss/GSSContext.java
@@ -0,0 +1,924 @@
+/* GSSContext.java -- The GSS context interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+
+package org.ietf.jgss;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * <p>This interface encapsulates the GSS-API security context and provides
+ * the security services ({@link #wrap(byte[],int,int,org.ietf.jgss.MessageProp)},
+ * {@link #unwrap(byte[],int,int,org.ietf.jgss.MessageProp)}, {@link
+ * #getMIC(byte[],int,int,org.ietf.jgss.MessageProp)}, {@link
+ * #verifyMIC(byte[],int,int,byte[],int,int,org.ietf.jgss.MessageProp)}) that
+ * are available over the context. Security contexts are established
+ * between peers using locally acquired credentials. Multiple contexts
+ * may exist simultaneously between a pair of peers, using the same or
+ * different set of credentials. GSS-API functions in a manner
+ * independent of the underlying transport protocol and depends on its
+ * calling application to transport its tokens between peers.</p>
+ *
+ * <p>Before the context establishment phase is initiated, the context
+ * initiator may request specific characteristics desired of the
+ * established context. These can be set using the set methods. After
+ * the context is established, the caller can check the actual
+ * characteristic and services offered by the context using the query
+ * methods.</p>
+ *
+ * <p>The context establishment phase begins with the first call to the
+ * init method by the context initiator. During this phase the
+ * {@link #initSecContext(byte[],int,int)} and {@link
+ * #acceptSecContext(byte[],int,int)} methods will produce GSS-API
+ * authentication tokens which the calling application needs to send to
+ * its peer. If an error occurs at any point, an exception will get
+ * thrown and the code will start executing in a catch block. If not,
+ * the normal flow of code continues and the application can make a call
+ * to the {@link #isEstablished()} method. If this method returns false it
+ * indicates that a token is needed from its peer in order to continue
+ * the context establishment phase. A return value of true signals that
+ * the local end of the context is established. This may still require
+ * that a token be sent to the peer, if one is produced by GSS-API.
+ * During the context establishment phase, the {@link #isProtReady()}
+ * method may be called to determine if the context can be used for the
+ * per-message operations. This allows applications to use per-message
+ * operations on contexts which aren't fully established.</p>
+ *
+ * <p>After the context has been established or the {@link #isProtReady()}
+ * method returns <code>true</code>, the query routines can be invoked to
+ * determine the actual characteristics and services of the established
+ * context. The application can also start using the per-message methods
+ * of {@link #wrap(byte[],int,int,org.ietf.jgss.MessageProp)} and
+ * {@link #getMIC(byte[],int,int,org.ietf.jgss.MessageProp)} to obtain
+ * cryptographic operations on application supplied data.</p>
+ *
+ * <p>When the context is no longer needed, the application should call
+ * {@link dispose()} to release any system resources the context may be
+ * using.</p>
+ *
+ * <h3>Example Code</h3>
+ *
+ * <pre>
+GSSManager mgr = GSSManager.getInstance();
+
+// start by creating the name for a service entity
+GSSName targetName = mgr.createName("service@host",
+ GSSName.NT_HOSTBASED_SERVICE);
+
+// create a context using default credentials for the above entity
+// and the implementation specific default mechanism
+GSSContext context = mgr.createContext(targetName,
+ null, // default mechanism
+ null, // default credentials
+ GSSContext.INDEFINITE_LIFETIME);
+
+// set desired context options - all others are false by default
+context.requestConf(true);
+context.requestMutualAuth(true);
+context.requestReplayDet(true);
+context.requestSequenceDet(true);
+
+// establish a context between peers - using byte arrays
+byte []inTok = new byte[0];
+
+try
+ {
+ do
+ {
+ byte[] outTok = context.initSecContext(inTok, 0,
+ inTok.length);
+
+ // send the token if present
+ if (outTok != null)
+ sendToken(outTok);
+
+ // check if we should expect more tokens
+ if (context.isEstablished())
+ break;
+
+ // another token expected from peer
+ inTok = readToken();
+
+ }
+ while (true);
+ }
+catch (GSSException e)
+ {
+ print("GSSAPI error: " + e.getMessage());
+ }
+
+// display context information
+print("Remaining lifetime in seconds = " + context.getLifetime());
+print("Context mechanism = " + context.getMech().toString());
+print("Initiator = " + context.getSrcName().toString());
+print("Acceptor = " + context.getTargName().toString());
+
+if (context.getConfState())
+ print("Confidentiality security service available");
+
+if (context.getIntegState())
+ print("Integrity security service available");
+
+// perform wrap on an application supplied message, appMsg,
+// using QOP = 0, and requesting privacy service
+byte[] appMsg ...
+MessageProp mProp = new MessageProp(0, true);
+byte[] tok = context.wrap(appMsg, 0, appMsg.length, mProp);
+
+if (mProp.getPrivacy())
+ print("Message protected with privacy.");
+
+sendToken(tok);
+
+
+// release the local-end of the context
+context.dispose();
+ * </pre>
+ */
+public interface GSSContext
+{
+
+ // Constants.
+ // -------------------------------------------------------------------------
+
+ /**
+ * A lifetime constant representing the default context lifetime.
+ */
+ int DEFAULT_LIFETIME = 0;
+
+ /**
+ * A lifetime constant representing indefinite context lifetime.
+ */
+ int INDEFINITE_LIFETIME = Integer.MAX_VALUE;
+
+ // Methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Called by the context initiator to start the context creation
+ * process. This is equivalent to the stream based method except that
+ * the token buffers are handled as byte arrays instead of using stream
+ * objects. This method may return an output token which the
+ * application will need to send to the peer for processing by the
+ * accept call. Typically, the application would do so by calling the
+ * {@link OutputStream#flush()} method on an OutputStream that
+ * encapsulates the connection between the two peers. The application
+ * can call {@link #isEstablished()} to determine if the context
+ * establishment phase is complete for this peer. A return value of
+ * <code>false</code> from {@link #isEstablished()} indicates that more
+ * tokens are expected to be supplied to the initSecContext() method. Note
+ * that it is possible that the initSecContext() method return a token for
+ * the peer, and {@link #isEstablished()} to return <code>true</code> also.
+ * This indicates that the token needs to be sent to the peer, but the local
+ * end of the context is now fully established.</p>
+ *
+ * <p>Upon completion of the context establishment, the available context
+ * options may be queried through the get methods.</p>
+ *
+ * @param inputBuf Token generated by the peer. This parameter is ignored
+ * on the first call.
+ * @param offset The offset within the <i>inputBuf</i> where the token
+ * begins.
+ * @param len The length of the token within the <i>inputBuf</i>
+ * (starting at the offset).
+ * @return The output token, if any.
+ * @throws GSSException If this operation fails.
+ */
+ byte[] initSecContext(byte[] inputBuf, int offset, int len)
+ throws GSSException;
+
+ /**
+ * <p>Called by the context initiator to start the context creation
+ * process. This is equivalent to the byte array based method. This
+ * method may write an output token to the <i>outStream</i>, which the
+ * application will need to send to the peer for processing by the
+ * accept call. Typically, the application would do so by calling the
+ * {@link OutputStream#flush()} method on an OutputStream that encapsulates
+ * the connection between the two peers. The application can call {@link
+ * #isEstablished()} to determine if the context establishment phase is
+ * complete for this peer. A return value of <code>false</code> from
+ * isEstablished indicates that more tokens are expected to be supplied
+ * to the initSecContext() method. Note that it is possible that the
+ * initSecContext() method return a token for the peer, and {@link
+ * #isEstablished() return <code>true</code> also. This indicates that
+ * the token needs to be sent to the peer, but the local end of the context
+ * is now fully established.</p>
+ *
+ * <p>The GSS-API authentication tokens contain a definitive start and end.
+ * This method will attempt to read one of these tokens per invocation,
+ * and may block on the stream if only part of the token is available.</p>
+ *
+ * <p>Upon completion of the context establishment, the available context
+ * options may be queried through the get methods.</p>
+ *
+ * @param inStream Contains the token generated by the peer. This
+ * parameter is ignored on the first call.
+ * @param outStream Output stream where the output token will be written.
+ * During the final stage of context establishment, there
+ * may be no bytes written.
+ * @return The number of bytes written to <i>outStream</i>, or 0 if no
+ * token is written.
+ * @throws GSSException If this operation fails.
+ */
+ int initSecContext(InputStream inStream, OutputStream outStream)
+ throws GSSException;
+
+ /**
+ * <p>Called by the context acceptor upon receiving a token from the peer.
+ * This call is equivalent to the stream based method except that the
+ * token buffers are handled as byte arrays instead of using stream
+ * objects.</p>
+ *
+ * <p>This method may return an output token which the application will
+ * need to send to the peer for further processing by the init call.</p>
+ *
+ * <p><code>null</code> return value indicates that no token needs to be
+ * sent to the peer. The application can call {@link #isEstablished()}
+ * to determine if the context establishment phase is complete for this
+ * peer. A return value of <code>false</code> from {@link #isEstablished()}
+ * indicates that more tokens are expected to be supplied to this
+ * method.</p>
+ *
+ * <p>Note that it is possible that acceptSecContext() return a token for
+ * the peer, and isEstablished() return <code>true</code> also. This
+ * indicates that the token needs to be sent to the peer, but the local
+ * end of the context is now fully established.</p>
+ *
+ * <p>Upon completion of the context establishment, the available context
+ * options may be queried through the get methods.</p>
+ *
+ * @param inTok Token generated by the peer.
+ * @param offset The offset within the <i>inTok</i> where the token begins.
+ * @param len The length of the token within the <i>inTok</i> (starting
+ * at the offset).
+ * @return The output token, if any.
+ * @throws GSSException If this operation fails.
+ */
+ byte[] acceptSecContext(byte[] inTok, int offset, int len)
+ throws GSSException;
+
+ /**
+ * <p>Called by the context acceptor upon receiving a token from the peer.
+ * This call is equivalent to the byte array method. It may write an
+ * output token to the outStream, which the application will need to
+ * send to the peer for processing by its initSecContext method.
+ * Typically, the application would do so by calling the {@link
+ * OutputStream#flush()} method on an OutputStream that encapsulates the
+ * connection between the two peers. The application can call {@link
+ * #isEstablished()} to determine if the context establishment phase is
+ * complete for this peer. A return value of <code>false</code> from
+ * {@link #isEstablished()} indicates that more tokens are expected to be
+ * supplied to this method.</p>
+ *
+ * <p>Note that it is possible that acceptSecContext() return a token for
+ * the peer, and isEstablished() return <code>true</code> also. This
+ * indicates that the token needs to be sent to the peer, but the local
+ * end of the context is now fully established.</p>
+ *
+ * <p>The GSS-API authentication tokens contain a definitive start and end.
+ * This method will attempt to read one of these tokens per invocation,
+ * and may block on the stream if only part of the token is available.</p>
+ *
+ * <p>Upon completion of the context establishment, the available context
+ * options may be queried through the get methods.</p>
+ *
+ * @param inStream Contains the token generated by the peer.
+ * @param outStream Output stream where the output token will be written.
+ * During the final stage of context establishment, there
+ * may be no bytes written.
+ * @return The number of bytes written, or 0 if no token is written.
+ * @throws GSSException If this operation fails.
+ */
+ void acceptSecContext(InputStream inStream, OutputStream outStream)
+ throws GSSException;
+
+ /**
+ * Used during context establishment to determine the state of the
+ * context. Returns <code>true</code> if this is a fully established
+ * context on the caller's side and no more tokens are needed from the
+ * peer. Should be called after a call to {@link
+ * #initSecContext(byte[],int,int)} or {@link
+ * #acceptSecContext(byte[],int,int)} when no {@link GSSException}
+ * is thrown.
+ *
+ * @return True of this context is fully established on this side.
+ */
+ boolean isEstablished();
+
+ /**
+ * Releases any system resources and cryptographic information stored in
+ * the context object. This will invalidate the context.
+ *
+ * @throws GSSException If this operation fails.
+ */
+ void dispose() throws GSSException;
+
+ /**
+ * <p>Returns the maximum message size that, if presented to the
+ * {@link #wrap(byte[],int,int,org.ietf.jgss.MessageProp)} method with
+ * the same <i>confReq</i> and <i>qop</i> parameters, will result in an
+ * output token containing no more than the <i>maxTokenSize</i> bytes.</p>
+ *
+ * <p>This call is intended for use by applications that communicate over
+ * protocols that impose a maximum message size. It enables the
+ * application to fragment messages prior to applying protection.</p>
+ *
+ * <p>GSS-API implementations are recommended but not required to detect
+ * invalid QOP values when getWrapSizeLimit is called. This routine
+ * guarantees only a maximum message size, not the availability of
+ * specific QOP values for message protection.</p>
+ *
+ * <p>Successful completion of this call does not guarantee that wrap will
+ * be able to protect a message of the computed length, since this
+ * ability may depend on the availability of system resources at the
+ * time that wrap is called. However, if the implementation itself
+ * imposes an upper limit on the length of messages that may be
+ * processed by wrap, the implementation should not return a value that
+ * is greater than this length.</p>
+ *
+ * @param qop Indicates the level of protection wrap will be asked
+ * to provide.
+ * @param confReq Indicates if wrap will be asked to provide privacy
+ * service.
+ * @param maxTokenSize The desired maximum size of the token emitted
+ * by {@link #wrap(byte[],int,int,org.ietf.jgss.MessageProp)}.
+ * @return The maximum wrapped output size.
+ * @throws GSSException If this operation fails.
+ */
+ int getWrapSizeLimit(int qop, boolean confReq, int maxTokenSize)
+ throws GSSException;
+
+ /**
+ * <p>Applies per-message security services over the established security
+ * context. The method will return a token with a cryptographic MIC and
+ * may optionally encrypt the specified <i>inBuf</i>. This method is
+ * equivalent in functionality to its stream counterpart. The returned
+ * byte array will contain both the MIC and the message.</p>
+ *
+ * <p>The {@link MessageProp} object is instantiated by the application
+ * and used to specify a QOP value which selects cryptographic algorithms,
+ * and a privacy service to optionally encrypt the message. The underlying
+ * mechanism that is used in the call may not be able to provide the
+ * privacy service. It sets the actual privacy service that it does
+ * provide in this {@link MessageProp} object which the caller should then
+ * query upon return. If the mechanism is not able to provide the
+ * requested QOP, it throws a {@link GSSException} with the {@link
+ * GSSException#BAD_QOP} code.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by wrap to provide "secure framing", implementations should support
+ * the wrapping of zero-length messages.</p>
+ *
+ * <p>The application will be responsible for sending the token to the
+ * peer.</p>
+ *
+ * @param inBuf Application data to be protected.
+ * @param offset The offset within the inBuf where the data begins.
+ * @param len The length of the data within the inBuf (starting at
+ * the offset).
+ * @param msgProp Instance of {@link MessageProp} that is used by the
+ * application to set the desired QOP and privacy state.
+ * Set the desired QOP to 0 to request the default QOP.
+ * Upon return from this method, this object will contain
+ * the the actual privacy state that was applied to the
+ * message by the underlying mechanism.
+ * @return The wrapped data.
+ * @throws GSSException If this operation fails.
+ */
+ byte[] wrap(byte[] inBuf, int offset, int len, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Allows to apply per-message security services over the established
+ * security context. The method will produce a token with a
+ * cryptographic MIC and may optionally encrypt the message in inStream.
+ * The outStream will contain both the MIC and the message.</p>
+ *
+ * <p>The {@link MessageProp} object is instantiated by the application and
+ * used to specify a QOP value which selects cryptographic algorithms, and
+ * a privacy service to optionally encrypt the message. The underlying
+ * mechanism that is used in the call may not be able to provide the
+ * privacy service. It sets the actual privacy service that it does
+ * provide in this MessageProp object which the caller should then query
+ * upon return. If the mechanism is not able to provide the requested
+ * QOP, it throws a {@link GSSException} with the {@link
+ * GSSException#BAD_QOP} code.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by wrap to provide "secure framing", implementations should support
+ * the wrapping of zero-length messages.</p>
+ *
+ * <p>The application will be responsible for sending the token to the
+ * peer.</p>
+ *
+ * @param inStream Input stream containing the application data to be
+ * protected.
+ * @param outStream The output stream to write the protected message to.
+ * The application is responsible for sending this to the
+ * other peer for processing in its unwrap method.
+ * @param msgProp Instance of {@link MessageProp} that is used by the
+ * application to set the desired QOP and privacy state.
+ * Set the desired QOP to 0 to request the default QOP.
+ * Upon return from this method, this object will contain
+ * the the actual privacy state that was applied to the
+ * message by the underlying mechanism.
+ * @throws GSSException If this operation fails.
+ */
+ void wrap(InputStream inStream, OutputStream outStream, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Used by the peer application to process tokens generated with the
+ * wrap call. This call is equal in functionality to its stream
+ * counterpart. The method will return the message supplied in the peer
+ * application to the wrap call, verifying the embedded MIC.</p>
+ *
+ * <p>The {@link MessageProp} object is instantiated by the application and
+ * is used by the underlying mechanism to return information to the caller
+ * such as the QOP, whether confidentiality was applied to the message, and
+ * other supplementary message state information.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by wrap to provide "secure framing", implementations should support
+ * the wrapping and unwrapping of zero-length messages.</p>
+ *
+ * @param inBuf GSS-API wrap token received from peer.
+ * @param offset The offset within the inBuf where the token begins.
+ * @param len The length of the token within the inBuf (starting at
+ * the offset).
+ * @param msgProp Upon return from the method, this object will contain
+ * the applied QOP, the privacy state of the message, and
+ * supplementary information stating whether the token was
+ * a duplicate, old, out of sequence or arriving after a gap.
+ * @return The unwrapped token.
+ * @throws GSSException If this operation fails.
+ */
+ byte[] unwrap(byte[] inBuf, int offset, int len, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Used by the peer application to process tokens generated with the
+ * wrap call. This call is equal in functionality to its byte array
+ * counterpart. It will produce the message supplied in the peer
+ * application to the wrap call, verifying the embedded MIC.</p>
+ *
+ * <p>The {@link MessageProp} object is instantiated by the application
+ * and is used by the underlying mechanism to return information to the
+ * caller such as the QOP, whether confidentiality was applied to the
+ * message, and other supplementary message state information.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by wrap to provide "secure framing", implementations should support
+ * the wrapping and unwrapping of zero-length messages.</p>
+ *
+ * @param inStream Input stream containing the GSS-API wrap token
+ * received from the peer.
+ * @param outStream The output stream to write the application message to.
+ * @param msgProp Upon return from the method, this object will contain
+ * the applied QOP, the privacy state of the message, and
+ * supplementary information stating whether the token was
+ * a duplicate, old, out of sequence or arriving after a gap.
+ * @throws GSSException If this operation fails.
+ */
+ void unwrap(InputStream inStream, OutputStream outStream, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Returns a token containing a cryptographic MIC for the supplied
+ * message, for transfer to the peer application. Unlike wrap, which
+ * encapsulates the user message in the returned token, only the message
+ * MIC is returned in the output token. This method is identical in
+ * functionality to its stream counterpart.</p>
+ *
+ * <p>Note that privacy can only be applied through the wrap call.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by getMIC to provide "secure framing", implementations should support
+ * derivation of MICs from zero-length messages.</p>
+ *
+ * @param inMsg Message to generate MIC over.
+ * @param offset The offset within the inMsg where the token begins.
+ * @param len The length of the token within the inMsg (starting at
+ * the offset).
+ * @param msgProp Instance of MessageProp that is used by the
+ * application to set the desired QOP. Set the desired
+ * QOP to 0 in msgProp to request the default QOP.
+ * Alternatively pass in <code>null</code> for msgProp to
+ * request default QOP.
+ * @return The MIC.
+ * @throws GSSException If this operation fails.
+ */
+ byte[] getMIC(byte[] inMsg, int offset, int len, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Produces a token containing a cryptographic MIC for the supplied
+ * message, for transfer to the peer application. Unlike wrap, which
+ * encapsulates the user message in the returned token, only the message
+ * MIC is produced in the output token. This method is identical in
+ * functionality to its byte array counterpart.</p>
+ *
+ * <p>Note that privacy can only be applied through the wrap call.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by getMIC to provide "secure framing", implementations should support
+ * derivation of MICs from zero-length messages.</p>
+ *
+ * @param inStream Input stream containing the message to generate
+ * the MIC over.
+ * @param outStream Output stream to write the GSS-API output token to.
+ * @param msgProp Instance of MessageProp that is used by the
+ * application to set the desired QOP. Set the desired
+ * QOP to 0 in msgProp to request the default QOP.
+ * Alternatively pass in <code>null</code> for msgProp
+ * to request default QOP.
+ * @throws GSSException If this operation fails.
+ */
+ void getMIC(InputStream inStream, OutputStream outStream, MessageProp mgProp)
+ throws GSSException;
+
+ /**
+ * <p>Verifies the cryptographic MIC, contained in the token parameter,
+ * over the supplied message. This method is equivalent in
+ * functionality to its stream counterpart.</p>
+ *
+ * <p>The MessageProp object is instantiated by the application and is used
+ * by the underlying mechanism to return information to the caller such
+ * as the QOP indicating the strength of protection that was applied to
+ * the message and other supplementary message state information.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by getMIC to provide "secure framing", implementations should support
+ * the calculation and verification of MICs over zero-length messages.</p>
+ *
+ * @param inTok Token generated by peer's getMIC method.
+ * @param tokOffset The offset within the inTok where the token begins.
+ * @param tokLen The length of the token within the inTok (starting at
+ * the offset).
+ * @param inMsg Application message to verify the cryptographic MIC
+ * over.
+ * @param msgOffset The offset within the inMsg where the message begins.
+ * @param msgLen The length of the message within the inMsg (starting
+ * at the offset).
+ * @param msgProp Upon return from the method, this object will contain
+ * the applied QOP and supplementary information
+ * stating whether the token was a duplicate, old, out
+ * of sequence or arriving after a gap. The
+ * confidentiality state will be set to <code>false</code>.
+ * @throws GSSException If this operation fails.
+ */
+ void verifyMIC(byte[] inTok, int tokOffset, int tokLen, byte[] inMsg,
+ int msgOffset, int msgLen, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Verifies the cryptographic MIC, contained in the token parameter,
+ * over the supplied message. This method is equivalent in
+ * functionality to its byte array counterpart.</p>
+ *
+ * <p>The MessageProp object is instantiated by the application and is used
+ * by the underlying mechanism to return information to the caller such
+ * as the QOP indicating the strength of protection that was applied to
+ * the message and other supplementary message state information.</p>
+ *
+ * <p>Since some application-level protocols may wish to use tokens emitted
+ * by getMIC to provide "secure framing", implementations should support
+ * the calculation and verification of MICs over zero-length messages.</p>
+ *
+ * @param tokStream Input stream containing the token generated by peer's
+ * getMIC method.
+ * @param msgStream Input stream containing the application message to
+ * verify the cryptographic MIC over.
+ * @param msgProp Upon return from the method, this object will contain
+ * the applied QOP and supplementary information
+ * stating whether the token was a duplicate, old, out of
+ * sequence or arriving after a gap. The confidentiality
+ * state will be set to <code>false</code>.
+ * @throws GSSException If this operation fails.
+ */
+ void verifyMIC(InputStream tokStream, InputStream msgStream, MessageProp msgProp)
+ throws GSSException;
+
+ /**
+ * <p>Provided to support the sharing of work between multiple processes.
+ * This routine will typically be used by the context-acceptor, in an
+ * application where a single process receives incoming connection
+ * requests and accepts security contexts over them, then passes the
+ * established context to one or more other processes for message
+ * exchange.</p>
+ *
+ * <p>This method deactivates the security context and creates an
+ * interprocess token which, when passed to the byte array constructor
+ * of the GSSContext interface in another process, will re-activate the
+ * context in the second process. Only a single instantiation of a
+ * given context may be active at any one time; a subsequent attempt by
+ * a context exporter to access the exported security context will fail.</p>
+ *
+ * <p>The implementation may constrain the set of processes by which the
+ * interprocess token may be imported, either as a function of local
+ * security policy, or as a result of implementation decisions. For
+ * example, some implementations may constrain contexts to be passed
+ * only between processes that run under the same account, or which are
+ * part of the same process group.</p>
+ *
+ * <p>The interprocess token may contain security-sensitive information
+ * (for example cryptographic keys). While mechanisms are encouraged to
+ * either avoid placing such sensitive information within interprocess
+ * tokens, or to encrypt the token before returning it to the
+ * application, in a typical GSS-API implementation this may not be
+ * possible. Thus the application must take care to protect the
+ * interprocess token, and ensure that any process to which the token is
+ * transferred is trustworthy.</p>
+ *
+ * @return The exported context.
+ * @throws GSSException If this operation fails.
+ */
+ byte[] export() throws GSSException;
+
+ /**
+ * <p>Sets the request state of the mutual authentication flag for the
+ * context. This method is only valid before the context creation
+ * process begins and only for the initiator.</p>
+ *
+ * @param state Boolean representing if mutual authentication should
+ * be requested during context establishment.
+ * @throws GSSException If this operation fails.
+ */
+ void requestMutualAuth(boolean state) throws GSSException;
+
+ /**
+ * <p>Sets the request state of the replay detection service for the
+ * context. This method is only valid before the context creation
+ * process begins and only for the initiator.</p>
+ *
+ * @param state Boolean representing if replay detection is desired
+ * over the established context.
+ * @throws GSSException If this operation fails.
+ */
+ void requestReplayDet(boolean state) throws GSSException;
+
+ /**
+ * <p>Sets the request state for the sequence checking service of the
+ * context. This method is only valid before the context creation
+ * process begins and only for the initiator.</p>
+ *
+ * @param state Boolean representing if sequence detection is desired
+ * over the established context.
+ * @throws GSSException If this operation fails.
+ */
+ void requestSequenceDet(boolean state) throws GSSException;
+
+ /**
+ * <p>Sets the request state for the credential delegation flag for the
+ * context. This method is only valid before the context creation
+ * process begins and only for the initiator.</p>
+ *
+ * @param state Boolean representing if credential delegation is
+ * desired.
+ * @throws GSSException If this operation fails.
+ */
+ void requestCredDeleg(boolean state) throws GSSException;
+
+ /**
+ * <p>Requests anonymous support over the context. This method is only
+ * valid before the context creation process begins and only for the
+ * initiator.</p>
+ *
+ * @param state Boolean representing if anonymity support is requested.
+ * @throws GSSException If this operation fails.
+ */
+ void requestAnonymity(boolean state) throws GSSException;
+
+ /**
+ * <p>Requests that confidentiality service be available over the context.
+ * This method is only valid before the context creation process begins
+ * and only for the initiator.</p>
+ *
+ * @param state Boolean indicating if confidentiality services are to
+ * be requested for the context.
+ * @throws GSSException If this operation fails.
+ */
+ void requestConf(boolean state) throws GSSException;
+
+ /**
+ * <p>Requests that integrity services be available over the context. This
+ * method is only valid before the context creation process begins and
+ * only for the initiator.</p>
+ *
+ * @param state Boolean indicating if integrity services are to be
+ * requested for the context.
+ * @throws GSSException If this operation fails.
+ */
+ void requestInteg(boolean state) throws GSSException;
+
+ /**
+ * <p>Sets the desired lifetime for the context in seconds. This method is
+ * only valid before the context creation process begins and only for
+ * the initiator. Use {@link #INDEFINITE_LIFETIME} and {@link
+ * #DEFAULT_LIFETIME} to request indefinite or default context lifetime.</p>
+ *
+ * @param lifetime The desired context lifetime in seconds.
+ * @throws GSSException If this operation fails.
+ */
+ void requestLifetime(int lifetime) throws GSSException;
+
+ /**
+ * <p>Sets the channel bindings to be used during context establishment.
+ * This method is only valid before the context creation process begins.</p>
+ *
+ * @param cb Channel bindings to be used.
+ * @throws GSSException If this operation fails.
+ */
+ void setChannelBinding(ChannelBinding cb) throws GSSException;
+
+ /**
+ * <p>Returns the state of the delegated credentials for the context.
+ * When issued before context establishment is completed or when the
+ * isProtReady method returns "false", it returns the desired state,
+ * otherwise it will indicate the actual state over the established
+ * context.</p>
+ *
+ * @return The state of the delegated credentials for the context.
+ */
+ boolean getCredDelegState();
+
+ /**
+ * <p>Returns the state of the mutual authentication option for the
+ * context. When issued before context establishment completes or when
+ * the isProtReady method returns "false", it returns the desired state,
+ * otherwise it will indicate the actual state over the established
+ * context.</p>
+ *
+ * @return The state of the mutual authentication option.
+ */
+ boolean getMutualAuthState();
+
+ /**
+ * <p>Returns the state of the replay detection option for the context.
+ * When issued before context establishment completes or when the
+ * isProtReady method returns "false", it returns the desired state,
+ * otherwise it will indicate the actual state over the established
+ * context.</p>
+ *
+ * @return The state of the replay detection option.
+ */
+ boolean getReplayDetState();
+
+ /**
+ * <p>Returns the state of the sequence detection option for the context.
+ * When issued before context establishment completes or when the
+ * isProtReady method returns "false", it returns the desired state,
+ * otherwise it will indicate the actual state over the established
+ * context.</p>
+ *
+ * @return The state of the sequence detection option.
+ */
+ boolean getSequenceDetState();
+
+ /**
+ * <p>Returns "true" if this is an anonymous context. When issued before
+ * context establishment completes or when the isProtReady method
+ * returns "false", it returns the desired state, otherwise it will
+ * indicate the actual state over the established context.</p>
+ *
+ * @return True if this is an anonymous context.
+ */
+ boolean getAnonymityState();
+
+ /**
+ * <p>Returns "true" if the context is transferable to other processes
+ * through the use of the {@link #export()} method. This call is only
+ * valid on fully established contexts.</p>
+ *
+ * @return True if the context is transferable.
+ * @throws GSSException If this operation fails.
+ */
+ boolean isTransferable() throws GSSException;
+
+ /**
+ * <p>Returns "true" if the per message operations can be applied over
+ * the context. Some mechanisms may allow the usage of per-message
+ * operations before the context is fully established. This will also
+ * indicate that the get methods will return actual context state
+ * characteristics instead of the desired ones.</p>
+ *
+ * @return True if the per message operations can be applied over
+ * the context.
+ */
+ boolean isProtReady();
+
+ /**
+ * <p>Returns the confidentiality service state over the context. When
+ * issued before context establishment completes or when the isProtReady
+ * method returns "false", it returns the desired state, otherwise it
+ * will indicate the actual state over the established context.</p>
+ *
+ * @return True the confidentiality service state.
+ */
+ boolean getConfState();
+
+ /**
+ * <p>Returns the integrity service state over the context. When issued
+ * before context establishment completes or when the isProtReady method
+ * returns "false", it returns the desired state, otherwise it will
+ * indicate the actual state over the established context.</p>
+ *
+ * @return The integrity service state.
+ */
+ boolean getIntegState();
+
+ /**
+ * <p>Returns the context lifetime in seconds. When issued before context
+ * establishment completes or when the isProtReady method returns
+ * "false", it returns the desired lifetime, otherwise it will indicate
+ * the remaining lifetime for the context.</p>
+ *
+ * @return The lifetime.
+ */
+ int getLifetime();
+
+ /**
+ * <p>Returns the name of the context initiator. This call is valid only
+ * after the context is fully established or the isProtReady method
+ * returns "true". It is guaranteed to return an MN.</p>
+ *
+ * @return The name of the context initiator.
+ * @throws GSSException If this operation fails.
+ */
+ GSSName getSrcName() throws GSSException;
+
+ /**
+ * <p>Returns the name of the context target (acceptor). This call is
+ * valid only after the context is fully established or the isProtReady
+ * method returns "true". It is guaranteed to return an MN.</p>
+ *
+ * @return The name of the context target.
+ * @throws GSSException If this operation fails.
+ */
+ GSSName getTargName() throws GSSException;
+
+ /**
+ * <p>Returns the mechanism oid for this context. This method may be called
+ * before the context is fully established, but the mechanism returned
+ * may change on successive calls in negotiated mechanism case.</p>
+ *
+ * @return The mechanism OID.
+ * @throws GSSException If this operation fails.
+ */
+ Oid getMech() throws GSSException;
+
+ /**
+ * <p>Returns the delegated credential object on the acceptor's side.
+ * To check for availability of delegated credentials call
+ * {@link #getDelegCredState()}. This call is only valid on fully
+ * established contexts.</p>
+ *
+ * @return The delegated credential object.
+ * @throws GSSException If this operation fails.
+ */
+ GSSCredential getDelegCred() throws GSSException;
+
+ /**
+ * <p>Returns "true" if this is the initiator of the context. This call is
+ * only valid after the context creation process has started.</p>
+ *
+ * @return True if this is the initiator.
+ * @throws GSSException If this operation fails.
+ */
+ boolean isInitiator() throws GSSException;
+}
diff --git a/libjava/org/ietf/jgss/GSSCredential.java b/libjava/org/ietf/jgss/GSSCredential.java
new file mode 100644
index 00000000000..318848ec90d
--- /dev/null
+++ b/libjava/org/ietf/jgss/GSSCredential.java
@@ -0,0 +1,334 @@
+/* GSSCredential.java -- GSS credential interface.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+/**
+ * <p>This interface encapsulates the GSS-API credentials for an entity.
+ * A credential contains all the necessary cryptographic information to
+ * enable the creation of a context on behalf of the entity that it
+ * represents. It may contain multiple, distinct, mechanism specific
+ * credential elements, each containing information for a specific
+ * security mechanism, but all referring to the same entity.</p>
+ *
+ * <p>A credential may be used to perform context initiation, acceptance,
+ * or both.</p>
+ *
+ * <p>GSS-API implementations must impose a local access-control policy on
+ * callers to prevent unauthorized callers from acquiring credentials to
+ * which they are not entitled. GSS-API credential creation is not
+ * intended to provide a "login to the network" function, as such a
+ * function would involve the creation of new credentials rather than
+ * merely acquiring a handle to existing credentials. Such functions,
+ * if required, should be defined in implementation-specific extensions
+ * to the API.</p>
+ *
+ * <p>If credential acquisition is time-consuming for a mechanism, the
+ * mechanism may choose to delay the actual acquisition until the
+ * credential is required (e.g. by {@link GSSContext}). Such mechanism-
+ * specific implementation decisions should be invisible to the calling
+ * application; thus the query methods immediately following the
+ * creation of a credential object must return valid credential data,
+ * and may therefore incur the overhead of a deferred credential
+ * acquisition.</p>
+ *
+ * <p>Applications will create a credential object passing the desired
+ * parameters. The application can then use the query methods to obtain
+ * specific information about the instantiated credential object
+ * (equivalent to the gss_inquire routines). When the credential is no
+ * longer needed, the application should call the dispose (equivalent to
+ * gss_release_cred) method to release any resources held by the
+ * credential object and to destroy any cryptographically sensitive
+ * information.</p>
+ *
+ * <p>Classes implementing this interface also implement the {@link Cloneable}
+ * interface. This indicates the the class will support the {@link
+ * Cloneable#clone()} method that will allow the creation of duplicate
+ * credentials. This is useful when called just before the {@link
+ * #add(org.ietf.jgss.GSSName,int,int,org.ietf.jgss.Oid,int)} call to retain
+ * a copy of the original credential.</p>
+ *
+ * <h3>Example Code</h3>
+ *
+ * <pre>
+GSSManager mgr = GSSManager.getInstance();
+
+// start by creating a name object for the entity
+GSSName name = mgr.createName("userName", GSSName.NT_USER_NAME);
+
+// now acquire credentials for the entity
+GSSCredential cred = mgr.createCredential(name,
+ GSSCredential.ACCEPT_ONLY);
+
+// display credential information - name, remaining lifetime,
+// and the mechanisms it has been acquired over
+print(cred.getName().toString());
+print(cred.getRemainingLifetime());
+
+Oid [] mechs = cred.getMechs();
+if (mechs != null)
+ {
+ for (int i = 0; i < mechs.length; i++)
+ print(mechs[i].toString());
+ }
+
+// release system resources held by the credential
+cred.dispose();
+ * </pre>
+ */
+public interface GSSCredential extends Cloneable
+{
+
+ // Constants.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Credential usage flag requesting that it be able to be used for both
+ * context initiation and acceptance.
+ */
+ int INITIATE_AND_ACCEPT = 0;
+
+ /**
+ * Credential usage flag requesting that it be able to be used for
+ * context initiation only.
+ */
+ int INITIATE_ONLY = 1;
+
+ /**
+ * Credential usage flag requesting that it be able to be used for
+ * context acceptance only.
+ */
+ int ACCEPT_ONLY = 2;
+
+ /**
+ * A lifetime constant representing the default credential lifetime.
+ */
+ int DEFAULT_LIFETIME = 0;
+
+ /**
+ * A lifetime constant representing indefinite credential lifetime.
+ */
+ int INDEFINITE_LIFETIME = Integer.MAX_VALUE;
+
+ // Methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Releases any sensitive information that the GSSCredential object may
+ * be containing. Applications should call this method as soon as the
+ * credential is no longer needed to minimize the time any sensitive
+ * information is maintained.
+ *
+ * @throws GSSException If this operation fails.
+ */
+ void dispose() throws GSSException;
+
+ /**
+ * Retrieves the name of the entity that the credential asserts.
+ *
+ * @return The name.
+ * @throws GSSException If this operation fails.
+ */
+ GSSName getName() throws GSSException;
+
+ /**
+ * Retrieves a mechanism name of the entity that the credential asserts.
+ * Equivalent to calling {@link GSSName#canonicalize(org.ietf.jgss.Oid)}
+ * on the name returned by {@link #getName()}.
+ *
+ * @param mechOID The mechanism for which information should be returned.
+ * @return The name.
+ * @throws GSSException If this operation fails.
+ */
+ GSSName getName(Oid mechOID) throws GSSException;
+
+ /**
+ * Returns the remaining lifetime in seconds for a credential. The
+ * remaining lifetime is the minimum lifetime for any of the underlying
+ * credential mechanisms. A return value of {@link
+ * GSSCredential#INDEFINITE_LIFETIME} indicates that the credential does
+ * not expire. A return value of 0 indicates that the credential is
+ * already expired.
+ *
+ * @return The remaining lifetime.
+ * @throws GSSException If this operation fails.
+ */
+ int getRemainingLifetime() throws GSSException;
+
+ /**
+ * Returns the remaining lifetime is seconds for the credential to
+ * remain capable of initiating security contexts under the specified
+ * mechanism. A return value of {@link GSSCredential#INDEFINITE_LIFETIME}
+ * indicates that the credential does not expire for context initiation.
+ * A return value of 0 indicates that the credential is already expired.
+ *
+ * @param mech The mechanism for which information should be returned.
+ * @return The remaining lifetime.
+ * @throws GSSException If this operation fails.
+ */
+ int getRemainingInitLifetime(Oid mech) throws GSSException;
+
+ /**
+ * Returns the remaining lifetime is seconds for the credential to
+ * remain capable of accepting security contexts under the specified
+ * mechanism. A return value of {@link GSSCredential#INDEFINITE_LIFETIME}
+ * indicates that the credential does not expire for context acceptance.
+ * A return value of 0 indicates that the credential is already expired.
+ *
+ * @param mech The mechanism for which information should be returned.
+ * @return The remaining lifetime.
+ * @throws GSSException If this operation fails.
+ */
+ int getRemainingAcceptLifetime(Oid mech) throws GSSException;
+
+ /**
+ * Returns the credential usage flag. The return value will be one of
+ * {@link GSSCredential#INITIATE_ONLY}, {@link GSSCredential#ACCEPT_ONLY},
+ * or {@link GSSCredential#INITIATE_AND_ACCEPT}.
+ *
+ * @return The credential usage flag.
+ * @throws GSSException If this operation fails.
+ */
+ int getUsage() throws GSSException;
+
+ /**
+ * Returns the credential usage flag for the specified credential
+ * mechanism. The return value will be one of
+ * {@link GSSCredential#INITIATE_ONLY}, {@link GSSCredential#ACCEPT_ONLY},
+ * or {@link GSSCredential#INITIATE_AND_ACCEPT}.
+ *
+ * @param mechOID The mechanism for which information should be returned.
+ * @return The credential usage flag.
+ * @throws GSSException If this operation fails.
+ */
+ int getUsage(Oid mechOID) throws GSSException;
+
+ /**
+ * Returns an array of mechanisms supported by this credential.
+ *
+ * @return The supported mechanism.
+ * @throws GSSException If this operation fails.
+ */
+ Oid[] getMechs() throws GSSException;
+
+ /**
+ * <p>Adds a mechanism specific credential-element to an existing
+ * credential. This method allows the construction of credentials one
+ * mechanism at a time.</p>
+ *
+ * <p>This routine is envisioned to be used mainly by context acceptors
+ * during the creation of acceptance credentials which are to be used
+ * with a variety of clients using different security mechanisms.</p>
+ *
+ * <p>This routine adds the new credential element "in-place". To add the
+ * element in a new credential, first call {@link Cloneable#clone()} to
+ * obtain a copy of this credential, then call its <code>add()</code>
+ * method.</p>
+ *
+ * @param aName Name of the principal for whom this credential
+ * is to be acquired. Use <code>null</code> to
+ * specify the default principal.
+ * @param initLifetime The number of seconds that credentials should
+ * remain valid for initiating of security contexts.
+ * Use {@link #INDEFINITE_LIFETIME} to request that
+ * the credentials have the maximum permitted lifetime.
+ * Use {@link GSSCredential#DEFAULT_LIFETIME} to
+ * request the default credential lifetime.
+ * @param acceptLifetime The number of seconds that credentials should
+ * remain valid for accepting of security contexts.
+ * Use {@link GSSCredential#INDEFINITE_LIFETIME} to
+ * request that the credentials have the maximum
+ * permitted lifetime. Use {@link
+ * GSSCredential#DEFAULT_LIFETIME} to request
+ * the default credential lifetime.
+ * @param mech The mechanisms over which the credential is to be
+ * acquired.
+ * @param usage The intended usage for this credential object. The
+ * value of this parameter must be one of:
+ * {@link GSSCredential#ACCEPT_AND_INITIATE},
+ * {@link GSSCredential#ACCEPT_ONLY},
+ * {@link GSSCredential#INITIATE_ONLY}.
+ * @throws GSSException If this operation fails.
+ */
+ void add(GSSName aName, int initLifetime, int acceptLifetime,
+ Oid mech, int usage) throws GSSException;
+
+ /**
+ * Tests if this GSSCredential refers to the same entity as the supplied
+ * object. The two credentials must be acquired over the same
+ * mechanisms and must refer to the same principal. Returns <code>true</code>
+ * if the two GSSCredentials refer to the same entity; <code>false</code>
+ * otherwise. (Note that the Java language specification requires that two
+ * objects that are equal according to the {@link
+ * Object#equals(java.lang.Object)} method must return the same integer
+ * result when the {@link Object#hashCode()} method is called on them.)
+ *
+ * @param another Another GSSCredential object for comparison.
+ * @return True if this object equals the other.
+ */
+ boolean equals(Object another);
+}
diff --git a/libjava/org/ietf/jgss/GSSException.java b/libjava/org/ietf/jgss/GSSException.java
new file mode 100644
index 00000000000..72d91c0da16
--- /dev/null
+++ b/libjava/org/ietf/jgss/GSSException.java
@@ -0,0 +1,431 @@
+/* GSSException.java -- a general exception in GSS.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+import java.util.PropertyResourceBundle;
+import java.util.ResourceBundle;
+
+/**
+ * This exception is thrown whenever a fatal GSS-API error occurs
+ * including mechanism specific errors. It may contain both, the major
+ * and minor, GSS-API status codes. The mechanism implementers are
+ * responsible for setting appropriate minor status codes when throwing
+ * this exception. Aside from delivering the numeric error code(s) to
+ * the caller, this class performs the mapping from their numeric values
+ * to textual representations. All Java GSS-API methods are declared
+ * throwing this exception.
+ */
+public class GSSException extends Exception
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ // These values do not jive with the "Constant Field Values" in the J2SE
+ // 1.4.1, but do follow RFC 2853. I trust the IETF, but not Sun.
+
+ /**
+ * Channel bindings mismatch error.
+ */
+ public static final int BAD_BINDINGS = 4;
+
+ /**
+ * Unsupported mechanism requested error.
+ */
+ public static final int BAD_MECH = 1;
+
+ /**
+ * Invalid name provided error.
+ */
+ public static final int BAD_NAME = 2;
+
+ /**
+ * Name of unsupported type provided error.
+ */
+ public static final int BAD_NAMETYPE = 3;
+
+ /**
+ * Invalid status code error - this is the default status value.
+ */
+ public static final int BAD_STATUS = 5;
+
+ /**
+ * Token had invalid integrity check error.
+ */
+ public static final int BAD_MIC = 6;
+
+ /**
+ * Specified security context expired error.
+ */
+ public static final int CONTEXT_EXPIRED = 12;
+
+ /**
+ * Expired credentials detected error.
+ */
+ public static final int CREDENTIALS_EXPIRED = 11;
+
+ /**
+ * Defective credential error.
+ */
+ public static final int DEFECTIVE_CREDENTIAL = 10;
+
+ /**
+ * Defective token error.
+ */
+ public static final int DEFECTIVE_TOKEN = 9;
+
+ /**
+ * General failure, unspecified at GSS-API level.
+ */
+ public static final int FAILURE = 13;
+
+ /**
+ * Invalid security context error.
+ */
+ public static final int NO_CONTEXT = 8;
+
+ /**
+ * Invalid credentials error.
+ */
+ public static final int NO_CRED = 7;
+
+ /**
+ * Unsupported QOP value error.
+ */
+ public static final int BAD_QOP = 14;
+
+ /**
+ * Operation unauthorized error.
+ */
+ public static final int UNAUTHORIZED = 15;
+
+ /**
+ * Operation unavailable error.
+ */
+ public static final int UNAVAILABLE = 16;
+
+ /**
+ * Duplicate credential element requested error.
+ */
+ public static final int DUPLICATE_ELEMENT = 17;
+
+ /**
+ * Name contains multi-mechanism elements error.
+ */
+ public static final int NAME_NOT_MN = 18;
+
+ /**
+ * The token was a duplicate of an earlier token. This is a fatal error
+ * code that may occur during context establishment. It is not used to
+ * indicate supplementary status values. The MessageProp object is used
+ * for that purpose.
+ */
+ public static final int DUPLICATE_TOKEN = 20;
+
+ /**
+ * The token's validity period has expired. This is a fatal error code
+ * that may occur during context establishment. It is not used to
+ * indicate supplementary status values. The MessageProp object is used
+ * for that purpose.
+ */
+ public static final int OLD_TOKEN = 19;
+
+ /**
+ * A later token has already been processed. This is a fatal error code
+ * that may occur during context establishment. It is not used to
+ * indicate supplementary status values. The MessageProp object is used
+ * for that purpose.
+ */
+ public static final int UNSEQ_TOKEN = 21;
+
+ /**
+ * An expected per-message token was not received. This is a fatal
+ * error code that may occur during context establishment. It is not
+ * used to indicate supplementary status values. The MessageProp object
+ * is used for that purpose.
+ */
+ public static final int GAP_TOKEN = 22;
+
+ private final int major;
+ private int minor;
+ private String minorString;
+
+ private ResourceBundle messages;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Create a new GSS exception with the given major code.
+ *
+ * @param major The major GSS error code.
+ */
+ public GSSException(int major)
+ {
+ this(major, 0, null);
+ }
+
+ /**
+ * Create a new GSS exception with the given major and minor codes, and a
+ * minor explanation string.
+ *
+ * @param major The major GSS error code.
+ * @param minor The minor application-specific error code.
+ * @param minorString An explanation of the minor error code.
+ */
+ public GSSException(int major, int minor, String minorString)
+ {
+ this.major = major;
+ this.minor = minor;
+ this.minorString = minorString;
+ try
+ {
+ messages = PropertyResourceBundle.getBundle("org/ietf/jgss/MessagesBundle");
+ }
+ catch (Exception e)
+ {
+ messages = null;
+ }
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the major code representing the GSS error code that caused
+ * this exception to be thrown.
+ *
+ * @return The major error code.
+ */
+ public int getMajor()
+ {
+ return major;
+ }
+
+ /**
+ * Returns the mechanism error code that caused this exception. The
+ * minor code is set by the underlying mechanism. Value of 0 indicates
+ * that mechanism error code is not set.
+ *
+ * @return The minor error code, or 0 if not set.
+ */
+ public int getMinor()
+ {
+ return minor;
+ }
+
+ /**
+ * Returns a string explaining the GSS major error code causing this
+ * exception to be thrown.
+ *
+ * @return The major error string.
+ */
+ public String getMajorString()
+ {
+ switch (major)
+ {
+ case BAD_MECH:
+ return getMsg("GSSException.BAD_MECH",
+ "An unsupported mechanism was requested.");
+ case BAD_NAME:
+ return getMsg("GSSException.BAD_NAME",
+ "An invalid name was supplied.");
+ case BAD_NAMETYPE:
+ return getMsg("GSSException.BAD_NAMETYPE",
+ "A supplied name was of an unsupported type.");
+ case BAD_BINDINGS:
+ return getMsg("GSSException.BAD_BINDINGS",
+ "Incorrect channel bindings were supplied.");
+ case BAD_STATUS:
+ return getMsg("GSSException.BAD_STATUS",
+ "An invalid status code was supplied.");
+ case BAD_MIC:
+ return getMsg("GSSException.BAD_MIC",
+ "A token had an invalid MIC.");
+ case NO_CRED:
+ return getMsg("GSSException.NO_CRED",
+ "No credentials were supplied, or the credentials were "+
+ "unavailable or inaccessible.");
+ case NO_CONTEXT:
+ return getMsg("GSSException.NO_CONTEXT",
+ "Invalid context has been supplied.");
+ case DEFECTIVE_TOKEN:
+ return getMsg("GSSException.DEFECTIVE_TOKEN",
+ "A supplied token was invalid.");
+ case DEFECTIVE_CREDENTIAL:
+ return getMsg("GSSException.DEFECTIVE_CREDENTIAL",
+ "A supplied credential was invalid.");
+ case CREDENTIALS_EXPIRED:
+ return getMsg("GSSException.CREDENTIALS_EXPIRED",
+ "The referenced credentials have expired.");
+ case CONTEXT_EXPIRED:
+ return getMsg("GSSException.CONTEXT_EXPIRED",
+ "The context has expired.");
+ case FAILURE:
+ return getMsg("GSSException.FAILURE",
+ "Miscellaneous failure.");
+ case BAD_QOP:
+ return getMsg("GSSException.BAD_QOP",
+ "The quality-of-protection requested could not be provided.");
+ case UNAUTHORIZED:
+ return getMsg("GSSException.UNAUTHORIZED",
+ "The operation is forbidden by local security policy.");
+ case UNAVAILABLE:
+ return getMsg("GSSException.UNAVAILABLE",
+ "The operation or option is unavailable.");
+ case DUPLICATE_ELEMENT:
+ return getMsg("GSSException.DUPLICATE_ELEMENT",
+ "The requested credential element already exists.");
+ case NAME_NOT_MN:
+ return getMsg("GSSException.NAME_NOT_MN",
+ "The provided name was not a mechanism name.");
+ case OLD_TOKEN:
+ return getMsg("GSSException.OLD_TOKEN",
+ "The token's validity period has expired.");
+ case DUPLICATE_TOKEN:
+ return getMsg("GSSException.DUPLICATE_TOKEN",
+ "The token was a duplicate of an earlier version.");
+ case UNSEQ_TOKEN:
+ return getMsg("GSSException.UNSEQ_TOKEN",
+ "A later token has already been processed.");
+ case GAP_TOKEN:
+ return getMsg("GSSException.GAP_TOKEN",
+ "An expected per-message token was not received.");
+ default: return "Unknown or invalid error code.";
+ }
+ }
+
+ /**
+ * Returns a string explaining the mechanism specific error code.
+ * <code>null</code> will be returned when no mechanism error code has
+ * been set.
+ *
+ * @return The minor error string, or <code>null</code>.
+ */
+ public String getMinorString()
+ {
+ return minorString;
+ }
+
+ /**
+ * Used internally by the GSS-API implementation and the underlying
+ * mechanisms to set the minor code and its textual representation.
+ *
+ * @param minorCode The mechanism specific error code.
+ * @param message A textual explanation of the mechanism error code.
+ */
+ public void setMinor(int minorCode, String message)
+ {
+ this.minor = minorCode;
+ this.minorString = message;
+ }
+
+ /**
+ * Returns a textual representation of both the major and minor status
+ * codes.
+ *
+ * @return The textual representation.
+ */
+ public String toString()
+ {
+ return GSSException.class.getName() + ": " + getMessage();
+ }
+
+ /**
+ * Returns a detailed message of this exception. Overrides {@link
+ * Throwable#getMessage()}. It is customary in Java to use this method to
+ * obtain exception information.
+ *
+ * @return The detail message.
+ */
+ public String getMessage()
+ {
+ if (minor == 0)
+ return getMajorString();
+ else
+ return getMajorString() + " (" + minorString + ")";
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private String getMsg(String key, String defaultText)
+ {
+ if (messages != null)
+ {
+ try
+ {
+ return messages.getString(key);
+ }
+ catch (Exception e)
+ {
+ }
+ }
+ return defaultText;
+ }
+}
diff --git a/libjava/org/ietf/jgss/GSSManager.java b/libjava/org/ietf/jgss/GSSManager.java
new file mode 100644
index 00000000000..26fdd14b67d
--- /dev/null
+++ b/libjava/org/ietf/jgss/GSSManager.java
@@ -0,0 +1,501 @@
+/* GSSManager.java -- manager class for the GSS-API.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+import java.security.Provider;
+import java.security.Security;
+
+/**
+ * <p>The GSSManager class is an abstract class that serves as a factory
+ * for three GSS interfaces: {@link GSSName}, {@link GSSCredential}, and
+ * {@link GSSContext}. It also provides methods for applications to determine
+ * what mechanisms are available from the GSS implementation and what
+ * nametypes these mechanisms support. An instance of the default GSSManager
+ * subclass may be obtained through the static method {@link #getInstance()},
+ * but applications are free to instantiate other subclasses of GSSManager.</p>
+ *
+ * <p>All but one method in this class are declared abstract. This means
+ * that subclasses have to provide the complete implementation for those
+ * methods. The only exception to this is the static method {@link
+ * #getInstance()} which will have platform specific code to return an
+ * instance of the default subclass.</p>
+ *
+ * <p>Platform providers of GSS are required not to add any constructors to
+ * this class, private, public, or protected. This will ensure that all
+ * subclasses invoke only the default constructor provided to the base
+ * class by the compiler.</p>
+ *
+ * <p>A subclass extending the GSSManager abstract class may be implemented
+ * as a modular provider based layer that utilizes some well known
+ * service provider specification. The GSSManager API provides the
+ * application with methods to set provider preferences on such an
+ * implementation. These methods also allow the implementation to throw
+ * a well-defined exception in case provider based configuration is not
+ * supported. Applications that expect to be portable should be aware of
+ * this and recover cleanly by catching the exception.</p>
+ *
+ * <p>It is envisioned that there will be three most common ways in which
+ * providers will be used:</p>
+ *
+ * <ol>
+ * <li>The application does not care about what provider is used (the
+ * default case).</li>
+ *
+ * <li>The application wants a particular provider to be used
+ * preferentially, either for a particular mechanism or all the
+ * time, irrespective of mechanism.</li>
+ *
+ * <li>The application wants to use the locally configured providers
+ * as far as possible but if support is missing for one or more
+ * mechanisms then it wants to fall back on its own provider.</li>
+ * </ol>
+ *
+ * <p>The GSSManager class has two methods that enable these modes of
+ * usage: {@link #addProviderAtFront(java.security.Provider,org.ietf.jgss.Oid)}
+ * and {@link #addProviderAtEnd(java.security.Provider,org.ietf.jgss.Oid)}.
+ * These methods have the effect of creating an ordered list of
+ * (<i>provider</i>, <i>oid</i>) pairs where each pair indicates a preference
+ * of provider for a given oid.</p>
+ *
+ * <p>The use of these methods does not require any knowledge of whatever
+ * service provider specification the GSSManager subclass follows. It is
+ * hoped that these methods will serve the needs of most applications.
+ * Additional methods may be added to an extended GSSManager that could
+ * be part of a service provider specification that is standardized
+ * later.</p>
+ *
+ * <h3>Example Code</h3>
+ *
+ * <pre>
+GSSManager mgr = GSSManager.getInstance();
+
+// What mechs are available to us?
+Oid[] supportedMechs = mgr.getMechs();
+
+// Set a preference for the provider to be used when support is needed
+// for the mechanisms "1.2.840.113554.1.2.2" and "1.3.6.1.5.5.1.1".
+
+Oid krb = new Oid("1.2.840.113554.1.2.2");
+Oid spkm1 = new Oid("1.3.6.1.5.5.1.1");
+
+Provider p = (Provider) (new com.foo.security.Provider());
+
+mgr.addProviderAtFront(p, krb);
+mgr.addProviderAtFront(p, spkm1);
+
+// What name types does this spkm implementation support?
+Oid[] nameTypes = mgr.getNamesForMech(spkm1);
+</pre>
+ */
+public abstract class GSSManager
+{
+
+ // Constructor.
+ // -------------------------------------------------------------------------
+
+ public GSSManager()
+ {
+ }
+
+ // Class method.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns the default GSSManager implementation.
+ *
+ * @return The default GSSManager implementation.
+ */
+ public static synchronized GSSManager getInstance()
+ {
+ String impl = Security.getProperty("org.ietf.jgss.GSSManager");
+ if (impl == null)
+ impl = "gnu.crypto.gssapi.GSSManagerImpl";
+ try
+ {
+ ClassLoader loader = GSSManager.class.getClassLoader();
+ if (loader == null)
+ loader = ClassLoader.getSystemClassLoader();
+ Class c = loader.loadClass(impl);
+ return (GSSManager) c.newInstance();
+ }
+ catch (Exception x)
+ {
+ throw new RuntimeException(x.toString());
+ }
+ }
+
+ // Abstract methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>This method is used to indicate to the GSSManager that the
+ * application would like a particular provider to be used if no other
+ * provider can be found that supports the given mechanism. When a value
+ * of null is used instead of an Oid for the mechanism, the GSSManager
+ * must use the indicated provider for any mechanism.</p>
+ *
+ * <p>Calling this method repeatedly preserves the older settings but
+ * raises them above newer ones in preference thus forming an ordered
+ * list of providers and Oid pairs that grows at the bottom. Thus the
+ * older provider settings will be utilized first before this one is.</p>
+ *
+ * <p>If there are any previously existing preferences that conflict with
+ * the preference being set here, then the GSSManager should ignore this
+ * request.</p>
+ *
+ * <p>If the GSSManager implementation does not support an SPI with a
+ * pluggable provider architecture it should throw a GSSException with
+ * the status code {@link GSSException#UNAVAILABLE} to indicate that the
+ * operation is unavailable.</p>
+ *
+ * @param p The provider instance that should be used whenever
+ * support is needed for <i>mech</i>.
+ * @param mech The mechanism for which the provider is being set.
+ * @throws GSSException If this service is unavailable.
+ */
+ public abstract void addProviderAtEnd(Provider p, Oid mech)
+ throws GSSException;
+
+ /**
+ * <p>This method is used to indicate to the GSSManager that the
+ * application would like a particular provider to be used ahead of all
+ * others when support is desired for the given mechanism. When a value
+ * of null is used instead of an Oid for the mechanism, the GSSManager
+ * must use the indicated provider ahead of all others no matter what
+ * the mechanism is. Only when the indicated provider does not support
+ * the needed mechanism should the GSSManager move on to a different
+ * provider.</p>
+ *
+ * <p>Calling this method repeatedly preserves the older settings but
+ * lowers them in preference thus forming an ordered list of provider
+ * and Oid pairs that grows at the top.</p>
+ *
+ * <p>Calling addProviderAtFront with a null Oid will remove all previous
+ * preferences that were set for this provider in the GSSManager
+ * instance. Calling addProviderAtFront with a non-null Oid will remove
+ * any previous preference that was set using this mechanism and this
+ * provider together.</p>
+ *
+ * <p>If the GSSManager implementation does not support an SPI with a
+ * pluggable provider architecture it should throw a GSSException with
+ * the status code {@link GSSException#UNAVAILABLE} to indicate that the
+ * operation is unavailable.</p>
+ *
+ * @param p The provider instance that should be used whenever
+ * support is needed for <i>mech</i>.
+ * @param mech The mechanism for which the provider is being set.
+ * @throws GSSException If this service is unavailable.
+ */
+ public abstract void addProviderAtFront(Provider p, Oid mech)
+ throws GSSException;
+
+ /**
+ * Factory method for creating a previously exported context. The
+ * context properties will be determined from the input token and can't
+ * be modified through the set methods.
+ *
+ * @param interProcessToken The token previously emitted from the
+ * export method.
+ * @return The context.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSContext createContext(byte[] interProcessToken)
+ throws GSSException;
+
+ /**
+ * Factory method for creating a context on the acceptor' side. The
+ * context's properties will be determined from the input token supplied
+ * to the accept method.
+ *
+ * @param myCred Credentials for the acceptor. Use <code>null</code> to
+ * act as a default acceptor principal.
+ * @return The context.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSContext createContext(GSSCredential myCred)
+ throws GSSException;
+
+ /**
+ * Factory method for creating a context on the initiator's side.
+ * Context flags may be modified through the mutator methods prior to
+ * calling {@link
+ * GSSContext#initSecContext(java.io.InputStream,java.io.OutputStream)}.
+ *
+ * @param peer Name of the target peer.
+ * @param mech Oid of the desired mechanism. Use <code>null</code>
+ * to request default mechanism.
+ * @param myCred Credentials of the initiator. Use <code>null</code>
+ * default initiator principal.
+ * @param lifetime The request lifetime, in seconds, for the context.
+ * Use {@link GSSContext#INDEFINITE_LIFETIME} and
+ * {@link GSSContext#DEFAULT_LIFETIME} to request
+ * indefinite or default context lifetime.
+ * @return The context.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSContext createContext(GSSName peer, Oid mech,
+ GSSCredential myCred, int lifetime)
+ throws GSSException;
+
+ /**
+ * Factory method for acquiring default credentials. This will cause
+ * the GSS-API to use system specific defaults for the set of
+ * mechanisms, name, and a DEFAULT lifetime.
+ *
+ * @param usage The intended usage for this credential object. The
+ * value of this parameter must be one of:
+ * {@link GSSCredential#ACCEPT_AND_INITIATE},
+ * {@link GSSCredential#ACCEPT_ONLY},
+ * {@link GSSCredential#INITIATE_ONLY}.
+ * @return The credential.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSCredential createCredential(int usage) throws GSSException;
+
+ /**
+ * Factory method for acquiring a single mechanism credential.
+ *
+ * @param aName Name of the principal for whom this credential is to
+ * be acquired. Use <code>null</code> to specify the
+ * default principal.
+ * @param lifetime The number of seconds that credentials should remain
+ * valid. Use {@link GSSCredential#INDEFINITE_LIFETIME}
+ * to request that the credentials have the maximum
+ * permitted lifetime. Use {@link
+ * GSSCredential#DEFAULT_LIFETIME} to request default
+ * credential lifetime.
+ * @param mech The oid of the desired mechanism. Use <code>null</code>
+ * to request the default mechanism(s).
+ * @param usage The intended usage for this credential object. The
+ * value of this parameter must be one of:
+ * {@link GSSCredential#ACCEPT_AND_INITIATE},
+ * {@link GSSCredential#ACCEPT_ONLY},
+ * {@link GSSCredential#INITIATE_ONLY}.
+ * @return The credential.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSCredential createCredential(GSSName aName, int lifetime,
+ Oid mech, int usage)
+ throws GSSException;
+
+ /**
+ * Factory method for acquiring credentials over a set of mechanisms.
+ * Acquires credentials for each of the mechanisms specified in the
+ * array called mechs. To determine the list of mechanisms' for which
+ * the acquisition of credentials succeeded, the caller should use the
+ * {@link GSSCredential#getMechs()} method.
+ *
+ * @param aName Name of the principal for whom this credential is to
+ * be acquired. Use <code>null</code> to specify the
+ * default principal.
+ * @param lifetime The number of seconds that credentials should remain
+ * valid. Use {@link GSSCredential#INDEFINITE_LIFETIME}
+ * to request that the credentials have the maximum
+ * permitted lifetime. Use {@link
+ * GSSCredential#DEFAULT_LIFETIME} to request default
+ * credential lifetime.
+ * @param mechs The array of mechanisms over which the credential is
+ * to be acquired. Use <code>null</code> for requesting
+ * a system specific default set of mechanisms.
+ * @param usage The intended usage for this credential object. The
+ * value of this parameter must be one of:
+ * {@link GSSCredential#ACCEPT_AND_INITIATE},
+ * {@link GSSCredential#ACCEPT_ONLY},
+ * {@link GSSCredential#INITIATE_ONLY}.
+ * @return The credential.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSCredential createCredential(GSSName aName, int lifetime,
+ Oid[] mechs, int usage)
+ throws GSSException;
+
+ /**
+ * Factory method to convert a contiguous byte array containing a name
+ * from the specified namespace to a {@link GSSName} object. In general,
+ * the {@link GSSName} object created will not be an MN; two examples that
+ * are exceptions to this are when the namespace type parameter indicates
+ * {@link GSSName#NT_EXPORT_NAME} or when the GSS-API implementation is not
+ * multi-mechanism.
+ *
+ * @param name The byte array containing the name to create.
+ * @param nameType The Oid specifying the namespace of the name supplied
+ * in the byte array. Note that nameType serves to
+ * describe and qualify the interpretation of the input
+ * name byte array, it does not necessarily imply a type
+ * for the output GSSName implementation. "null" value
+ * can be used to specify that a mechanism specific
+ * default syntax should be assumed by each mechanism
+ * that examines the byte array.
+ * @return The name.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSName createName(byte[] name, Oid nameType)
+ throws GSSException;
+
+ /**
+ * Factory method to convert a contiguous byte array containing a name
+ * from the specified namespace to a GSSName object that is an MN. In
+ * other words, this method is a utility that does the equivalent of two
+ * steps: {@link #createName(byte[],org.ietf.jgss.Oid)} and then also
+ * {@link GSSName#canonicalize(org.ietf.jgss.Oid)}.
+ *
+ * @param name The byte array representing the name to create.
+ * @param nameType The Oid specifying the namespace of the name supplied
+ * in the byte array. Note that nameType serves to
+ * describe and qualify the interpretation of the input
+ * name byte array, it does not necessarily imply a type
+ * for the output GSSName implementation. "null" value
+ * can be used to specify that a mechanism specific
+ * default syntax should be assumed by each mechanism
+ * that examines the byte array.
+ * @param mech Oid specifying the mechanism for which this name
+ * should be created.
+ * @return The name.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSName createName(byte[] name, Oid nameType, Oid mech)
+ throws GSSException;
+
+ /**
+ * Factory method to convert a contiguous string name from the specified
+ * namespace to a {@link GSSName} object. In general, the {@link GSSName}
+ * object created will not be an MN; two examples that are exceptions to
+ * this are when the namespace type parameter indicates {@link
+ * GSSName#NT_EXPORT_NAME} or when the GSS-API implementation is not
+ * multi-mechanism.
+ *
+ * @param nameStr The string representing a printable form of the name
+ * to create.
+ * @param nameType The Oid specifying the namespace of the printable name
+ * supplied. Note that nameType serves to describe and
+ * qualify the interpretation of the input nameStr, it
+ * does not necessarily imply a type for the output
+ * GSSName implementation. "null" value can be used to
+ * specify that a mechanism specific default printable
+ * syntax should be assumed by each mechanism that
+ * examines nameStr.
+ * @return The name.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSName createName(String nameStr, Oid nameType)
+ throws GSSException;
+
+ /**
+ * Factory method to convert a contiguous string name from the specified
+ * namespace to an GSSName object that is a mechanism name (MN). In
+ * other words, this method is a utility that does the equivalent of two
+ * steps: the {@link #createName(java.lang.String,org.ietf.jgss.Oid)}
+ * and then also {@link GSSName#canonicalize(org.ietf.jgss.Oid)}.
+ *
+ * @param nameStr The string representing a printable form of the name
+ * to create.
+ * @param nameType The Oid specifying the namespace of the printable name
+ * supplied. Note that nameType serves to describe and
+ * qualify the interpretation of the input nameStr, it
+ * does not necessarily imply a type for the output
+ * GSSName implementation. "null" value can be used to
+ * specify that a mechanism specific default printable
+ * syntax should be assumed when the mechanism examines
+ * nameStr.
+ * @param mech Oid specifying the mechanism for which this name
+ * should be created.
+ * @return The name.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract GSSName createName(String nameStr, Oid nameType, Oid mech)
+ throws GSSException;
+
+ /**
+ * Returns an array of {@link Oid} objects indicating mechanisms available
+ * to GSS-API callers. A <code>null</code> value is returned when no
+ * mechanism are available (an example of this would be when mechanism are
+ * dynamically configured, and currently no mechanisms are installed).
+ *
+ * @return The array of available mechanisms, or <code>null</code>.
+ */
+ public abstract Oid[] getMechs();
+
+ /**
+ * Returns an array of {@link Oid} objects corresponding to the mechanisms
+ * that support the specific name type. <code>null</code> is returned when
+ * no mechanisms are found to support the specified name type.
+ *
+ * @param name The Oid object for the name type.
+ * @return The array of mechanisms, or <code>null</code>.
+ */
+ public abstract Oid[] getMechsForName(Oid name);
+
+ /**
+ * Returns name type Oid's supported by the specified mechanism.
+ *
+ * @param mechanism The Oid object for the mechanism to query.
+ * @return The name type Oid's supported by the mechanism.
+ * @throws GSSException If this operation fails.
+ */
+ public abstract Oid[] getNamesForMech(Oid mechanism) throws GSSException;
+}
diff --git a/libjava/org/ietf/jgss/GSSName.java b/libjava/org/ietf/jgss/GSSName.java
new file mode 100644
index 00000000000..fd158a90016
--- /dev/null
+++ b/libjava/org/ietf/jgss/GSSName.java
@@ -0,0 +1,269 @@
+/* GSSName.java -- a name interface for GSS.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+/**
+ * <p>This interface encapsulates a single GSS-API principal entity.
+ * Different name formats and their definitions are identified with
+ * universal Object Identifiers (Oids). The format of the names can be
+ * derived based on the unique oid of its namespace type.</p>
+ *
+ * <h3>Example Code</h3>
+ *
+ * <pre>
+GSSManager mgr = GSSManager.getInstance();
+
+// create a host based service name
+GSSName name = mgr.createName("service@host",
+ GSSName.NT_HOSTBASED_SERVICE);
+
+Oid krb5 = new Oid("1.2.840.113554.1.2.2");
+
+GSSName mechName = name.canonicalize(krb5);
+
+// the above two steps are equivalent to the following
+GSSName mechName = mgr.createName("service@host",
+ GSSName.NT_HOSTBASED_SERVICE, krb5);
+
+// perform name comparison
+if (name.equals(mechName))
+ print("Names are equal.");
+
+// obtain textual representation of name and its printable
+// name type
+print(mechName.toString() +
+ mechName.getStringNameType().toString());
+
+// export and re-import the name
+byte [] exportName = mechName.export();
+
+// create a new name object from the exported buffer
+GSSName newName = mgr.createName(exportName,
+ GSSName.NT_EXPORT_NAME);
+</pre>
+ */
+public interface GSSName
+{
+
+ // Constants.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Name type for representing an anonymous entity. It represents the
+ * following value: <code>{ 1(iso), 3(org), 6(dod), 1(internet), 5(security),
+ * 6(nametypes), 3(gss-anonymous-name) }</code>.</p>
+ */
+ Oid NT_ANONYMOUS = new Oid(new int[] { 1, 3, 6, 1, 5, 6, 3 });
+
+ /**
+ * <p>Name type used to indicate an exported name produced by the export
+ * method. It represents the following value: <code>{ 1(iso), 3(org), 6(dod),
+ * 1(internet), 5(security), 6(nametypes), 4(gss-api-exported-name)
+ * }</code>.</p>
+ */
+ Oid NT_EXPORT_NAME = new Oid(new int[] { 1, 3, 6, 1, 5, 6, 4 });
+
+ /**
+ * <p>Oid indicating a host-based service name form. It is used to
+ * represent services associated with host computers. This name form is
+ * constructed using two elements, "service" and "hostname", as follows:</p>
+ *
+ * <blockquote><code>service@hostname</code></blockquote>
+ *
+ * <p>Values for the "service" element are registered with the IANA. It
+ * represents the following value: <code>{ 1(iso), 3(org), 6(dod),
+ * 1(internet), 5(security), 6(nametypes), 2(gss-host-based-services)
+ * }</code>.</p>
+ */
+ Oid NT_HOSTBASED_SERVICE = new Oid(new int[] { 1, 3, 6, 1, 5, 6, 2 });
+
+ /**
+ * <p>Name type to indicate a numeric user identifier corresponding to a
+ * user on a local system. (e.g. Uid). It represents the following
+ * value: <code>{ iso(1) member-body(2) United States(840) mit(113554)
+ * infosys(1) gssapi(2) generic(1) machine_uid_name(2) }</code>.</p>
+ */
+ Oid NT_MACHINE_UID_NAME = new Oid(new int[] { 1, 2, 840, 113554, 1, 2, 1, 2 });
+
+ /**
+ * <p>Name type to indicate a string of digits representing the numeric
+ * user identifier of a user on a local system. It represents the
+ * following value: <code>{ iso(1) member-body(2) United States(840)
+ * mit(113554) infosys(1) gssapi(2) generic(1) string_uid_name(3)
+ * }</code>.</p>
+ */
+ Oid NT_STRING_UID_NAME = new Oid(new int[] { 1, 2, 840, 113554, 1, 2, 1, 3 });
+
+ /**
+ * <p>Name type to indicate a named user on a local system. It represents
+ * the following value: <code>{ iso(1) member-body(2) United States(840)
+ * mit(113554) infosys(1) gssapi(2) generic(1) user_name(1) }</code>.</p>
+ */
+ Oid NT_USER_NAME = new Oid(new int[] { 1, 2, 840, 113554, 1, 2, 1, 1 });
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Compares two GSSName objects to determine whether they refer to the
+ * same entity. This method may throw a {@link GSSException} when the
+ * names cannot be compared. If either of the names represents an
+ * anonymous entity, the method will return <code>false</code>.
+ *
+ * @param another GSSName object to compare with.
+ * @return True if this name equals the other, and if neither name
+ * represents an anonymous entity.
+ * @throws GSSException If the names cannot be compared.
+ */
+ boolean equals(GSSName another) throws GSSException;
+
+ /**
+ * A variation of the {@link #equals(org.ietf.jgss.GSSName)} method that
+ * is provided to override the {@link Object#equals(java.lang.Object)}
+ * method that the implementing class will inherit. The behavior is
+ * exactly the same as that in the other equals method except that no
+ * {@link GSSException} is thrown; instead, <code>false</code> will be
+ * returned in the situation where an error occurs. (Note that the Java
+ * language specification requires that two objects that are equal
+ * according to the {@link Object#equals(java.lang.Object)} method must
+ * return the same integer when the {@link hashCode()} method is called
+ * on them.
+ *
+ * @param another GSSName object to compare with.
+ * @return True if this name equals the other, if neither name
+ * represents an anonymous entity, or if an error occurs.
+ */
+ boolean equals(Object another);
+
+ /**
+ * Creates a mechanism name (MN) from an arbitrary internal name. This
+ * is equivalent to using the factory methods {@link
+ * GSSManager#createName(java.lang.String,org.ietf.jgss.Oid,org.ietf.jgss.Oid)}
+ * or {@link
+ * GSSManager#createName(byte[],org.ietf.jgss.Oid,org.ietf.jgss.Oid)}.
+ *
+ * @param mech The oid for the mechanism for which the canonical form
+ * of the name is requested.
+ * @return The mechanism name.
+ * @throws GSSException If this operation fails.
+ */
+ GSSName canonicalize(Oid mech) throws GSSException;
+
+ /**
+ * Returns a canonical contiguous byte representation of a mechanism
+ * name (MN), suitable for direct, byte by byte comparison by
+ * authorization functions. If the name is not an MN, implementations
+ * may throw a {@link GSSException} with the {@link GSSException#NAME_NOT_MN}
+ * status code. If an implementation chooses not to throw an exception,
+ * it should use some system specific default mechanism to canonicalize
+ * the name and then export it. The format of the header of the output
+ * buffer is specified in <a
+ * href="http://www.ietf.org/rfc/rfc2743.txt">RFC 2743</a>.
+ *
+ * @return The exported name.
+ * @throws GSSException If the name is not an MN and the implementation
+ * throws an exception for this case.
+ */
+ byte[] export() throws GSSException;
+
+ /**
+ * Returns a textual representation of the GSSName object. To retrieve
+ * the printed name format, which determines the syntax of the returned
+ * string, the {@link #getStringNameType()} method can be used.
+ *
+ * @return The textual representation of the GSSName object.
+ */
+ String toString();
+
+ /**
+ * Returns the oid representing the type of name returned through the
+ * {@link #toString()} method. Using this oid, the syntax of the printable
+ * name can be determined.
+ *
+ * @return The name type.
+ * @throws GSSException If this operation fails.
+ */
+ Oid getStringNameType() throws GSSException;
+
+ /**
+ * Tests if this name object represents an anonymous entity. Returns
+ * <code>true</code> if this is an anonymous name.
+ *
+ * @return True if this name represents an anonymous entity.
+ */
+ boolean isAnonymous();
+
+ /**
+ * Tests if this name object contains only one mechanism element and is
+ * thus a mechanism name as defined by <a
+ * href="http://www.ietf.org/rfc/rfc2743.txt">RFC 2743</a>.
+ *
+ * @return True if this name is a mechanism name.
+ */
+ boolean isMN();
+}
diff --git a/libjava/org/ietf/jgss/MessageProp.java b/libjava/org/ietf/jgss/MessageProp.java
new file mode 100644
index 00000000000..a3fd22e55a8
--- /dev/null
+++ b/libjava/org/ietf/jgss/MessageProp.java
@@ -0,0 +1,273 @@
+/* MessageProp.java -- GSS-API message property.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+/**
+ * <p>This is a utility class used within the per-message {@link
+ * GSSContext} methods to convey per-message properties.</p>
+ *
+ * <p>When used with the GSSContext interface's {@link
+ * GSSContext#wrap(byte[],int,int,org.ietf.jgss.MessageProp)} and {@link
+ * GSSContext#getMIC(byte[],int,int,org.ietf.jgss.MessageProp)} methods, an
+ * instance of this class is used to indicate the desired QOP and to
+ * request if confidentiality services are to be applied to caller
+ * supplied data (wrap only). To request default QOP, the value of 0
+ * should be used for QOP.</p>
+ *
+ * <p>When used with the {@link
+ * GSSContext#unwrap(byte[],int,int,org.ietf.jgss.MessageProp)} and {@link
+ * GSSContext#verifyMIC(byte[],int,int,byte[],int,int,org.ietf.jgss.MessageProp)}
+ * methods of the GSSContext interface, an instance of this class will be
+ * used to indicate the applied QOP and confidentiality services over the
+ * supplied message. In the case of verifyMIC, the confidentiality state
+ * will always be "false". Upon return from these methods, this object will
+ * also contain any supplementary status values applicable to the processed
+ * token. The supplementary status values can indicate old tokens, out
+ * of sequence tokens, gap tokens or duplicate tokens.</p>
+ */
+public class MessageProp
+{
+
+ // Fields.
+ // -------------------------------------------------------------------------
+
+ private int qopVal;
+ private boolean privState;
+ private boolean duplicate;
+ private boolean old;
+ private boolean unseq;
+ private boolean gap;
+ private int minorStatus;
+ private String minorString;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ /**
+ * <p>Constructor which sets QOP to 0 indicating that the default QOP is
+ * requested.</p>
+ *
+ * @param privState The desired privacy state. "true" for privacy and
+ * "false" for integrity only.
+ */
+ public MessageProp(boolean privState)
+ {
+ this(0, privState);
+ }
+
+ /**
+ * <p>Constructor which sets the values for the qop and privacy state.</p>
+ *
+ * @param qop The desired QOP. Use 0 to request a default QOP.
+ * @param privState The desired privacy state. "true" for privacy and
+ * "false" for integrity only.
+ */
+ public MessageProp(int qop, boolean privState)
+ {
+ this.qopVal = qop;
+ this.privState = privState;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Retrieves the QOP value.
+ *
+ * @return The QOP value.
+ */
+ public int getQOP()
+ {
+ return qopVal;
+ }
+
+ /**
+ * Retrieves the privacy state.
+ *
+ * @return The privacy state.
+ */
+ public boolean getPrivacy()
+ {
+ return privState;
+ }
+
+ /**
+ * Retrieves the minor status that the underlying mechanism might have
+ * set.
+ *
+ * @return The minor status.
+ */
+ public int getMinorStatus()
+ {
+ return minorStatus;
+ }
+
+ /**
+ * Returns a string explaining the mechanism specific error code.
+ * <code>null</code> will be returned when no mechanism error code has
+ * been set.
+ *
+ * @return The minor status string.
+ */
+ public String getMinorString()
+ {
+ return minorString;
+ }
+
+ /**
+ * Sets the QOP value.
+ *
+ * @param qopVal The QOP value to be set. Use 0 to request a default
+ * QOP value.
+ */
+ public void setQOP(int qopVal)
+ {
+ this.qopVal = qopVal;
+ }
+
+ /**
+ * Sets the privacy state.
+ *
+ * @param privState The privacy state to set.
+ */
+ public void setPrivacy(boolean privState)
+ {
+ this.privState = privState;
+ }
+
+ /**
+ * Returns "true" if this is a duplicate of an earlier token.
+ *
+ * @return True if this is a duplicate of an earlier token.
+ */
+ public boolean isDuplicateToken()
+ {
+ return duplicate;
+ }
+
+ /**
+ * Returns "true" if the token's validity period has expired.
+ *
+ * @return True if the token's validity period has expired.
+ */
+ public boolean isOldToken()
+ {
+ return old;
+ }
+
+ /**
+ * Returns "true" if a later token has already been processed.
+ *
+ * @return True if a later token has already been processed.
+ */
+ public boolean isUnseqToken()
+ {
+ return unseq;
+ }
+
+ /**
+ * Returns "true" if an expected per-message token was not received.
+ *
+ * @return True if an expected per-message token was not received.
+ */
+ public boolean isGapToken()
+ {
+ return gap;
+ }
+
+ /**
+ * This method sets the state for the supplementary information flags
+ * and the minor status in MessageProp. It is not used by the
+ * application but by the GSS implementation to return this information
+ * to the caller of a per-message context method.
+ *
+ * @param duplicate True if the token was a duplicate of an earlier
+ * token, false otherwise.
+ * @param old True if the token's validity period has expired,
+ * false otherwise.
+ * @param unseq True if a later token has already been processed,
+ * false otherwise.
+ * @param gap True if one or more predecessor tokens have not yet
+ * been successfully processed, false otherwise.
+ * @param minorStatus The integer minor status code that the underlying
+ * mechanism wants to set.
+ * @param minorString The textual representation of the minorStatus
+ * value.
+ */
+ public void setSupplementaryStates(boolean duplicate, boolean old,
+ boolean unseq, boolean gap,
+ int minorStatus, String minorString)
+ {
+ this.duplicate = duplicate;
+ this.old = old;
+ this.unseq = unseq;
+ this.gap = gap;
+ this.minorStatus = minorStatus;
+ this.minorString = minorString;
+ }
+}
diff --git a/libjava/org/ietf/jgss/MessagesBundle.properties b/libjava/org/ietf/jgss/MessagesBundle.properties
new file mode 100644
index 00000000000..af8247cbff8
--- /dev/null
+++ b/libjava/org/ietf/jgss/MessagesBundle.properties
@@ -0,0 +1,60 @@
+# MessagesBundle.properties -- English GSS messages.
+# Copyright (C) 2004 Free Software Foundation, Inc.
+#
+# This file is a part of GNU Classpath.
+#
+# GNU Classpath is free software; you can redistribute it and/or
+# modify it under the terms of the GNU General Public License as
+# published by the Free Software Foundation; either version 2 of the
+# License, or (at your option) any later version.
+#
+# GNU Classpath is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+# General Public License for more details.
+#
+# You should have received a copy of the GNU General Public License
+# along with GNU Classpath; if not, write to the Free Software
+# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
+# USA
+#
+# Linking this library statically or dynamically with other modules is
+# making a combined work based on this library. Thus, the terms and
+# conditions of the GNU General Public License cover the whole
+# combination.
+#
+# As a special exception, the copyright holders of this library give
+# you permission to link this library with independent modules to
+# produce an executable, regardless of the license terms of these
+# independent modules, and to copy and distribute the resulting
+# executable under terms of your choice, provided that you also meet,
+# for each linked independent module, the terms and conditions of the
+# license of that module. An independent module is a module which is
+# not derived from or based on this library. If you modify this
+# library, you may extend this exception to your version of the
+# library, but you are not obligated to do so. If you do not wish to
+# do so, delete this exception statement from your version.
+
+GSSException.BAD_MECH=An unsupported mechanism was requested.
+GSSException.BAD_NAME=An invalid name was supplied.
+GSSException.BAD_NAMETYPE=A supplied name was of an unsupported type.
+GSSException.BAD_BINDINGS=Incorrect channel bindings were supplied.
+GSSException.BAD_STATUS=An invalid status code was supplied.
+GSSException.BAD_MIC=A token had an invalid MIC.
+GSSException.NO_CRED=No credentials were supplied, or the credentials were unavailable or inaccessible.
+GSSException.NO_CONTEXT=Invalid context has been supplied.
+GSSException.DEFECTIVE_TOKEN=A supplied token was invalid.
+GSSException.DEFECTIVE_CREDENTIAL=A supplied credential was invalid.
+GSSException.CREDENTIALS_EXPIRED=The referenced credentials have expired.
+GSSException.CONTEXT_EXPIRED=The context has expired.
+GSSException.FAILURE=Miscellaneous failure.
+GSSException.BAD_QOP=The quality-of-protection requested could not be provided.
+GSSException.UNAUTHORIZED=The operation is forbidden by local security policy.
+GSSException.UNAVAILABLE=The operation or option is unavailable.
+GSSException.DUPLICATE_ELEMENT=The requested credential element already exists.
+GSSException.NAME_NOT_MN=The provided name was not a mechanism name.
+GSSException.OLD_TOKEN=The token\'s validity period has expired.
+GSSException.DUPLICATE_TOKEN=The token was a duplicate of an earlier version.
+GSSException.UNSEQ_TOKEN=A later token has already been processed.
+GSSException.GAP_TOKEN=An expected per-message token was not received.
+
diff --git a/libjava/org/ietf/jgss/Oid.java b/libjava/org/ietf/jgss/Oid.java
new file mode 100644
index 00000000000..a7c67a7103a
--- /dev/null
+++ b/libjava/org/ietf/jgss/Oid.java
@@ -0,0 +1,385 @@
+/* Oid.java -- Object identifier class.
+ Copyright (C) 2004 Free Software Foundation, Inc.
+
+This file is part of GNU Classpath.
+
+GNU Classpath is free software; you can redistribute it and/or modify
+it under the terms of the GNU General Public License as published by
+the Free Software Foundation; either version 2, or (at your option)
+any later version.
+
+GNU Classpath is distributed in the hope that it will be useful, but
+WITHOUT ANY WARRANTY; without even the implied warranty of
+MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+General Public License for more details.
+
+You should have received a copy of the GNU General Public License
+along with GNU Classpath; see the file COPYING. If not, write to the
+Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
+02111-1307 USA.
+
+Linking this library statically or dynamically with other modules is
+making a combined work based on this library. Thus, the terms and
+conditions of the GNU General Public License cover the whole
+combination.
+
+As a special exception, the copyright holders of this library give you
+permission to link this library with independent modules to produce an
+executable, regardless of the license terms of these independent
+modules, and to copy and distribute the resulting executable under
+terms of your choice, provided that you also meet, for each linked
+independent module, the terms and conditions of the license of that
+module. An independent module is a module which is not derived from
+or based on this library. If you modify this library, you may extend
+this exception to your version of the library, but you are not
+obligated to do so. If you do not wish to do so, delete this
+exception statement from your version. */
+
+/* The documentation comments of this class are derived from the text
+ of RFC 2853: Generic Security Service API Version 2: Java Bindings.
+ That document is covered under the following license notice:
+
+Copyright (C) The Internet Society (2000). All Rights Reserved.
+
+This document and translations of it may be copied and furnished to
+others, and derivative works that comment on or otherwise explain it
+or assist in its implementation may be prepared, copied, published and
+distributed, in whole or in part, without restriction of any kind,
+provided that the above copyright notice and this paragraph are
+included on all such copies and derivative works. However, this
+document itself may not be modified in any way, such as by removing
+the copyright notice or references to the Internet Society or other
+Internet organizations, except as needed for the purpose of developing
+Internet standards in which case the procedures for copyrights defined
+in the Internet Standards process must be followed, or as required to
+translate it into languages other than English.
+
+The limited permissions granted above are perpetual and will not be
+revoked by the Internet Society or its successors or assigns.
+
+This document and the information contained herein is provided on an
+"AS IS" basis and THE INTERNET SOCIETY AND THE INTERNET ENGINEERING
+TASK FORCE DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT
+NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE INFORMATION HEREIN
+WILL NOT INFRINGE ANY RIGHTS OR ANY IMPLIED WARRANTIES OF
+MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. */
+
+
+package org.ietf.jgss;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+
+import java.math.BigInteger;
+
+import java.util.Arrays;
+import java.util.StringTokenizer;
+
+/**
+ * <p>This class represents Universal Object Identifiers (Oids) and their
+ * associated operations.</p>
+ *
+ * <p>Oids are hierarchically globally-interpretable identifiers used
+ * within the GSS-API framework to identify mechanisms and name formats.</p>
+ *
+ * <p>The structure and encoding of Oids is defined in ISOIEC-8824 and
+ * ISOIEC-8825. For example the Oid representation of Kerberos V5
+ * mechanism is "1.2.840.113554.1.2.2".</p>
+ *
+ * <p>The {@link GSSName} name class contains <code>public static Oid</code>
+ * objects representing the standard name types defined in GSS-API.</p>
+ */
+public class Oid
+{
+
+ // Constants and fields.
+ // -------------------------------------------------------------------------
+
+ private static final int OBJECT_IDENTIFIER = 0x06;
+ private static final int RELATIVE_OID = 0x0d;
+
+ private final int[] components;
+ private byte[] derOid;
+ private String strOid;
+ private boolean relative;
+
+ // Constructors.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Creates an Oid object from a string representation of its integer
+ * components (e.g. "1.2.840.113554.1.2.2").
+ *
+ * @param strOid The string representation for the oid.
+ * @throws GSSException If the argument is badly formed.
+ */
+ public Oid(String strOid) throws GSSException
+ {
+ if (strOid == null)
+ throw new NullPointerException();
+ this.strOid = strOid;
+ try
+ {
+ StringTokenizer tok = new StringTokenizer(strOid, ".");
+ components = new int[tok.countTokens()];
+ int i = 0;
+ while (tok.hasMoreTokens() && i < components.length)
+ {
+ components[i++] = Integer.parseInt(tok.nextToken());
+ }
+ }
+ catch (Exception x)
+ {
+ throw new GSSException(GSSException.FAILURE);
+ }
+ relative = false;
+ }
+
+ /**
+ * Creates an Oid object from its DER encoding. This refers to the full
+ * encoding including tag and length. The structure and encoding of
+ * Oids is defined in ISOIEC-8824 and ISOIEC-8825. This method is
+ * identical in functionality to its byte array counterpart.
+ *
+ * @param derOid Stream containing the DER encoded oid.
+ * @throws GSSException If the DER stream is badly formed, or if the
+ * input stream throws an exception.
+ */
+ public Oid(InputStream derOid) throws GSSException
+ {
+ DataInputStream in = new DataInputStream(derOid);
+ try
+ {
+ int tag = in.read() & 0x1F;
+ if (tag != OBJECT_IDENTIFIER && tag != RELATIVE_OID)
+ throw new IOException();
+ int len = in.read();
+ if ((len & ~0x7F) != 0)
+ {
+ byte[] buf = new byte[len & 0x7F];
+ in.readFully(buf);
+ len = new BigInteger(1, buf).intValue();
+ }
+ if (len < 0)
+ throw new IOException();
+ byte[] enc = new byte[len];
+ in.readFully(enc);
+ int[] comp = new int[len + 1];
+ int count = 0;
+ int i = 0;
+ relative = tag == RELATIVE_OID;
+ if (!relative && i < len)
+ {
+ int j = (enc[i] & 0xFF);
+ comp[count++] = j / 40;
+ comp[count++] = j % 40;
+ i++;
+ }
+ while (i < len)
+ {
+ int j = 0;
+ do
+ {
+ j = enc[i++] & 0xFF;
+ comp[count] <<= 7;
+ comp[count] |= j & 0x7F;
+ if (i >= len && (j & 0x80) != 0)
+ throw new IOException();
+ }
+ while ((j & 0x80) != 0);
+ count++;
+ }
+ if (count == len)
+ this.components = comp;
+ else
+ {
+ this.components = new int[count];
+ System.arraycopy(comp, 0, components, 0, count);
+ }
+ }
+ catch (IOException ioe)
+ {
+ throw new GSSException(GSSException.FAILURE);
+ }
+ }
+
+ /**
+ * Creates an Oid object from its DER encoding. This refers to the full
+ * encoding including tag and length. The structure and encoding of
+ * Oids is defined in ISOIEC-8824 and ISOIEC-8825. This method is
+ * identical in functionality to its streaming counterpart.
+ *
+ * @param derOid Byte array storing a DER encoded oid.
+ * @throws GSSException If the DER bytes are badly formed.
+ */
+ public Oid(byte[] derOid) throws GSSException
+ {
+ this(new ByteArrayInputStream(derOid));
+ this.derOid = (byte[]) derOid.clone();
+ }
+
+ Oid(int[] components)
+ {
+ this.components = components;
+ relative = false;
+ }
+
+ // Instance methods.
+ // -------------------------------------------------------------------------
+
+ /**
+ * Returns a string representation of the oid's integer components in
+ * dot separated notation (e.g. "1.2.840.113554.1.2.2").
+ *
+ * @return The string representation of this oid.
+ */
+ public String toString()
+ {
+ if (strOid == null)
+ {
+ StringBuffer buf = new StringBuffer();
+ for (int i = 0; i < components.length; i++)
+ {
+ buf.append(components[i]);
+ if (i < components.length - 1)
+ buf.append('.');
+ }
+ strOid = buf.toString();
+ }
+ return strOid;
+ }
+
+ /**
+ * Returns the full ASN.1 DER encoding for this oid object, which
+ * includes the tag and length.
+ *
+ * @return The ASN.1 DER encoding for this oid.
+ * @throws GSSException If encoding fails.
+ */
+ public byte[] getDER() throws GSSException
+ {
+ if (derOid == null)
+ {
+ ByteArrayOutputStream out = new ByteArrayOutputStream(256);
+ try
+ {
+ int i = 0;
+ if (!relative)
+ {
+ int b = components[i++] * 40 + (components.length > 1
+ ? components[i++] : 0);
+ encodeSubId(out, b);
+ }
+ for ( ; i < components.length; i++)
+ encodeSubId(out, components[i]);
+ byte[] oid = out.toByteArray();
+ out.reset();
+ if (relative)
+ out.write(RELATIVE_OID);
+ else
+ out.write(OBJECT_IDENTIFIER);
+ if (oid.length < 128)
+ out.write(oid.length);
+ else if (oid.length < 256)
+ {
+ out.write(0x81);
+ out.write(oid.length);
+ }
+ else if (oid.length < 65536)
+ {
+ out.write(0x82);
+ out.write((oid.length >>> 8) & 0xFF);
+ out.write(oid.length & 0xFF);
+ }
+ else if (oid.length < 16777216)
+ {
+ out.write(0x83);
+ out.write((oid.length >>> 16) & 0xFF);
+ out.write((oid.length >>> 8) & 0xFF);
+ out.write(oid.length & 0xFF);
+ }
+ else
+ {
+ out.write(0x84);
+ out.write((oid.length >>> 24) & 0xFF);
+ out.write((oid.length >>> 16) & 0xFF);
+ out.write((oid.length >>> 8) & 0xFF);
+ out.write(oid.length & 0xFF);
+ }
+ out.write(oid);
+ }
+ catch (IOException ioe)
+ {
+ throw new GSSException(GSSException.FAILURE);
+ }
+ derOid = out.toByteArray();
+ }
+ return (byte[]) derOid.clone();
+ }
+
+ /**
+ * A utility method to test if an Oid object is contained within the
+ * supplied Oid object array.
+ *
+ * @param oids An array of oids to search.
+ * @return True if this oid is contained in the given array.
+ */
+ public boolean containedIn(Oid[] oids)
+ {
+ for (int i = 0; i < oids.length; i++)
+ {
+ if (equals(oids[i]))
+ return true;
+ }
+ return false;
+ }
+
+ public boolean equals(Object o)
+ {
+ if (!(o instanceof Oid))
+ return false;
+ Oid that = (Oid) o;
+ return Arrays.equals(components, that.components);
+ }
+
+ public int hashCode()
+ {
+ int code = 0;
+ for (int i = 0; i < components.length; i++)
+ code += components[i];
+ return code;
+ }
+
+ // Own methods.
+ // -------------------------------------------------------------------------
+
+ private static void encodeSubId(OutputStream out, int id) throws IOException
+ {
+ if (id < 128)
+ {
+ out.write(id);
+ }
+ else if (id < 16384)
+ {
+ out.write((id >>> 7) | 0x80);
+ out.write(id & 0x7F);
+ }
+ else if (id < 2097152)
+ {
+ out.write((id >>> 14) | 0x80);
+ out.write(((id >>> 7) | 0x80) & 0xFF);
+ out.write(id & 0x7F);
+ }
+ else if (id < 268435456)
+ {
+ out.write( (id >>> 21) | 0x80);
+ out.write(((id >>> 14) | 0x80) & 0xFF);
+ out.write(((id >>> 7) | 0x80) & 0xFF);
+ out.write(id & 0x7F);
+ }
+ }
+}
diff --git a/libjava/testsuite/libjava.compile/AssertBug.java b/libjava/testsuite/libjava.compile/AssertBug.java
new file mode 100644
index 00000000000..3938b11da28
--- /dev/null
+++ b/libjava/testsuite/libjava.compile/AssertBug.java
@@ -0,0 +1,7 @@
+// PR java/16927
+public class AssertBug {
+ public void bug(Integer i) {
+ assert(false):
+ i.toString() + "!";
+ }
+}
diff --git a/libjava/testsuite/libjava.compile/pr15656.java b/libjava/testsuite/libjava.compile/pr15656.java
new file mode 100644
index 00000000000..4076c9f6870
--- /dev/null
+++ b/libjava/testsuite/libjava.compile/pr15656.java
@@ -0,0 +1,8 @@
+// This used to cause a gcj crash in error_if_numeric_overflow.
+
+public class pr15656 {
+ public static void defineClass ()
+ {
+ Object ctor = new Object;
+ }
+}
diff --git a/libjava/testsuite/libjava.compile/pr15656.xfail b/libjava/testsuite/libjava.compile/pr15656.xfail
new file mode 100644
index 00000000000..e3b083b1fa5
--- /dev/null
+++ b/libjava/testsuite/libjava.compile/pr15656.xfail
@@ -0,0 +1 @@
+shouldfail
diff --git a/libjava/testsuite/libjava.compile/pr17329.java b/libjava/testsuite/libjava.compile/pr17329.java
new file mode 100644
index 00000000000..fa31f18a726
--- /dev/null
+++ b/libjava/testsuite/libjava.compile/pr17329.java
@@ -0,0 +1,14 @@
+// gcj had a problem with "SomeClass.field++" when gimplifying.
+
+class helper
+{
+ static int value;
+}
+
+public class pr17329
+{
+ static void doit ()
+ {
+ helper.value += 2;
+ }
+}
diff --git a/libjava/testsuite/libjava.compile/pr17500.java b/libjava/testsuite/libjava.compile/pr17500.java
new file mode 100644
index 00000000000..825133dc1bd
--- /dev/null
+++ b/libjava/testsuite/libjava.compile/pr17500.java
@@ -0,0 +1,28 @@
+// gcj had a problem compiling code where two anonymous classes had
+// captured constructor arguments of the same type but with different
+// names.
+
+public class pr17500
+{
+ public Object m1 (final Object one)
+ {
+ return new Comparable()
+ {
+ public int compareTo(Object other)
+ {
+ return one == other ? 0 : 1;
+ }
+ };
+ }
+
+ public Object m2 (final Object two)
+ {
+ return new Comparable()
+ {
+ public int compareTo(Object other)
+ {
+ return two == other ? 0 : 1;
+ }
+ };
+ }
+}
diff --git a/libjava/testsuite/libjava.lang/pr16789.java b/libjava/testsuite/libjava.lang/pr16789.java
new file mode 100644
index 00000000000..64c43f30417
--- /dev/null
+++ b/libjava/testsuite/libjava.lang/pr16789.java
@@ -0,0 +1,15 @@
+// gcj used to generate incorrect bytecode for
+// staticMethod().staticMethod()
+public class pr16789
+{
+ public void foo()
+ {
+ System.out.println(Thread.currentThread().holdsLock(this));
+ }
+
+ public static void main(String[] args)
+ {
+ new pr16789().foo();
+ }
+}
+
diff --git a/libjava/testsuite/libjava.lang/pr16789.out b/libjava/testsuite/libjava.lang/pr16789.out
new file mode 100644
index 00000000000..c508d5366f7
--- /dev/null
+++ b/libjava/testsuite/libjava.lang/pr16789.out
@@ -0,0 +1 @@
+false
diff --git a/libstdc++-v3/testsuite/21_strings/basic_string/element_access/char/empty.cc b/libstdc++-v3/testsuite/21_strings/basic_string/element_access/char/empty.cc
new file mode 100644
index 00000000000..37c9420bc13
--- /dev/null
+++ b/libstdc++-v3/testsuite/21_strings/basic_string/element_access/char/empty.cc
@@ -0,0 +1,48 @@
+// Copyright (C) 2004 Free Software Foundation, Inc.
+//
+// This file is part of the GNU ISO C++ Library. This library is free
+// software; you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the
+// Free Software Foundation; either version 2, or (at your option)
+// any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this library; see the file COPYING. If not, write to the Free
+// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+// As a special exception, you may use this file as part of a free software
+// library without restriction. Specifically, if other files instantiate
+// templates or use macros or inline functions from this file, or you compile
+// this file and link it with other files to produce an executable, this
+// file does not by itself cause the resulting executable to be covered by
+// the GNU General Public License. This exception does not however
+// invalidate any other reasons why the executable file might be covered by
+// the GNU General Public License.
+
+#include <string>
+#include <testsuite_hooks.h>
+
+// as per 21.3.4
+int main()
+{
+ bool test __attribute__((unused)) = true;
+
+ {
+ std::string empty;
+ char c = empty[0];
+ VERIFY( c == char() );
+ }
+
+ {
+ const std::string empty;
+ char c = empty[0];
+ VERIFY( c == char() );
+ }
+ return 0;
+}
diff --git a/libstdc++-v3/testsuite/21_strings/basic_string/element_access/wchar_t/empty.cc b/libstdc++-v3/testsuite/21_strings/basic_string/element_access/wchar_t/empty.cc
new file mode 100644
index 00000000000..b0391691dac
--- /dev/null
+++ b/libstdc++-v3/testsuite/21_strings/basic_string/element_access/wchar_t/empty.cc
@@ -0,0 +1,48 @@
+// Copyright (C) 2004 Free Software Foundation, Inc.
+//
+// This file is part of the GNU ISO C++ Library. This library is free
+// software; you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the
+// Free Software Foundation; either version 2, or (at your option)
+// any later version.
+//
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+//
+// You should have received a copy of the GNU General Public License along
+// with this library; see the file COPYING. If not, write to the Free
+// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+//
+// As a special exception, you may use this file as part of a free software
+// library without restriction. Specifically, if other files instantiate
+// templates or use macros or inline functions from this file, or you compile
+// this file and link it with other files to produce an executable, this
+// file does not by itself cause the resulting executable to be covered by
+// the GNU General Public License. This exception does not however
+// invalidate any other reasons why the executable file might be covered by
+// the GNU General Public License.
+
+#include <string>
+#include <testsuite_hooks.h>
+
+// as per 21.3.4
+int main()
+{
+ bool test __attribute__((unused)) = true;
+
+ {
+ std::wstring empty;
+ wchar_t c = empty[0];
+ VERIFY( c == wchar_t() );
+ }
+
+ {
+ const std::wstring empty;
+ wchar_t c = empty[0];
+ VERIFY( c == wchar_t() );
+ }
+ return 0;
+}
diff --git a/libstdc++-v3/testsuite/21_strings/basic_string/operations/char/1.cc b/libstdc++-v3/testsuite/21_strings/basic_string/operations/char/1.cc
new file mode 100644
index 00000000000..5194be7f5e2
--- /dev/null
+++ b/libstdc++-v3/testsuite/21_strings/basic_string/operations/char/1.cc
@@ -0,0 +1,42 @@
+// Copyright (C) 2004 Free Software Foundation, Inc.
+//
+// This file is part of the GNU ISO C++ Library. This library is free
+// software; you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the
+// Free Software Foundation; either version 2, or (at your option)
+// any later version.
+
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License along
+// with this library; see the file COPYING. If not, write to the Free
+// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+
+// 21.3.6 string operations
+
+#include <string>
+#include <testsuite_hooks.h>
+
+int test01(void)
+{
+ bool test __attribute__((unused)) = true;
+
+ std::string empty;
+
+ // data() for size == 0 is non-NULL.
+ VERIFY( empty.size() == 0 );
+ const std::string::value_type* p = empty.data();
+ VERIFY( p != NULL );
+
+ return 0;
+}
+
+int main()
+{
+ test01();
+ return 0;
+}
diff --git a/libstdc++-v3/testsuite/21_strings/basic_string/operations/wchar_t/1.cc b/libstdc++-v3/testsuite/21_strings/basic_string/operations/wchar_t/1.cc
new file mode 100644
index 00000000000..86374ccdf6a
--- /dev/null
+++ b/libstdc++-v3/testsuite/21_strings/basic_string/operations/wchar_t/1.cc
@@ -0,0 +1,42 @@
+// Copyright (C) 2004 Free Software Foundation, Inc.
+//
+// This file is part of the GNU ISO C++ Library. This library is free
+// software; you can redistribute it and/or modify it under the
+// terms of the GNU General Public License as published by the
+// Free Software Foundation; either version 2, or (at your option)
+// any later version.
+
+// This library is distributed in the hope that it will be useful,
+// but WITHOUT ANY WARRANTY; without even the implied warranty of
+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+// GNU General Public License for more details.
+
+// You should have received a copy of the GNU General Public License along
+// with this library; see the file COPYING. If not, write to the Free
+// Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307,
+// USA.
+
+// 21.3.6 string operations
+
+#include <string>
+#include <testsuite_hooks.h>
+
+int test01(void)
+{
+ bool test __attribute__((unused)) = true;
+
+ std::wstring empty;
+
+ // data() for size == 0 is non-NULL.
+ VERIFY( empty.size() == 0 );
+ const std::wstring::value_type* p = empty.data();
+ VERIFY( p != NULL );
+
+ return 0;
+}
+
+int main()
+{
+ test01();
+ return 0;
+}