diff --git a/.hgtags b/.hgtags index 85783d82daebd9442a1c15034c8088b16da63740..1a27baa7cacebee57bcf880d40956730cf3894b2 100644 --- a/.hgtags +++ b/.hgtags @@ -45,3 +45,5 @@ a952aafd5181af953b0ef3010dbd2fcc28460e8a jdk7-b67 b23d905cb5d3b382295240d28ab0bfb266b4503c jdk7-b68 226b20019b1f020c09ea97d137d98e011ce65d76 jdk7-b69 893bcca951b747ddcf6986362b877f0e1dbb835b jdk7-b70 +b3f3240135f0c10b9f2481c174b81b7fcf0daa60 jdk7-b71 +460639b036f327282832a4fe52b7aa45688afd50 jdk7-b72 diff --git a/README b/README index e3cc63ec993be85b2eb12e21d38d3e1a16f007f4..d774ab80b70466958efc3ae02347b54eb84fc1b5 100644 --- a/README +++ b/README @@ -9,35 +9,25 @@ Simple Build Instructions: http://java.sun.com/javase/downloads/index.jsp Set the environment variable ALT_BOOTDIR to the location of this JDK 6. - 2. Download and install the JIBX libraries, version 1.1.5 from - http://sourceforge.net/project/showfiles.php?group_id=69358&package_id=68290 - You'll need the following four JAR files: - bcel.jar - jibx-bind.jar - jibx-run.jar - xpp3.jar - Set the environment variable ALT_JIBX_LIBS_PATH to the location of - these JAR files. - - 3. Download and install the Binary Plugs for the most recent JDK7 from + 2. Download and install the Binary Plugs for the most recent JDK7 from http://download.java.net/openjdk/jdk7/ Set the environment variable ALT_BINARY_PLUGS_PATH to the location of these binary plugs. - 4. Either download and install the latest JDK7 from + 3. Either download and install the latest JDK7 from http://download.java.net/openjdk/jdk7/, or build your own complete OpenJDK7 by using the top level Makefile in the OpenJDK Mercurial forest. Set the environment variable ALT_JDK_IMPORT_PATH to the location of this latest JDK7 or OpenJDK7 build. - 5. Check the sanity of doing a build with the current machine: + 4. Check the sanity of doing a build with the current machine: cd make && gnumake sanity See README-builds.html if you run into problems. - 6. Do a partial build of the jdk: + 5. Do a partial build of the jdk: cd make && gnumake all - 7. Construct the images: + 6. Construct the images: cd make && gnumake images The resulting JDK image should be found in build/*/j2sdk-image diff --git a/make/common/Sanity.gmk b/make/common/Sanity.gmk index aa15361ff71990adcbb278c448d27b517856a5d1..a136e6d8d34f314fe30f622b9d6492961e774e73 100644 --- a/make/common/Sanity.gmk +++ b/make/common/Sanity.gmk @@ -93,8 +93,7 @@ sanity-all:: sanity-base \ sane-alt_bootdir \ sane-bootdir \ sane-local-bootdir \ - sane-alsa-headers \ - sane-jibx + sane-alsa-headers ifdef OPENJDK sanity-all:: sane-freetype diff --git a/make/common/shared/Defs-java.gmk b/make/common/shared/Defs-java.gmk index 9d918af877dfe6b2c80a932544d01eba86b29abf..f9ed635313135f7d95d0102244c53c1724389337 100644 --- a/make/common/shared/Defs-java.gmk +++ b/make/common/shared/Defs-java.gmk @@ -201,7 +201,10 @@ endif ifeq ($(JAVAC_WARNINGS_FATAL), true) BOOT_JAVACFLAGS += -Werror endif -BOOT_JAVACFLAGS += -encoding ascii + +BOOT_SOURCE_LANGUAGE_VERSION = 6 +BOOT_TARGET_CLASS_VERSION = 6 +BOOT_JAVACFLAGS += -encoding ascii -source $(BOOT_SOURCE_LANGUAGE_VERSION) -target $(BOOT_TARGET_CLASS_VERSION) BOOT_JAR_JFLAGS += $(JAR_JFLAGS) BOOT_JAVACFLAGS += $(NO_PROPRIETARY_API_WARNINGS) diff --git a/make/common/shared/Defs.gmk b/make/common/shared/Defs.gmk index 199d07668218a995c27281934b00f2470e9c229e..2ad6fd4a19f497f2469f7b80efb9b24ae2797d2f 100644 --- a/make/common/shared/Defs.gmk +++ b/make/common/shared/Defs.gmk @@ -536,15 +536,6 @@ endif # NOTE: ISA_DIR is usually empty, on Solaris it might be /sparcv9 or /amd64 BINDIR = $(OUTPUTDIR)/bin$(ISA_DIR) -# JIBX_LIBS_PATH: path to JIBX libraries, needed for NimbusLookAndFeel -ifdef ALT_JIBX_LIBS_PATH - JIBX_LIBS_PATH:=$(call FullPath,$(ALT_JIBX_LIBS_PATH)) - JIBX_LIBS_PATH:=$(call AltCheckSpaces,JIBX_LIBS_PATH) - JIBX_LIBS_PATH:=$(call AltCheckValue,JIBX_LIBS_PATH) -else - JIBX_LIBS_PATH=$(JDK_DEVTOOLS_DIR)/share/jibx/lib -endif - # MOZILLA_HEADERS_PATH: path to mozilla header files for plugin ifdef ALT_MOZILLA_HEADERS_PATH MOZILLA_HEADERS_PATH :=$(call FullPath,$(ALT_MOZILLA_HEADERS_PATH)) diff --git a/make/common/shared/Sanity-Settings.gmk b/make/common/shared/Sanity-Settings.gmk index 283598e394db424f6cac63f832dddac05129209e..b64e3b52a136a931d3230425feebadcd5fad802b 100644 --- a/make/common/shared/Sanity-Settings.gmk +++ b/make/common/shared/Sanity-Settings.gmk @@ -233,7 +233,6 @@ ifeq ($(PLATFORM),windows) endif endif ALL_SETTINGS+=$(call addAltSetting,CACERTS_FILE) -ALL_SETTINGS+=$(call addAltSetting,JIBX_LIBS_PATH) ifndef OPENJDK ALL_SETTINGS+=$(call addAltSetting,MOZILLA_HEADERS_PATH) endif diff --git a/make/common/shared/Sanity.gmk b/make/common/shared/Sanity.gmk index 87d9120b1a4cc6b57130ad301ef25f49a8ea44f0..e8b19c942ebf03e2ec14a73070787f0152b03415 100644 --- a/make/common/shared/Sanity.gmk +++ b/make/common/shared/Sanity.gmk @@ -214,7 +214,6 @@ include $(JDK_MAKE_SHARED_DIR)/Sanity-Settings.gmk sane-link \ sane-cacerts \ sane-alsa-headers \ - sane-jibx \ sane-ant_version \ sane-zip_version \ sane-unzip_version \ @@ -1516,22 +1515,6 @@ ifeq ($(PLATFORM), solaris) endif -###################################################### -# JIBX_LIBS_PATH must be valid -###################################################### -sane-jibx: -ifdef DISABLE_NIMBUS - $(call SanityWarning,Disabling Nimbus will remove public API in javax.swing.plaf.nimbus.) -else - @if [ ! -r $(subst \,/,$(JIBX_LIBS_PATH))/jibx-run.jar ]; then \ - $(ECHO) "ERROR: You do not have access to valid JIBX library files. \n" \ - " Please check your access to \n" \ - " $(subst \,/,$(JIBX_LIBS_PATH))/jibx-run.jar \n" \ - " and/or check your value of ALT_JDK_DEVTOOLS_DIR, ALT_JIBX_LIBS_PATH \n" \ - "" >> $(ERROR_FILE) ; \ - fi -endif - ###################################################### # MOZILLA_HEADERS_PATH must be valid ###################################################### diff --git a/make/java/java/FILES_java.gmk b/make/java/java/FILES_java.gmk index e8a2223f67a53e64f6f21a5fdc2fec1dc84639ba..2ad599cbe235749e97c5128835fc249191bce42c 100644 --- a/make/java/java/FILES_java.gmk +++ b/make/java/java/FILES_java.gmk @@ -454,6 +454,8 @@ JAVA_JAVA_java = \ sun/misc/JavaLangAccess.java \ sun/misc/JavaIOAccess.java \ sun/misc/JavaIOFileDescriptorAccess.java \ - sun/misc/JavaNioAccess.java + sun/misc/JavaNioAccess.java \ + sun/misc/Perf.java \ + sun/misc/PerfCounter.java FILES_java = $(JAVA_JAVA_java) diff --git a/make/java/logging/Makefile b/make/java/logging/Makefile index c6ed1879fecd64bf9d36d4fe0f2dc8061e5bef7e..444c1c63b5a76d35c182dd7667240ada67a58b8d 100644 --- a/make/java/logging/Makefile +++ b/make/java/logging/Makefile @@ -31,7 +31,7 @@ include $(BUILDDIR)/common/Defs.gmk # # Files to compile. # -AUTO_FILES_JAVA_DIRS = java/util/logging +AUTO_FILES_JAVA_DIRS = java/util/logging sun/util/logging # # Resources @@ -46,7 +46,6 @@ RESOURCE_BUNDLES_COMPILED_PROPERTIES = \ include $(BUILDDIR)/common/Classes.gmk properties: $(LIBDIR)/logging.properties - $(LIBDIR)/logging.properties: $(SHARE_SRC)/lib/logging.properties $(install-file) diff --git a/make/javax/swing/plaf/Makefile b/make/javax/swing/plaf/Makefile index cf3bf0aa2745470ee0a647f95759237a961381d5..c0c5ebecc70a0bf4e65b7a25688a1f2c84633298 100644 --- a/make/javax/swing/plaf/Makefile +++ b/make/javax/swing/plaf/Makefile @@ -34,16 +34,14 @@ include $(BUILDDIR)/common/Defs.gmk # include FILES.gmk AUTO_FILES_JAVA_DIRS = javax/swing/plaf sun/swing com/sun/java/swing/plaf -ifndef DISABLE_NIMBUS - SUBDIRS = nimbus -endif - -# Nimbus is handled in its own directory -AUTO_JAVA_PRUNE = nimbus ifeq ($(PLATFORM), windows) # Don't build GTK L&F on Windows - AUTO_JAVA_PRUNE += gtk + AUTO_JAVA_PRUNE = gtk +endif + +ifdef DISABLE_NIMBUS + AUTO_JAVA_PRUNE += nimbus endif MISC_FILES = $(MISC_SWING_FILES) @@ -52,6 +50,10 @@ ifneq ($(PLATFORM), windows) MISC_FILES += $(MISC_SWING_FILES_UNIX) endif +NIMBUS_GENSRC_DIR = $(GENSRCDIR)/javax/swing/plaf/nimbus +NIMBUS_SKIN_FILE = $(SWING_SRC)/plaf/nimbus/skin.laf +NIMBUS_GENERATOR_JAR = $(BUILDTOOLJARDIR)/generatenimbus.jar + FILES_java = $(FILES_SWING_java) # @@ -75,14 +77,25 @@ endif # Process LOGO_ICONS and Motif Icons first. # build: $(LOGO_ICONS) $(MISC_SWING_FILES_MOTIF_GIF) $(MISC_SWING_FILES_MOTIF_PNG) other_files - $(SUBDIRS-loop) -clean clobber:: - $(SUBDIRS-loop) +$(NIMBUS_GENSRC_DIR): $(NIMBUS_SKIN_FILE) $(NIMBUS_GENERATOR_JAR) + @$(ECHO) "Generating Nimbus source files:" + $(RM) -r $(NIMBUS_GENSRC_DIR) + $(BOOT_JAVA_CMD) -jar $(NIMBUS_GENERATOR_JAR) \ + -skinFile $(NIMBUS_SKIN_FILE) -buildDir $(GENSRCDIR) \ + -packagePrefix $(PACKAGE).nimbus -lafName Nimbus + @$(ECHO) "Finished generating Nimbus source files" + +clean:: classes.clean + $(RM) -r $(NIMBUS_GENSRC_DIR) # # Include # +ifndef DISABLE_NIMBUS + CLASSES_INIT = $(NIMBUS_GENSRC_DIR) +endif + include $(BUILDDIR)/common/Classes.gmk ifndef OPENJDK diff --git a/make/sun/javazic/tzdata/VERSION b/make/sun/javazic/tzdata/VERSION index 373805077ff36156afb1c90fd918f36552785e9f..17a8a1b2984e5d062beb86036f1de34d2133961f 100644 --- a/make/sun/javazic/tzdata/VERSION +++ b/make/sun/javazic/tzdata/VERSION @@ -21,4 +21,4 @@ # CA 95054 USA or visit www.sun.com if you need additional information or # have any questions. # -tzdata2009g +tzdata2009l diff --git a/make/sun/javazic/tzdata/africa b/make/sun/javazic/tzdata/africa index 072bc251c1d04de0f515c79c88719b7884ff736d..2032f3862d74a4a443501361a7b7aabd7ea1ce12 100644 --- a/make/sun/javazic/tzdata/africa +++ b/make/sun/javazic/tzdata/africa @@ -22,6 +22,8 @@ # have any questions. # #
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # This data is by no means authoritative; if you think you know better,
 # go ahead and edit the file (and please send any changes to
@@ -263,18 +265,18 @@ Rule	Egypt	2007	only	-	Sep	Thu>=1	23:00s	0	-
 # The following appeared in Red Hat bugzilla[1] (edited):
 #
 # > $ zdump -v /usr/share/zoneinfo/Africa/Cairo | grep 2009
-# > /usr/share/zoneinfo/Africa/Cairo  Thu Apr 23 21:59:59 2009 UTC =3D Thu =
+# > /usr/share/zoneinfo/Africa/Cairo  Thu Apr 23 21:59:59 2009 UTC = Thu =
 # Apr 23
-# > 23:59:59 2009 EET isdst=3D0 gmtoff=3D7200
-# > /usr/share/zoneinfo/Africa/Cairo  Thu Apr 23 22:00:00 2009 UTC =3D Fri =
+# > 23:59:59 2009 EET isdst=0 gmtoff=7200
+# > /usr/share/zoneinfo/Africa/Cairo  Thu Apr 23 22:00:00 2009 UTC = Fri =
 # Apr 24
-# > 01:00:00 2009 EEST isdst=3D1 gmtoff=3D10800
-# > /usr/share/zoneinfo/Africa/Cairo  Thu Aug 27 20:59:59 2009 UTC =3D Thu =
+# > 01:00:00 2009 EEST isdst=1 gmtoff=10800
+# > /usr/share/zoneinfo/Africa/Cairo  Thu Aug 27 20:59:59 2009 UTC = Thu =
 # Aug 27
-# > 23:59:59 2009 EEST isdst=3D1 gmtoff=3D10800
-# > /usr/share/zoneinfo/Africa/Cairo  Thu Aug 27 21:00:00 2009 UTC =3D Thu =
+# > 23:59:59 2009 EEST isdst=1 gmtoff=10800
+# > /usr/share/zoneinfo/Africa/Cairo  Thu Aug 27 21:00:00 2009 UTC = Thu =
 # Aug 27
-# > 23:00:00 2009 EET isdst=3D0 gmtoff=3D7200
+# > 23:00:00 2009 EET isdst=0 gmtoff=7200
 #
 # > end date should be Thu Sep 24 2009 (Last Thursday in September at 23:59=
 # :59)
@@ -282,11 +284,11 @@ Rule	Egypt	2007	only	-	Sep	Thu>=1	23:00s	0	-
 #
 # timeanddate[2] and another site I've found[3] also support that.
 #
-# [1] 
-# https://bugzilla.redhat.com/show_bug.cgi?id=3D492263
+# [1] 
+# https://bugzilla.redhat.com/show_bug.cgi?id=492263
 # 
-# [2] 
-# http://www.timeanddate.com/worldclock/clockchange.html?n=3D53
+# [2] 
+# http://www.timeanddate.com/worldclock/clockchange.html?n=53
 # 
 # [3] 
 # http://wwp.greenwichmeantime.com/time-zone/africa/egypt/
@@ -296,8 +298,27 @@ Rule	Egypt	2007	only	-	Sep	Thu>=1	23:00s	0	-
 # In 2009 (and for the next several years), Ramadan ends before the fourth
 # Thursday in September; Egypt is expected to revert to the last Thursday
 # in September.
+
+# From Steffen Thorsen (2009-08-11):
+# We have been able to confirm the August change with the Egyptian Cabinet 
+# Information and Decision Support Center:
+# 
+# http://www.timeanddate.com/news/time/egypt-dst-ends-2009.html
+# 
+# 
+# The Middle East News Agency
+# 
+# http://www.mena.org.eg/index.aspx
+# 
+# also reports "Egypt starts winter time on August 21"
+# today in article numbered "71, 11/08/2009 12:25 GMT." 
+# Only the title above is available without a subscription to their service,
+# and can be found by searching for "winter" in their search engine
+# (at least today).
+
 Rule	Egypt	2008	only	-	Aug	lastThu	23:00s	0	-
-Rule	Egypt	2009	max	-	Sep	lastThu	23:00s	0	-
+Rule	Egypt	2009	only	-	Aug	20	23:00s	0	-
+Rule	Egypt	2010	max	-	Sep	lastThu	23:00s	0	-
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Africa/Cairo	2:05:00 -	LMT	1900 Oct
@@ -499,8 +520,8 @@ Zone Africa/Nouakchott	-1:03:48 -	LMT	1912
 
 # From Riad M. Hossen Ally (2008-08-03):
 # The Government of Mauritius weblink
-# 
-# http://www.gov.mu/portal/site/pmosite/menuitem.4ca0efdee47462e7440a600248a521ca/?content_id=3D4728ca68b2a5b110VgnVCM1000000a04a8c0RCRD
+# 
+# http://www.gov.mu/portal/site/pmosite/menuitem.4ca0efdee47462e7440a600248a521ca/?content_id=4728ca68b2a5b110VgnVCM1000000a04a8c0RCRD
 # 
 # Cabinet Decision of July 18th, 2008 states as follows:
 #
@@ -522,11 +543,33 @@ Zone Africa/Nouakchott	-1:03:48 -	LMT	1912
 # http://www.gov.mu/portal/goc/assemblysite/file/bill2708.pdf
 # 
 
+# From Steffen Thorsen (2009-06-05):
+# According to several sources, Mauritius will not continue to observe
+# DST the coming summer...
+#
+# Some sources, in French:
+# 
+# http://www.defimedia.info/news/946/Rashid-Beebeejaun-:-%C2%AB-L%E2%80%99heure-d%E2%80%99%C3%A9t%C3%A9-ne-sera-pas-appliqu%C3%A9e-cette-ann%C3%A9e-%C2%BB
+# 
+# 
+# http://lexpress.mu/Story/3398~Beebeejaun---Les-objectifs-d-%C3%A9conomie-d-%C3%A9nergie-de-l-heure-d-%C3%A9t%C3%A9-ont-%C3%A9t%C3%A9-atteints-
+# 
+#
+# Our wrap-up:
+# 
+# http://www.timeanddate.com/news/time/mauritius-dst-will-not-repeat.html
+# 
+
+# From Arthur David Olson (2009-07-11):
+# The "mauritius-dst-will-not-repeat" wrapup includes this: 
+# "The trial ended on March 29, 2009, when the clocks moved back by one hour
+# at 2am (or 02:00) local time..."
+
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule Mauritius	1982	only	-	Oct	10	0:00	1:00	S
 Rule Mauritius	1983	only	-	Mar	21	0:00	0	-
-Rule Mauritius	2008	max	-	Oct	lastSun	2:00s	1:00	S
-Rule Mauritius	2009	max	-	Mar	lastSun	2:00s	0	-
+Rule Mauritius	2008	only	-	Oct	lastSun	2:00	1:00	S
+Rule Mauritius	2009	only	-	Mar	lastSun	2:00	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Indian/Mauritius	3:50:00 -	LMT	1907		# Port Louis
 			4:00 Mauritius	MU%sT	# Mauritius Time
diff --git a/make/sun/javazic/tzdata/antarctica b/make/sun/javazic/tzdata/antarctica
index bed6d441938c56e1976ed39e947c3a21e4042247..31a624b0e101448d33b7c21b2b31d7ab3a78fd42 100644
--- a/make/sun/javazic/tzdata/antarctica
+++ b/make/sun/javazic/tzdata/antarctica
@@ -22,6 +22,8 @@
 # have any questions.
 #
 # 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # From Paul Eggert (1999-11-15):
 # To keep things manageable, we list only locations occupied year-round; see
diff --git a/make/sun/javazic/tzdata/asia b/make/sun/javazic/tzdata/asia
index 64e6b0504a0a00e08760301c9cac520b862943a0..81534b919a44d20827ead361026d86bb7570ba96 100644
--- a/make/sun/javazic/tzdata/asia
+++ b/make/sun/javazic/tzdata/asia
@@ -22,6 +22,8 @@
 # have any questions.
 #
 # 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # This data is by no means authoritative; if you think you know better,
 # go ahead and edit the file (and please send any changes to
@@ -147,6 +149,57 @@ Zone	Asia/Bahrain	3:22:20 -	LMT	1920		# Al Manamah
 			3:00	-	AST
 
 # Bangladesh
+# From Alexander Krivenyshev (2009-05-13):
+# According to newspaper Asian Tribune (May 6, 2009) Bangladesh may introduce
+# Daylight Saving Time from June 16 to Sept 30
+#
+# Bangladesh to introduce daylight saving time likely from June 16
+# 
+# http://www.asiantribune.com/?q=node/17288
+# 
+# or
+# 
+# http://www.worldtimezone.com/dst_news/dst_news_bangladesh02.html
+# 
+#
+# "... Bangladesh government has decided to switch daylight saving time from
+# June
+# 16 till September 30 in a bid to ensure maximum use of daylight to cope with
+# crippling power crisis. "
+#
+# The switch will remain in effect from June 16 to Sept 30 (2009) but if
+# implemented the next year, it will come in force from April 1, 2010
+
+# From Steffen Thorsen (2009-06-02):
+# They have finally decided now, but changed the start date to midnight between
+# the 19th and 20th, and they have not set the end date yet.
+#
+# Some sources:
+# 
+# http://in.reuters.com/article/southAsiaNews/idINIndia-40017620090601
+# 
+# 
+# http://bdnews24.com/details.php?id=85889&cid=2
+# 
+#
+# Our wrap-up:
+# 
+# http://www.timeanddate.com/news/time/bangladesh-daylight-saving-2009.html
+# 
+
+# From A. N. M. Kamrus Saadat (2009-06-15):
+# Finally we've got the official mail regarding DST start time where DST start 
+# time is mentioned as Jun 19 2009, 23:00 from BTRC (Bangladesh 
+# Telecommunication Regulatory Commission). 
+#
+# No DST end date has been announced yet.
+
+# From Arthur David Olson (2009-07-11):
+# Arbitrarily end DST at the end of 2009 so that a POSIX-sytle time zone string
+# can appear in the Dhaka binary file and for the benefit of old glibc
+# reimplementations of the time zone software that mishandle permanent DST.
+# A change will be required once the end date is known.
+
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Dhaka	6:01:40 -	LMT	1890
 			5:53:20	-	HMT	1941 Oct    # Howrah Mean Time?
@@ -154,7 +207,9 @@ Zone	Asia/Dhaka	6:01:40 -	LMT	1890
 			5:30	-	IST	1942 Sep
 			6:30	-	BURT	1951 Sep 30
 			6:00	-	DACT	1971 Mar 26 # Dacca Time
-			6:00	-	BDT	# Bangladesh Time
+			6:00	-	BDT	2009 Jun 19 23:00 # Bangladesh Time
+			6:00	1:00	BDST	2010
+			6:00	-	BDT
 
 # Bhutan
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -1129,7 +1184,7 @@ Rule	Jordan	1995	1998	-	Sep	Fri>=15	0:00s	0	-
 Rule	Jordan	1999	only	-	Jul	 1	0:00s	1:00	S
 Rule	Jordan	1999	2002	-	Sep	lastFri	0:00s	0	-
 Rule	Jordan	2000	2001	-	Mar	lastThu	0:00s	1:00	S
-Rule	Jordan	2002	max	-	Mar	lastFri	0:00s	1:00	S
+Rule	Jordan	2002	max	-	Mar	lastThu	24:00	1:00	S
 Rule	Jordan	2003	only	-	Oct	24	0:00s	0	-
 Rule	Jordan	2004	only	-	Oct	15	0:00s	0	-
 Rule	Jordan	2005	only	-	Sep	lastFri	0:00s	0	-
diff --git a/make/sun/javazic/tzdata/australasia b/make/sun/javazic/tzdata/australasia
index 823550415e0a765bb202def9001b532cccb395a1..8e336dcea30fe15c7209d1a076a10041d489134d 100644
--- a/make/sun/javazic/tzdata/australasia
+++ b/make/sun/javazic/tzdata/australasia
@@ -22,6 +22,8 @@
 # have any questions.
 #
 # 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # This file also includes Pacific islands.
 
@@ -447,6 +449,22 @@ Zone Pacific/Pago_Pago	 12:37:12 -	LMT	1879 Jul  5
 			-11:00	-	SST			# S=Samoa
 
 # Samoa
+
+# From Alexander Krivenyshev (2008-12-06):
+# The Samoa government (Western Samoa) may implement DST on the first Sunday of 
+# October 2009 (October 4, 2009) until the last Sunday of March 2010 (March 28, 
+# 2010). 
+# 
+# "Selected Committee reports to Cabinet on Daylight Saving Time",
+# Government of Samoa:
+# 
+# http://www.govt.ws/pr_article.cfm?pr_id=560
+# 
+# or
+# 
+# http://www.worldtimezone.com/dst_news/dst_news_samoa01.html
+# 
+
 Zone Pacific/Apia	 12:33:04 -	LMT	1879 Jul  5
 			-11:26:56 -	LMT	1911
 			-11:30	-	SAMT	1950		# Samoa Time
@@ -1141,6 +1159,27 @@ Zone	Pacific/Wallis	12:15:20 -	LMT	1901
 # From Paul Eggert (2007-07-23):
 # See "southeast Australia" above for 2008 and later.
 
+# From Steffen Thorsen (2009-04-28):
+# According to the official press release, South Australia's extended daylight 
+# saving period will continue with the same rules as used during the 2008-2009 
+# summer (southern hemisphere).
+# 
+# From
+# 
+# http://www.safework.sa.gov.au/uploaded_files/DaylightDatesSet.pdf
+# 
+# The extended daylight saving period that South Australia has been trialling 
+# for over the last year is now set to be ongoing.
+# Daylight saving will continue to start on the first Sunday in October each 
+# year and finish on the first Sunday in April the following year.
+# Industrial Relations Minister, Paul Caica, says this provides South Australia 
+# with a consistent half hour time difference with NSW, Victoria, Tasmania and 
+# the ACT for all 52 weeks of the year...
+# 
+# We have a wrap-up here:
+# 
+# http://www.timeanddate.com/news/time/south-australia-extends-dst.html
+# 
 ###############################################################################
 
 # New Zealand
diff --git a/make/sun/javazic/tzdata/backward b/make/sun/javazic/tzdata/backward
index 57bb988bc9942ffa307a7132942a4e1e5fcecb90..8a53120f78bccfefc5cc9c65f54142c8ca423010 100644
--- a/make/sun/javazic/tzdata/backward
+++ b/make/sun/javazic/tzdata/backward
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # This file provides links between current names for time zones
 # and their old names.  Many names changed in late 1993.
diff --git a/make/sun/javazic/tzdata/etcetera b/make/sun/javazic/tzdata/etcetera
index 28ae4445ef03824aeb8bbbb7b6ee11e69fb29574..9583d16428d35ee6d68dbdcc911d32fbbe235dca 100644
--- a/make/sun/javazic/tzdata/etcetera
+++ b/make/sun/javazic/tzdata/etcetera
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # These entries are mostly present for historical reasons, so that
 # people in areas not otherwise covered by the tz files could "zic -l"
diff --git a/make/sun/javazic/tzdata/europe b/make/sun/javazic/tzdata/europe
index a80f1bc9cffe3608f556fcb701615ce54b37d3f2..16dbe0ee500e089a17b578f83fd38d3710946cba 100644
--- a/make/sun/javazic/tzdata/europe
+++ b/make/sun/javazic/tzdata/europe
@@ -22,6 +22,8 @@
 # have any questions.
 #
 # 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # This data is by no means authoritative; if you think you know better,
 # go ahead and edit the file (and please send any changes to
@@ -479,7 +481,7 @@ Rule	EU	1979	1995	-	Sep	lastSun	 1:00u	0	-
 Rule	EU	1981	max	-	Mar	lastSun	 1:00u	1:00	S
 Rule	EU	1996	max	-	Oct	lastSun	 1:00u	0	-
 # The most recent directive covers the years starting in 2002.  See:
-# 
+# 
 # Directive 2000/84/EC of the European Parliament and of the Council
 # of 19 January 2001 on summer-time arrangements.
 # 
diff --git a/make/sun/javazic/tzdata/factory b/make/sun/javazic/tzdata/factory
index 3842b9b08d7c4a22853a76a2987266f8c6e14409..244234f23eab39270db052bfded023084b21f2f4 100644
--- a/make/sun/javazic/tzdata/factory
+++ b/make/sun/javazic/tzdata/factory
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # For companies who don't want to put time zone specification in
 # their installation procedures.  When users run date, they'll get the message.
diff --git a/make/sun/javazic/tzdata/iso3166.tab b/make/sun/javazic/tzdata/iso3166.tab
index 6931ee04a716aeb588b6aba9749ae220d904f9f1..01de3059ed387ca78fb1cbd4340c71444d96f88b 100644
--- a/make/sun/javazic/tzdata/iso3166.tab
+++ b/make/sun/javazic/tzdata/iso3166.tab
@@ -21,9 +21,11 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 # ISO 3166 alpha-2 country codes
 #
-#
 # From Paul Eggert (2006-09-27):
 #
 # This file contains a table with the following columns:
diff --git a/make/sun/javazic/tzdata/leapseconds b/make/sun/javazic/tzdata/leapseconds
index ab4f97377fd123661fd89dad39443f267cc34ac2..6a84f2db12f942b9464ec8fb18c41ea88ccc8ffe 100644
--- a/make/sun/javazic/tzdata/leapseconds
+++ b/make/sun/javazic/tzdata/leapseconds
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # Allowance for leapseconds added to each timezone file.
 
@@ -75,13 +78,13 @@ Leap	2008	Dec	31	23:59:60	+	S
 # SERVICE DE LA ROTATION TERRESTRE
 # OBSERVATOIRE DE PARIS
 # 61, Av. de l'Observatoire 75014 PARIS (France)
-# Tel.      : 33 (0) 1 40 51 22 29
+# Tel.      : 33 (0) 1 40 51 22 26
 # FAX       : 33 (0) 1 40 51 22 91
 # Internet  : services.iers@obspm.fr
 #
-# Paris, 15 January 2009
+# Paris, 4 July 2009
 #
-# Bulletin C 37
+# Bulletin C 38
 #
 # To authorities responsible
 # for the measurement and
@@ -89,7 +92,7 @@ Leap	2008	Dec	31	23:59:60	+	S
 #
 # INFORMATION ON UTC - TAI
 #
-# NO positive leap second will be introduced at the end of June 2009.
+# NO positive leap second will be introduced at the end of December 2009.
 # The difference between Coordinated Universal Time UTC and the
 # International Atomic Time TAI is :		
 #
@@ -101,6 +104,6 @@ Leap	2008	Dec	31	23:59:60	+	S
 # will be no time step at the next possible date.
 #
 # Daniel GAMBIS
-# Head			
-# Earth Orientation Center of the IERS
+# Director			
+# Earth Orientation Center of IERS
 # Observatoire de Paris, France
diff --git a/make/sun/javazic/tzdata/northamerica b/make/sun/javazic/tzdata/northamerica
index a4dd95217b583b36a607e512e2b090bf793f644e..1b8cb7a27edbbfbd611205e85cc1c3cc15049518 100644
--- a/make/sun/javazic/tzdata/northamerica
+++ b/make/sun/javazic/tzdata/northamerica
@@ -22,6 +22,8 @@
 # have any questions.
 #
 # 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # also includes Central America and the Caribbean
 
diff --git a/make/sun/javazic/tzdata/pacificnew b/make/sun/javazic/tzdata/pacificnew
index 5cc43873d3cb49e2557d5bbe29f26e3a4173bc17..7ad10d9b8bb03a781686fdfeb8dde94caa28c855 100644
--- a/make/sun/javazic/tzdata/pacificnew
+++ b/make/sun/javazic/tzdata/pacificnew
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # From Arthur David Olson (1989-04-05):
 # On 1989-04-05, the U. S. House of Representatives passed (238-154) a bill
diff --git a/make/sun/javazic/tzdata/solar87 b/make/sun/javazic/tzdata/solar87
index 6e3bfe5027dde1b5573c733cb4f98e936227b363..ca1be9c4f40d5ee040ed30b9a162149603ab4596 100644
--- a/make/sun/javazic/tzdata/solar87
+++ b/make/sun/javazic/tzdata/solar87
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # So much for footnotes about Saudi Arabia.
 # Apparent noon times below are for Riyadh; your mileage will vary.
diff --git a/make/sun/javazic/tzdata/solar88 b/make/sun/javazic/tzdata/solar88
index e5d3265c5802a5c35b43390d3b578f6a214cdb0a..f1d018c4545c70fc30a3a96a37753fb47f404d19 100644
--- a/make/sun/javazic/tzdata/solar88
+++ b/make/sun/javazic/tzdata/solar88
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # Apparent noon times below are for Riyadh; they're a bit off for other places.
 # Times were computed using formulas in the U.S. Naval Observatory's
diff --git a/make/sun/javazic/tzdata/solar89 b/make/sun/javazic/tzdata/solar89
index 4805c9e98886aec0ba72241c4c9e28adb18e0d40..c76873fec10fee1c22f68ce077e034164b2d6b8d 100644
--- a/make/sun/javazic/tzdata/solar89
+++ b/make/sun/javazic/tzdata/solar89
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # Apparent noon times below are for Riyadh; they're a bit off for other places.
 # Times were computed using a formula provided by the U. S. Naval Observatory:
diff --git a/make/sun/javazic/tzdata/southamerica b/make/sun/javazic/tzdata/southamerica
index 7da29e0925de5b48c52e25d7d4e09d01869d3923..c886a28b1263de0629c63c3b6674f5c044ed54ee 100644
--- a/make/sun/javazic/tzdata/southamerica
+++ b/make/sun/javazic/tzdata/southamerica
@@ -22,6 +22,8 @@
 # have any questions.
 #
 # 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # This data is by no means authoritative; if you think you know better,
 # go ahead and edit the file (and please send any changes to
@@ -696,8 +698,8 @@ Zone	America/La_Paz	-4:32:36 -	LMT	1890
 
 # From Rodrigo Severo (2008-06-24):
 # Just correcting the URL:
-# 
-# https://www.in.gov.br/imprensa/visualiza/index.jsp?jornal=3Ddo&secao=3D1&pagina=3D1&data=3D25/04/2008
+# 
+# https://www.in.gov.br/imprensa/visualiza/index.jsp?jornal=do&secao=1&pagina=1&data=25/04/2008
 # 
 #
 # As a result of the above Decree I believe the America/Rio_Branco
diff --git a/make/sun/javazic/tzdata/systemv b/make/sun/javazic/tzdata/systemv
index e0604dc3f9d6dc97059d20d3bec43f6541aaae6e..152734e30299172dc2803867304e797bbf1d8df0 100644
--- a/make/sun/javazic/tzdata/systemv
+++ b/make/sun/javazic/tzdata/systemv
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 
 # Old rules, should the need arise.
 # No attempt is made to handle Newfoundland, since it cannot be expressed
diff --git a/make/sun/javazic/tzdata/zone.tab b/make/sun/javazic/tzdata/zone.tab
index 467367e2d72eea7c50cdcfdee0f522528f345496..2a323ebb90ef172802ae7845d2333b90b55edebe 100644
--- a/make/sun/javazic/tzdata/zone.tab
+++ b/make/sun/javazic/tzdata/zone.tab
@@ -21,6 +21,9 @@
 # CA 95054 USA or visit www.sun.com if you need additional information or
 # have any questions.
 #
+# 
+# This file is in the public domain, so clarified as of
+# 2009-05-17 by Arthur David Olson.
 #
 # TZ zone descriptions
 #
@@ -123,7 +126,7 @@ BR	-0640-06952	America/Eirunepe	W Amazonas
 BR	-0958-06748	America/Rio_Branco	Acre
 BS	+2505-07721	America/Nassau
 BT	+2728+08939	Asia/Thimphu
-BW	-2545+02555	Africa/Gaborone
+BW	-2439+02555	Africa/Gaborone
 BY	+5354+02734	Europe/Minsk
 BZ	+1730-08812	America/Belize
 CA	+4734-05243	America/St_Johns	Newfoundland Time, including SE Labrador
@@ -307,7 +310,7 @@ MY	+0310+10142	Asia/Kuala_Lumpur	peninsular Malaysia
 MY	+0133+11020	Asia/Kuching	Sabah & Sarawak
 MZ	-2558+03235	Africa/Maputo
 NA	-2234+01706	Africa/Windhoek
-NC	-2216+16530	Pacific/Noumea
+NC	-2216+16627	Pacific/Noumea
 NE	+1331+00207	Africa/Niamey
 NF	-2903+16758	Pacific/Norfolk
 NG	+0627+00324	Africa/Lagos
@@ -387,7 +390,7 @@ TK	-0922-17114	Pacific/Fakaofo
 TL	-0833+12535	Asia/Dili
 TM	+3757+05823	Asia/Ashgabat
 TN	+3648+01011	Africa/Tunis
-TO	-2110+17510	Pacific/Tongatapu
+TO	-2110-17510	Pacific/Tongatapu
 TR	+4101+02858	Europe/Istanbul
 TT	+1039-06131	America/Port_of_Spain
 TV	-0831+17913	Pacific/Funafuti
@@ -431,7 +434,7 @@ US	+211825-1575130	Pacific/Honolulu	Hawaii
 UY	-3453-05611	America/Montevideo
 UZ	+3940+06648	Asia/Samarkand	west Uzbekistan
 UZ	+4120+06918	Asia/Tashkent	east Uzbekistan
-VA	+4154+01227	Europe/Vatican
+VA	+415408+0122711	Europe/Vatican
 VC	+1309-06114	America/St_Vincent
 VE	+1030-06656	America/Caracas
 VG	+1827-06437	America/Tortola
diff --git a/make/sun/jkernel/Makefile b/make/sun/jkernel/Makefile
index 047efeae5aa3a7dc671b71bf53247ba46dc1b45c..97f2f38aca5e1080b8ee744d47bd6582c03bc9ed 100644
--- a/make/sun/jkernel/Makefile
+++ b/make/sun/jkernel/Makefile
@@ -35,10 +35,6 @@ include $(BUILDDIR)/common/Defs.gmk
 #
 _OPT = $(CC_HIGHEST_OPT)
 
-# This re-directs all the class files to a separate location
-CLASSDESTDIR = $(TEMPDIR)/classes
-
-
 #
 # Java source files
 #
diff --git a/make/sun/net/FILES_java.gmk b/make/sun/net/FILES_java.gmk
index 5082c3d370f152b5dca162ab8e1c724152a57ab6..19dd2d6d7f57330b1415b68dc8ff7160267ed218 100644
--- a/make/sun/net/FILES_java.gmk
+++ b/make/sun/net/FILES_java.gmk
@@ -86,9 +86,11 @@ FILES_java = \
 	sun/net/www/protocol/http/AuthCache.java \
 	sun/net/www/protocol/http/AuthCacheImpl.java \
 	sun/net/www/protocol/http/AuthCacheValue.java \
+	sun/net/www/protocol/http/AuthScheme.java \
 	sun/net/www/protocol/http/BasicAuthentication.java \
 	sun/net/www/protocol/http/DigestAuthentication.java \
 	sun/net/www/protocol/http/NTLMAuthentication.java \
+	sun/net/www/protocol/http/NTLMAuthenticationProxy.java \
 	sun/net/www/protocol/http/NegotiateAuthentication.java \
 	sun/net/www/protocol/http/NegotiatorImpl.java \
 	sun/net/www/protocol/http/NegotiateCallbackHandler.java \
@@ -123,8 +125,7 @@ FILES_java = \
 	sun/net/idn/UCharacterEnums.java \
 	sun/net/idn/UCharacterDirection.java \
 	sun/net/idn/StringPrepDataReader.java \
-	sun/net/idn/StringPrep.java \
-	sun/net/www/protocol/http/InMemoryCookieStore.java
+	sun/net/idn/StringPrep.java
 
 ifeq ($(PLATFORM), windows)
     FILES_java += sun/net/www/protocol/http/NTLMAuthSequence.java 
diff --git a/make/sun/security/Makefile b/make/sun/security/Makefile
index 2b7cc6b2ab342719694df42a2015780f5c07fad8..92371cc60cbf5681f4434dbcb355ac8cafcc7117 100644
--- a/make/sun/security/Makefile
+++ b/make/sun/security/Makefile
@@ -60,8 +60,15 @@ ifeq ($(PLATFORM), windows)
   endif
 endif
 
-SUBDIRS = ec other action util tools jgss krb5 smartcardio $(PKCS11) \
-          $(JGSS_WRAPPER) $(MSCAPI)
+# Build in-tree elliptic curve crypto provider only when
+# DISABLE_INTREE_EC is not set
+INTREE_EC = ec
+ifdef DISABLE_INTREE_EC
+  INTREE_EC =
+endif
+
+SUBDIRS = $(INTREE_EC) other action util tools jgss krb5 smartcardio \
+	  $(PKCS11) $(JGSS_WRAPPER) $(MSCAPI)
 
 all build clean clobber::
 	$(SUBDIRS-loop)
diff --git a/make/sun/security/ec/Makefile b/make/sun/security/ec/Makefile
index 297a2deab084778eb9f71507ecf69296fe50c012..53a3e3e9e51a16cd311deae0768090187ecb0219 100644
--- a/make/sun/security/ec/Makefile
+++ b/make/sun/security/ec/Makefile
@@ -24,7 +24,7 @@
 #
 
 #
-# Makefile for building sunec.jar and sunecc native library.
+# Makefile for building sunec.jar and sunec native library.
 #
 # This file was derived from make/com/sun/crypto/provider/Makefile.
 #
@@ -121,7 +121,15 @@ CLASSDESTDIR = $(TEMPDIR)/classes
 #
 AUTO_FILES_JAVA_DIRS = $(PKGDIR)
 
-include $(BUILDDIR)/common/Classes.gmk
+#
+# Exclude the sources that get built by ../other/Makefile
+#
+AUTO_JAVA_PRUNE = \
+    ECKeyFactory.java \
+    ECParameters.java \
+    ECPrivateKeyImpl.java \
+    ECPublicKeyImpl.java \
+    NamedCurve.java
 
 #
 # Some licensees do not get the native ECC sources, but we still need to
@@ -130,7 +138,7 @@ include $(BUILDDIR)/common/Classes.gmk
 #
 
 NATIVE_ECC_AVAILABLE := $(shell \
-    if [ -d $(SHARE_SRC)/native/$(PKGDIR) ] ; then \
+    if [ -d $(SHARE_SRC)/native/$(PKGDIR)/impl ] ; then \
 	$(ECHO) true; \
     else \
 	$(ECHO) false; \
@@ -138,7 +146,7 @@ NATIVE_ECC_AVAILABLE := $(shell \
 
 ifeq ($(NATIVE_ECC_AVAILABLE), true)
 
-  LIBRARY = sunecc
+  LIBRARY = sunec
 
   #
   # Java files that define native methods
@@ -166,12 +174,12 @@ ifeq ($(NATIVE_ECC_AVAILABLE), true)
   #
   vpath %.cpp $(SHARE_SRC)/native/$(PKGDIR)
 
-  vpath %.c $(SHARE_SRC)/native/$(PKGDIR)
+  vpath %.c $(SHARE_SRC)/native/$(PKGDIR)/impl
 
   #
   # Find include files
   #
-  OTHER_INCLUDES += -I$(SHARE_SRC)/native/$(PKGDIR)
+  OTHER_INCLUDES += -I$(SHARE_SRC)/native/$(PKGDIR)/impl
 
   #
   # Compiler flags
@@ -191,6 +199,10 @@ ifeq ($(NATIVE_ECC_AVAILABLE), true)
 
   include $(BUILDDIR)/common/Library.gmk
 
+else # NATIVE_ECC_AVAILABLE
+
+  include $(BUILDDIR)/common/Classes.gmk
+
 endif # NATIVE_ECC_AVAILABLE
 
 #
diff --git a/make/sun/security/other/Makefile b/make/sun/security/other/Makefile
index 3f120fa473f18e04df7adabf9d2771dcffcd9384..2722fbc32cd643a2aa2fc67bbca8319da84fc6a6 100644
--- a/make/sun/security/other/Makefile
+++ b/make/sun/security/other/Makefile
@@ -44,6 +44,16 @@ AUTO_FILES_JAVA_DIRS = \
     sun/security/x509 \
     com/sun/net/ssl/internal/ssl
 
+#
+# EC classes used by the packages above
+#
+FILES_java += \
+    sun/security/ec/ECKeyFactory.java \
+    sun/security/ec/ECParameters.java \
+    sun/security/ec/ECPrivateKeyImpl.java \
+    sun/security/ec/ECPublicKeyImpl.java \
+    sun/security/ec/NamedCurve.java
+
 #
 # Rules
 #
diff --git a/make/tools/Makefile b/make/tools/Makefile
index badfa687a31bf5d44ab515ce7cd4badb73e68c82..1fffa1bcaebc72f995b8867d2e9bb23b1cfbecdd 100644
--- a/make/tools/Makefile
+++ b/make/tools/Makefile
@@ -54,7 +54,7 @@ SUBDIRS =                   \
   CharsetMapping
 
 ifndef DISABLE_NIMBUS
-  SUBDIRS += swing-nimbus
+  SUBDIRS += generate_nimbus
 endif
 
 all build clean clobber::
diff --git a/make/tools/freetypecheck/Makefile b/make/tools/freetypecheck/Makefile
index 94c983565aceff1f91dbd4b96834ba0cb0c651c3..23161969558c231326346e20d5a57cbf98820c75 100644
--- a/make/tools/freetypecheck/Makefile
+++ b/make/tools/freetypecheck/Makefile
@@ -28,16 +28,21 @@ BUILDDIR = ../..
 include $(BUILDDIR)/common/Defs.gmk
 
 # Default name
-FT_TEST = $(BUILDTOOLBINDIR)/freetype_versioncheck$(EXE_SUFFIX)
+PROGRAM = freetype_versioncheck
+FT_OBJ = $(BUILDTOOLBINDIR)/$(PROGRAM).$(OBJECT_SUFFIX)
+FT_TEST = $(BUILDTOOLBINDIR)/$(PROGRAM)$(EXE_SUFFIX)
 
 # Used on openjdk only
 ifeq ($(OPENJDK),true)
 
 # Start with CFLAGS (which gets us the required -xarch setting on solaris)
 ifeq ($(PLATFORM), windows)
-  FT_OPTIONS  = /nologo $(CC_OBJECT_OUTPUT_FLAG)$(TEMPDIR)
+  FT_OPTIONS  = /nologo /c
   FREETYPE_DLL = $(FREETYPE_LIB_PATH)/freetype.dll
   FT_LD_OPTIONS  = $(FREETYPE_LIB_PATH)/freetype.lib
+ifdef MT
+  FT_LD_OPTIONS += /manifest
+endif
 else
   FT_OPTIONS  = $(CFLAGS)
   FT_LD_OPTIONS = -L$(FREETYPE_LIB_PATH)
@@ -55,15 +60,22 @@ FT_LD_OPTIONS += $(LFLAGS_$(COMPILER_VERSION))
 
 # Create test program
 all: $(FT_TEST)
-	@$(FT_TEST)
+	$(FT_TEST)
 
 # On windows we need to copy dll to test dir to ensure it will be found
 #   at runtime
 $(FT_TEST): freetypecheck.c
-	@$(prep-target)
-	@$(CC) $(FT_OPTIONS) $(CC_PROGRAM_OUTPUT_FLAG)$@ $< $(FT_LD_OPTIONS)
+	$(prep-target)
 ifeq ($(PLATFORM), windows)
-	@$(CP) $(FREETYPE_DLL) `dirname $@`
+	$(CC) $(FT_OPTIONS) $(CC_OBJECT_OUTPUT_FLAG)$(FT_OBJ) $<
+	$(LINK) $(FT_LD_OPTIONS) /OUT:$(FT_TEST) $(FT_OBJ)
+	$(CP) $(FREETYPE_DLL) $(@D)/
+ifdef MT
+	$(CP) $(MSVCRNN_DLL_PATH)/$(MSVCRNN_DLL) $(@D)/
+	$(MT) /manifest $(FT_TEST).manifest /outputresource:$(FT_TEST);#1
+endif
+else
+	@$(CC) $(FT_OPTIONS) $(CC_PROGRAM_OUTPUT_FLAG)$@ $< $(FT_LD_OPTIONS)
 endif
 
 else
diff --git a/make/tools/freetypecheck/freetypecheck.c b/make/tools/freetypecheck/freetypecheck.c
index 3f900a840a9afcebd62ab2c8cb271e87eaabdf30..71d32022beecdc2211bc0522980a48e8541216a5 100644
--- a/make/tools/freetypecheck/freetypecheck.c
+++ b/make/tools/freetypecheck/freetypecheck.c
@@ -32,6 +32,45 @@
 #include "ft2build.h"
 #include FT_FREETYPE_H
 
+#ifdef _MSC_VER
+#if _MSC_VER > 1400
+
+/*
+ * When building for Microsoft Windows, your program has a dependency
+ * on msvcr??.dll.
+ *
+ * When using Visual Studio 2005 or later, that must be recorded in
+ * the .exe.manifest file.
+ *
+ * Reference:
+ *     C:/Program Files/Microsoft SDKs/Windows/v6.1/include/crtdefs.h
+ */
+#include 
+#ifdef _M_IX86
+
+#pragma comment(linker,"/manifestdependency:\"type='win32' "            \
+        "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT' "              \
+        "version='" _CRT_ASSEMBLY_VERSION "' "                          \
+        "processorArchitecture='x86' "                                  \
+        "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"")
+
+#endif /* _M_IX86 */
+
+//This may not be necessary yet for the Windows 64-bit build, but it
+//will be when that build environment is updated.  Need to test to see
+//if it is harmless:
+#ifdef _M_AMD64
+
+#pragma comment(linker,"/manifestdependency:\"type='win32' "            \
+        "name='" __LIBRARIES_ASSEMBLY_NAME_PREFIX ".CRT' "              \
+        "version='" _CRT_ASSEMBLY_VERSION "' "                          \
+        "processorArchitecture='amd64' "                                \
+        "publicKeyToken='" _VC_ASSEMBLY_PUBLICKEYTOKEN "'\"")
+
+#endif  /* _M_AMD64 */
+#endif  /* _MSC_VER > 1400 */
+#endif  /* _MSC_VER */
+
 #define QUOTEMACRO(x) QUOTEME(x)
 #define QUOTEME(x) #x
 
diff --git a/make/javax/swing/plaf/nimbus/Makefile b/make/tools/generate_nimbus/Makefile
similarity index 53%
rename from make/javax/swing/plaf/nimbus/Makefile
rename to make/tools/generate_nimbus/Makefile
index ed59f137e5379b64d7e73d3a8a5c1ff271fa086d..ed531e5c84172ad11a288eb06571c95351d96afd 100644
--- a/make/javax/swing/plaf/nimbus/Makefile
+++ b/make/tools/generate_nimbus/Makefile
@@ -1,5 +1,5 @@
 #
-# Copyright 1998-2007 Sun Microsystems, Inc.  All Rights Reserved.
+# Copyright 1998-2005 Sun Microsystems, Inc.  All Rights Reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -23,38 +23,50 @@
 # have any questions.
 #
 
-BUILDDIR  = ../../../..
-PACKAGE   = javax.swing.plaf.nimbus
-PRODUCT   = com
-SWING_SRC = $(SHARE_SRC)/classes/javax/swing
+#
+# Makefile for building the Nimbus generator
+#
+
+BUILDDIR = ../..
+PACKAGE = build.tools.generatenimbus
+PRODUCT = tools
+PROGRAM = generatenimbus
 include $(BUILDDIR)/common/Defs.gmk
 
+BUILDTOOL_SOURCE_ROOT = $(BUILDDIR)/tools/src
+BUILDTOOL_MAIN        = $(PKGDIR)/Generator.java
+
+
 #
 # Files
 #
-NIMBUS_PKG = javax/swing/plaf/nimbus
-NIMBUS_COMPAT_PKG = com/sun/java/swing/plaf/nimbus
-NIMBUS_GENSRC_DIR = $(GENSRCDIR)/$(NIMBUS_PKG)
-NIMBUS_SKIN_FILE = $(SHARE_SRC)/classes/$(NIMBUS_PKG)/skin.laf
-NIMBUS_GENERATOR_JAR = $(BUILDTOOLJARDIR)/nimbus_generator.jar
 
-AUTO_FILES_JAVA_DIRS = $(NIMBUS_PKG) $(NIMBUS_COMPAT_PKG)
+SOURCE_FILES    = Generator.java \
+                  ObjectFactory.java \
+                  Paint.java \
+                  SynthModel.java \
+                  UIDefault.java \
+                  UIStyle.java
+TEMPLATE_FILES  = Defaults.template \
+                  PainterImpl.template \
+                  StateImpl.template
+TEMPLATE_DEST   = $(BUILDTOOLCLASSDIR)/$(PKGDIR)/resources
 
 
 #
 # Rules
 #
-CLASSES_INIT = $(NIMBUS_GENSRC_DIR)
 
-include $(BUILDDIR)/common/Classes.gmk
+all: $(TEMPLATE_DEST) $(BUILDTOOL_JAR_FILE)
+
+include $(BUILDDIR)/common/BuildToolJar.gmk
+
+$(TEMPLATE_DEST): $(TEMPLATE_FILES:%=$(SHARE_SRC)/classes/javax/swing/plaf/nimbus/%)
+	$(MKDIR) -p $@
+	$(RM) $(TEMPLATE_FILES:%=$@/%)
+	$(CP) $^ $@
 
-$(NIMBUS_GENSRC_DIR): $(NIMBUS_SKIN_FILE) $(NIMBUS_GENERATOR_JAR)
-	@$(ECHO) "Generating Nimbus source files:"
-	$(BOOT_JAVA_CMD) -jar $(NIMBUS_GENERATOR_JAR) \
-	    -skinFile $(NIMBUS_SKIN_FILE) \
-	    -buildDir $(GENSRCDIR) -srcDir $(GENSRCDIR) \
-	    -packagePrefix $(PACKAGE) -lafName Nimbus
-	@$(ECHO) "Finished generating Nimbus source files"
+BUILDTOOL_MAIN_SOURCE_FILE = $(SOURCE_FILES:%=$(BUILDTOOL_SOURCE_ROOT)/$(PKGDIR)/%)
 
 clean clobber::
-	$(RM) -r $(NIMBUS_GENSRC_DIR)
+	$(RM) -r $(TEMPLATE_DEST)
diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/Generator.java b/make/tools/src/build/tools/generatenimbus/Generator.java
similarity index 53%
rename from make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/Generator.java
rename to make/tools/src/build/tools/generatenimbus/Generator.java
index 6ab4b87d18ad38d9f28eb5895ed16b9be4478094..a345305a88d7c7bd9ecb38f4e1db3b9567c5472c 100644
--- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/Generator.java
+++ b/make/tools/src/build/tools/generatenimbus/Generator.java
@@ -22,20 +22,13 @@
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
-package org.jdesktop.synthdesigner.generator;
+package build.tools.generatenimbus;
 
-import static org.jdesktop.synthdesigner.generator.TemplateWriter.read;
-import static org.jdesktop.synthdesigner.generator.TemplateWriter.writeSrcFile;
-import org.jdesktop.synthdesigner.synthmodel.SynthModel;
-import org.jibx.runtime.BindingDirectory;
-import org.jibx.runtime.IBindingFactory;
-import org.jibx.runtime.IUnmarshallingContext;
-
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
+import java.io.*;
 import java.util.HashMap;
 import java.util.Map;
+import javax.xml.bind.JAXBContext;
+import javax.xml.bind.Unmarshaller;
 
 /**
  * Generates the various Java artifacts based on a SynthModel.
@@ -51,12 +44,12 @@ import java.util.Map;
  * @author  Jasper Potts
  */
 public class Generator {
+    private static Generator instance;
+
     /** A map of variables that are used for variable substitution in the template files. */
     private Map variables;
-
     private boolean full = false;
     private File buildPackageRoot;
-    private File srcPackageRoot;
     private String packageNamePrefix;
     private String lafName;
     private SynthModel model;
@@ -68,7 +61,7 @@ public class Generator {
      *
      * @param args The commandline arguments
      */
-    public static void main(String[] args) {
+    public static void main(String[] args) throws Exception {
         if (args.length == 0 || (args.length % 2) != 0) {
             System.out.println("Usage: generator [-options]\n" +
                     "    -full      True if we should build the whole LAF or false for building just states and painters.\n" +
@@ -76,9 +69,6 @@ public class Generator {
                     "    -buildDir       The directory beneath which the build-controlled artifacts (such as the Painters) should\n" +
                     "                           be placed. This is the root directory beneath which the necessary packages and source\n" +
                     "                           files will be created.\n" +
-                    "    -srcDir         The directory beneath which the normal user-controlled artifacts (such as the core\n" +
-                    "                           LookAndFeel file) should be placed. These are one-time generated files. This is the root\n" +
-                    "                           directory beneath which the necessary packages and source files will be created.\n" +
                     "    -resourcesDir   The resources directory containing templates and images.\n" +
                     "    -packagePrefix  The package name associated with this synth look and feel. For example,\n" +
                     "                           \"org.mypackage.mylaf\"\n" +
@@ -87,7 +77,6 @@ public class Generator {
             boolean full = false;
             File skinFile = new File(System.getProperty("user.dir"));
             File buildDir = new File(System.getProperty("user.dir"));
-            File srcDir = new File(System.getProperty("user.dir"));
             File resourcesDir = new File(System.getProperty("user.dir"));
             String packagePrefix = "org.mypackage.mylaf";
             String lafName = "MyLAF";
@@ -100,8 +89,6 @@ public class Generator {
                     skinFile = new File(value);
                 } else if ("-builddir".equals(key)) {
                     buildDir = new File(value);
-                } else if ("-srcdir".equals(key)) {
-                    srcDir = new File(value);
                 } else if ("-resourcesdir".equals(key)) {
                     resourcesDir = new File(value);
                 } else if ("-packageprefix".equals(key)) {
@@ -114,25 +101,15 @@ public class Generator {
             System.out.println("   full          :" + full);
             System.out.println("   skinFile      :" + skinFile.getAbsolutePath());
             System.out.println("   buildDir      :" + buildDir.getAbsolutePath());
-            System.out.println("   srcDir        :" + srcDir.getAbsolutePath());
             System.out.println("   resourcesDir  :" + resourcesDir.getAbsolutePath());
             System.out.println("   packagePrefix :" +packagePrefix);
             System.out.println("   lafName       :" +lafName);
-            try {
-                // LOAD SKIN MODEL
-                IBindingFactory bindingFactory = BindingDirectory.getFactory(SynthModel.class);
-                IUnmarshallingContext mctx = bindingFactory.createUnmarshallingContext();
-                mctx.setDocument(new FileInputStream(skinFile), "UTF-8");
-                // pass resources directory in as user context so it can be used in SynthModel preSet
-                mctx.setUserContext(resourcesDir);
-                SynthModel model = (SynthModel) mctx.unmarshalElement();
-                // create and run generator
-                Generator generator = new Generator(full, buildDir, srcDir, packagePrefix, lafName, model);
-                generator.generate();
-            } catch (Exception e) {
-                System.err.println("Error loading skin and generating java src:");
-                e.printStackTrace();
-            }
+
+            JAXBContext ctx = JAXBContext.newInstance("build.tools.generatenimbus");
+            Unmarshaller u = ctx.createUnmarshaller();
+            SynthModel model = (SynthModel) u.unmarshal(skinFile);
+            Generator.init(full, buildDir, packagePrefix, lafName, model);
+            Generator.getInstance().generate();
         }
     }
 
@@ -152,8 +129,8 @@ public class Generator {
      * @param lafName           The name of the laf, such as MyLAF.
      * @param model             The actual SynthModel to base these generated files on.
      */
-    public Generator(boolean full, File buildDir, File srcDir, String packageNamePrefix, String lafName,
-                     SynthModel model) {
+    private Generator(boolean full, File buildDir,
+            String packageNamePrefix, String lafName, SynthModel model) {
         this.full = full;
         //validate the input variables
         if (packageNamePrefix == null) {
@@ -162,9 +139,6 @@ public class Generator {
         if (buildDir == null) {
             throw new IllegalArgumentException("You must specify the build directory");
         }
-        if (srcDir == null) {
-            throw new IllegalArgumentException("You must specify the source directory");
-        }
         if (model == null) {
             throw new IllegalArgumentException("You must specify the SynthModel");
         }
@@ -183,8 +157,6 @@ public class Generator {
         //org.mypackage.mylaf subdirectories)
         buildPackageRoot = new File(buildDir, packageNamePrefix.replaceAll("\\.", "\\/"));
         buildPackageRoot.mkdirs();
-        srcPackageRoot = new File(srcDir, packageNamePrefix.replaceAll("\\.", "\\/"));
-        srcPackageRoot.mkdirs();
 
         //save the variables
         this.packageNamePrefix = packageNamePrefix;
@@ -192,98 +164,104 @@ public class Generator {
         this.model = model;
     }
 
-    public void generate() {
-        //Generate the one-time files. If these files already exist, skip the
-        //ones that exist and create the missing ones. Register warnings for the
-        //already existing files.
-
-        //TODO Skip existing files, send warnings, etc.
-        if (full) {
-            try {
-                //create the LookAndFeel file
-                String template = read("resources/LookAndFeel.template");
-                writeSrcFile(template, variables, new File(srcPackageRoot, lafName + "LookAndFeel.java"));
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-        }
-        //create the painters and such.
-        regenerate();
+    public static void init(boolean full, File buildDir,
+            String packageNamePrefix, String lafName, SynthModel model) {
+        instance = new Generator(full, buildDir, packageNamePrefix, lafName, model);
+        model.initStyles();
     }
 
-    public void regenerate() {
-        try {
-            if (full) {
-                //first, create the AbstractRegionPainter.java file.
-                String template = read("resources/AbstractRegionPainter.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "AbstractRegionPainter.java"));
-
-                //write out BlendingMode.java
-                template = read("resources/BlendingMode.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "BlendingMode.java"));
-
-                //create the SynthPainterImpl class
-                template = read("resources/SynthPainterImpl.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "SynthPainterImpl.java"));
+    public static Generator getInstance() {
+        return instance;
+    }
 
-                //create the IconImpl class
-                template = read("resources/IconImpl.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, lafName + "Icon.java"));
+    public static Map getVariables() {
+        return new HashMap(instance.variables);
+    }
 
-                //create the StyleImpl class
-                template = read("resources/StyleImpl.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, lafName + "Style.java"));
+    public void generate() {
+        if (full) {
+            //create the LookAndFeel file
+            writeSrcFileImpl("LookAndFeel", variables, lafName + "LookAndFeel");
 
-                //write out Effect.java
-                template = read("resources/Effect.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "Effect.java"));
+            writeSrcFileImpl("AbstractRegionPainter", variables);
+            writeSrcFileImpl("BlendingMode", variables);
+            writeSrcFileImpl("SynthPainterImpl", variables);
+            writeSrcFileImpl("IconImpl", variables, lafName + "Icon.java");
+            writeSrcFileImpl("StyleImpl", variables, lafName + "Style.java");
+            writeSrcFileImpl("Effect", variables);
+            writeSrcFileImpl("EffectUtils", variables);
+            writeSrcFileImpl("ShadowEffect", variables);
+            writeSrcFileImpl("DropShadowEffect", variables);
+            writeSrcFileImpl("InnerShadowEffect", variables);
+            writeSrcFileImpl("InnerGlowEffect", variables);
+            writeSrcFileImpl("OuterGlowEffect", variables);
+            writeSrcFileImpl("State", variables);
+            writeSrcFileImpl("ImageCache", variables);
+            writeSrcFileImpl("ImageScalingHelper", variables);
+        }
+        //next, populate the first set of ui defaults based on what is in the
+        //various palettes of the synth model
+        StringBuilder defBuffer = new StringBuilder();
+        StringBuilder styleBuffer = new StringBuilder();
+        model.write(defBuffer, styleBuffer, packageNamePrefix);
 
-                //write out EffectUtils.java
-                template = read("resources/EffectUtils.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "EffectUtils.java"));
+        Map vars = getVariables();
+        vars.put("UI_DEFAULT_INIT", defBuffer.toString());
+        vars.put("STYLE_INIT", styleBuffer.toString());
+        writeSrcFile("Defaults", vars, lafName + "Defaults");
+    }
 
-                //write out ShadowEffect.java
-                template = read("resources/ShadowEffect.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "ShadowEffect.java"));
+    private void writeSrcFileImpl(String name, Map variables) {
+        writeSrcFileImpl(name, variables, name);
+    }
 
-                //write out DropShadowEffect.java
-                template = read("resources/DropShadowEffect.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "DropShadowEffect.java"));
+    private void writeSrcFileImpl(String templateName,
+            Map variables, String outputName) {
+        PrintWriter out = null;
+        try {
+            InputStream stream = getClass().getResourceAsStream(
+                    "resources/" + templateName + ".template");
+            TemplateReader in = new TemplateReader(variables, stream);
 
-                //write out InnerShadowEffect.java
-                template = read("resources/InnerShadowEffect.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "InnerShadowEffect.java"));
+            out = new PrintWriter(new File(buildPackageRoot, outputName + ".java"));
+            String line = in.readLine();
+            while (line != null) {
+                out.println(line);
+                line = in.readLine();
+            }
+        } catch (IOException e) {
+            throw new RuntimeException("IOException in writer", e);
+        } finally {
+            if (out != null) out.close();
+        }
+    }
 
-                //write out InnerGlowEffect.java
-                template = read("resources/InnerGlowEffect.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "InnerGlowEffect.java"));
+    public static void writeSrcFile(String templateName,
+            Map variables, String outputName) {
+        instance.writeSrcFileImpl(templateName, variables, outputName);
+    }
 
-                //write out OuterGlowEffect.java
-                template = read("resources/OuterGlowEffect.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "OuterGlowEffect.java"));
+    /** A BufferedReader implementation that automatically performs
+     * string replacements as needed.
+     */
+    private static final class TemplateReader extends BufferedReader {
+        private Map variables;
 
-                //write out State.java
-                template = read("resources/State.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "State.java"));
+        TemplateReader(Map variables, InputStream template) {
+            super(new InputStreamReader(template));
+            this.variables = variables;
+        }
 
-                template = read("resources/ImageCache.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "ImageCache.java"));
+        @Override public String readLine() throws IOException {
+            return substituteVariables(super.readLine());
+        }
 
-                template = read("resources/ImageScalingHelper.template");
-                writeSrcFile(template, variables, new File(buildPackageRoot, "ImageScalingHelper.java"));
+        private String substituteVariables(String input) {
+            if (input == null) return null;
+            for (Map.Entry variable : variables.entrySet()) {
+                input = input.replace("${" + variable.getKey() + "}", variable.getValue());
             }
-            //next, populate the first set of ui defaults based on what is in the
-            //various palettes of the synth model
-            StringBuilder uiDefaultInit = new StringBuilder();
-            StringBuilder styleInit = new StringBuilder();
-            DefaultsGenerator.generateDefaults(uiDefaultInit, styleInit, model, variables, packageNamePrefix,
-                    buildPackageRoot);
-            variables.put("UI_DEFAULT_INIT", uiDefaultInit.toString());
-            variables.put("STYLE_INIT", styleInit.toString());
-            writeSrcFile(read("resources/Defaults.template"), variables,
-                    new File(buildPackageRoot, lafName + "Defaults.java"));
-        } catch (IOException e) {
-            e.printStackTrace();
+            return input;
         }
     }
 }
diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/InnerGlowEffect.java b/make/tools/src/build/tools/generatenimbus/ObjectFactory.java
similarity index 57%
rename from make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/InnerGlowEffect.java
rename to make/tools/src/build/tools/generatenimbus/ObjectFactory.java
index ea0b2d153597e873477b1975fd383b2a6d0d8a19..1fdd7cd972c406fa34eab85e1654c290f6428785 100644
--- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/InnerGlowEffect.java
+++ b/make/tools/src/build/tools/generatenimbus/ObjectFactory.java
@@ -22,34 +22,41 @@
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
-package org.jdesktop.swingx.designer.effects;
 
-import org.jdesktop.swingx.designer.paint.Matte;
+package build.tools.generatenimbus;
+
+import javax.xml.bind.annotation.XmlRegistry;
 
-import javax.swing.UIDefaults;
-import java.awt.Color;
 
 /**
- * InnerGlowEffect
+ * This object contains factory methods for each
+ * Java content interface and Java element interface
+ * generated in the test package.
+ * 

An ObjectFactory allows you to programatically + * construct new instances of the Java representation + * for XML content. The Java representation of XML + * content can consist of schema derived interfaces + * and classes representing the binding of schema + * type definitions, element declarations and model + * groups. Factory methods for each of these are + * provided in this class. * - * @author Created by Jasper Potts (Jun 21, 2007) */ -public class InnerGlowEffect extends InnerShadowEffect { - - protected InnerGlowEffect() { - distance = 0; - } +@XmlRegistry +public class ObjectFactory { - public InnerGlowEffect(UIDefaults uiDefaults) { - color = new Matte(new Color(255, 255, 211), uiDefaults); + /** + * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: test + * + */ + public ObjectFactory() { } /** - * Get the display name for this effect + * Create an instance of {@link SynthModel } * - * @return The user displayable name */ - public String getDisplayName() { - return "Inner Glow"; + public SynthModel createSynthModel() { + return new SynthModel(); } } diff --git a/make/tools/src/build/tools/generatenimbus/Paint.java b/make/tools/src/build/tools/generatenimbus/Paint.java new file mode 100644 index 0000000000000000000000000000000000000000..85678410affb35e2a3780b42e4ac6991a086d813 --- /dev/null +++ b/make/tools/src/build/tools/generatenimbus/Paint.java @@ -0,0 +1,181 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package build.tools.generatenimbus; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; + +public abstract class Paint { +} + +class Matte extends Paint { + @XmlAttribute private int red; + @XmlAttribute private int green; + @XmlAttribute private int blue; + @XmlAttribute private int alpha; + + @XmlAttribute private String uiDefaultParentName = null; + @XmlAttribute private float hueOffset = 0; + @XmlAttribute private float saturationOffset = 0; + @XmlAttribute private float brightnessOffset = 0; + @XmlAttribute private int alphaOffset = 0; + + @XmlAttribute private String componentPropertyName = null; + public String getComponentPropertyName() { return componentPropertyName; } + + @XmlAttribute private boolean uiResource = true; + + public boolean isAbsolute() { + return uiDefaultParentName == null; + } + + public String getDeclaration() { + if (isAbsolute()) { + return String.format("new Color(%d, %d, %d, %d)", + red, green, blue, alpha); + } else { + return String.format("decodeColor(\"%s\", %sf, %sf, %sf, %d)", + uiDefaultParentName, String.valueOf(hueOffset), + String.valueOf(saturationOffset), + String.valueOf(brightnessOffset), alphaOffset); + } + } + + public String write() { + if (isAbsolute()) { + return String.format("%s, %s, %s, %s", red, green, blue, alpha); + } else { + String s = String.format("\"%s\", %sf, %sf, %sf, %d", + uiDefaultParentName, String.valueOf(hueOffset), + String.valueOf(saturationOffset), + String.valueOf(brightnessOffset), alphaOffset); + if (! uiResource) { + s += ", false"; + } + return s; + } + } + + public ComponentColor createComponentColor(String variableName) { + return new ComponentColor(componentPropertyName, variableName, + saturationOffset, brightnessOffset, alphaOffset); + } +} + +class ComponentColor { + private String propertyName; + private String defaultColorVariableName; + private float saturationOffset = 0, brightnessOffset = 0; + private int alphaOffset = 0; + + ComponentColor(String propertyName, + String defaultColorVariableName, + float saturationOffset, + float brightnessOffset, + int alphaOffset) { + this.propertyName = propertyName; + this.defaultColorVariableName = defaultColorVariableName; + this.saturationOffset = saturationOffset; + this.brightnessOffset = brightnessOffset; + this.alphaOffset = alphaOffset; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + ComponentColor c = (ComponentColor) o; + if (alphaOffset != c.alphaOffset) { + return false; + } + if (Float.compare(saturationOffset, c.saturationOffset) != 0) { + return false; + } + if (Float.compare(brightnessOffset, c.brightnessOffset) != 0) { + return false; + } + if (defaultColorVariableName != null ? !defaultColorVariableName.equals(c.defaultColorVariableName) : c.defaultColorVariableName != null) { + return false; + } + if (propertyName != null ? !propertyName.equals(c.propertyName) : c.propertyName != null) { + return false; + } + return true; + } + + @Override + public int hashCode() { + int hash = 5; + hash = 61 * hash + (this.propertyName != null ? this.propertyName.hashCode() : 0); + hash = 61 * hash + (this.defaultColorVariableName != null ? this.defaultColorVariableName.hashCode() : 0); + hash = 61 * hash + Float.floatToIntBits(this.saturationOffset); + hash = 61 * hash + Float.floatToIntBits(this.brightnessOffset); + hash = 61 * hash + this.alphaOffset; + return hash; + } + + public void write(StringBuilder sb) { + sb.append(" getComponentColor(c, \""). + append(propertyName).append("\", "). + append(defaultColorVariableName).append(", "). + append(saturationOffset).append("f, "). + append(brightnessOffset).append("f, "). + append(alphaOffset); + } +} + +class GradientStop { + @XmlAttribute private float position; + public float getPosition() { return position; } + + @XmlAttribute private float midpoint; + public float getMidpoint() { return midpoint; } + + @XmlElement private Matte matte; + public Matte getColor() { return matte; } +} + +class AbstractGradient extends Paint { + public static enum CycleMethod { + NO_CYCLE, REFLECT, REPEAT + } + + @XmlElement(name="stop") private ArrayList stops; + public List getStops() { return stops; } +} + +class Gradient extends AbstractGradient { +} + +class RadialGradient extends AbstractGradient { +} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/PainterGenerator.java b/make/tools/src/build/tools/generatenimbus/PainterGenerator.java similarity index 52% rename from make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/PainterGenerator.java rename to make/tools/src/build/tools/generatenimbus/PainterGenerator.java index 781fb21ba933ecee9628d75b6210a27147def150..69821862e96930b7bcf74c6ebd22e9dc8971f90d 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/PainterGenerator.java +++ b/make/tools/src/build/tools/generatenimbus/PainterGenerator.java @@ -22,49 +22,15 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.synthdesigner.generator; - -import org.jdesktop.swingx.designer.BezierControlPoint; -import org.jdesktop.swingx.designer.Canvas; -import org.jdesktop.swingx.designer.EllipseShape; -import org.jdesktop.swingx.designer.Layer; -import org.jdesktop.swingx.designer.PaintedShape; -import org.jdesktop.swingx.designer.PathShape; -import org.jdesktop.swingx.designer.RectangleShape; -import org.jdesktop.swingx.designer.SimpleShape; -import org.jdesktop.swingx.designer.TemplateLayer; -import org.jdesktop.swingx.designer.paint.Gradient; -import org.jdesktop.swingx.designer.paint.Matte; -import org.jdesktop.swingx.designer.paint.PaintModel; -import org.jdesktop.swingx.designer.paint.RadialGradient; -import org.jdesktop.swingx.designer.paint.GradientStop; -import org.jdesktop.swingx.designer.paint.AbstractGradient; -import static org.jdesktop.synthdesigner.generator.GeneratorUtils.makePretty; -import static org.jdesktop.synthdesigner.generator.GeneratorUtils.toClassName; -import static org.jdesktop.synthdesigner.generator.GeneratorUtils.toConstantName; -import static org.jdesktop.synthdesigner.generator.TemplateWriter.read; -import static org.jdesktop.synthdesigner.generator.TemplateWriter.writeSrcFile; -import org.jdesktop.synthdesigner.synthmodel.UIIconRegion; -import org.jdesktop.synthdesigner.synthmodel.UIRegion; -import org.jdesktop.synthdesigner.synthmodel.UIState; - -import java.awt.*; +package build.tools.generatenimbus; + import java.awt.geom.Point2D; -import java.beans.Beans; -import java.io.File; -import java.io.IOException; -import java.lang.reflect.Method; -import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import javax.swing.JList; -import javax.swing.JTable; -import javax.swing.text.JTextComponent; + /** * PainterGenerator - Class for generating Painter class java source from a Canvas @@ -91,22 +57,6 @@ import javax.swing.text.JTextComponent; * @author Jasper Potts */ public class PainterGenerator { - private static String painterImplTemplate; - private static String getPainterImplTemplate() { - if (painterImplTemplate == null) { - //load the painter template file into an in-memory string to improve performance - //when generating a lot of classes - try { - painterImplTemplate = read("resources/PainterImpl.template"); - } catch (IOException e) { - System.err.println("Failed to read template files."); - throw new RuntimeException(e); - } - } - return painterImplTemplate; - } - - //a handful of counters, incremented whenever the associated object type is encounted. //These counters form the basis of the field and method suffixes. //These are all 1 based, because I felt like it :-) @@ -170,10 +120,8 @@ public class PainterGenerator { private void generate(UIRegion r) { for (UIState state : r.getBackgroundStates()) { - System.out.println("------>" + state.getName()); - Canvas canvas = state.getCanvas(); - String type = r instanceof UIIconRegion ? ((UIIconRegion)r).getKey() : "Background"; + String type = (r instanceof UIIconRegion ? r.getKey() : "Background"); generate(state, canvas, type); } for (UIState state : r.getForegroundStates()) { @@ -203,13 +151,7 @@ public class PainterGenerator { .append(" extendedCacheKeys = new Object[] {\n"); for (int i=0; i(); @@ -257,171 +199,166 @@ public class PainterGenerator { Layer[] layers = canvas.getLayers().toArray(new Layer[0]); for (int index=layers.length-1; index >= 0; index--) { Layer layer = layers[index]; - if (layer instanceof TemplateLayer) { - continue; - } + //shapes must be painted in reverse order - List shapes = layer.getShapes(); + List shapes = layer.getShapes(); for (int i=shapes.size()-1; i>=0; i--) { - SimpleShape s = shapes.get(i); - if (s instanceof PaintedShape) { - PaintedShape shape = (PaintedShape)s; - PaintModel paint = shape.getPaintModel(); - - /* - We attempt to write the minimal number of bytecodes as possible when - generating code. Due to the inherit complexities in determining what - is extraneous, we use the following system: - - We first generate the code for the shape. Then, we check to see if - this shape has already been generated. If so, then we defer to an - existing method. If not, then we will create a new methods, stick - the code in it, and refer to that method. - */ - - String shapeMethodName = null; // will contain the name of the method which creates the shape - String shapeVariable = null; // will be one of rect, roundRect, ellipse, or path. - String shapeMethodBody = null; - - if (shape instanceof RectangleShape) { - RectangleShape rshape = (RectangleShape) shape; - float x1 = encode((float)rshape.getX1(), a, b, width); - float y1 = encode((float)rshape.getY1(), c, d, height); - float x2 = encode((float)rshape.getX2(), a, b, width); - float y2 = encode((float)rshape.getY2(), c, d, height); - if (rshape.isRounded()) { - //it is a rounded rectangle - float rounding = (float)rshape.getRounding(); - - shapeMethodBody = - " roundRect.setRoundRect(" + - writeDecodeX(x1) + ", //x\n" + - " " + writeDecodeY(y1) + ", //y\n" + - " " + writeDecodeX(x2) + " - " + writeDecodeX(x1) + ", //width\n" + - " " + writeDecodeY(y2) + " - " + writeDecodeY(y1) + ", //height\n" + - " " + rounding + "f, " + rounding + "f); //rounding"; - shapeVariable = "roundRect"; - } else { - shapeMethodBody = - " rect.setRect(" + - writeDecodeX(x1) + ", //x\n" + - " " + writeDecodeY(y1) + ", //y\n" + - " " + writeDecodeX(x2) + " - " + writeDecodeX(x1) + ", //width\n" + - " " + writeDecodeY(y2) + " - " + writeDecodeY(y1) + "); //height"; - shapeVariable = "rect"; - } - } else if (shape instanceof EllipseShape) { - EllipseShape eshape = (EllipseShape) shape; - float x1 = encode((float)eshape.getX1(), a, b, width); - float y1 = encode((float)eshape.getY1(), c, d, height); - float x2 = encode((float)eshape.getX2(), a, b, width); - float y2 = encode((float)eshape.getY2(), c, d, height); + Shape shape = shapes.get(i); + Paint paint = shape.getPaint(); + + /* + We attempt to write the minimal number of bytecodes as possible when + generating code. Due to the inherit complexities in determining what + is extraneous, we use the following system: + + We first generate the code for the shape. Then, we check to see if + this shape has already been generated. If so, then we defer to an + existing method. If not, then we will create a new methods, stick + the code in it, and refer to that method. + */ + + String shapeMethodName = null; // will contain the name of the method which creates the shape + String shapeVariable = null; // will be one of rect, roundRect, ellipse, or path. + String shapeMethodBody = null; + + if (shape instanceof Rectangle) { + Rectangle rshape = (Rectangle) shape; + float x1 = encode((float)rshape.getX1(), a, b, width); + float y1 = encode((float)rshape.getY1(), c, d, height); + float x2 = encode((float)rshape.getX2(), a, b, width); + float y2 = encode((float)rshape.getY2(), c, d, height); + if (rshape.isRounded()) { + //it is a rounded rectangle + float rounding = (float)rshape.getRounding(); + shapeMethodBody = - " ellipse.setFrame(" + + " roundRect.setRoundRect(" + + writeDecodeX(x1) + ", //x\n" + + " " + writeDecodeY(y1) + ", //y\n" + + " " + writeDecodeX(x2) + " - " + writeDecodeX(x1) + ", //width\n" + + " " + writeDecodeY(y2) + " - " + writeDecodeY(y1) + ", //height\n" + + " " + rounding + "f, " + rounding + "f); //rounding"; + shapeVariable = "roundRect"; + } else { + shapeMethodBody = + " rect.setRect(" + writeDecodeX(x1) + ", //x\n" + " " + writeDecodeY(y1) + ", //y\n" + " " + writeDecodeX(x2) + " - " + writeDecodeX(x1) + ", //width\n" + " " + writeDecodeY(y2) + " - " + writeDecodeY(y1) + "); //height"; - shapeVariable = "ellipse"; - } else if (shape instanceof PathShape) { - PathShape pshape = (PathShape) shape; - List controlPoints = pshape.getBezierControlPoints(); - BezierControlPoint first, last; - first = last = controlPoints.get(0); - StringBuilder buffer = new StringBuilder(); - buffer.append(" path.reset();\n"); - buffer.append(" path.moveTo(" + writeDecodeX(encode((float)first.getX(), a, b, width)) + ", " + writeDecodeY(encode((float)first.getY(), c, d, height)) + ");\n"); - for (int j=1; j controlPoints = pshape.getControlPoints(); + Point first, last; + first = last = controlPoints.get(0); + StringBuilder buffer = new StringBuilder(); + buffer.append(" path.reset();\n"); + buffer.append(" path.moveTo(" + writeDecodeX(encode((float)first.getX(), a, b, width)) + ", " + writeDecodeY(encode((float)first.getY(), c, d, height)) + ");\n"); + for (int j=1; j b) { + r = 2 + ((x - b) / (w - b)); + } else if (x == a && x == b) { + return 1.5f; + } else { + r = 1 + ((x - a) / (b - a)); + } + + if (Float.isNaN(r)) { + System.err.println("[Error] Encountered NaN: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + return 0; + } else if (Float.isInfinite(r)) { + System.err.println("[Error] Encountered Infinity: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + return 0; + } else if (r < 0) { + System.err.println("[Error] encoded value was less than 0: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + return 0; + } else if (r > 3) { + System.err.println("[Error] encoded value was greater than 3: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); + return 3; + } else { + return r; + } } private String writeDecodeX(float encodedX) { @@ -469,30 +431,17 @@ public class PainterGenerator { } private String encodeMatte(Matte m) { - String declaration = null; - if (m.isAbsolute()) { - Color c = m.getColor(); - declaration = ObjectCodeConvertors.convert(c); - } else { - declaration = "decodeColor(\"" + m.getUiDefaultParentName() + - "\", " + m.getHueOffset() + "f, " + - m.getSaturationOffset() + "f, " + - m.getBrightnessOffset() + "f, " + - m.getAlphaOffset() + ")"; - } - + String declaration = m.getDeclaration(); String variableName = colors.get(declaration); if (variableName == null) { variableName = "color" + colorCounter++; colors.put(declaration, variableName); - colorCode.append(" private Color ").append(variableName).append(" = "); - colorCode.append(declaration).append(";\n"); + colorCode.append(String.format(" private Color %s = %s;\n", + variableName, declaration)); } // handle component colors if (m.getComponentPropertyName() != null) { - ComponentColor cc = new ComponentColor(m.getComponentPropertyName(), - variableName, m.getSaturationOffset(), - m.getBrightnessOffset(), m.getAlphaOffset()); + ComponentColor cc = m.createComponentColor(variableName); int index = componentColors.indexOf(cc); if (index == -1) { index = componentColors.size(); @@ -504,20 +453,7 @@ public class PainterGenerator { } } - private String encodeColor(Color c) { - String declaration = ObjectCodeConvertors.convert(c); - String variableName = colors.get(declaration); - if (variableName == null) { - variableName = "color" + colorCounter++; - colors.put(declaration, variableName); - colorCode.append(" private Color ").append(variableName).append(" = "); - colorCode.append(declaration).append(";\n"); - } - - return variableName; - } - - private String encodeGradient(PaintedShape ps, Gradient g) { + private String encodeGradient(Shape ps, Gradient g) { StringBuilder b = new StringBuilder(); float x1 = (float)ps.getPaintX1(); float y1 = (float)ps.getPaintY1(); @@ -633,7 +569,7 @@ public class PainterGenerator { b.append("}"); } - private String encodeRadial(PaintedShape ps, RadialGradient g) { + private String encodeRadial(Shape ps, RadialGradient g) { float centerX1 = (float)ps.getPaintX1(); float centerY1 = (float)ps.getPaintY1(); float x2 = (float)ps.getPaintX2(); @@ -669,15 +605,14 @@ public class PainterGenerator { } //note that this method is not thread-safe. In fact, none of this class is. - static void writePainter(UIRegion r, Map variables, File painterPackageRoot, String prefix) throws IOException { + public static void writePainter(UIRegion r, String painterName) { //Need only write out the stuff for this region, don't need to worry about subregions //since this method will be called for each of those (and they go in their own file, anyway). //The only subregion that we compound into this is the one for icons. - - String painterName = makePretty(prefix) + "Painter"; PainterGenerator gen = new PainterGenerator(r); System.out.println("Generating source file: " + painterName + ".java"); - System.out.println(gen.stateTypeCode.toString()); + + Map variables = Generator.getVariables(); variables.put("PAINTER_NAME", painterName); variables.put("STATIC_DECL", gen.stateTypeCode.toString()); variables.put("COLORS_DECL", gen.colorCode.toString()); @@ -687,72 +622,6 @@ public class PainterGenerator { variables.put("SHAPES_DECL", gen.shapesCode.toString()); variables.put("GRADIENTS_DECL", gen.gradientsCode.toString()); - writeSrcFile(getPainterImplTemplate(), variables, new File(painterPackageRoot, painterName + ".java")); - - variables.remove("PAINTER_NAME"); - variables.remove("STATIC_DECL"); - variables.remove("COLORS_DECL"); - variables.remove("DO_PAINT_SWITCH_BODY"); - variables.remove("PAINTING_DECL"); - variables.remove("SHAPES_DECL"); - variables.remove("GRADIENTS_DECL"); - } - - /** - * Represents the usage of a color from a component within a painter. That - * is, a painter can use colors from the component when it paints. This - * class represents the usage of such a color, containing a reference to - * the name of the property that contains the color, and the various - * derivation offsets to apply to that color. - */ - private static class ComponentColor { - public String propertyName; - public String defaultColorVariableName; - private float saturationOffset = 0, brightnessOffset = 0; - private int alphaOffset = 0; - - private ComponentColor(String propertyName, - String defaultColorVariableName, - float saturationOffset, - float brightnessOffset, - int alphaOffset) { - this.propertyName = propertyName; - this.defaultColorVariableName = defaultColorVariableName; - this.saturationOffset = saturationOffset; - this.brightnessOffset = brightnessOffset; - this.alphaOffset = alphaOffset; - } - - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - ComponentColor c = (ComponentColor)o; - if (alphaOffset != c.alphaOffset) return false; - if (Float.compare(saturationOffset, c.saturationOffset) != 0) - return false; - if (Float.compare(brightnessOffset, c.brightnessOffset) != 0) - return false; - if (defaultColorVariableName != null ? - !defaultColorVariableName.equals(c.defaultColorVariableName) : - c.defaultColorVariableName != null) return false; - if (propertyName != null ? !propertyName.equals(c.propertyName) : - c.propertyName != null) return false; - return true; - } - - @Override - public int hashCode() { - int hash = 5; - hash = 61 * hash + (this.propertyName != null ? - this.propertyName.hashCode() : 0); - hash = 61 * hash + (this.defaultColorVariableName != null ? - this.defaultColorVariableName.hashCode() : 0); - hash = 61 * hash + Float.floatToIntBits(this.saturationOffset); - hash = 61 * hash + Float.floatToIntBits(this.brightnessOffset); - hash = 61 * hash + this.alphaOffset; - return hash; - } + Generator.writeSrcFile("PainterImpl", variables, painterName); } } diff --git a/make/tools/src/build/tools/generatenimbus/Shape.java b/make/tools/src/build/tools/generatenimbus/Shape.java new file mode 100644 index 0000000000000000000000000000000000000000..46e1a08bd68bf6d169263d05232f7861e59dd6cb --- /dev/null +++ b/make/tools/src/build/tools/generatenimbus/Shape.java @@ -0,0 +1,140 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package build.tools.generatenimbus; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlElements; + + +public abstract class Shape { + @XmlElement + private PaintPoints paintPoints; + public double getPaintX1() { return paintPoints.x1; } + public double getPaintX2() { return paintPoints.x2; } + public double getPaintY1() { return paintPoints.y1; } + public double getPaintY2() { return paintPoints.y2; } + + @XmlElements({ + @XmlElement(name = "matte", type = Matte.class), + @XmlElement(name = "gradient", type = Gradient.class), + @XmlElement(name = "radialGradient", type = RadialGradient.class) + }) + private Paint paint; + public Paint getPaint() { return paint; } + + static class PaintPoints { + @XmlAttribute double x1; + @XmlAttribute double y1; + @XmlAttribute double x2; + @XmlAttribute double y2; + } +} + +class Point { + @XmlAttribute private double x; + public double getX() { return x; } + + @XmlAttribute private double y; + public double getY() { return y; } + + @XmlAttribute(name="cp1x") private double cp1x; + public double getCp1X() { return cp1x; } + + @XmlAttribute(name="cp1y") private double cp1y; + public double getCp1Y() { return cp1y; } + + @XmlAttribute(name="cp2x") private double cp2x; + public double getCp2X() { return cp2x; } + + @XmlAttribute(name="cp2y") private double cp2y; + public double getCp2Y() { return cp2y; } + + public boolean isP1Sharp() { + return cp1x == x && cp1y == y; + } + + public boolean isP2Sharp() { + return cp2x == x && cp2y == y; + } +} + +class Path extends Shape { + @XmlElement(name="point") + @XmlElementWrapper(name="points") + private List controlPoints = new ArrayList(); + public List getControlPoints() { return controlPoints; } +} + +class Rectangle extends Shape { + @XmlAttribute private double x1; + public double getX1() { return x1; } + + @XmlAttribute private double x2; + public double getX2() { return x2; } + + @XmlAttribute private double y1; + public double getY1() { return y1; } + + @XmlAttribute private double y2; + public double getY2() { return y2; } + + @XmlAttribute + public double getRounding() { + double rounding = Math.abs(roundingX - x1) * 2; + return rounding > 2 ? rounding : 0; + } + + public void setRounding(double rounding) { + if (rounding > 0 && rounding < 2) { + rounding = 0; + } + roundingX = rounding / 2d + x1; + } + private double roundingX; + + public boolean isRounded() { + return getRounding() > 0; + } + +} + +class Ellipse extends Shape { + @XmlAttribute private double x1; + public double getX1() { return x1; } + + @XmlAttribute private double x2; + public double getX2() { return x2; } + + @XmlAttribute private double y1; + public double getY1() { return y1; } + + @XmlAttribute private double y2; + public double getY2() { return y2; } +} diff --git a/make/tools/src/build/tools/generatenimbus/SynthModel.java b/make/tools/src/build/tools/generatenimbus/SynthModel.java new file mode 100644 index 0000000000000000000000000000000000000000..6fbaa01f14ce37429fbd886d653ff95ee12153f4 --- /dev/null +++ b/make/tools/src/build/tools/generatenimbus/SynthModel.java @@ -0,0 +1,216 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package build.tools.generatenimbus; + +import java.awt.Font; +import java.util.ArrayList; +import java.util.List; +import javax.xml.bind.annotation.*; + + +@XmlRootElement(name="synthModel") +public class SynthModel { + @XmlElement private UIStyle style; + + @XmlElement(name="uiColor") + @XmlElementWrapper(name="colors") + private ArrayList colors; + + @XmlElement(name="uiFont") + @XmlElementWrapper(name="fonts") + private ArrayList fonts; + + @XmlElement(name="uiComponent") + @XmlElementWrapper(name="components") + private ArrayList components; + + public void initStyles() { + for (UIComponent c: components) { + c.initStyles(this.style); + } + } + + public void write(StringBuilder defBuffer, StringBuilder styleBuffer, String packageName) { + defBuffer.append(" //Color palette\n"); + for (UIColor c: colors) defBuffer.append(c.write()); + defBuffer.append('\n'); + + defBuffer.append(" //Font palette\n"); + defBuffer.append(" d.put(\"defaultFont\", new FontUIResource(defaultFont));\n"); + for (UIFont f: fonts) defBuffer.append(f.write()); + defBuffer.append('\n'); + + defBuffer.append(" //Border palette\n"); + defBuffer.append('\n'); + + defBuffer.append(" //The global style definition\n"); + defBuffer.append(style.write("")); + defBuffer.append('\n'); + + for (UIComponent c: components) { + String prefix = Utils.escape(c.getKey()); + defBuffer.append(" //Initialize ").append(prefix).append("\n"); + c.write(defBuffer, styleBuffer, c, prefix, packageName); + defBuffer.append('\n'); + } + } +} + +class Typeface { + public enum DeriveStyle { + Default, Off, On; + + @Override public String toString() { + switch (this) { + default: return "null"; + case On: return "true"; + case Off: return "false"; + } + } + } + + @XmlAttribute private String uiDefaultParentName; + @XmlAttribute(name="family") private String name; + @XmlAttribute private int size; + @XmlAttribute private DeriveStyle bold = DeriveStyle.Default; + @XmlAttribute private DeriveStyle italic = DeriveStyle.Default; + @XmlAttribute private float sizeOffset = 1f; + + public boolean isAbsolute() { + return uiDefaultParentName == null; + } + + public String write() { + if (isAbsolute()) { + int style = Font.PLAIN; + if (bold == DeriveStyle.On) { + style = style | Font.BOLD; + } + if (italic == DeriveStyle.On) { + style = style | Font.ITALIC; + } + + return String.format( + "new javax.swing.plaf.FontUIResource(\"%s\", %d, %d)", + name, style, size); + } else { + return String.format( + "new DerivedFont(\"%s\", %sf, %s, %s)", + uiDefaultParentName, String.valueOf(sizeOffset), bold, italic); + } + } +} + +class Border { + enum BorderType { + @XmlEnumValue("empty") EMPTY, + @XmlEnumValue("painter") PAINTER + } + @XmlAttribute private BorderType type; + @XmlAttribute private String painter; + @XmlAttribute private int top; + @XmlAttribute private int left; + @XmlAttribute private int bottom; + @XmlAttribute private int right; + + public String write() { + switch (type) { + case PAINTER: + return String.format("new PainterBorder(\"%s\", new Insets(%d, %d, %d, %d))", + painter, top, left, bottom, right); + case EMPTY: + return String.format("BorderFactory.createEmptyBorder(%d, %d, %d, %d)", + top, left, bottom, right); + default: + return "### Look, here's an unknown border! $$$"; + } + } +} + +class Insets { + @XmlAttribute int top; + @XmlAttribute int left; + @XmlAttribute int bottom; + @XmlAttribute int right; + + public Insets() { + this(0, 0, 0, 0); + } + + public Insets(int top, int left, int bottom, int right) { + this.top = top; + this.left = left; + this.bottom = bottom; + this.right = right; + } + + public String write(boolean uiResource) { + String uiSuffix = (uiResource ? "UIResource" : ""); + return String.format("new Insets%s(%d, %d, %d, %d)", + uiSuffix, top, left, bottom, right); + } +} + +class Dimension { + @XmlAttribute int width; + @XmlAttribute int height; + + public String write(boolean uiResource) { + String uiSuffix = (uiResource ? "UIResource" : ""); + return String.format("new Dimension%s(%d, %d)", uiSuffix, width, height); + } +} + +class Canvas { + @XmlElement private Dimension size; + public Dimension getSize() { return size; } + + @XmlElement(name="layer") private List layers; + public List getLayers() { return layers; } + + @XmlElement private Insets stretchingInsets = null; + public Insets getStretchingInsets() { return stretchingInsets; } + + public boolean isBlank() { + return layers.size() == 0 || (layers.size() == 1 && layers.get(0).isEmpty()); + } +} + +class Layer { + /** List of shapes in this layer, first shape is painted on top */ + @XmlElements({ + @XmlElement(name = "ellipse", type = Ellipse.class), + @XmlElement(name = "path", type = Path.class), + @XmlElement(name = "rectangle", type = Rectangle.class) + }) + @XmlElementWrapper(name="shapes") + private List shapes = new ArrayList(); + public List getShapes() { return shapes; } + + public boolean isEmpty() { + return shapes.isEmpty(); + } +} diff --git a/make/tools/src/build/tools/generatenimbus/UIDefault.java b/make/tools/src/build/tools/generatenimbus/UIDefault.java new file mode 100644 index 0000000000000000000000000000000000000000..10560a011dc3a33e6d42b6a2eeec6b8caa37910a --- /dev/null +++ b/make/tools/src/build/tools/generatenimbus/UIDefault.java @@ -0,0 +1,126 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package build.tools.generatenimbus; + +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; + +public class UIDefault { + @XmlAttribute private String name; + private T value; + + public String getName() { + return name; + } + + public T getValue() { + return value; + } + + public void setValue(T value) { + this.value = value; + } +} + +class UIColor extends UIDefault { + + @XmlElement + public void setMatte(Matte m) { + setValue(m); + } + + public String write() { + return String.format(" addColor(d, \"%s\", %s);\n", + getName(), getValue().write()); + } +} + +class UIFont extends UIDefault { + @XmlElement + public void setTypeface(Typeface t) { + setValue(t); + } + + public String write() { + return String.format(" d.put(\"%s\", %s);\n", + getName(), getValue().write()); + } +} + +class UIProperty extends UIDefault { + public static enum PropertyType { + BOOLEAN, INT, FLOAT, DOUBLE, STRING, FONT, COLOR, INSETS, DIMENSION, BORDER + } + @XmlAttribute private PropertyType type; + + @XmlElement private Border border; + @XmlElement private Dimension dimension; + @XmlElement private Insets insets; + @XmlElement private Matte matte; + @XmlElement private Typeface typeface; + + @XmlAttribute + @Override public void setValue(String value) { + super.setValue(value); + } + + public String write(String prefix) { + switch (type) { + case BOOLEAN: + return String.format(" d.put(\"%s%s\", Boolean.%s);\n", + prefix, getName(), getValue().toUpperCase()); ///autobox + case STRING: + return String.format(" d.put(\"%s%s\", \"%s\");\n", + prefix, getName(), getValue()); + case INT: + return String.format(" d.put(\"%s%s\", new Integer(%s));\n", + prefix, getName(), getValue()); + case FLOAT: + return String.format(" d.put(\"%s%s\", new Float(%sf));\n", + prefix, getName(), getValue()); + case DOUBLE: + return String.format(" d.put(\"%s%s\", new Double(%s));\n", + prefix, getName(), getValue()); + case COLOR: + return String.format(" addColor(d, \"%s%s\", %s);\n", + prefix, getName(), matte.write()); + case FONT: + return String.format(" d.put(\"%s%s\", %s);\n", + prefix, getName(), typeface.write()); + case INSETS: + return String.format(" d.put(\"%s%s\", %s);\n", + prefix, getName(), insets.write(true)); + case DIMENSION: + return String.format(" d.put(\"%s%s\", new DimensionUIResource(%d, %d));\n", + prefix, getName(), dimension.width, dimension.height); + case BORDER: + return String.format(" d.put(\"%s%s\", new BorderUIResource(%s));\n", + prefix, getName(), border.write()); + default: + return "### Look, something's wrong with UIProperty.write() $$$"; + } + } +} diff --git a/make/tools/src/build/tools/generatenimbus/UIStyle.java b/make/tools/src/build/tools/generatenimbus/UIStyle.java new file mode 100644 index 0000000000000000000000000000000000000000..1e5c5043f6c8b1fb51cd92fefed5c56aa529dd60 --- /dev/null +++ b/make/tools/src/build/tools/generatenimbus/UIStyle.java @@ -0,0 +1,399 @@ +/* + * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package build.tools.generatenimbus; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import javax.xml.bind.annotation.XmlAttribute; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlElementWrapper; +import javax.xml.bind.annotation.XmlElements; + + +class UIStyle { + public static enum CacheMode { + NO_CACHING, FIXED_SIZES, NINE_SQUARE_SCALE + } + + @XmlElement private UIColor textForeground = null; + @XmlElement(name="inherit-textForeground") + private boolean textForegroundInherited = true; + + @XmlElement private UIColor textBackground = null; + @XmlElement(name="inherit-textBackground") + private boolean textBackgroundInherited = true; + + @XmlElement private UIColor background = null; + @XmlElement(name="inherit-background") + private boolean backgroundInherited = true; + + @XmlElement private boolean cacheSettingsInherited = true; + @XmlElement CacheMode cacheMode = CacheMode.FIXED_SIZES; + @XmlElement String maxHozCachedImgScaling = "1.0"; + @XmlElement String maxVertCachedImgScaling = "1.0"; + + @XmlElement(name="uiProperty") + @XmlElementWrapper(name="uiproperties") + private List uiProperties = new ArrayList(); + + private UIStyle parentStyle = null; + public void setParentStyle(UIStyle parentStyle) { + this.parentStyle = parentStyle; + } + + public CacheMode getCacheMode() { + if (cacheSettingsInherited) { + return (parentStyle == null ? + CacheMode.FIXED_SIZES : parentStyle.getCacheMode()); + } else { + return cacheMode; + } + } + + public String getMaxHozCachedImgScaling() { + if (cacheSettingsInherited) { + return (parentStyle == null ? + "1.0" : parentStyle.getMaxHozCachedImgScaling()); + } else { + return maxHozCachedImgScaling; + } + } + + public String getMaxVertCachedImgScaling() { + if (cacheSettingsInherited) { + return (parentStyle == null ? + "1.0" : parentStyle.getMaxVertCachedImgScaling()); + } else { + return maxVertCachedImgScaling; + } + } + + public String write(String prefix) { + StringBuilder sb = new StringBuilder(); + if (! textForegroundInherited) { + sb.append(String.format(" addColor(d, \"%s%s\", %s);\n", + prefix, "textForeground", textForeground.getValue().write())); + } + if (! textBackgroundInherited) { + sb.append(String.format(" addColor(d, \"%s%s\", %s);\n", + prefix, "textBackground", textBackground.getValue().write())); + } + if (! backgroundInherited) { + sb.append(String.format(" addColor(d, \"%s%s\", %s);\n", + prefix, "background", background.getValue().write())); + } + for (UIProperty property : uiProperties) { + sb.append(property.write(prefix)); + } + return sb.toString(); + } +} + +class UIRegion { + @XmlAttribute protected String name; + @XmlAttribute protected String key; + @XmlAttribute private boolean opaque = false; + + @XmlElement private Insets contentMargins = new Insets(0, 0, 0, 0); + + @XmlElement(name="state") + @XmlElementWrapper(name="backgroundStates") + protected List backgroundStates = new ArrayList(); + public List getBackgroundStates() { return backgroundStates; } + + @XmlElement(name="state") + @XmlElementWrapper(name="foregroundStates") + protected List foregroundStates = new ArrayList(); + public List getForegroundStates() { return foregroundStates; } + + @XmlElement(name="state") + @XmlElementWrapper(name="borderStates") + protected List borderStates = new ArrayList(); + public List getBorderStates() { return borderStates; } + + @XmlElement private UIStyle style = new UIStyle(); + + @XmlElements({ + @XmlElement(name = "region", type = UIRegion.class), + @XmlElement(name = "uiComponent", type = UIComponent.class), + @XmlElement(name = "uiIconRegion", type = UIIconRegion.class) + }) + @XmlElementWrapper(name="regions") + private List subRegions = new ArrayList(); + public List getSubRegions() { return subRegions; } + + protected void initStyles(UIStyle parentStyle) { + style.setParentStyle(parentStyle); + for (UIState state: backgroundStates) { + state.getStyle().setParentStyle(this.style); + } + for (UIState state: foregroundStates) { + state.getStyle().setParentStyle(this.style); + } + for (UIState state: borderStates) { + state.getStyle().setParentStyle(this.style); + } + for (UIRegion region: subRegions) { + region.initStyles(this.style); + } + } + + public String getKey() { + return key == null || "".equals(key) ? name : key; + } + + private boolean hasCanvas() { + for (UIState s : backgroundStates) { + if (s.hasCanvas()) return true; + } + for (UIState s : borderStates) { + if (s.hasCanvas()) return true; + } + for (UIState s : foregroundStates) { + if (s.hasCanvas()) return true; + } + for (UIRegion r: subRegions) { + if (r.hasCanvas()) return true; + } + return false; + } + + public void write(StringBuilder sb, StringBuilder styleBuffer, + UIComponent comp, String prefix, String pkg) { + // write content margins + sb.append(String.format(" d.put(\"%s.contentMargins\", %s);\n", + prefix, contentMargins.write(true))); + // write opaque if true + if (opaque) { + sb.append(String.format(" d.put(\"%s.opaque\", Boolean.TRUE);\n", prefix)); + } + + // register component with LAF + String regionCode = "Region." + Utils.regionNameToCaps(name); + styleBuffer.append(String.format(" register(%s, \"%s\");\n", + regionCode, prefix)); + + //write the State, if necessary + StringBuffer regString = new StringBuffer(); + List types = comp.getStateTypes(); + if (types != null && types.size() > 0) { + for (UIStateType type : types) { + regString.append(type.getKey()); + regString.append(","); + } + //remove the last "," + regString.deleteCharAt(regString.length() - 1); + } + + if (! regString.equals("Enabled,MouseOver,Pressed,Disabled,Focused,Selected,Default") && types.size() > 0) { + //there were either custom states, or the normal states were in a custom order + //so go ahead and write out prefix.State + sb.append(String.format(" d.put(\"%s.States\", \"%s\");\n", + prefix, regString)); + } + + // write out any custom states, if necessary + for (UIStateType type : types) { + String synthState = type.getKey(); + if (! "Enabled".equals(synthState) && + ! "MouseOver".equals(synthState) && + ! "Pressed".equals(synthState) && + ! "Disabled".equals(synthState) && + ! "Focused".equals(synthState) && + ! "Selected".equals(synthState) && + ! "Default".equals(synthState)) { + + //what we have here, gentlemen, is a bona-fide custom state. + //if the type is not one of the standard types, then construct a name for + //the new type, and write out a new subclass of State. + String className = Utils.normalize(prefix) + synthState + "State"; + sb.append(String.format(" d.put(\"%s.%s\", new %s());\n", + prefix, synthState, className)); + + String body = type.getCodeSnippet(); + Map variables = Generator.getVariables(); + variables.put("STATE_NAME", className); + variables.put("STATE_KEY", synthState); + variables.put("BODY", body); + + Generator.writeSrcFile("StateImpl", variables, className); + } + } + + // write style + sb.append(style.write(prefix + '.')); + + String fileName = Utils.normalize(prefix) + "Painter"; + boolean hasCanvas = hasCanvas(); + if (hasCanvas) { + PainterGenerator.writePainter(this, fileName); + } + // write states ui defaults + for (UIState state : backgroundStates) { + state.write(sb, prefix, pkg, fileName, "background"); + } + for (UIState state : foregroundStates) { + state.write(sb, prefix, pkg, fileName, "foreground"); + } + for (UIState state : borderStates) { + state.write(sb, prefix, pkg, fileName, "border"); + } + + // handle sub regions + for (UIRegion subreg : subRegions) { + String p = prefix; + if (! (subreg instanceof UIIconRegion)) { + p = prefix + ":" + Utils.escape(subreg.getKey()); + } + UIComponent c = comp; + if (subreg instanceof UIComponent) { + c = (UIComponent) subreg; + } + subreg.write(sb, styleBuffer, c, p, pkg); + } + } +} + +class UIIconRegion extends UIRegion { + @XmlAttribute private String basicKey; + + @Override public void write(StringBuilder sb, StringBuilder styleBuffer, UIComponent comp, String prefix, String pkg) { + Dimension size = null; + String fileNamePrefix = Utils.normalize(prefix) + "Painter"; + // write states ui defaults + for (UIState state : backgroundStates) { + Canvas canvas = state.getCanvas(); + if (!canvas.isBlank()) { + state.write(sb, prefix, pkg, fileNamePrefix, getKey()); + size = canvas.getSize(); + } + } + + if (size != null) { + // Put SynthIconImpl wrapper in UiDefaults + String k = (basicKey == null ? prefix + "." + getKey() : basicKey); + sb.append(String.format( + " d.put(\"%s\", new NimbusIcon(\"%s\", \"%sPainter\", %d, %d));\n", + k, prefix, getKey(), size.width, size.height)); + } + } +} + +class UIComponent extends UIRegion { + @XmlAttribute private String componentName; + + @XmlElement(name="stateType") + @XmlElementWrapper(name="stateTypes") + private List stateTypes = new ArrayList(); + public List getStateTypes() { return stateTypes; } + + @Override public String getKey() { + if (key == null || "".equals(key)) { + if (componentName == null || "".equals(componentName)) { + return name; + } else { + return "\"" + componentName + "\""; + } + } else { + return key; + } + } +} + +class UIState { + @XmlAttribute private String stateKeys; + public String getStateKeys() { return stateKeys; } + + /** Indicates whether to invert the meaning of the 9-square stretching insets */ + @XmlAttribute private boolean inverted; + + /** A cached string representing the list of stateKeys deliminated with "+" */ + private String cachedName = null; + + @XmlElement private Canvas canvas; + public Canvas getCanvas() { return canvas; } + + @XmlElement private UIStyle style; + public UIStyle getStyle() { return style; } + + public boolean hasCanvas() { + return ! canvas.isBlank(); + } + + public static List stringToKeys(String keysString) { + return Arrays.asList(keysString.split("\\+")); + } + + public String getName() { + if (cachedName == null) { + StringBuilder buf = new StringBuilder(); + List keys = stringToKeys(stateKeys); + Collections.sort(keys); + for (Iterator iter = keys.iterator(); iter.hasNext();) { + buf.append(iter.next()); + if (iter.hasNext()) { + buf.append('+'); + } + } + cachedName = buf.toString(); + } + return cachedName; + } + + public void write(StringBuilder sb, String prefix, String pkg, String fileNamePrefix, String painterPrefix) { + String statePrefix = prefix + "[" + getName() + "]"; + // write state style + sb.append(style.write(statePrefix + '.')); + // write painter + if (hasCanvas()) { + writeLazyPainter(sb, statePrefix, pkg, fileNamePrefix, painterPrefix); + } + } + + private void writeLazyPainter(StringBuilder sb, String statePrefix, String packageNamePrefix, String fileNamePrefix, String painterPrefix) { + String cacheModeString = "AbstractRegionPainter.PaintContext.CacheMode." + style.getCacheMode(); + String stateConstant = Utils.statesToConstantName(painterPrefix + "_" + stateKeys); + sb.append(String.format( + " d.put(\"%s.%sPainter\", new LazyPainter(\"%s.%s\", %s.%s, %s, %s, %b, %s, %s, %s));\n", + statePrefix, painterPrefix, packageNamePrefix, fileNamePrefix, + fileNamePrefix, stateConstant, canvas.getStretchingInsets().write(false), + canvas.getSize().write(false), inverted, cacheModeString, + Utils.formatDouble(style.getMaxHozCachedImgScaling()), + Utils.formatDouble(style.getMaxVertCachedImgScaling()))); + } +} + +class UIStateType { + @XmlAttribute private String key; + public String getKey() { return key; } + + @XmlElement private String codeSnippet; + public String getCodeSnippet() { return codeSnippet; } +} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/GeneratorUtils.java b/make/tools/src/build/tools/generatenimbus/Utils.java similarity index 59% rename from make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/GeneratorUtils.java rename to make/tools/src/build/tools/generatenimbus/Utils.java index 0d0fb75f52aa01891b417bd11178f37b05a510f1..09599303cae361087976954e2705d7ecb8aaa9b3 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/GeneratorUtils.java +++ b/make/tools/src/build/tools/generatenimbus/Utils.java @@ -22,158 +22,61 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.synthdesigner.generator; -import javax.swing.plaf.synth.Region; -import javax.swing.plaf.synth.SynthConstants; - -/** - * GeneratorUtils - * - * @author Richard Bair - * @author Jasper Potts - */ -class GeneratorUtils { - private GeneratorUtils() {} +package build.tools.generatenimbus; - /** - * Given a synth state, create the appropriate name as it would be used for a ui default key. - *

- * For example: - *

- * enabled enabled+over enabled+over+selected - */ - static String toUIDefaultKey(int state) { - StringBuffer buffer = new StringBuffer(); - if ((state & SynthConstants.DEFAULT) == SynthConstants.DEFAULT) { - buffer.append("default"); - } - if ((state & SynthConstants.DISABLED) == SynthConstants.DISABLED) { - if (buffer.length() > 0) buffer.append("+"); - buffer.append("disabled"); - } - if ((state & SynthConstants.ENABLED) == SynthConstants.ENABLED) { - if (buffer.length() > 0) buffer.append("+"); - buffer.append("enabled"); - } - if ((state & SynthConstants.FOCUSED) == SynthConstants.FOCUSED) { - if (buffer.length() > 0) buffer.append("+"); - buffer.append("focused"); - } - if ((state & SynthConstants.MOUSE_OVER) == SynthConstants.MOUSE_OVER) { - if (buffer.length() > 0) buffer.append("+"); - buffer.append("over"); - } - if ((state & SynthConstants.PRESSED) == SynthConstants.PRESSED) { - if (buffer.length() > 0) buffer.append("+"); - buffer.append("down"); - } - if ((state & SynthConstants.SELECTED) == SynthConstants.SELECTED) { - if (buffer.length() > 0) buffer.append("+"); - buffer.append("selected"); - } - return buffer.toString(); - } +import java.util.ArrayList; +import java.util.List; +import javax.swing.plaf.synth.Region; - //takes a states string of the form Enabled+Foo+Bar. - //removes any whitespace. Replaces the + signs with And. - static String toClassName(String states) { - String s = states.replace(" ", ""); - s = states.replace("+", "And"); - return s; - } +public class Utils { - //takes a states string of the form Enabled+Foo+Bar. - //removes any whitespace. Replaces the + signs with _. - //capitalizes the whole lot - static String toConstantName(String states) { - String s = states.replace(" ", ""); - s = states.replace("+", "_"); - return s.toUpperCase(); + public static String escape(String s) { + return s.replace("\"", "\\\""); } - /** - * Given a string "s" of the form: - * - * A.\"A.a\".B - * - * Make it such that: - * - * AAAB - * - * For example, ComboBox.\"ComboBox.arrowButton\" would become - * ComboBoxComboBoxArrowButton - * - * @param s - * @return - */ - static String makePretty(String s) { + public static String normalize(String s) { char[] src = s.toCharArray(); - char[] dst = new char[src.length]; - int dstIndex = 0; - for (int i=0; i parts = new ArrayList(); + boolean capitalize = false; + + for (int i = 0; i < src.length; i++) { + switch (src[i]) { + case '\\': + case '"': + break; + case '.': + capitalize = true; + break; + case ':': + parts.add(buf.toString()); + buf.delete(0, buf.length()); + capitalize = true; + break; + default: + buf.append(capitalize ? Character.toUpperCase(src[i]) : src[i]); + capitalize = false; + break; } - //copy over the current char. - dst[dstIndex++] = src[i]; } - //at this point, dstIndex is 1 greater than the last valid index position in dst - //or in other words it represents the count. - return new String(dst, 0, dstIndex); - } + parts.add(buf.toString()); - /** - * Encodes the given synth state as if it were specified in java code, such as - *

- * SynthConstants.ENABLED | SynthConstants.MOUSE_OVER - */ - static String toJavaList(int state) { - StringBuffer buffer = new StringBuffer(); - if ((state & SynthConstants.DEFAULT) == SynthConstants.DEFAULT) { - buffer.append("SynthConstants.DEFAULT"); - } - if ((state & SynthConstants.DISABLED) == SynthConstants.DISABLED) { - if (buffer.length() > 0) buffer.append(" | "); - buffer.append("SynthConstants.DISABLED"); - } - if ((state & SynthConstants.ENABLED) == SynthConstants.ENABLED) { - if (buffer.length() > 0) buffer.append(" | "); - buffer.append("SynthConstants.ENABLED"); - } - if ((state & SynthConstants.FOCUSED) == SynthConstants.FOCUSED) { - if (buffer.length() > 0) buffer.append(" | "); - buffer.append("SynthConstants.FOCUSED"); - } - if ((state & SynthConstants.MOUSE_OVER) == SynthConstants.MOUSE_OVER) { - if (buffer.length() > 0) buffer.append(" | "); - buffer.append("SynthConstants.MOUSE_OVER"); - } - if ((state & SynthConstants.PRESSED) == SynthConstants.PRESSED) { - if (buffer.length() > 0) buffer.append(" | "); - buffer.append("SynthConstants.PRESSED"); - } - if ((state & SynthConstants.SELECTED) == SynthConstants.SELECTED) { - if (buffer.length() > 0) buffer.append(" | "); - buffer.append("SynthConstants.SELECTED"); + // Try to optimize long class names by omitting repeating prefixes, e.g. + // SliderTrackPainter.java instead of SliderSliderTrackPainter.java + String result = parts.get(0); + for (int i = 1; i < parts.size(); i++) { + String part = parts.get(i); + if (part.startsWith(result)) { + result = part; + } else { + result += part; + } } - return buffer.toString(); + return result; } - /** - * Checks the given region name to discover if it is one of the standard synth regions. If so, return the name in - * caps and such. Otherwise, return a big fat null. - *

- * I have to do this because, unfortunately, synth's Region doesn't implement equals. - */ - static String getRegionNameCaps(String regionName) { + public static String regionNameToCaps(String regionName) { if (Region.ARROW_BUTTON.getName().equals(regionName)) { return "ARROW_BUTTON"; } else if (Region.BUTTON.getName().equals(regionName)) { @@ -289,7 +192,24 @@ class GeneratorUtils { } else if (Region.VIEWPORT.getName().equals(regionName)) { return "VIEWPORT"; } - System.err.println("[Info] Couldn't find a Region for " + regionName); - return null; + throw new RuntimeException("Bad Region name " + regionName); + } + + public static String statesToConstantName(String states) { + String s = states.replace(" ", ""); + s = states.replace("+", "_"); + return s.toUpperCase(); + } + + //takes a states string of the form Enabled+Foo+Bar. + //removes any whitespace. Replaces the + signs with And. + public static String statesToClassName(String states) { + String s = states.replace(" ", ""); + s = states.replace("+", "And"); + return s; + } + + public static String formatDouble(String doubleValue) { + return doubleValue.replace("INF", "Double.POSITIVE_INFINITY"); } } diff --git a/make/tools/swing-nimbus/Makefile b/make/tools/swing-nimbus/Makefile deleted file mode 100644 index 36df571c5f5be4c8f7a283ecdc8af1d905dee0fa..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/Makefile +++ /dev/null @@ -1,91 +0,0 @@ -# -# Copyright 1998-2005 Sun Microsystems, Inc. All Rights Reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. Sun designates this -# particular file as subject to the "Classpath" exception as provided -# by Sun in the LICENSE file that accompanied this code. -# -# This code 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 -# version 2 for more details (a copy is included in the LICENSE file that -# accompanied this code). -# -# You should have received a copy of the GNU General Public License version -# 2 along with this work; if not, write to the Free Software Foundation, -# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. -# -# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, -# CA 95054 USA or visit www.sun.com if you need additional information or -# have any questions. -# - -# -# Makefile for building the Nimbus generator -# - -BUILDDIR = ../.. -PACKAGE = org.jdesktop.synthdesigner.generator -PRODUCT = tools -PROGRAM = nimbus_generator -include $(BUILDDIR)/common/Defs.gmk - -BUILDTOOL_SOURCE_ROOT = classes -BUILDTOOL_MAIN = $(PKGDIR)/Generator.java - -# -# Files -# - -MAIN_CLASS_FILE = $(BUILDTOOLCLASSDIR)/$(BUILDTOOL_MAIN:%.java=%.class) -SOURCE_FILES = $(shell $(FIND) $(BUILDTOOL_SOURCE_ROOT) -name '*.java' -print) - -TEMPLATE_FILES = $(SHARE_SRC)/classes/javax/swing/plaf/nimbus/Defaults.template \ - $(SHARE_SRC)/classes/javax/swing/plaf/nimbus/PainterImpl.template \ - $(SHARE_SRC)/classes/javax/swing/plaf/nimbus/StateImpl.template -TEMPLATE_DEST = $(BUILDTOOLCLASSDIR)/org/jdesktop/synthdesigner/generator/resources - -JIBX_FILES = $(BUILDTOOL_SOURCE_ROOT)/org/jdesktop/swingx/designer/Designer.jibx.xml \ - $(BUILDTOOL_SOURCE_ROOT)/org/jdesktop/synthdesigner/synthmodel/SynthModel.jibx.xml -JIBX_LIBS_CP = $(JIBX_LIBS_PATH)/bcel.jar$(CLASSPATH_SEPARATOR)$(JIBX_LIBS_PATH)/xpp3.jar$(CLASSPATH_SEPARATOR)$(JIBX_LIBS_PATH)/jibx-bind.jar$(CLASSPATH_SEPARATOR)$(JIBX_LIBS_PATH)/jibx-run.jar -JIBX_LIBS_LIST = $(subst $(CLASSPATH_SEPARATOR), ,$(JIBX_LIBS_CP)) - - -# -# Rules -# - -include $(BUILDDIR)/common/BuildToolJar.gmk - -$(MAIN_CLASS_FILE): $(SOURCE_FILES) $(JIBX_LIBS_LIST) - @$(MKDIR) -p $(BUILDTOOLCLASSDIR) - $(BOOT_JAVAC_CMD) -classpath "$(JIBX_LIBS_CP)" \ - -d $(BUILDTOOLCLASSDIR) -sourcepath $(BUILDTOOL_SOURCE_ROOT) \ - $(SOURCE_FILES) - -$(TEMPLATE_DEST): $(TEMPLATE_FILES) - $(MKDIR) -p $(TEMPLATE_DEST) - $(RM) $(TEMPLATE_DEST)/*.template - $(CP) $(TEMPLATE_FILES) $(TEMPLATE_DEST) - -$(BUILDTOOL_MANIFEST_FILE): $(MAIN_CLASS_FILE) - $(ECHO) "Main-Class: $(BUILTTOOL_MAINCLASS)" > $@ - $(ECHO) "Class-Path: $(JIBX_LIBS_LIST:$(JIBX_LIBS_PATH)/%=%)" >> $@ - $(CP) $(JIBX_LIBS_LIST) $(BUILDTOOLJARDIR) - -$(BUILDTOOL_JAR_FILE): $(MAIN_CLASS_FILE) $(TEMPLATE_DEST) \ - $(JIBX_FILES) $(BUILDTOOL_MANIFEST_FILE) - @$(prep-target) - $(BOOT_JAVA_CMD) \ - -classpath "$(JIBX_LIBS_CP)$(CLASSPATH_SEPARATOR)$(BUILDTOOLCLASSDIR)" \ - org.jibx.binding.Compile $(JIBX_FILES) - $(BOOT_JAR_CMD) cfm $@ $(BUILDTOOL_MANIFEST_FILE) \ - -C $(BUILDTOOLCLASSDIR) org \ - $(BOOT_JAR_JFLAGS) || $(RM) $@ - @$(java-vm-cleanup) - -clean clobber:: - $(RM) -r $(TEMPLATE_DEST) diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/beans/AbstractBean.java b/make/tools/swing-nimbus/classes/org/jdesktop/beans/AbstractBean.java deleted file mode 100644 index 91325319b1ac01edaa86954e5f4cb56e92e1ee23..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/beans/AbstractBean.java +++ /dev/null @@ -1,475 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.beans; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.beans.PropertyChangeSupport; -import java.beans.PropertyVetoException; -import java.beans.VetoableChangeListener; -import java.beans.VetoableChangeSupport; - -/** - *

A convenience class from which to extend all non-visual AbstractBeans. It - * manages the PropertyChange notification system, making it relatively trivial - * to add support for property change events in getters/setters.

- * - *

A non-visual java bean is a Java class that conforms to the AbstractBean - * patterns to allow visual manipulation of the bean's properties and event - * handlers at design-time.

- * - *

Here is a simple example bean that contains one property, foo, and the - * proper pattern for implementing property change notification: - *


- *  public class ABean extends AbstractBean {
- *    private String foo;
- *
- *    public void setFoo(String newFoo) {
- *      String old = getFoo();
- *      this.foo = newFoo;
- *      firePropertyChange("foo", old, getFoo());
- *    }
- *
- *    public String getFoo() {
- *      return foo;
- *    }
- *  }
- * 

- * - *

You will notice that "getFoo()" is used in the setFoo method rather than - * accessing "foo" directly for the gets. This is done intentionally so that if - * a subclass overrides getFoo() to return, for instance, a constant value the - * property change notification system will continue to work properly.

- * - *

The firePropertyChange method takes into account the old value and the new - * value. Only if the two differ will it fire a property change event. So you can - * be assured from the above code fragment that a property change event will only - * occur if old is indeed different from getFoo()

- * - *

AbstractBean also supports {@link VetoablePropertyChange} events. - * These events are similar to PropertyChange events, except a special - * exception can be used to veto changing the property. For example, perhaps the - * property is changing from "fred" to "red", but a listener deems that "red" is - * unexceptable. In this case, the listener can fire a veto exception and the property must - * remain "fred". For example: - *


- *  public class ABean extends AbstractBean {
- *    private String foo;
- *
- *    public void setFoo(String newFoo) throws PropertyVetoException {
- *      String old = getFoo();
- *      this.foo = newFoo;
- *      fireVetoableChange("foo", old, getFoo());
- *    }
- *
- *    public String getFoo() {
- *      return foo;
- *    }
- *  }
- *
- *  public class Tester {
- *    public static void main(String... args) {
- *      try {
- *        ABean a = new ABean();
- *        a.setFoo("fred");
- *        a.addVetoableChangeListener(new VetoableChangeListener() {
- *          public void vetoableChange(PropertyChangeEvent evt) throws PropertyVetoException {
- *            if ("red".equals(evt.getNewValue()) {
- *              throw new PropertyVetoException("Cannot be red!", evt);
- *            }
- *          }
- *        }
- *        a.setFoo("red");
- *      } catch (Exception e) {
- *        e.printStackTrace(); // this will be executed
- *      }
- *    }
- *  }
- * 

- * - * @status REVIEWED - * @author rbair - */ -public abstract class AbstractBean { - /** - * Helper class that manages all the property change notification machinery. - * PropertyChangeSupport cannot be extended directly because it requires - * a bean in the constructor, and the "this" argument is not valid until - * after super construction. Hence, delegation instead of extension - */ - private transient PropertyChangeSupport pcs; - - /** - * Helper class that manages all the veto property change notification machinery. - */ - private transient VetoableChangeSupport vcs; - - /** Creates a new instance of AbstractBean */ - protected AbstractBean() { - pcs = new PropertyChangeSupport(this); - vcs = new VetoableChangeSupport(this); - } - - /** - * Creates a new instance of AbstractBean, using the supplied PropertyChangeSupport and - * VetoableChangeSupport delegates. Neither of these may be null. - */ - protected AbstractBean(PropertyChangeSupport pcs, VetoableChangeSupport vcs) { - if (pcs == null) { - throw new NullPointerException("PropertyChangeSupport must not be null"); - } - if (vcs == null) { - throw new NullPointerException("VetoableChangeSupport must not be null"); - } - - this.pcs = pcs; - this.vcs = vcs; - } - - /** - * Add a PropertyChangeListener to the listener list. - * The listener is registered for all properties. - * The same listener object may be added more than once, and will be called - * as many times as it is added. - * If listener is null, no exception is thrown and no action - * is taken. - * - * @param listener The PropertyChangeListener to be added - */ - public final void addPropertyChangeListener(PropertyChangeListener listener) { - pcs.addPropertyChangeListener(listener); - } - - /** - * Remove a PropertyChangeListener from the listener list. - * This removes a PropertyChangeListener that was registered - * for all properties. - * If listener was added more than once to the same event - * source, it will be notified one less time after being removed. - * If listener is null, or was never added, no exception is - * thrown and no action is taken. - * - * @param listener The PropertyChangeListener to be removed - */ - public final void removePropertyChangeListener(PropertyChangeListener listener) { - pcs.removePropertyChangeListener(listener); - } - - /** - * Returns an array of all the listeners that were added to the - * PropertyChangeSupport object with addPropertyChangeListener(). - *

- * If some listeners have been added with a named property, then - * the returned array will be a mixture of PropertyChangeListeners - * and PropertyChangeListenerProxys. If the calling - * method is interested in distinguishing the listeners then it must - * test each element to see if it's a - * PropertyChangeListenerProxy, perform the cast, and examine - * the parameter. - * - *

-     * PropertyChangeListener[] listeners = bean.getPropertyChangeListeners();
-     * for (int i = 0; i < listeners.length; i++) {
-     *   if (listeners[i] instanceof PropertyChangeListenerProxy) {
-     *     PropertyChangeListenerProxy proxy =
-     *                    (PropertyChangeListenerProxy)listeners[i];
-     *     if (proxy.getPropertyName().equals("foo")) {
-     *       // proxy is a PropertyChangeListener which was associated
-     *       // with the property named "foo"
-     *     }
-     *   }
-     * }
-     *
- * - * @see java.beans.PropertyChangeListenerProxy - * @return all of the PropertyChangeListeners added or an - * empty array if no listeners have been added - */ - public final PropertyChangeListener[] getPropertyChangeListeners() { - return pcs.getPropertyChangeListeners(); - } - - /** - * Add a PropertyChangeListener for a specific property. The listener - * will be invoked only when a call on firePropertyChange names that - * specific property. - * The same listener object may be added more than once. For each - * property, the listener will be invoked the number of times it was added - * for that property. - * If propertyName or listener is null, no - * exception is thrown and no action is taken. - * - * @param propertyName The name of the property to listen on. - * @param listener The PropertyChangeListener to be added - */ - public final void addPropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.addPropertyChangeListener(propertyName, listener); - } - - /** - * Remove a PropertyChangeListener for a specific property. - * If listener was added more than once to the same event - * source for the specified property, it will be notified one less time - * after being removed. - * If propertyName is null, no exception is thrown and no - * action is taken. - * If listener is null, or was never added for the specified - * property, no exception is thrown and no action is taken. - * - * @param propertyName The name of the property that was listened on. - * @param listener The PropertyChangeListener to be removed - */ - public final void removePropertyChangeListener(String propertyName, PropertyChangeListener listener) { - pcs.removePropertyChangeListener(propertyName, listener); - } - - /** - * Returns an array of all the listeners which have been associated - * with the named property. - * - * @param propertyName The name of the property being listened to - * @return all of the PropertyChangeListeners associated with - * the named property. If no such listeners have been added, - * or if propertyName is null, an empty array is - * returned. - */ - public final PropertyChangeListener[] getPropertyChangeListeners(String propertyName) { - return pcs.getPropertyChangeListeners(propertyName); - } - - /** - * Report a bound property update to any registered listeners. - * No event is fired if old and new are equal and non-null. - * - *

- * This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code - * PropertyChangeEvent} value. - * - * @param propertyName The programmatic name of the property - * that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. - */ - protected final void firePropertyChange(String propertyName, Object oldValue, Object newValue) { - pcs.firePropertyChange(propertyName, oldValue, newValue); - } - - /** - * Fire an existing PropertyChangeEvent to any registered listeners. - * No event is fired if the given event's old and new values are - * equal and non-null. - * @param evt The PropertyChangeEvent object. - */ - protected final void firePropertyChange(PropertyChangeEvent evt) { - pcs.firePropertyChange(evt); - } - - - /** - * Report a bound indexed property update to any registered - * listeners. - *

- * No event is fired if old and new values are equal - * and non-null. - * - *

- * This is merely a convenience wrapper around the more general - * firePropertyChange method that takes {@code PropertyChangeEvent} value. - * - * @param propertyName The programmatic name of the property that - * was changed. - * @param index index of the property element that was changed. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. - */ - protected final void fireIndexedPropertyChange(String propertyName, - int index, Object oldValue, Object newValue) { - pcs.fireIndexedPropertyChange(propertyName, index, oldValue, newValue); - } - - /** - * Check if there are any listeners for a specific property, including - * those registered on all properties. If propertyName - * is null, only check for listeners registered on all properties. - * - * @param propertyName the property name. - * @return true if there are one or more listeners for the given property - */ - protected final boolean hasPropertyChangeListeners(String propertyName) { - return pcs.hasListeners(propertyName); - } - - /** - * Check if there are any listeners for a specific property, including - * those registered on all properties. If propertyName - * is null, only check for listeners registered on all properties. - * - * @param propertyName the property name. - * @return true if there are one or more listeners for the given property - */ - protected final boolean hasVetoableChangeListeners(String propertyName) { - return vcs.hasListeners(propertyName); - } - - /** - * Add a VetoableListener to the listener list. - * The listener is registered for all properties. - * The same listener object may be added more than once, and will be called - * as many times as it is added. - * If listener is null, no exception is thrown and no action - * is taken. - * - * @param listener The VetoableChangeListener to be added - */ - - public final void addVetoableChangeListener(VetoableChangeListener listener) { - vcs.addVetoableChangeListener(listener); - } - - /** - * Remove a VetoableChangeListener from the listener list. - * This removes a VetoableChangeListener that was registered - * for all properties. - * If listener was added more than once to the same event - * source, it will be notified one less time after being removed. - * If listener is null, or was never added, no exception is - * thrown and no action is taken. - * - * @param listener The VetoableChangeListener to be removed - */ - public final void removeVetoableChangeListener(VetoableChangeListener listener) { - vcs.removeVetoableChangeListener(listener); - } - - /** - * Returns the list of VetoableChangeListeners. If named vetoable change listeners - * were added, then VetoableChangeListenerProxy wrappers will returned - *

- * @return List of VetoableChangeListeners and VetoableChangeListenerProxys - * if named property change listeners were added. - */ - public final VetoableChangeListener[] getVetoableChangeListeners(){ - return vcs.getVetoableChangeListeners(); - } - - /** - * Add a VetoableChangeListener for a specific property. The listener - * will be invoked only when a call on fireVetoableChange names that - * specific property. - * The same listener object may be added more than once. For each - * property, the listener will be invoked the number of times it was added - * for that property. - * If propertyName or listener is null, no - * exception is thrown and no action is taken. - * - * @param propertyName The name of the property to listen on. - * @param listener The VetoableChangeListener to be added - */ - - public final void addVetoableChangeListener(String propertyName, - VetoableChangeListener listener) { - vcs.addVetoableChangeListener(propertyName, listener); - } - - /** - * Remove a VetoableChangeListener for a specific property. - * If listener was added more than once to the same event - * source for the specified property, it will be notified one less time - * after being removed. - * If propertyName is null, no exception is thrown and no - * action is taken. - * If listener is null, or was never added for the specified - * property, no exception is thrown and no action is taken. - * - * @param propertyName The name of the property that was listened on. - * @param listener The VetoableChangeListener to be removed - */ - - public final void removeVetoableChangeListener(String propertyName, - VetoableChangeListener listener) { - vcs.removeVetoableChangeListener(propertyName, listener); - } - - /** - * Returns an array of all the listeners which have been associated - * with the named property. - * - * @param propertyName The name of the property being listened to - * @return all the VetoableChangeListeners associated with - * the named property. If no such listeners have been added, - * or if propertyName is null, an empty array is - * returned. - */ - public final VetoableChangeListener[] getVetoableChangeListeners(String propertyName) { - return vcs.getVetoableChangeListeners(propertyName); - } - - /** - * Report a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. - *

- * No event is fired if old and new are equal and non-null. - * - * @param propertyName The programmatic name of the property - * that is about to change.. - * @param oldValue The old value of the property. - * @param newValue The new value of the property. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. - */ - protected final void fireVetoableChange(String propertyName, - Object oldValue, Object newValue) - throws PropertyVetoException { - vcs.fireVetoableChange(propertyName, oldValue, newValue); - } - - /** - * Fire a vetoable property update to any registered listeners. If - * anyone vetos the change, then fire a new event reverting everyone to - * the old value and then rethrow the PropertyVetoException. - *

- * No event is fired if old and new are equal and non-null. - * - * @param evt The PropertyChangeEvent to be fired. - * @exception PropertyVetoException if the recipient wishes the property - * change to be rolled back. - */ - protected final void fireVetoableChange(PropertyChangeEvent evt) - throws PropertyVetoException { - vcs.fireVetoableChange(evt); - } - - /** - * @inheritDoc - */ - public Object clone() throws CloneNotSupportedException { - AbstractBean result = (AbstractBean) super.clone(); - result.pcs = new PropertyChangeSupport(result); - result.vcs = new VetoableChangeSupport(result); - return result; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/BezierControlPoint.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/BezierControlPoint.java deleted file mode 100644 index be2bc4efbd9ca675436b1a3d1313ff24a665ecfb..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/BezierControlPoint.java +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import java.awt.BasicStroke; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.awt.geom.GeneralPath; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; - -/** - * BezierControlPoint - * - * @author Created by Jasper Potts (May 29, 2007) - */ -public class BezierControlPoint extends ControlPoint { - private HandleControlPoint cp1 = new HandleControlPoint(); - private HandleControlPoint cp2 = new HandleControlPoint(); - private transient boolean makingChange = false; - private transient PropertyChangeListener cpListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { -// if (!makingChange) { -// makingChange = true; -// if (evt.getSource() == cp1) { -// double angle = Math.tan((cp1.getY() - getY())/(cp1.getX() - getX())); -// double cp2len = Math.sqrt( -// Math.pow(cp2.getX() - getX(),2) + -// Math.pow(cp2.getY() - getY(),2) -// ); -// double offsetX = cp2len * Math.sin(angle); -// double offsetY = cp2len * Math.cos(angle); -// cp2.setPosition(getX() - offsetX, getY() - offsetY); -// } else { -// double angle = Math.tan((cp2.getY() - getY())/(cp2.getX() - getX())); -// double cp1len = Math.sqrt( -// Math.pow(cp1.getX() - getX(),2) + -// Math.pow(cp1.getY() - getY(),2) -// ); -// double offsetX = cp1len * Math.sin(angle); -// double offsetY = cp1len * Math.cos(angle); -// cp1.setPosition(getX() - offsetX, getY() - offsetY); -// } -//// if (evt.getSource() == cp1) { -//// double offsetX = cp1.getX() - getX(); -//// double offsetY = cp1.getY() - getY(); -//// cp2.setPosition(getX() - offsetX, getY() - offsetY); -//// } else { -//// double offsetX = cp2.getX() - getX(); -//// double offsetY = cp2.getY() - getY(); -//// cp1.setPosition(getX() - offsetX, getY() - offsetY); -//// } -// makingChange = false; -// firePropertyChange("cp1", null, cp1); -// firePropertyChange("cp2", null, cp1); -// } - firePropertyChange("shape",null,getShape()); - } - }; - - public BezierControlPoint() { - cp1.addPropertyChangeListener(cpListener); - cp2.addPropertyChangeListener(cpListener); - } - - public BezierControlPoint(double x, double y) { - super(x, y); - cp1.addPropertyChangeListener(cpListener); - cp2.addPropertyChangeListener(cpListener); - cp1.setPosition(x, y); - cp2.setPosition(x, y); - } - - public boolean isSharpCorner() { - return - (cp1.getX() == x.getValue()) && - (cp1.getY() == y.getValue()) && - (cp2.getX() == x.getValue()) && - (cp2.getY() == y.getValue()); - } - - public void flip(int width, int height){ - makingChange = true; - if (width > 0){ - x.setValue(width - x.getValue()); - cp1.x.setValue(width - cp1.x.getValue()); - cp2.x.setValue(width - cp2.x.getValue()); - } - if (height > 0){ - y.setValue(height - y.getValue()); - cp1.y.setValue(height - cp1.y.getValue()); - cp2.y.setValue(height - cp2.y.getValue()); - } - makingChange = false; - } - - public void convertToSharpCorner() { - cp1.setPosition(x.getValue(), y.getValue()); - cp2.setPosition(x.getValue(), y.getValue()); - } - - public List getControlPoints() { - if (isSharpCorner()) { - return Collections.emptyList(); - } else { - List points = new ArrayList(); - points.add(cp1); - points.add(cp2); - return points; - } - } - - public HandleControlPoint getCp1() { - return cp1; - } - - public HandleControlPoint getCp2() { - return cp2; - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - g2.setStroke(new BasicStroke((float) pixelSize)); - // paint control line - g2.setColor(GraphicsHelper.BEZIER_CONTROL_LINE); - g2.draw(new Line2D.Double(cp1.getX(), cp1.getY(), getX(), getY())); - g2.draw(new Line2D.Double(getX(), getY(), cp2.getX(), cp2.getY())); - // paint this control point - Shape s; - if (isSharpCorner()) { - double size = pixelSize * 4d; - GeneralPath path = new GeneralPath(); - path.moveTo(getX() - size, getY()); - path.lineTo(getX(), getY() + size); - path.lineTo(getX() + size, getY()); - path.lineTo(getX(), getY() - size); - path.closePath(); - s = path; - } else { - double size = pixelSize * 3d; - s = new Ellipse2D.Double(getX() - size, getY() - size, - size * 2, size * 2); - } - g2.setColor(GraphicsHelper.BEZIER_CONTROL_POINT_FILL); - g2.fill(s); - g2.setColor(GraphicsHelper.BEZIER_CONTROL_POINT_LINE); - g2.draw(s); - // paint child control points - if (!isSharpCorner()) { - cp1.paintControls(g2, pixelSize, true); - cp2.paintControls(g2, pixelSize, true); - } - } - - - public void move(double moveX, double moveY, boolean snapPixels) { - makingChange = true; - super.move(moveX, moveY, snapPixels); - cp1.move(moveX, moveY, snapPixels); - cp2.move(moveX, moveY, snapPixels); - makingChange = false; - } - - public double getCp1X() { - return cp1.getX(); - } - - public void setCp1X(double v) { - cp1.setX(v); - } - - public double getCp1Y() { - return cp1.getY(); - } - - public void setCp1Y(double v) { - cp1.setY(v); - } - - public double getCp2X() { - return cp2.getX(); - } - - public void setCp2X(double v) { - cp2.setX(v); - } - - public double getCp2Y() { - return cp2.getY(); - } - - public void setCp2Y(double v) { - cp2.setY(v); - } - - // ================================================================================================================= - // Bezier handle control point - - public class HandleControlPoint extends ControlPoint { - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - if (!isSharp()){ - double size = pixelSize * 3d; - Shape s = new Ellipse2D.Double(getX() - size, getY() - size, - size * 2, size * 2); - g2.setColor(GraphicsHelper.BEZIER_CONTROL_POINT_FILL); - g2.fill(s); - g2.setColor(GraphicsHelper.BEZIER_CONTROL_POINT_LINE); - g2.draw(s); - g2.draw(new Rectangle2D.Double(getX() - (pixelSize / 2), getY() - (pixelSize / 2), pixelSize, pixelSize)); - } - } - - public boolean isHit(Point2D p, double pixelSize) { - return !isSharp() && super.isHit(p, pixelSize); - } - - /** - * Is the line controled by this handle in or out of the parent BezierControlPoint sharp. - * - * @return true If this is the exact same point as the parent BezierControlPoint. - */ - public boolean isSharp(){ - return x.getValue() == BezierControlPoint.this.x.getValue() && - y.getValue() == BezierControlPoint.this.y.getValue(); - } - - public void convertToSharp(){ - setPosition(BezierControlPoint.this.x.getValue(),BezierControlPoint.this.y.getValue()); - } - - public BezierControlPoint getParentControlPoint(){ - return BezierControlPoint.this; - } - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/BlendingMode.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/BlendingMode.java deleted file mode 100644 index ade7d08c39e652bad7d238e2b1cf6a4554b0fea9..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/BlendingMode.java +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - - -/** - * BlendingMode - Enum of composite blending modes, setup to match photoshop as closely as possible - * - * @author Created by Jasper Potts (May 31, 2007) - */ -public enum BlendingMode { - NORMAL, - // DISSOLVE, missing - // ----------------------------- - DARKEN, - MULTIPLY, - COLOR_BURN, - LINEAR_BURN, // (SUBTRACT) - // ----------------------------- - LIGHTEN, - SCREEN, - COLOR_DODGE, - LINEAR_DODGE, // (ADD) - // ----------------------------- - OVERLAY, - SOFT_LIGHT, - HARD_LIGHT, - VIVID_LIGHT, // (HEAT) is close - LINEAR_LIGHT, // (GLOW) is close - //PIN_LIGHT, missing - //HARD_MIX, missing - // ----------------------------- - DIFFERENCE, - EXCLUSION, - // ----------------------------- - HUE, // nowhere close - SATURATION, - COLOR, - LUMINOSITY, // close but not exact - //LIGHTER_COLOR, missing - //DARKER_COLOR, missing - ; - - - // ================================================================================================================= - // Helper methods for creating Blending Mode Combo Box - - public static final Object[] BLENDING_MODES = new Object[]{ - BlendingMode.NORMAL, - // DISSOLVE, missing - "-", - BlendingMode.DARKEN, - BlendingMode.MULTIPLY, - BlendingMode.COLOR_BURN, - BlendingMode.LINEAR_BURN, // (SUBTRACT) - "-", - BlendingMode.LIGHTEN, - BlendingMode.SCREEN, - BlendingMode.COLOR_DODGE, - BlendingMode.LINEAR_DODGE, // (ADD) - "-", - BlendingMode.OVERLAY, - BlendingMode.SOFT_LIGHT, - BlendingMode.HARD_LIGHT, - BlendingMode.VIVID_LIGHT, // (HEAT) is close - BlendingMode.LINEAR_LIGHT, // (GLOW) is close - //PIN_LIGHT, missing - //HARD_MIX, missing - "-", - BlendingMode.DIFFERENCE, - BlendingMode.EXCLUSION, - "-", - BlendingMode.HUE, // nowhere close - BlendingMode.SATURATION, - BlendingMode.COLOR, - BlendingMode.LUMINOSITY, // close but not exact - }; -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Canvas.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Canvas.java deleted file mode 100644 index 43f9cc621792a025eab9be8e31714bb2ce18b011..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Canvas.java +++ /dev/null @@ -1,308 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.utils.HasResources; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -import javax.swing.UIDefaults; -import java.awt.AlphaComposite; -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * ComponentRegion - * - * @author Created by Jasper Potts (May 22, 2007) - */ -public class Canvas extends AbstractBean implements LayerContainer, HasUIDefaults, HasResources { - private Dimension size; - /** list of all layers in the canvas, the first layer is painted on top */ - private List layers; - private int nextLayerNameIndex = 1; - private BufferedImage buffer; - private boolean isValid = false; - private Insets stretchingInsets = null; - private Layer workingLayer = null; - private PropertyChangeListener layersPropertyChangeListener; - private UIDefaults canvasUIDefaults = null; - private transient File resourcesDir; - private transient File imagesDir; - private transient File templatesDir; - - // ================================================================================================================= - // Constructor - - /** Private constructor for JIBX */ - protected Canvas() { - layersPropertyChangeListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - isValid = false; - // pass on layer change - int index = layers.indexOf((Layer) evt.getSource()); - if (index != -1) { - firePropertyChange("layers[" + index + "]." + evt.getPropertyName(), evt.getOldValue(), - evt.getNewValue()); - } - } - }; - } - - public Canvas(int width, int height) { - this(); - stretchingInsets = new Insets(1, 1, 1, 1); - layers = new ArrayList(); - setSize(new Dimension(width, height)); - addLayer(new Layer()); - } - - // ================================================================================================================= - // JIBX Methods - - /** - * Called by JIBX before all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - private void preSet(IUnmarshallingContext context) { - canvasUIDefaults = (UIDefaults) context.getUserContext(); - } - - // ================================================================================================================= - // Bean Methods - - /** - * Get the UIDefaults for this canvas. The UIDefaults is used to store default pallet of colors, fonts etc. - * - * @return Canvas UIDefaults - */ - public UIDefaults getUiDefaults() { - return canvasUIDefaults; - } - - /** - * Set the UIDefaults for this canvas. The UIDefaults is used to store default pallet of colors, fonts etc. - * - * @param canvasUIDefaults Canvas UIDefaults - */ - public void setUiDefaults(UIDefaults canvasUIDefaults) { - this.canvasUIDefaults = canvasUIDefaults; - } - - /** - * Get the current working layer, is is the layer that new shapes will be drawn into - * - * @return The current working layer, may be null if there is no working layer - */ - public Layer getWorkingLayer() { - return workingLayer; - } - - /** - * Set the current working layer, is is the layer that new shapes will be drawn into - * - * @param workingLayer the new working layer, must be a child of this canvas - */ - public void setWorkingLayer(Layer workingLayer) { - Layer old = getWorkingLayer(); - this.workingLayer = workingLayer; - firePropertyChange("workingLayer", old, getWorkingLayer()); - } - - public int getNextLayerNameIndex() { - return nextLayerNameIndex++; - } - - public Dimension getSize() { - return size; - } - - public void setSize(Dimension size) { - Dimension old = getSize(); - this.size = size; - buffer = new BufferedImage(this.size.width, this.size.height, BufferedImage.TYPE_INT_ARGB); - isValid = false; - firePropertyChange("size", old, getSize()); - } - - - public Insets getStretchingInsets() { - return stretchingInsets; - } - - public void setStretchingInsets(Insets stretchingInsets) { - Insets old = getStretchingInsets(); - this.stretchingInsets = stretchingInsets; - firePropertyChange("stretchingInsets", old, getStretchingInsets()); - } - - public BufferedImage getRenderedImage() { - if (!isValid) { - Graphics2D g2 = buffer.createGraphics(); - // clear - g2.setComposite(AlphaComposite.Clear); - g2.fillRect(0, 0, buffer.getWidth(), buffer.getHeight()); - // paint - g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - g2.setComposite(AlphaComposite.SrcOver); - for (int i = layers.size() - 1; i >= 0; i--) { - layers.get(i).paint(g2, 1); - } - g2.dispose(); - } - return buffer; - } - - /** - * @return true if this Canvas has not been edited. - *

- * TODO Currently this is not a bound property, but should be. That is, when the Canvas becomes edited - * (usually due to the Layer having a shape added to it), then a property change event should be fired. - */ - public boolean isBlank() { - return layers.size() == 0 || (layers.size() == 1 && layers.get(0).isEmpty()); - } - - public File getResourcesDir() { - return resourcesDir; - } - - public void setResourcesDir(File resourcesDir) { - File old = getResourcesDir(); - this.resourcesDir = resourcesDir; - firePropertyChange("resourcesDir", old, getResourcesDir()); - } - - public File getImagesDir() { - return imagesDir; - } - - public void setImagesDir(File imagesDir) { - File old = getImagesDir(); - this.imagesDir = imagesDir; - firePropertyChange("imagesDir", old, getImagesDir()); - } - - public File getTemplatesDir() { - return templatesDir; - } - - public void setTemplatesDir(File templatesDir) { - File old = getTemplatesDir(); - this.templatesDir = templatesDir; - firePropertyChange("templatesDir", old, getTemplatesDir()); - } - - // ================================================================================================================= - // LayerContainer Methods - - public LayerContainer getParent() { - // we are root so null - return null; - } - - public void addLayerToBottom(Layer layer) { - layers.add(layer); - layer.setParent(this); - layer.addPropertyChangeListener(layersPropertyChangeListener); - // no single layer changes so fire all changed event - firePropertyChange("layers", null, layers); - } - - public void addLayer(int i, Layer layer) { - layers.add(i, layer); - layer.setParent(this); - layer.addPropertyChangeListener(layersPropertyChangeListener); - // no single layer changes so fire all changed event - firePropertyChange("layers", null, layers); - } - - public void addLayer(Layer layer) { - layers.add(0, layer); - layer.setParent(this); - layer.addPropertyChangeListener(layersPropertyChangeListener); - // no single layer changes so fire all changed event - firePropertyChange("layers", null, layers); - } - - public Layer getLayer(int index) { - return layers.get(index); - } - - public int getLayerCount() { - return layers.size(); - } - - public Iterator getLayerIterator() { - return Collections.unmodifiableList(layers).iterator(); - } - - public Collection getLayers() { - return Collections.unmodifiableList(layers); - } - - public int indexOfLayer(Layer layer) { - return layers.indexOf(layer); - } - - public void removeLayer(Layer layer) { - int index = layers.indexOf(layer); - if (index != -1) { - layers.remove(layer); - layer.removePropertyChangeListener(layersPropertyChangeListener); - fireIndexedPropertyChange("layers", index, layer, null); - } - } - - public Dimension getRootSize() { - return getSize(); - } - - // ================================================================================================================= - // JIBX Helper Methods - - /** Called by JIBX after "layers" has been filled so we can set parents and listeners */ - private void setupLayers() { - for (Layer layer : layers) { - layer.setParent(this); - layer.addPropertyChangeListener(layersPropertyChangeListener); - } - // no single layer changes so fire all changed event - firePropertyChange("layers", null, layers); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/ControlPoint.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/ControlPoint.java deleted file mode 100644 index b4d231c5ca9cd3275658b6488c1785036b239ceb..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/ControlPoint.java +++ /dev/null @@ -1,157 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Collections; -import java.util.List; - -/** - * ControlPoint - * - * @author Created by Jasper Potts (May 24, 2007) - */ -public class ControlPoint extends SimpleShape { - protected Color fillColor; - protected Color lineColor; - protected DoubleBean x, y; - - public ControlPoint() { - this(new DoubleBean(), new DoubleBean()); - } - - public ControlPoint(Color fillColor, Color lineColor) { - this(new DoubleBean(), new DoubleBean(), fillColor, lineColor); - } - - public ControlPoint(double x, double y) { - this(new DoubleBean(x), new DoubleBean(y)); - } - - public ControlPoint(DoubleBean x, DoubleBean y) { - this(x, y, GraphicsHelper.CONTROL_POINT_FILL, GraphicsHelper.CONTROL_POINT_LINE); - } - - public ControlPoint(DoubleBean x, DoubleBean y, Color fillColor, Color lineColor) { - this.x = x; - this.y = y; - this.fillColor = fillColor; - this.lineColor = lineColor; - x.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("position", - new Point2D.Double((Double) evt.getOldValue(), getY()), - getPosition()); - } - }); - y.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("position", - new Point2D.Double(getX(), (Double) evt.getOldValue()), - getPosition()); - } - }); - } - - public double getX() { - return x.getValue(); - } - - public double getY() { - return y.getValue(); - } - - public void setX(double x) { - this.x.setValue(x); - } - - public void setY(double y) { - this.y.setValue(y); - } - - public void setPosition(Point2D position) { - x.setValue(position.getX()); - y.setValue(position.getY()); - } - - public void setPosition(double x, double y) { - setPosition(new Point2D.Double(x, y)); - } - - public Point2D getPosition() { - return new Point2D.Double(getX(), getY()); - } - - public Rectangle2D getBounds(double pixelSize) { - double size = pixelSize * 4d; - return new Rectangle2D.Double(getX() - size, getY() - size, - size * 2, size * 2); - } - - public boolean isHit(Point2D p, double pixelSize) { - return getBounds(pixelSize).contains(p); - } - - - public Shape getShape() { - return getBounds(0); - } - - public void paint(Graphics2D g2, double pixelSize) { - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - g2.setStroke(new BasicStroke((float) pixelSize)); - Shape s = getBounds(pixelSize); - g2.setColor(fillColor); - g2.fill(s); - g2.setColor(lineColor); - g2.draw(s); - } - - public List getControlPoints() { - return Collections.emptyList(); - } - - - public void move(double moveX, double moveY, boolean snapPixels) { - if (snapPixels) { - setPosition( - Math.round(x.getValue() + moveX), - Math.round(y.getValue() + moveY)); - } else { - setPosition(x.getValue() + moveX, y.getValue() + moveY); - } - } - - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Designer.jibx.xml b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Designer.jibx.xml deleted file mode 100644 index 0f80bcf40989481b45ac56a9a1289f7523d45f8f..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Designer.jibx.xml +++ /dev/null @@ -1,173 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/DoubleBean.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/DoubleBean.java deleted file mode 100644 index 7297b809bfeb30e4c37c9b55d88df451bef806c5..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/DoubleBean.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import org.jdesktop.beans.AbstractBean; - -/** - * DoubleBean - Simple bean for a observable double value - * - * @author Created by Jasper Potts (May 25, 2007) - */ -public class DoubleBean extends AbstractBean { - private double value = 0; - - public DoubleBean() {} - - public DoubleBean(double value) { - this.value = value; - } - - public double getValue() { - return value; - } - - public void setValue(double value) { - double old = this.value; - this.value = value; - firePropertyChange("value", old, this.value); - } - - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - - DoubleBean that = (DoubleBean) o; - - if (Double.compare(that.value, value) != 0) return false; - - return true; - } - - public int hashCode() { - long temp = value != +0.0d ? Double.doubleToLongBits(value) : 0L; - return (int) (temp ^ (temp >>> 32)); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/EllipseShape.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/EllipseShape.java deleted file mode 100644 index e0d12371697166ee8a45fa4cb362dd70a4da69f3..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/EllipseShape.java +++ /dev/null @@ -1,189 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import javax.swing.*; -import java.awt.*; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.List; - -/** - * EllipseShape - * - * @author Created by Jasper Potts (May 22, 2007) - */ -public class EllipseShape extends PaintedShape { - - private DoubleBean x1 = new DoubleBean(); - private DoubleBean x2 = new DoubleBean(); - private DoubleBean y1 = new DoubleBean(); - private DoubleBean y2 = new DoubleBean(); - private ControlPoint tl = new ControlPoint(x1, y1); - private ControlPoint tr = new ControlPoint(x2, y1); - private ControlPoint bl = new ControlPoint(x1, y2); - private ControlPoint br = new ControlPoint(x2, y2); - - // ================================================================================================================= - // Constructors - - /** private noargs constructor for JIBX */ - private EllipseShape() { - this(null); - } - - public EllipseShape(UIDefaults canvasUiDefaults) { - super(canvasUiDefaults); - PropertyChangeListener listener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("bounds", null, getBounds(0)); - } - }; - x1.addPropertyChangeListener(listener); - y1.addPropertyChangeListener(listener); - x2.addPropertyChangeListener(listener); - y2.addPropertyChangeListener(listener); - } - - public EllipseShape(double x, double y, double w, double h) { - this(); - x1.setValue(x); - y1.setValue(y); - x2.setValue(x + w); - y2.setValue(y + h); - } - - public Rectangle2D getBounds(double pixelSize) { - double left = Math.min(x1.getValue(), x2.getValue()); - double right = Math.max(x1.getValue(), x2.getValue()); - double top = Math.min(y1.getValue(), y2.getValue()); - double bottom = Math.max(y1.getValue(), y2.getValue()); - return new Rectangle2D.Double(left, top, right - left, bottom - top); - } - - public Ellipse2D getShape() { - double left = Math.min(x1.getValue(), x2.getValue()); - double right = Math.max(x1.getValue(), x2.getValue()); - double top = Math.min(y1.getValue(), y2.getValue()); - double bottom = Math.max(y1.getValue(), y2.getValue()); - return new Ellipse2D.Double(left, top, right - left, bottom - top); - } - - public boolean isHit(Point2D p, double pixelSize) { - return getBounds(pixelSize).contains(p); - } - - public void paint(Graphics2D g2, double pixelSize) { - g2.setPaint(getPaint()); - g2.fill(getShape()); - } - - public void setFrame(double x1, double y1, double x2, double y2) { - this.x1.setValue(x1); - this.y1.setValue(y1); - this.x2.setValue(x2); - this.y2.setValue(y2); - } - - @Override - public String toString() { - Rectangle2D bounds = getBounds(0); - return "ELLIPSE { x=" + bounds.getX() + ", y=" + bounds.getY() + ", w=" + bounds.getWidth() + ", h=" + bounds.getHeight() + " }"; - } - - public List getControlPoints() { - List points = new ArrayList(); - points.addAll(super.getControlPoints()); - points.add(tl); - points.add(tr); - points.add(bl); - points.add(br); - return points; - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - if (paintControlLines) { - g2.setStroke(new BasicStroke((float) pixelSize)); - g2.setColor(GraphicsHelper.CONTROL_LINE); - g2.draw(getShape()); - } - tl.paintControls(g2, pixelSize, true); - tr.paintControls(g2, pixelSize, true); - bl.paintControls(g2, pixelSize, true); - br.paintControls(g2, pixelSize, true); -// super.paintControls(g2, pixelSize, paintControlLines); - } - - public void move(double moveX, double moveY, boolean snapPixels) { - if (snapPixels) { - x1.setValue(Math.round(x1.getValue() + moveX)); - x2.setValue(Math.round(x2.getValue() + moveX)); - y1.setValue(Math.round(y1.getValue() + moveY)); - y2.setValue(Math.round(y2.getValue() + moveY)); - } else { - x1.setValue(x1.getValue() + moveX); - x2.setValue(x2.getValue() + moveX); - y1.setValue(y1.getValue() + moveY); - y2.setValue(y2.getValue() + moveY); - } - } - - public double getX1() { - return x1.getValue(); - } - - public void setX1(double x1) { - this.x1.setValue(x1); - } - - public double getX2() { - return x2.getValue(); - } - - public void setX2(double x2) { - this.x2.setValue(x2); - } - - public double getY1() { - return y1.getValue(); - } - - public void setY1(double y1) { - this.y1.setValue(y1); - } - - public double getY2() { - return y2.getValue(); - } - - public void setY2(double y2) { - this.y2.setValue(y2); - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/GraphicsHelper.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/GraphicsHelper.java deleted file mode 100644 index 519c42e94e50052a060ed205cb5112f993890d3f..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/GraphicsHelper.java +++ /dev/null @@ -1,45 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import java.awt.Color; - -/** - * GraphicsHelper - * - * @author Created by Jasper Potts (May 29, 2007) - */ -public class GraphicsHelper { - public static final Color FILL_LINE = Color.BLUE; - public static final Color FILL_CP_LINE = Color.BLUE; - public static final Color FILL_CP_FILL = Color.WHITE; - public static final Color CONTROL_LINE = Color.RED; - public static final Color CONTROL_POINT_LINE = Color.RED; - public static final Color CONTROL_POINT_FILL = Color.WHITE; - public static final Color BEZIER_CONTROL_POINT_LINE = CONTROL_POINT_LINE; - public static final Color BEZIER_CONTROL_POINT_FILL = CONTROL_POINT_FILL; - public static final Color BEZIER_CONTROL_LINE = Color.DARK_GRAY; - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Layer.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Layer.java deleted file mode 100644 index 3b112ae93fb1302a96149dddd1fd6659f36115bc..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/Layer.java +++ /dev/null @@ -1,443 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import org.jdesktop.swingx.designer.effects.Effect; - -import java.awt.Dimension; -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * Layer - * - * @author Created by Jasper Potts (May 22, 2007) - */ -public class Layer extends SimpleShape implements Iterable, LayerContainer { - public static enum LayerType { - standard, template - } - - private String name; - protected LayerType type = LayerType.standard; - /** List of shapes in this layer, first shape is painted on top */ - private List shapes = new ArrayList(); - private List effects = new ArrayList(); - private double opacity = 1; - private double fillOpacity = 1; - private BlendingMode blendingMode = BlendingMode.NORMAL; - private boolean locked = false; - private boolean visible = true; - private PropertyChangeListener shapeChangeListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - int index = shapes.indexOf((SimpleShape) evt.getSource()); - firePropertyChange("shapes[" + index + "]." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }; - private PropertyChangeListener effectChangeListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - int index = effects.indexOf((Effect) evt.getSource()); - System.out.println( - "Layer.propertyChange EFFECT PROPERTY CHANGED " + evt.getSource() + " -- " + evt.getPropertyName()); - firePropertyChange("effects[" + index + "]." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }; - private BufferedImage buffer = null; - // ================================================================================================================= - // Constructors - - public Layer() { - } - - public Layer(String name) { - this(); - this.name = name; - } - - /** Called by JIBX after populating this layer so we can add listeners to children */ - protected void postInit() { - for (SimpleShape shape : shapes) { - shape.addPropertyChangeListener(shapeChangeListener); - shape.setParent(this); - } - for (Effect effect : effects) { - effect.addPropertyChangeListener(effectChangeListener); - } - } - - // ================================================================================================================= - // Bean Methods - - public LayerType getType() { - return type; - } - - public boolean isLocked() { - return locked; - } - - public void setLocked(boolean locked) { - boolean old = isLocked(); - this.locked = locked; - firePropertyChange("locked", old, isLocked()); - } - - public boolean isVisible() { - return visible; - } - - public void setVisible(boolean visible) { - boolean old = isVisible(); - this.visible = visible; - firePropertyChange("visible", old, isVisible()); - } - - public String getName() { - return name; - } - - public void setName(String name) { - String old = getName(); - this.name = name; - firePropertyChange("name", old, getName()); - } - - public void setParent(LayerContainer parent) { - super.setParent(parent); - // generate a name if null - if (name == null) { - Canvas c = null; - LayerContainer p = parent; - while (true) { - if (p instanceof Canvas) { - c = (Canvas) p; - break; - } else if (p == null) { - break; - } - p = p.getParent(); - } - if (c != null) { - setName("Layer " + c.getNextLayerNameIndex()); - } - } - } - - /** - * Add shape to top of layer so it paints above all other shapes - * - * @param shape The shape to add - */ - public void add(SimpleShape shape) { - shapes.add(0, shape); - shape.setParent(this); - shape.addPropertyChangeListener(shapeChangeListener); - fireIndexedPropertyChange("shapes", 0, null, shape); - } - - public void remove(SimpleShape shape) { - int index = shapes.indexOf(shape); - if (index != -1) { - shapes.remove(shape); - shape.setParent(null); - fireIndexedPropertyChange("shapes", index, shape, null); - } - } - - /** - * Returns an unmodifianle iterator over a set of elements of type SimpleShape. - * - * @return an Iterator. - */ - public Iterator iterator() { - return Collections.unmodifiableList(shapes).iterator(); - } - - - public List getEffects() { - return Collections.unmodifiableList(effects); - } - - public void addEffect(Effect effect) { - int index = effects.size(); - effects.add(effect); - effect.addPropertyChangeListener(effectChangeListener); - fireIndexedPropertyChange("effects", index, null, effects); - } - - public void removeEffect(Effect effect) { - int index = effects.indexOf(effect); - if (index != -1) { - effects.remove(effect); - effect.removePropertyChangeListener(effectChangeListener); - fireIndexedPropertyChange("effects", index, effect, null); - } - } - - public double getOpacity() { - return opacity; - } - - public void setOpacity(double opacity) { - if (opacity < 0 || opacity > 1) return; - double old = getOpacity(); - this.opacity = opacity; - firePropertyChange("opacity", old, getOpacity()); - } - - public double getFillOpacity() { - return fillOpacity; - } - - public void setFillOpacity(double fillOpacity) { - if (fillOpacity < 0 || fillOpacity > 1) return; - double old = getFillOpacity(); - this.fillOpacity = fillOpacity; - firePropertyChange("fillOpacity", old, getFillOpacity()); - } - - public BlendingMode getBlendingMode() { - return blendingMode; - } - - public void setBlendingMode(BlendingMode blendingMode) { - BlendingMode old = getBlendingMode(); - this.blendingMode = blendingMode; - firePropertyChange("blendingMode", old, getBlendingMode()); - } - - // ================================================================================================================= - // Layer Methods - - /** - * Get the parent canvas that contains this layer - * - * @return Parant canvas, or null if the layer is not in a canvas - */ - public Canvas getCanvas() { - LayerContainer lc = this; - while (lc != null) { - if (lc instanceof Canvas) return (Canvas) lc; - lc = lc.getParent(); - } - return null; - } - - public List getShapes() { - return new ArrayList(shapes); - } - - public List getIntersectingShapes(Point2D p, double pixelSize) { - if (isLocked() || !isVisible()) return Collections.emptyList(); - List intersectingShapes = new ArrayList(); - for (SimpleShape shape : shapes) { - if (shape instanceof Layer) { - intersectingShapes.addAll(((Layer) shape).getIntersectingShapes(p, pixelSize)); - } else { - if (shape.isHit(p, pixelSize)) intersectingShapes.add(shape); - } - } - return intersectingShapes; - } - - public List getIntersectingShapes(Rectangle2D rect, double pixelSize) { - if (isLocked() || !isVisible()) return Collections.emptyList(); - List intersectingShapes = new ArrayList(); - for (SimpleShape shape : shapes) { - if (shape instanceof Layer) { - intersectingShapes.addAll(((Layer) shape).getIntersectingShapes(rect, pixelSize)); - } else { - if (shape.intersects(rect, pixelSize)) intersectingShapes.add(shape); - } - } - return intersectingShapes; - - } - - public boolean isEmpty() { - return shapes.isEmpty(); - } - - // ================================================================================================================= - // SimpleShape Methods - - public Rectangle2D getBounds(double pixelSize) { - Rectangle2D.Double rect = new Rectangle2D.Double(); - for (SimpleShape shape : shapes) { - rect.add(shape.getBounds(pixelSize)); - } - return rect; - } - - - public Shape getShape() { - return getBounds(0); - } - - public boolean isHit(Point2D p, double pixelSize) { - if (isLocked() || !isVisible()) return false; - for (SimpleShape shape : shapes) { - if (shape.isHit(p, pixelSize)) return true; - } - return false; - } - - public boolean intersects(Rectangle2D rect, double pixelSize) { - if (isLocked() || !isVisible()) return false; - for (SimpleShape shape : shapes) { - if (shape.intersects(rect, pixelSize)) return true; - } - return false; - } - - public List getControlPoints() { - return Collections.emptyList(); - } - - public void paint(Graphics2D g2, double pixelSize) { - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - - } - - public String toString() { - return getName(); - } - - // ================================================================================================================= - // LayerContainer Methods - - public void addLayer(int i, Layer layer) { - // get existing layer at index i - Layer existingLayer = getLayer(i); - if (existingLayer == null) { - addLayer(layer); - } else { - int index = indexOfLayer(existingLayer); - shapes.add(index, layer); - layer.setParent(this); - layer.addPropertyChangeListener(shapeChangeListener); - fireIndexedPropertyChange("layers", index, null, layer); - } - } - - public void addLayer(Layer layer) { - shapes.add(layer); - layer.setParent(this); - layer.addPropertyChangeListener(shapeChangeListener); - int index = indexOfLayer(layer); - fireIndexedPropertyChange("layers", index, null, layer); - } - - public Layer getLayer(int index) { - int i = -1; - for (SimpleShape shape : shapes) { - if (shape instanceof Layer) i++; - if (i == index) return (Layer) shape; - } - return null; - } - - public int getLayerCount() { - int count = 0; - for (SimpleShape shape : shapes) { - if (shape instanceof Layer) count++; - } - return count; - } - - - public Collection getLayers() { - List layers = new ArrayList(); - for (SimpleShape shape : shapes) { - if (shape instanceof Layer) layers.add((Layer) shape); - } - return Collections.unmodifiableList(layers); - } - - public Iterator getLayerIterator() { - return new Iterator() { - private int index = 0; - - public boolean hasNext() { - for (int i = index; i < shapes.size(); i++) { - if (shapes.get(i) instanceof Layer) { - return true; - } - } - return false; - } - - public Layer next() { - for (; index < shapes.size(); index++) { - if (shapes.get(index) instanceof Layer) { - Layer nextLayer = (Layer) shapes.get(index); - index++; // increment index so we don't find the same one again - return nextLayer; - } - } - return null; - } - - public void remove() { - throw new UnsupportedOperationException(); - } - }; - } - - public int indexOfLayer(Layer layer) { - int i = -1; - for (SimpleShape s : shapes) { - if (s instanceof Layer) i++; - if (s == layer) return i; - } - return -1; - } - - public void removeLayer(Layer layer) { - int index = indexOfLayer(layer); - if (index != -1) { - shapes.remove(layer); - layer.removePropertyChangeListener(shapeChangeListener); - fireIndexedPropertyChange("layers", index, layer, null); - } - } - - - public Dimension getRootSize() { - return getParent().getRootSize(); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/LayerContainer.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/LayerContainer.java deleted file mode 100644 index b5af519cc39da8a9b9549699e977192f7038c089..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/LayerContainer.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import java.awt.Dimension; -import java.beans.PropertyChangeListener; -import java.util.Collection; -import java.util.Iterator; - -/** - * LayerContainer - * - * @author Created by Jasper Potts (May 31, 2007) - */ -public interface LayerContainer { - public void addPropertyChangeListener(PropertyChangeListener listener); - - public void removePropertyChangeListener(PropertyChangeListener listener); - - public LayerContainer getParent(); - - public void addLayer(Layer layer); - - public void addLayer(int i, Layer layer); - - public void removeLayer(Layer layer); - - public int getLayerCount(); - - public Layer getLayer(int index); - - public int indexOfLayer(Layer layer); - - public Iterator getLayerIterator(); - - public Collection getLayers(); - - /** - * Get the size in pixels of the root of the layer tree, this is usualy a canvas - * - * @return The size of the whole layer tree - */ - public Dimension getRootSize(); - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/PaintedShape.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/PaintedShape.java deleted file mode 100644 index 2d6d3cbf5996dd085674588da8784cf5b0cd8965..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/PaintedShape.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import org.jdesktop.swingx.designer.paint.Matte; -import org.jdesktop.swingx.designer.paint.PaintModel; - -import javax.swing.UIDefaults; -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.GradientPaint; -import java.awt.Graphics2D; -import java.awt.LinearGradientPaint; -import java.awt.Paint; -import java.awt.RadialGradientPaint; -import java.awt.Shape; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; - -/** - * PaintedShape - * - * @author Created by Jasper Potts (May 22, 2007) - */ -public abstract class PaintedShape extends SimpleShape { - - private PaintModel paint; - // control points for paint control types - private DoubleBean px1 = new DoubleBean(0.25); - private DoubleBean px2 = new DoubleBean(0.75); - private DoubleBean py1 = new DoubleBean(0); - private DoubleBean py2 = new DoubleBean(1); - private ControlPoint ptl = new PaintControlPoint(px1, py1); - private ControlPoint ptr = new PaintControlPoint(px2, py1); - private ControlPoint pbl = new PaintControlPoint(px1, py2); - private ControlPoint pbr = new PaintControlPoint(px2, py2); - private PropertyChangeListener paintListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("paint." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }; - - protected PaintedShape() { - px1.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("x1", evt.getOldValue(), evt.getNewValue()); - } - }); - py1.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("y1", evt.getOldValue(), evt.getNewValue()); - } - }); - px2.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("x2", evt.getOldValue(), evt.getNewValue()); - } - }); - py2.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("y2", evt.getOldValue(), evt.getNewValue()); - } - }); - } - - protected PaintedShape(UIDefaults canvasUiDefaults) { - this(); - setPaintModel(new Matte(Color.ORANGE, canvasUiDefaults)); - } - - public PaintModel getPaintModel() { - return paint; - } - - public void setPaintModel(PaintModel paint) { - PaintModel old = getPaintModel(); - if (old != null) old.removePropertyChangeListener(paintListener); - this.paint = paint; - this.paint.addPropertyChangeListener(paintListener); - firePropertyChange("paintModel", old, getPaintModel()); - } - - public Paint getPaint() { - Paint p = getPaintModel().getPaint(); - if (p instanceof Color) { - return p; - } - //resize p as necessary to fit the bounds of this PaintedShape - Rectangle2D bounds = getBounds(0); - if (p instanceof LinearGradientPaint) { - LinearGradientPaint lgp = (LinearGradientPaint) p; - return new LinearGradientPaint( - convertLocalPoint(ptl.getPosition(), bounds), - convertLocalPoint(pbr.getPosition(), bounds), - lgp.getFractions(), - lgp.getColors()); - } else if (p instanceof RadialGradientPaint) { - RadialGradientPaint rgp = (RadialGradientPaint) p; - Point2D outer = convertLocalPoint(ptl.getPosition(), bounds); - Point2D center = convertLocalPoint(pbr.getPosition(), bounds); - double deltaX = Math.abs(center.getX() - outer.getX()); - double deltaY = Math.abs(center.getY() - outer.getY()); - float radius = (float) Math.sqrt((deltaX * deltaX) + (deltaY * deltaY)); - return new RadialGradientPaint( - center, - radius, - rgp.getFractions(), - rgp.getColors()); - } else { - return p; - } - } - - public List getControlPoints() { - switch (paint.getPaintControlType()) { - case control_line: - return Arrays.asList(ptl, pbr); - case control_rect: - return Arrays.asList(ptl, ptr, pbl, pbr); - default: - return Collections.emptyList(); - } - } - - public void paintFillControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - switch (paint.getPaintControlType()) { - case control_line: - Point2D p1 = convertLocalPoint(ptl.getPosition(), PaintedShape.this.getBounds(0)); - Point2D p2 = convertLocalPoint(pbr.getPosition(), PaintedShape.this.getBounds(0)); - g2.setStroke(new BasicStroke((float) pixelSize)); - g2.setColor(GraphicsHelper.FILL_LINE); - g2.draw(new Line2D.Double(p1.getX(), p1.getY(), p2.getX(), p2.getY())); - ptl.paintControls(g2, pixelSize, true); - pbr.paintControls(g2, pixelSize, true); - break; - case control_rect: - g2.setStroke(new BasicStroke((float) pixelSize)); - g2.setColor(GraphicsHelper.FILL_LINE); - g2.draw(new Rectangle2D.Double( - px1.getValue(), - py1.getValue(), - px2.getValue() - px1.getValue(), - py2.getValue() - py1.getValue())); - ptl.paintControls(g2, pixelSize, true); - ptr.paintControls(g2, pixelSize, true); - pbl.paintControls(g2, pixelSize, true); - pbr.paintControls(g2, pixelSize, true); - break; - } - } - - public void move(double moveX, double moveY, boolean snapPixels) { - for (ControlPoint controlPoint : getControlPoints()) { - if (!(controlPoint instanceof PaintControlPoint)) controlPoint.move(moveX, moveY, snapPixels); - } - } - - public double getPaintX1() { - return px1.getValue(); - } - - public void setPaintX1(double x1) { - this.px1.setValue(x1); - } - - public double getPaintX2() { - return px2.getValue(); - } - - public void setPaintX2(double x2) { - this.px2.setValue(x2); - } - - public double getPaintY1() { - return py1.getValue(); - } - - public void setPaintY1(double y1) { - this.py1.setValue(y1); - } - - public double getPaintY2() { - return py2.getValue(); - } - - public void setPaintY2(double y2) { - this.py2.setValue(y2); - } - - // ================================================================================================================= - // Private helper methods - - private Point2D convertLocalPoint(Point2D point, Rectangle2D bounds) { - point.setLocation( - bounds.getX() + (point.getX() * bounds.getWidth()), - bounds.getY() + (point.getY() * bounds.getHeight()) - ); - return point; - } - - private Point2D convertScreenPoint(Point2D point, Rectangle2D bounds) { - return new Point2D.Double( - (point.getX() - bounds.getX()) / bounds.getWidth(), - (point.getY() - bounds.getY()) / bounds.getHeight() - ); - } - - // ================================================================================================================= - // Gradient ControlPoint - - /** - * A Special ControlPoint thats internal values are in coordinates relative to the shapes bounds. With 0,0 being the - * top left of the shape and 1.0X == shape width and 1.0Y == shapes height. - */ - public class PaintControlPoint extends ControlPoint { - public PaintControlPoint() { - super(GraphicsHelper.FILL_CP_FILL, GraphicsHelper.FILL_CP_LINE); - } - - public PaintControlPoint(DoubleBean x, DoubleBean y) { - super(x, y, GraphicsHelper.FILL_CP_FILL, GraphicsHelper.FILL_CP_LINE); - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - Point2D p = convertLocalPoint(getPosition(), PaintedShape.this.getBounds(0)); - g2.setStroke(new BasicStroke((float) pixelSize)); - double size = pixelSize * 4d; - Shape s = new Ellipse2D.Double(p.getX() - size, p.getY() - size, - size * 2, size * 2); - g2.setPaint(new GradientPaint( - (float) p.getX(), (float) (p.getY() - size), Color.CYAN, - (float) p.getX(), (float) (p.getY() + size), Color.WHITE - )); - g2.fill(s); - g2.setColor(GraphicsHelper.FILL_CP_LINE); - g2.draw(s); - } - - public void move(double moveX, double moveY, boolean snapPixels) { - Rectangle2D bounds = PaintedShape.this.getBounds(0); - moveX = moveX / bounds.getWidth(); - moveY = moveY / bounds.getHeight(); - if (snapPixels) { - // snap to neareast 0.5 - double newX = Math.round((x.getValue() + moveX) * 2d) / 2d; - double newY = Math.round((y.getValue() + moveY) * 2d) / 2d; - setPosition(newX, newY); - } else { - setPosition(x.getValue() + moveX, y.getValue() + moveY); - } - } - - public Rectangle2D getBounds(double pixelSize) { - Point2D p = convertLocalPoint(getPosition(), PaintedShape.this.getBounds(0)); - double size = pixelSize * 4d; - return new Rectangle2D.Double(p.getX() - size, p.getY() - size, - size * 2, size * 2); - } - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/PathShape.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/PathShape.java deleted file mode 100644 index 969972643636b4e4f41301b1692a89cd8c82056c..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/PathShape.java +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import javax.swing.*; -import java.awt.*; -import java.awt.geom.GeneralPath; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.List; - -/** - * PathShape - * - * @author Created by Jasper Potts (May 29, 2007) - */ -public class PathShape extends PaintedShape { - - private Shape cachedShape = null; - private List controlPoints = new ArrayList(); - private PropertyChangeListener cpListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - rebuildShape(); - } - }; - - // ================================================================================================================= - // Constructors - - /** private noargs constructor for JIBX */ - private PathShape() { - this(null); - } - - public PathShape(UIDefaults canvasUiDefaults) { - super(canvasUiDefaults); - } - - public BezierControlPoint addPoint(double x, double y) { - BezierControlPoint cp = new BezierControlPoint(x, y); - controlPoints.add(cp); - cp.addPropertyChangeListener(cpListener); - // update shape - rebuildShape(); - // return new control point - return cp; - } - - public Shape getShape() { - if (cachedShape == null) { - rebuildShape(); - } - return cachedShape; - } - - private void rebuildShape() { - GeneralPath path = new GeneralPath(); - BezierControlPoint first, last; - first = last = controlPoints.get(0); - path.moveTo((float) first.getX(), (float) first.getY()); - for (int i = 0; i < controlPoints.size(); i++) { - BezierControlPoint controlPoint = controlPoints.get(i); - if (last.getCp2().isSharp() && controlPoint.getCp1().isSharp()) { - path.lineTo(controlPoint.getX(), controlPoint.getY()); - } else { - path.curveTo( - (float) last.getCp2().getX(), (float) last.getCp2().getY(), - (float) controlPoint.getCp1().getX(), (float) controlPoint.getCp1().getY(), - (float) controlPoint.getX(), (float) controlPoint.getY() - ); - } - last = controlPoint; - } - // close path - if (last.getCp2().isSharp() && first.getCp1().isSharp()) { - path.lineTo(first.getX(), first.getY()); - } else { - path.curveTo( - (float) last.getCp2().getX(), (float) last.getCp2().getY(), - (float) first.getCp1().getX(), (float) first.getCp1().getY(), - (float) first.getX(), (float) first.getY() - ); - } - path.closePath(); - // fire change - cachedShape = path; - firePropertyChange("shape", null, cachedShape); - } - - @Override - public String toString() { - String p = "PATH {\n"; - BezierControlPoint first, last; - first = last = controlPoints.get(0); - p += " path.moveTo(" + first.getX() + "," + first.getY() + ");"; - for (int i = 0; i < controlPoints.size(); i++) { - BezierControlPoint controlPoint = controlPoints.get(i); - p += " path.curveTo(" + - (float) last.getCp2().getX() + "," + (float) last.getCp2().getY() + "," + - (float) controlPoint.getCp1().getX() + "," + (float) controlPoint.getCp1().getY() + "," + - (float) controlPoint.getX() + "," + (float) controlPoint.getY() + - ");\n"; - last = controlPoint; - } - // close path - p += " path.curveTo(" + - (float) last.getCp2().getX() + "," + (float) last.getCp2().getY() + "," + - (float) first.getCp1().getX() + "," + (float) first.getCp1().getY() + "," + - (float) first.getX() + "," + (float) first.getY() + - ");\n"; - p += "}\n"; - return p; - } - - // ================================================================================================================= - // Shape Methods - - public Rectangle2D getBounds(double pixelSize) { - return getShape().getBounds2D(); - } - - public List getControlPoints() { - List pts = new ArrayList(); - for (BezierControlPoint controlPoint : controlPoints) { - pts.add(controlPoint); - } - for (ControlPoint controlPoint : super.getControlPoints()) { - pts.add(controlPoint); - } - return pts; - } - - public void setControlPoints(List controlPoints) { - List old = this.controlPoints; - for (BezierControlPoint cp : old) { - cp.removePropertyChangeListener(cpListener); - } - this.controlPoints = controlPoints; - for (BezierControlPoint cp : this.controlPoints) { - cp.addPropertyChangeListener(cpListener); - } - // update shape - rebuildShape(); - } - - public boolean isHit(Point2D p, double pixelSize) { - return getShape().contains(p); - } - - public void paint(Graphics2D g2, double pixelSize) { - g2.setPaint(getPaint()); - g2.fill(getShape()); - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - if (paintControlLines) { - g2.setStroke(new BasicStroke((float) pixelSize)); - g2.setColor(GraphicsHelper.CONTROL_LINE); - g2.draw(getShape()); - } - for (BezierControlPoint controlPoint : controlPoints) { - if (!controlPoint.isSharpCorner()) controlPoint.paintControls(g2, pixelSize, true); - } - } - - public List getBezierControlPoints() { - return controlPoints; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/RectangleShape.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/RectangleShape.java deleted file mode 100644 index d93ef3f1ef5849749c9b816a98179dc5a0cf78d6..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/RectangleShape.java +++ /dev/null @@ -1,266 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import javax.swing.*; -import java.awt.*; -import java.awt.geom.Ellipse2D; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.awt.geom.RoundRectangle2D; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.List; - -/** - * RectangleShape - * - * @author Created by Jasper Potts (May 22, 2007) - */ -public class RectangleShape extends PaintedShape { - - private DoubleBean x1 = new DoubleBean(); - private DoubleBean x2 = new DoubleBean(); - private DoubleBean y1 = new DoubleBean(); - private DoubleBean y2 = new DoubleBean(); - private ControlPoint tl = new ControlPoint(x1, y1); - private ControlPoint tr = new ControlPoint(x2, y1); - private ControlPoint bl = new ControlPoint(x1, y2); - private ControlPoint br = new ControlPoint(x2, y2); - private DoubleBean roundingX = new DoubleBean() { - public void setValue(double value) { - // contrain y = y1 and x is between x1+1 and (x2-x1)/2 - boolean x1isLess = x1.getValue() < x2.getValue(); - double min = x1isLess ? x1.getValue() + 1 : x1.getValue() - 1; - double max = x1isLess ? x1.getValue() + ((x2.getValue() - x1.getValue()) / 2) : - x2.getValue() + ((x1.getValue() - x2.getValue()) / 2); - double newX = value; - if (newX < min) newX = min; - if (newX > max) newX = max; - super.setValue(newX); - } - }; - private ControlPoint rounding = new ControlPoint(roundingX, y1) { - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - double size = pixelSize * 3d; - Shape s = new Ellipse2D.Double(getX() - size, getY() - size, - size * 2, size * 2); - g2.setColor(GraphicsHelper.BEZIER_CONTROL_POINT_FILL); - g2.fill(s); - g2.setColor(GraphicsHelper.BEZIER_CONTROL_POINT_LINE); - g2.draw(s); - } - - public void setPosition(Point2D position) { - // only alow X to change - x.setValue(position.getX()); - } - - }; - - // ================================================================================================================= - // Constructors - - /** private noargs constructor for JIBX */ - private RectangleShape() { - this(null); - } - - public RectangleShape(UIDefaults canvasUiDefaults) { - super(canvasUiDefaults); - x1.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - // keep rounding point in sync - roundingX.setValue(roundingX.getValue() + - ((Double) evt.getNewValue() - (Double) evt.getOldValue())); - firePropertyChange("bounds", null, getBounds(0)); - } - }); - x2.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - // keep rounding point in sync - double distanceFromX1 = Math.abs(roundingX.getValue() - x1.getValue()); - roundingX.setValue( - (x1.getValue() < x2.getValue()) ? x1.getValue() + distanceFromX1 : - x1.getValue() - distanceFromX1 - ); - firePropertyChange("bounds", null, getBounds(0)); - } - }); - PropertyChangeListener listener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("bounds", null, getBounds(0)); - } - }; - y1.addPropertyChangeListener(listener); - y2.addPropertyChangeListener(listener); - rounding.addPropertyChangeListener(listener); - } - - public RectangleShape(double x, double y, double w, double h) { - this(); - x1.setValue(x); - y1.setValue(y); - x2.setValue(x + w); - y2.setValue(y + h); - } - - public Shape getShape() { - double rounding = getRounding(); - double left = Math.min(x1.getValue(), x2.getValue()); - double right = Math.max(x1.getValue(), x2.getValue()); - double top = Math.min(y1.getValue(), y2.getValue()); - double bottom = Math.max(y1.getValue(), y2.getValue()); - if (rounding > 0) { - return new RoundRectangle2D.Double( - left, top, right - left, bottom - top, rounding, rounding - ); - } else { - return new Rectangle2D.Double(left, top, right - left, bottom - top); - } - } - - public double getRounding() { - double rounding = Math.abs(roundingX.getValue() - x1.getValue()) * 2; - return rounding > 2 ? rounding : 0; - } - - public void setRounding(double rounding) { - if (rounding > 0 && rounding < 2) rounding = 0; - roundingX.setValue((rounding / 2d) + x1.getValue()); - } - - public boolean isRounded() { - return getRounding() > 0; - } - - public double getX1() { - return x1.getValue(); - } - - public void setX1(double x1) { - this.x1.setValue(x1); - } - - public double getX2() { - return x2.getValue(); - } - - public void setX2(double x2) { - this.x2.setValue(x2); - } - - public double getY1() { - return y1.getValue(); - } - - public void setY1(double y1) { - this.y1.setValue(y1); - } - - public double getY2() { - return y2.getValue(); - } - - public void setY2(double y2) { - this.y2.setValue(y2); - } - - // ================================================================================================================= - // SimpleShape Methods - - public Rectangle2D getBounds(double pixelSize) { - double left = Math.min(x1.getValue(), x2.getValue()); - double right = Math.max(x1.getValue(), x2.getValue()); - double top = Math.min(y1.getValue(), y2.getValue()); - double bottom = Math.max(y1.getValue(), y2.getValue()); - return new Rectangle2D.Double(left, top, right - left, bottom - top); - } - - public boolean isHit(Point2D p, double pixelSize) { - return getShape().contains(p); - } - - public void paint(Graphics2D g2, double pixelSize) { - g2.setPaint(getPaint()); - g2.fill(getShape()); - } - - public void setFrame(double x1, double y1, double x2, double y2) { - this.x1.setValue(x1); - this.y1.setValue(y1); - this.x2.setValue(x2); - this.y2.setValue(y2); - } - - @Override - public String toString() { - Rectangle2D bounds = getBounds(0); - if (isRounded()) { - return "ROUND RECT { x=" + bounds.getX() + ", y=" + bounds.getY() + ", w=" + bounds.getWidth() + ", h=" + bounds.getHeight() + ", rounding=" + getRounding() + " }"; - } else { - return "ROUND RECT { x=" + bounds.getX() + ", y=" + bounds.getY() + ", w=" + bounds.getWidth() + ", h=" + bounds.getHeight() + " }"; - } - } - - public List getControlPoints() { - List points = new ArrayList(); - points.addAll(super.getControlPoints()); - points.add(tl); - points.add(tr); - points.add(bl); - points.add(br); - points.add(rounding); - return points; - } - - public void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines) { - if (paintControlLines) { - g2.setStroke(new BasicStroke((float) pixelSize)); - g2.setColor(GraphicsHelper.CONTROL_LINE); - g2.draw(getShape()); - } - tl.paintControls(g2, pixelSize, true); - tr.paintControls(g2, pixelSize, true); - bl.paintControls(g2, pixelSize, true); - br.paintControls(g2, pixelSize, true); - rounding.paintControls(g2, pixelSize, true); - } - - public void move(double moveX, double moveY, boolean snapPixels) { - if (snapPixels) { - x1.setValue(Math.round(x1.getValue() + moveX)); - x2.setValue(Math.round(x2.getValue() + moveX)); - y1.setValue(Math.round(y1.getValue() + moveY)); - y2.setValue(Math.round(y2.getValue() + moveY)); - } else { - x1.setValue(x1.getValue() + moveX); - x2.setValue(x2.getValue() + moveX); - y1.setValue(y1.getValue() + moveY); - y2.setValue(y2.getValue() + moveY); - } - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/SimpleShape.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/SimpleShape.java deleted file mode 100644 index c001c0f42b1f3649e8c7a263b2669d952b61095a..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/SimpleShape.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import org.jdesktop.beans.AbstractBean; - -import java.awt.Graphics2D; -import java.awt.Shape; -import java.awt.geom.AffineTransform; -import java.awt.geom.Point2D; -import java.awt.geom.Rectangle2D; -import java.util.List; - -/** - * SimpleShape - * - * @author Created by Jasper Potts (May 22, 2007) - */ -public abstract class SimpleShape extends AbstractBean { - - protected AffineTransform transform = new AffineTransform(); - protected LayerContainer parent = null; - - public void applyTransform(AffineTransform t) { - transform.concatenate(t); - } - - public abstract Rectangle2D getBounds(double pixelSize); - - public abstract void paint(Graphics2D g2, double pixelSize); - - public abstract boolean isHit(Point2D p, double pixelSize); - - public boolean intersects(Rectangle2D rect, double pixelSize) { - return getBounds(pixelSize).intersects(rect); - } - - public abstract List getControlPoints(); - - public abstract void paintControls(Graphics2D g2, double pixelSize, boolean paintControlLines); - - public void move(double moveX, double moveY, boolean snapPixels) { - for (ControlPoint controlPoint : getControlPoints()) { - controlPoint.move(moveX, moveY, snapPixels); - } - } - - public LayerContainer getParent() { - return parent; - } - - public void setParent(LayerContainer parent) { - LayerContainer old = getParent(); - this.parent = parent; - firePropertyChange("parent", old, getParent()); - } - - public abstract Shape getShape(); -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/TemplateLayer.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/TemplateLayer.java deleted file mode 100644 index d0e51c29ed9433c4a1776734cf542d36cf77c221..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/TemplateLayer.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer; - -import org.jdesktop.swingx.designer.effects.Effect; - -import javax.imageio.ImageIO; -import javax.swing.JOptionPane; -import javax.swing.SwingUtilities; -import java.awt.Color; -import java.awt.FontMetrics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Image; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.io.File; -import java.io.IOException; -import java.lang.ref.SoftReference; - -/** - * TemplateLayer - * - * @author Created by Jasper Potts (Jul 2, 2007) - */ -public class TemplateLayer extends Layer { - - private String fileName; - private transient SoftReference imgRef = null; - - public TemplateLayer() { - type = LayerType.template; - } - - public TemplateLayer(String fileName, BufferedImage templateImage) { - super("Template"); - this.fileName = fileName; - type = LayerType.template; - if (templateImage != null) { - imgRef = new SoftReference(templateImage); - } - } - - // ================================================================================================================= - // Methods - - public String getName() { - return super.getName(); - } - - /** - * template layers are always locked - * - * @return true - */ - public boolean isLocked() { - return true; - } - - public void add(SimpleShape shape) { - throw new IllegalStateException("Template layers can't contain shapes"); - } - - public void addEffect(Effect effect) { - throw new IllegalStateException("Template layers can't contain effects"); - } - - public void addLayer(int i, Layer layer) { - throw new IllegalStateException("Template layers can't contain sub layers"); - } - - public void addLayer(Layer layer) { - throw new IllegalStateException("Template layers can't contain sub layers"); - } - - public void paint(Graphics2D g2, double pixelSize) { - if (isVisible()) { - BufferedImage img = getTemplateImage(); - if (img != null) g2.drawImage(img, 0, 0, null); - } - } - - - public Image getBuffer(GraphicsConfiguration graphicsConfiguration) { - return getTemplateImage(); - } - - public BufferedImage getTemplateImage() { - BufferedImage img = null; - if (imgRef == null || (img = imgRef.get()) == null) { - - // can not access canvas - final File templateImgFile = new File(getCanvas().getTemplatesDir(), fileName); - System.out.println("templateImgFile = " + templateImgFile.getAbsolutePath()); - System.out.println("templateImgFile.exists = " + templateImgFile.exists()); - try { - img = ImageIO.read(templateImgFile); - imgRef = new SoftReference(img); - } catch (IOException e) { - e.printStackTrace(); - // create error image - img = new BufferedImage(getCanvas().getSize().width, getCanvas().getSize().height, - BufferedImage.TYPE_INT_RGB); - Graphics2D g2 = img.createGraphics(); - g2.setColor(Color.RED); - g2.fillRect(0, 0, img.getWidth(), img.getHeight()); - g2.setColor(Color.WHITE); - g2.setFont(g2.getFont().deriveFont(8f)); - FontMetrics fontMetrics = g2.getFontMetrics(); - Rectangle2D stringBounds = fontMetrics.getStringBounds("Missing Image", g2); - int offsetX = (int) ((img.getWidth() - stringBounds.getWidth()) / 2d); - int offsetY = (int) (((img.getHeight() - stringBounds.getHeight()) / 2d) - stringBounds.getY()); - g2.drawString("Missing Image", offsetX, offsetY); - g2.dispose(); - imgRef = new SoftReference(img); - } - } - return img; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/DropShadowEffect.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/DropShadowEffect.java deleted file mode 100644 index ae95ea50ce367d879b83191c21760502ab8674d1..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/DropShadowEffect.java +++ /dev/null @@ -1,137 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - -import org.jdesktop.swingx.designer.paint.Matte; - -import javax.swing.UIDefaults; -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.util.Arrays; - -/** - * DropShadowEffect - * - * @author Created by Jasper Potts (Jun 18, 2007) - */ -public class DropShadowEffect extends ShadowEffect { - - protected DropShadowEffect() {} - - ; - - public DropShadowEffect(UIDefaults uiDefaults) { - color = new Matte(Color.BLACK, uiDefaults); - } - - // ================================================================================================================= - // Effect Methods - - /** - * Get the display name for this effect - * - * @return The user displayable name - */ - public String getDisplayName() { - return "Drop Shadow"; - } - - /** - * Get the type of this effect, one of UNDER,BLENDED,OVER. UNDER means the result of apply effect should be painted - * under the src image. BLENDED means the result of apply sffect contains a modified src image so just it should be - * painted. OVER means the result of apply effect should be painted over the src image. - * - * @return The effect type - */ - public EffectType getEffectType() { - return EffectType.UNDER; - } - - /** - * Apply the effect to the src image generating the result . The result image may or may not contain the source - * image depending on what the effect type is. - * - * @param src The source image for applying the effect to - * @param dst The dstination image to paint effect result into. If this is null then a new image will be created - * @param w The width of the src image to apply effect to, this allow the src and dst buffers to be bigger than - * the area the need effect applied to it - * @param h The height of the src image to apply effect to, this allow the src and dst buffers to be bigger than - * the area the need effect applied to it - * @return The result of appl - */ - public BufferedImage applyEffect(BufferedImage src, BufferedImage dst, int w, int h) { - // calculate offset - double trangleAngle = Math.toRadians(angle - 90); - int offsetX = (int) (Math.sin(trangleAngle) * distance); - int offsetY = (int) (Math.cos(trangleAngle) * distance); - // clac expanded size - int tmpOffX = offsetX + size; - int tmpOffY = offsetY + size; - int tmpW = w + offsetX + size + size; - int tmpH = h + offsetY + size + size; - // create tmp buffers - int[] lineBuf = getTmpIntArray(w); - byte[] tmpBuf1 = getTmpByteArray1(tmpW * tmpH); - Arrays.fill(tmpBuf1, (byte) 0x00); - byte[] tmpBuf2 = getTmpByteArray2(tmpW * tmpH); - // extract src image alpha channel and inverse and offset - Raster srcRaster = src.getRaster(); - for (int y = 0; y < h; y++) { - int dy = (y + tmpOffY); - int offset = dy * tmpW; - srcRaster.getDataElements(0, y, w, 1, lineBuf); - for (int x = 0; x < w; x++) { - int dx = x + tmpOffX; - tmpBuf1[offset + dx] = (byte) ((lineBuf[x] & 0xFF000000) >>> 24); - } - } - // blur - float[] kernel = EffectUtils.createGaussianKernel(size); - EffectUtils.blur(tmpBuf1, tmpBuf2, tmpW, tmpH, kernel, size); // horizontal pass - EffectUtils.blur(tmpBuf2, tmpBuf1, tmpH, tmpW, kernel, size);// vertical pass - //rescale - float spread = Math.min(1 / (1 - (0.01f * this.spread)), 255); - for (int i = 0; i < tmpBuf1.length; i++) { - int val = (int) (((int) tmpBuf1[i] & 0xFF) * spread); - tmpBuf1[i] = (val > 255) ? (byte) 0xFF : (byte) val; - } - // create color image with shadow color and greyscale image as alpha - if (dst == null) dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - WritableRaster shadowRaster = dst.getRaster(); - int red = color.getRed(), green = color.getGreen(), blue = color.getBlue(); - for (int y = 0; y < h; y++) { - int srcY = y + tmpOffY; - int shadowOffset = (srcY - offsetY) * tmpW; - for (int x = 0; x < w; x++) { - int srcX = x + tmpOffX; - lineBuf[x] = tmpBuf1[shadowOffset + (srcX - offsetX)] << 24 | red << 16 | green << 8 | blue; - } - shadowRaster.setDataElements(0, y, w, 1, lineBuf); - } - return dst; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/Effect.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/Effect.java deleted file mode 100644 index 7b8b697caaf5393968f2bd886683d9826864eef1..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/Effect.java +++ /dev/null @@ -1,153 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.BlendingMode; - -import java.awt.image.BufferedImage; -import java.lang.ref.SoftReference; - -/** - * Effect - * - * @author Created by Jasper Potts (Jun 18, 2007) - */ -public abstract class Effect extends AbstractBean { - protected boolean visible = true; - - public enum EffectType { - UNDER, BLENDED, OVER - } - - public boolean isVisible() { - return visible; - } - - public void setVisible(boolean visible) { - boolean old = isVisible(); - this.visible = visible; - firePropertyChange("visible", old, isVisible()); - } - - public String toString() { - return getDisplayName(); - } - - // ================================================================================================================= - // Abstract Methods - - /** - * Get the display name for this effect - * - * @return The user displayable name - */ - public abstract String getDisplayName(); - - /** - * Get the type of this effect, one of UNDER,BLENDED,OVER. UNDER means the result of apply effect should be painted - * under the src image. BLENDED means the result of apply sffect contains a modified src image so just it should be - * painted. OVER means the result of apply effect should be painted over the src image. - * - * @return The effect type - */ - public abstract EffectType getEffectType(); - - /** - * Get the blending mode to use to paint the result effected image if the EffectType is UNDER or OVER. - * - * @return The blending mode for the effect - */ - public abstract BlendingMode getBlendingMode(); - - /** - * Get the opacity to use to paint the result effected image if the EffectType is UNDER or OVER. - * - * @return The opactity for the effect, 0.0f -> 1.0f - */ - public abstract float getOpacity(); - - /** - * Apply the effect to the src image generating the result . The result image may or may not contain the source - * image depending on what the effect type is. - * - * @param src The source image for applying the effect to - * @param dst The dstination image to paint effect result into. If this is null then a new image will be created - * @param w The width of the src image to apply effect to, this allow the src and dst buffers to be bigger than - * the area the need effect applied to it - * @param h The height of the src image to apply effect to, this allow the src and dst buffers to be bigger than - * the area the need effect applied to it - * @return The result of appl - */ - public abstract BufferedImage applyEffect(BufferedImage src, BufferedImage dst, int w, int h); - - // ================================================================================================================= - // Static data cache - - private static SoftReference tmpIntArray = null; - private static SoftReference tmpByteArray1 = null; - private static SoftReference tmpByteArray2 = null; - private static SoftReference tmpByteArray3 = null; - - protected static int[] getTmpIntArray(int size) { - int[] tmp; - if (tmpIntArray == null || (tmp = tmpIntArray.get()) == null || tmp.length < size) { - // create new array - tmp = new int[size]; - tmpIntArray = new SoftReference(tmp); - } - return tmp; - } - - protected static byte[] getTmpByteArray1(int size) { - byte[] tmp; - if (tmpByteArray1 == null || (tmp = tmpByteArray1.get()) == null || tmp.length < size) { - // create new array - tmp = new byte[size]; - tmpByteArray1 = new SoftReference(tmp); - } - return tmp; - } - - protected static byte[] getTmpByteArray2(int size) { - byte[] tmp; - if (tmpByteArray2 == null || (tmp = tmpByteArray2.get()) == null || tmp.length < size) { - // create new array - tmp = new byte[size]; - tmpByteArray2 = new SoftReference(tmp); - } - return tmp; - } - - protected static byte[] getTmpByteArray3(int size) { - byte[] tmp; - if (tmpByteArray3 == null || (tmp = tmpByteArray3.get()) == null || tmp.length < size) { - // create new array - tmp = new byte[size]; - tmpByteArray3 = new SoftReference(tmp); - } - return tmp; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/EffectUtils.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/EffectUtils.java deleted file mode 100644 index 9a6876b5a5a041b9a7804ef2421c2c6978961f5a..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/EffectUtils.java +++ /dev/null @@ -1,99 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - - -/** - * EffectUtils - * - * @author Created by Jasper Potts (Jun 18, 2007) - */ -public class EffectUtils { - - /** - *

Blurs the source pixels into the destination pixels. The force of the blur is specified by the radius which - * must be greater than 0.

The source and destination pixels arrays are expected to be in the BYTE_GREY - * format.

After this method is executed, dstPixels contains a transposed and filtered copy of - * srcPixels.

- * - * @param srcPixels the source pixels - * @param dstPixels the destination pixels - * @param width the width of the source picture - * @param height the height of the source picture - * @param kernel the kernel of the blur effect - * @param radius the radius of the blur effect - */ - public static void blur(byte[] srcPixels, byte[] dstPixels, - int width, int height, - float[] kernel, int radius) { - float p; - int cp; - for (int y = 0; y < height; y++) { - int index = y; - int offset = y * width; - for (int x = 0; x < width; x++) { - p = 0.0f; - for (int i = -radius; i <= radius; i++) { - int subOffset = x + i; - if (subOffset < 0 || subOffset >= width) { - subOffset = (x + width) % width; - } - int pixel = srcPixels[offset + subOffset] & 0xFF; - float blurFactor = kernel[radius + i]; - p += blurFactor * pixel; - } - cp = (int) (p + 0.5f); - dstPixels[index] = (byte) (cp > 255 ? 255 : cp); - index += height; - } - } - } - - public static float[] createGaussianKernel(int radius) { - if (radius < 1) { - throw new IllegalArgumentException("Radius must be >= 1"); - } - - float[] data = new float[radius * 2 + 1]; - - float sigma = radius / 3.0f; - float twoSigmaSquare = 2.0f * sigma * sigma; - float sigmaRoot = (float) Math.sqrt(twoSigmaSquare * Math.PI); - float total = 0.0f; - - for (int i = -radius; i <= radius; i++) { - float distance = i * i; - int index = i + radius; - data[index] = (float) Math.exp(-distance / twoSigmaSquare) / sigmaRoot; - total += data[index]; - } - - for (int i = 0; i < data.length; i++) { - data[i] /= total; - } - - return data; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/EffectUtilsTemp.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/EffectUtilsTemp.java deleted file mode 100644 index 17bfd333f9bcd56dff8485aa6a69f31ede44442f..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/EffectUtilsTemp.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - -import java.awt.Composite; -import java.awt.CompositeContext; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.awt.image.ColorModel; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; - -/** - * EffectUtilsTemp - effect utils methods that are not being used for now but we might want later - * - * @author Created by Jasper Potts (Jun 18, 2007) - */ -public class EffectUtilsTemp { - - /** - * Extract the alpha channel of a image into new greyscale buffered image - * - * @param src Must but INT_ARGB buffered image - * @return new TYPE_BYTE_GRAY image of just the alpha channel - */ - public static BufferedImage extractAlpha(BufferedImage src) { - int w = src.getWidth(); - int h = src.getHeight(); - // extract image alpha channel as greyscale image - final BufferedImage greyImg = new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY); - Graphics2D g2 = greyImg.createGraphics(); - g2.setComposite(new Composite() { - public CompositeContext createContext(ColorModel srcColorModel, ColorModel dstColorModel, - RenderingHints hints) { - return new CompositeContext() { - public void dispose() {} - - public void compose(Raster src, Raster dstIn, WritableRaster dstOut) { - int width = Math.min(src.getWidth(), dstIn.getWidth()); - int height = Math.min(src.getHeight(), dstIn.getHeight()); - int[] srcPixels = new int[width]; - byte[] dstPixels = new byte[width]; - for (int y = 0; y < height; y++) { - src.getDataElements(0, y, width, 1, srcPixels); - for (int x = 0; x < width; x++) { - dstPixels[x] = (byte) ((srcPixels[x] & 0xFF000000) >>> 24); - } - dstOut.setDataElements(0, y, width, 1, dstPixels); - } - } - }; - } - }); - g2.drawImage(src, 0, 0, null); - g2.dispose(); - return greyImg; - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/InnerShadowEffect.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/InnerShadowEffect.java deleted file mode 100644 index 502c4a0537ef80e2b5b0a21f287ff3fb0c9c77e3..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/InnerShadowEffect.java +++ /dev/null @@ -1,142 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - -import org.jdesktop.swingx.designer.paint.Matte; - -import javax.swing.UIDefaults; -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.awt.image.Raster; -import java.awt.image.WritableRaster; -import java.util.Arrays; - -/** - * InnerShadowEffect - * - * @author Created by Jasper Potts (Jun 18, 2007) - */ -public class InnerShadowEffect extends ShadowEffect { - - protected InnerShadowEffect() {} - - ; - - public InnerShadowEffect(UIDefaults uiDefaults) { - color = new Matte(Color.BLACK, uiDefaults); - } - - // ================================================================================================================= - // Effect Methods - - /** - * Get the display name for this effect - * - * @return The user displayable name - */ - public String getDisplayName() { - return "Inner Shadow"; - } - - /** - * Get the type of this effect, one of UNDER,BLENDED,OVER. UNDER means the result of apply effect should be painted - * under the src image. BLENDED means the result of apply sffect contains a modified src image so just it should be - * painted. OVER means the result of apply effect should be painted over the src image. - * - * @return The effect type - */ - public Effect.EffectType getEffectType() { - return Effect.EffectType.OVER; - } - - /** - * Apply the effect to the src image generating the result . The result image may or may not contain the source - * image depending on what the effect type is. - * - * @param src The source image for applying the effect to - * @param dst The dstination image to paint effect result into. If this is null then a new image will be created - * @param w The width of the src image to apply effect to, this allow the src and dst buffers to be bigger than - * the area the need effect applied to it - * @param h The height of the src image to apply effect to, this allow the src and dst buffers to be bigger than - * the area the need effect applied to it - * @return The result of appl - */ - public BufferedImage applyEffect(BufferedImage src, BufferedImage dst, int w, int h) { - // calculate offset - double trangleAngle = Math.toRadians(angle - 90); - int offsetX = (int) (Math.sin(trangleAngle) * distance); - int offsetY = (int) (Math.cos(trangleAngle) * distance); - // clac expanded size - int tmpOffX = offsetX + size; - int tmpOffY = offsetY + size; - int tmpW = w + offsetX + size + size; - int tmpH = h + offsetY + size + size; - // create tmp buffers - int[] lineBuf = getTmpIntArray(w); - byte[] srcAlphaBuf = getTmpByteArray1(tmpW * tmpH); - Arrays.fill(srcAlphaBuf, (byte) 0xFF); - byte[] tmpBuf1 = getTmpByteArray2(tmpW * tmpH); - byte[] tmpBuf2 = getTmpByteArray3(tmpW * tmpH); - // extract src image alpha channel and inverse and offset - Raster srcRaster = src.getRaster(); - for (int y = 0; y < h; y++) { - int dy = (y + tmpOffY); - int offset = dy * tmpW; - srcRaster.getDataElements(0, y, w, 1, lineBuf); - for (int x = 0; x < w; x++) { - int dx = x + tmpOffX; - srcAlphaBuf[offset + dx] = (byte) ((255 - ((lineBuf[x] & 0xFF000000) >>> 24)) & 0xFF); - } - } - // blur - float[] kernel = EffectUtils.createGaussianKernel(size * 2); - EffectUtils.blur(srcAlphaBuf, tmpBuf2, tmpW, tmpH, kernel, size * 2); // horizontal pass - EffectUtils.blur(tmpBuf2, tmpBuf1, tmpH, tmpW, kernel, size * 2);// vertical pass - //rescale - float spread = Math.min(1 / (1 - (0.01f * this.spread)), 255); - for (int i = 0; i < tmpBuf1.length; i++) { - int val = (int) (((int) tmpBuf1[i] & 0xFF) * spread); - tmpBuf1[i] = (val > 255) ? (byte) 0xFF : (byte) val; - } - // create color image with shadow color and greyscale image as alpha - if (dst == null) dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB); - WritableRaster shadowRaster = dst.getRaster(); - int red = color.getRed(), green = color.getGreen(), blue = color.getBlue(); - for (int y = 0; y < h; y++) { - int srcY = y + tmpOffY; - int offset = srcY * tmpW; - int shadowOffset = (srcY - offsetY) * tmpW; - for (int x = 0; x < w; x++) { - int srcX = x + tmpOffX; - int origianlAlphaVal = 255 - ((int) srcAlphaBuf[offset + srcX] & 0xFF); - int shadowVal = (int) tmpBuf1[shadowOffset + (srcX - offsetX)] & 0xFF; - int alphaVal = Math.min(origianlAlphaVal, shadowVal); - lineBuf[x] = ((byte) alphaVal & 0xFF) << 24 | red << 16 | green << 8 | blue; - } - shadowRaster.setDataElements(0, y, w, 1, lineBuf); - } - return dst; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/OuterGlowEffect.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/OuterGlowEffect.java deleted file mode 100644 index c431ed747eaa3eac19e86c9490fc7f245d0d59ed..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/OuterGlowEffect.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - -import org.jdesktop.swingx.designer.paint.Matte; - -import javax.swing.UIDefaults; -import java.awt.Color; - -/** - * OuterGlowEffect - * - * @author Created by Jasper Potts (Jun 21, 2007) - */ -public class OuterGlowEffect extends DropShadowEffect { - - protected OuterGlowEffect() { - distance = 0; - } - - public OuterGlowEffect(UIDefaults uiDefaults) { - color = new Matte(new Color(255, 255, 211), uiDefaults); - } - - /** - * Get the display name for this effect - * - * @return The user displayable name - */ - public String getDisplayName() { - return "Outer Glow"; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/ShadowEffect.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/ShadowEffect.java deleted file mode 100644 index 39620d5491191f354271195ccd30a306c3766fd1..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/effects/ShadowEffect.java +++ /dev/null @@ -1,132 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.effects; - -import org.jdesktop.swingx.designer.BlendingMode; -import org.jdesktop.swingx.designer.paint.Matte; - -import javax.swing.UIDefaults; -import java.awt.Color; - -/** - * ShadowEffect - base class with all the standard properties for shadow effects - * - * @author Created by Jasper Potts (Jun 18, 2007) - */ -public abstract class ShadowEffect extends Effect { - protected Matte color; - protected BlendingMode blendingMode = BlendingMode.NORMAL; - /** Opacity a float 0-1 for percentage */ - protected float opacity = 0.75f; - /** Angle in degrees between 0-360 */ - protected int angle = 135; - /** Distance in pixels */ - protected int distance = 5; - /** The shadow spread between 0-100 % */ - protected int spread = 0; - /** Size in pixels */ - protected int size = 5; - - protected ShadowEffect() {} - - ; - - public ShadowEffect(UIDefaults uiDefaults) { - color = new Matte(Color.BLACK, uiDefaults); - } - - // ================================================================================================================= - // Bean methods - - public Matte getColor() { - return color; - } - - public void setColor(Matte color) { - Matte old = getColor(); - this.color = color; - firePropertyChange("color", old, getColor()); - } - - public BlendingMode getBlendingMode() { - return blendingMode; - } - - public void setBlendingMode(BlendingMode blendingMode) { - BlendingMode old = getBlendingMode(); - this.blendingMode = blendingMode; - firePropertyChange("blendingMode", old, getBlendingMode()); - } - - public float getOpacity() { - return opacity; - } - - public void setOpacity(float opacity) { - float old = getOpacity(); - this.opacity = opacity; - firePropertyChange("opacity", old, getOpacity()); - } - - public int getAngle() { - return angle; - } - - public void setAngle(int angle) { - int old = getAngle(); - this.angle = angle; - firePropertyChange("angle", old, getAngle()); - } - - public int getDistance() { - return distance; - } - - public void setDistance(int distance) { - int old = getDistance(); - this.distance = distance; - firePropertyChange("distance", old, getDistance()); - } - - public int getSpread() { - return spread; - } - - public void setSpread(int spread) { - int old = getSpread(); - this.spread = spread; - firePropertyChange("spread", old, getSpread()); - } - - public int getSize() { - return size; - } - - public void setSize(int size) { - int old = getSize(); - this.size = size; - firePropertyChange("size", old, getSize()); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/font/Typeface.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/font/Typeface.java deleted file mode 100644 index 89d4675f3745e60652584943731abdaafff54b8c..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/font/Typeface.java +++ /dev/null @@ -1,484 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.font; - -import java.awt.Font; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import javax.swing.UIDefaults; -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -/** - * I don't think the name is technically correct (ie: a typeface is not a font), - * but I wanted something besides "font" so, here it is. - * - * This is a mutable font, much like Matte is a mutable color. Also like Matte, - * Typeface can be derived. - * - * @author rbair - */ -public class Typeface extends AbstractBean { - //specifies whether to derive bold, or italic. - //Default means, get my value from my parent. - //Off means, leave bold/italic off. - //On means, make bold/italic on. - public enum DeriveStyle { Default, Off, On } - - private String uiDefaultParentName; - /** This is a local UIDefaults that contains all the UIDefaults in the Model. */ - private transient UIDefaults uiDefaults = new UIDefaults(); - private PropertyChangeListener uiDefaultsChangeListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - if (uiDefaultParentName != null && uiDefaultParentName.equals(evt.getPropertyName())) { - updateFontFromOffsets(); - } - } - }; - - /** - * The name of the font. If uiDefaultParentName is specified, then this name - * will be set to be equal to the name of the parent font. - */ - private String name; - /** - * The size of the font. If uiDefaultParentName is set, then this value is - * updated to reflect the size of the parent font * the sizeOffset. - */ - private int size; - - //this field is not publically accessible. Rather, it is updated based on - //"bold" and "italic" as necessary. - private int style = Font.PLAIN; - private DeriveStyle bold = DeriveStyle.Default; - private DeriveStyle italic = DeriveStyle.Default; - - /** - * The size offset. Only used if uiDefaultParentName is specified. This offset - * will be multiplied with the parent font's size to determine the size of this - * typeface. The offset is specified as a percentage, either positive or negative. - * - * The reason a percentage was used, was so that things would look correctly - * when scaled, such as with high DPI situations. - */ - private float sizeOffset; - - /** - * Create a new Typeface. Note that, without specifying the uiDefaults, - * you cannot have font derivation. Thus, this constructor should never - * be called, except for the XML binding stuff. - */ - public Typeface() { } - - /** - * Creates a new Typeface. - * - * @param f The font from which to get the font name, size, and style to use - * to initialize this typeface. Note that this font is not used as a parent - * font for derivation purposes. Rather, it is used as a source from which to - * copy initial settings. - * - * @param uiDefaults The uiDefaults to use for font derivation purposes. - * When the uiDefaultParentName is specified, then this Typeface will inspect - * the given UIDefaults for that parent font. Note that the UIDefaults - * should be populated with a font, and not with a typeface. - */ - public Typeface(Font f, UIDefaults uiDefaults) { - if (f != null) { - this.name = f.getName(); - this.size = f.getSize(); - this.style = f.getStyle(); - } - setUiDefaults(uiDefaults); - } - - // ================================================================================================================= - // JIBX Methods - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - protected void postSet(IUnmarshallingContext context) { - // walk up till we get synth model - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof HasUIDefaults) { - UIDefaults uiDefaults = ((HasUIDefaults) context.getStackObject(i)).getUiDefaults(); - if (uiDefaults != null) { - setUiDefaults(uiDefaults); - break; - } - } - } - } - - // ================================================================================================================= - // Typeface methods - - /** - * Is the Typeface an absolute Font not derived from a parent ui default - * - * @return true if this is a absolute not uidefault derived font - */ - public boolean isAbsolute() { - return uiDefaultParentName == null; - } - - /** - * Set all properties of this Typeface to be the same as src and fire all the change events - * - * @param src the Typeface to copy properties from - */ - public void copy(Typeface src) { - // keep old values - Font oldFont = getFont(); - String oldParentName = uiDefaultParentName; - String oldName = name; - int oldSize = size; - float oldSizeOffset = sizeOffset; - DeriveStyle oldBold = bold, oldItalic = italic; - - style = src.style; - - //Note, I don't just call the setters here, because I want to make - //sure the "font" PCE is only fired once, at the end. - name = src.name; - firePropertyChange("name", oldName, name); - size = src.size; - firePropertyChange("size", oldSize, size); - bold = src.bold; - firePropertyChange("bold", oldBold, bold); - italic = src.italic; - firePropertyChange("italic", oldItalic, italic); - sizeOffset = src.sizeOffset; - firePropertyChange("sizeOffset", oldSizeOffset, sizeOffset); - uiDefaultParentName = src.uiDefaultParentName; - firePropertyChange("uiDefaultParentName", oldParentName, uiDefaultParentName); - setUiDefaults(src.uiDefaults); - firePropertyChange("font", oldFont, getFont()); - } - - // ================================================================================================================= - // Bean Methods - - /** - * Get the local UIDefaults that contains all the UIDefaults in the Model. - * - * @return The UIDefaults for the model that contains this Typeface, can be null if this Typeface is not part of a bigger - * model - */ - public UIDefaults getUiDefaults() { - return uiDefaults; - } - - /** - * Set the local UIDefaults that contains all the UIDefaults in the Model. - * - * @param uiDefaults The UIDefaults for the model that contains this Typeface, can be null if this Typeface is not part of - * a bigger model - */ - public void setUiDefaults(UIDefaults uiDefaults) { - if (uiDefaults != this.uiDefaults) { - UIDefaults old = getUiDefaults(); - if (old != null) old.removePropertyChangeListener(uiDefaultsChangeListener); - this.uiDefaults = uiDefaults; - if (uiDefaults != null) this.uiDefaults.addPropertyChangeListener(uiDefaultsChangeListener); - firePropertyChange("uiDefaults", old, getUiDefaults()); - } - } - - /** - * Get the name if the uidefault font that is the parent that this Typeface is derived from. If null then this is a - * absolute font. - * - * @return Parent font ui default name - */ - public String getUiDefaultParentName() { - return uiDefaultParentName; - } - - /** - * Set the name if the uidefault font that is the parent that this Typeface is derived from. If null then this is a - * absolute font. - * - * @param uiDefaultParentName Parent font ui default name - */ - public void setUiDefaultParentName(String uiDefaultParentName) { - String old = getUiDefaultParentName(); - this.uiDefaultParentName = uiDefaultParentName; - firePropertyChange("uiDefaultParentName", old, getUiDefaultParentName()); - if (isAbsolute()) { - // reset offsets - float oldSizeOffset = sizeOffset; - sizeOffset = 0; - firePropertyChange("sizeOffset", oldSizeOffset, sizeOffset); - } else { - updateFontFromOffsets(); - } - } - - /** - * @return Gets the name of the font - */ - public final String getName() { - return name; - } - - /** - * Sets the name of the font. This method call only works if - * isAbsolute returns true. Otherwise, it is ignored. - * @param name the name of the font - */ - public void setName(String name) { - if (isAbsolute()) { - String old = this.name; - Font oldF = getFont(); - this.name = name; - firePropertyChange("name", old, this.name); - firePropertyChange("font", oldF, getFont()); - } - } - - /** - * @return gets the size of the font. - */ - public final int getSize() { - return size; - } - - /** - *

Sets the size of the font. THis method call will work whether - * isAbsolute returns true or false. If this is an absolute - * typeface, then the size is set directly. Otherwise, if this is a - * derived typeface, then the sizeOffset will be updated to reflect the - * proper offset based on this size, and the size of the parent font.

- * - *

For example, if the parent font's size was 12, and the sizeOffset was - * -2 (thus yielding as size on this typeface of 10), and you call setSize - * passing in "14" as the size, then the sizeOffset will be updated to be - * equal to "2".

- * - * @param size the new size for this typeface. - */ - public void setSize(int size) { - int old = this.size; - Font oldF = getFont(); - this.size = size; - firePropertyChange("size", old, this.size); - firePropertyChange("font", oldF, getFont()); - updateOffsetsFromFont(); - } - - /** - * @return the size offset - */ - public final float getSizeOffset() { - return sizeOffset; - } - - /** - * Sets the percentage by which the size of this font should be different - * from its parent font. This property is kept in synch with the size property. - * - * @param sizeOffset the size offset. May be any float. The value "1" means, - * 100%. -1 means "-100%". 2 means "200%", and so on. - */ - public void setSizeOffset(float sizeOffset) { - float old = this.sizeOffset; - Font oldF = getFont(); - this.sizeOffset = sizeOffset; - firePropertyChange("sizeOffset", old, this.sizeOffset); - firePropertyChange("font", oldF, getFont()); - updateFontFromOffsets(); - } - - public DeriveStyle getBold() { - return bold; - } - - public void setBold(DeriveStyle bold) { - DeriveStyle old = this.bold; - this.bold = bold == null ? DeriveStyle.Default : bold; - firePropertyChange("bold", old, this.bold); - updateFontFromOffsets(); - } - - public DeriveStyle getItalic() { - return italic; - } - - public void setItalic(DeriveStyle italic) { - DeriveStyle old = this.italic; - this.italic = italic == null ? DeriveStyle.Default : italic; - firePropertyChange("italic", old, this.italic); - updateFontFromOffsets(); - } - - /** - * @return whether or not the font represented by this typeface is supported - * on this operating system platform. - */ - public boolean isFontSupported() { - return true;//Font.getFont(name) != null; - } - - /** - * @return Gets the font associated with this Typeface. If font derivation is - * being used, then the Font returned is the result of that derivation. - */ - public Font getFont() { - return new Font(name, style, size); - } - - /** - * Sets the font from which this Typeface should extract the font name, style, - * and size. If font derivation is being used, then the font name will be ignored, - * the style will be used (and always override the parent font), and the size - * will be set and the sizeOffset updated appropriately. - * - * @param f the Font - */ - public void setFont(Font f) { - Font oldFont = getFont(); - String oldName = name; - int oldSize = size; - DeriveStyle oldBold = bold, oldItalic = italic; - name = f.getName(); - size = f.getSize(); - style = f.getStyle(); - updateOffsetsFromFont(); - firePropertyChange("name", oldName, name); - firePropertyChange("size", oldSize, size); - firePropertyChange("bold", oldBold, bold); - firePropertyChange("italic", oldItalic, italic); - firePropertyChange("font", oldFont, getFont()); - } - - /** - * @inheritDoc - * - * @return A formatted string representing this Typeface. This String should - * not be considered public API, as it may change in a future release. - */ - @Override public String toString() { - Font f = getFont(); - String strStyle; - if (f.isBold()) { - strStyle = f.isItalic() ? "bolditalic" : "bold"; - } else { - strStyle = f.isItalic() ? "italic" : "plain"; - } - - if (isAbsolute()) { - return Typeface.class.getName() + "[name=" + name + ", size=" + size + ", style=" + strStyle + "]"; - } else { - return Typeface.class.getName() + "[base=" + uiDefaultParentName + - ", name=" + name + ", size=" + size + "(offset " + sizeOffset + ")" + - ", style=" + strStyle + "]"; - } - } - - @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Typeface typeface = (Typeface) o; - if (!typeface.name.equals(name)) return false; - if (size != typeface.size) return false; - if (bold != typeface.bold) return false; - if (italic != typeface.italic) return false; - if (sizeOffset != typeface.sizeOffset) return false; - if (uiDefaultParentName != null ? !uiDefaultParentName.equals(typeface.uiDefaultParentName) : - typeface.uiDefaultParentName != null) return false; - return true; - } - - @Override public int hashCode() { - int result; - result = name.hashCode(); - result = 31 * result + size; - result = 31 * result + bold.ordinal(); - result = 31 * result + italic.ordinal(); - result = 31 * result + (int)(sizeOffset*100); - result = 31 * result + (uiDefaultParentName != null ? uiDefaultParentName.hashCode() : 0); - return result; - } - - @Override public Typeface clone() { - Typeface clone = new Typeface(); - clone.name = name; - clone.size = size; - clone.style = style; - clone.bold = bold; - clone.italic = italic; - clone.sizeOffset = sizeOffset; - clone.uiDefaultParentName = uiDefaultParentName; - clone.setUiDefaults(uiDefaults); - return clone; - } - - // ================================================================================================================= - // Private Helper Methods - - private void updateOffsetsFromFont() { - if (!isAbsolute()) { - float oldSizeOffset = sizeOffset; - Font parentFont = uiDefaults.getFont(uiDefaultParentName); - if (parentFont != null) { - float s = size; - float p = parentFont.getSize(); - sizeOffset = (s/p) - 1f; - firePropertyChange("sizeOffset", oldSizeOffset, sizeOffset); - } - } - } - - private void updateFontFromOffsets() { - if (!isAbsolute()) { - Font oldFont = getFont(); - // get parent font data - Font parentFont = uiDefaults.getFont(uiDefaultParentName); - if (parentFont != null) { - String oldName = name; - int oldSize = size; - - name = parentFont.getName(); - size = Math.round(parentFont.getSize() * (1f + sizeOffset)); - - boolean isBold = (bold == DeriveStyle.Default && parentFont.isBold()) || bold == DeriveStyle.On; - boolean isItalic = (italic == DeriveStyle.Default && parentFont.isItalic()) || italic == DeriveStyle.On; - style = Font.PLAIN; - if (isBold) style = style | Font.BOLD; - if (isItalic) style = style | Font.ITALIC; - - // update fire events - firePropertyChange("name", oldName, name); - firePropertyChange("size", oldSize, size); - firePropertyChange("font", oldFont, getFont()); - } - } - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/CanvasMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/CanvasMapper.java deleted file mode 100644 index 6c201fd0feece936056c5b4f90294dcb957f408c..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/CanvasMapper.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.jibxhelpers; - -import org.jdesktop.swingx.designer.Canvas; -import org.jdesktop.swingx.designer.utils.HasPath; -import org.jdesktop.swingx.designer.utils.HasResources; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.BindingDirectory; -import org.jibx.runtime.IBindingFactory; -import org.jibx.runtime.IMarshallable; -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - -import javax.swing.UIDefaults; -import java.io.File; - -/** - * CanvasMapper - * - * @author Created by Jasper Potts (Jun 12, 2007) - */ -public class CanvasMapper implements IMarshaller, IUnmarshaller { - private static final String ELEMENT_NAME = "canvas"; - private IBindingFactory bindingFactory; - - - public CanvasMapper() { - try { - bindingFactory = BindingDirectory.getFactory(Canvas.class); - } catch (JiBXException e) { - e.printStackTrace(); - } - } - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(null, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof Canvas)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - // version found, create marshaller for the associated binding -// IBindingFactory bindingFactory = BindingDirectory.getFactory(object.getClass()); - MarshallingContext context = (MarshallingContext) bindingFactory.createMarshallingContext(); - // configure marshaller for writing document - context.setXmlWriter(iMarshallingContext.getXmlWriter()); - // output object as document - ((IMarshallable) object).marshal(context); - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(null, ELEMENT_NAME)) { - ctx.throwStartTagNameError(null, ELEMENT_NAME); - } - -// IBindingFactory bindingFactory = BindingDirectory.getFactory(Canvas.class); - UnmarshallingContext uctx = (UnmarshallingContext) bindingFactory.createUnmarshallingContext(); - uctx.setFromContext(ctx); - // get the uiDefaults from SynthModel and set them as user context - UIDefaults uiDefaults = ((HasUIDefaults) ctx.getStackObject(ctx.getStackDepth() - 1)).getUiDefaults(); - uctx.setUserContext(uiDefaults); - // get has resources - HasResources hasResources = (HasResources) ctx.getStackObject(ctx.getStackDepth() - 1); - // get path - HasPath hasPath = null; - for (int i = 0; i < ctx.getStackDepth(); i++) { - if (ctx.getStackObject(i) instanceof HasPath) { - hasPath = (HasPath) ctx.getStackObject(i); - break; - } - } - // Unmarshal the Canvas - Canvas canvas = (Canvas) uctx.unmarshalElement(); - // set canvas's ui defaults - canvas.setUiDefaults(uiDefaults); - // get canvas path - String canvasPath = hasPath.getPath(); - // calc and set resources - canvas.setResourcesDir(new File(hasResources.getResourcesDir(), canvasPath)); - canvas.setTemplatesDir(new File(hasResources.getTemplatesDir(), canvasPath)); - canvas.setImagesDir(new File(hasResources.getImagesDir(), canvasPath)); - // return canvas - return canvas; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/ColorMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/ColorMapper.java deleted file mode 100644 index 81cc738506f1adc481adc7e8dd65ce0302162a29..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/ColorMapper.java +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.jibxhelpers; - -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - -import java.awt.Color; - -/** - * ColorMapper - * - * @author Created by Jasper Potts (Jun 8, 2007) - */ -public class ColorMapper implements IMarshaller, IUnmarshaller { - private static final String ELEMENT_NAME = "color"; - private static final String RED_NAME = "red"; - private static final String GREEN_NAME = "green"; - private static final String BLUE_NAME = "blue"; - private static final String ALPHA_NAME = "alpha"; - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(null, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof Color)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - Color color = (Color) object; - ctx.startTagAttributes(0, ELEMENT_NAME). - attribute(0, RED_NAME, color.getRed()). - attribute(0, GREEN_NAME, color.getGreen()). - attribute(0, BLUE_NAME, color.getBlue()). - attribute(0, ALPHA_NAME, color.getAlpha()). - closeStartEmpty(); - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(null, ELEMENT_NAME)) { - ctx.throwStartTagNameError(null, ELEMENT_NAME); - } - // get values - int red = ctx.attributeInt(null, RED_NAME, 0); - int green = ctx.attributeInt(null, GREEN_NAME, 0); - int blue = ctx.attributeInt(null, BLUE_NAME, 0); - int alpha = ctx.attributeInt(null, ALPHA_NAME, 0); - ctx.parsePastEndTag(null, ELEMENT_NAME); - // create - return new Color(red, green, blue, alpha); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/DimensionMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/DimensionMapper.java deleted file mode 100644 index 44a0f264bf020637c2243ad1219d351776dd8ff3..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/DimensionMapper.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.jibxhelpers; - -import org.jibx.runtime.IAliasable; -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - -import java.awt.Dimension; - -/** - * DimensionMapper - * - * @author Created by Jasper Potts (Jun 12, 2007) - */ -public class DimensionMapper implements IMarshaller, IUnmarshaller, IAliasable { - private static final String ELEMENT_NAME = "dimension"; - private static final String WIDTH_NAME = "width"; - private static final String HEIGHT_NAME = "height"; - - private String uri; - private int index; - private String name; - - public DimensionMapper() { - uri = null; - index = 0; - name = ELEMENT_NAME; - } - - public DimensionMapper(String uri, int index, String name) { - this.uri = uri; - this.index = index; - this.name = name; - } - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(uri, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof Dimension)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - Dimension dimension = (Dimension) object; - ctx.startTagAttributes(index, name). - attribute(index, WIDTH_NAME, dimension.width). - attribute(index, HEIGHT_NAME, dimension.height). - closeStartEmpty(); - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(uri, name)) { - ctx.throwStartTagNameError(uri, name); - } - // get values - int width = ctx.attributeInt(uri, WIDTH_NAME, index); - int height = ctx.attributeInt(uri, HEIGHT_NAME, index); - // state finished parsing - ctx.parsePastEndTag(uri, name); - // create - return new Dimension(width, height); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/InsetsMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/InsetsMapper.java deleted file mode 100644 index e50cb1495518a1b572d6380177309ef516f4d0a7..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/jibxhelpers/InsetsMapper.java +++ /dev/null @@ -1,117 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.jibxhelpers; - -import org.jibx.runtime.IAliasable; -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - -import java.awt.Insets; - -/** - * InsetsMapper - * - * @author Created by Jasper Potts (Jun 8, 2007) - */ -public class InsetsMapper implements IMarshaller, IUnmarshaller, IAliasable { - private static final String ELEMENT_NAME = "insets"; - private static final String TOP_NAME = "top"; - private static final String BOTTOM_NAME = "bottom"; - private static final String LEFT_NAME = "left"; - private static final String RIGHT_NAME = "right"; - - private String uri; - private int index; - private String name; - - public InsetsMapper() { - uri = null; - index = 0; - name = ELEMENT_NAME; - } - - public InsetsMapper(String uri, int index, String name) { - this.uri = uri; - this.index = index; - this.name = name; -// System.out.println("InsetsMapper.CONSTRCUTED with uri="+uri+" index="+index+" name="+name); - } - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(uri, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof Insets)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { -// System.out.println("InsetsMapper.marshal name="+name); - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - Insets insets = (Insets) object; - ctx.startTagAttributes(index, name). - attribute(index, TOP_NAME, insets.top). - attribute(index, BOTTOM_NAME, insets.bottom). - attribute(index, LEFT_NAME, insets.left). - attribute(index, RIGHT_NAME, insets.right). - closeStartEmpty(); - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(uri, name)) { -// System.out.println("InsetsMapper.unmarshal name="+name+" uri="+uri+" currentNode="+ctx.getName()); - ctx.throwStartTagNameError(uri, name); - } else { -// System.out.println("InsetsMapper.unmarshal name="+name+" uri="+uri+" currentNode="+ctx.getName()); - } - // get values - int top = ctx.attributeInt(uri, TOP_NAME, index); - int bottom = ctx.attributeInt(uri, BOTTOM_NAME, index); - int left = ctx.attributeInt(uri, LEFT_NAME, index); - int right = ctx.attributeInt(uri, RIGHT_NAME, index); - // create new hashmap if needed - Insets insets = (Insets) object; - if (insets == null) { - insets = new Insets(top, left, bottom, right); - } else { - insets.set(top, left, bottom, right); - } - ctx.parsePastEndTag(uri, name); - return insets; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/AbstractGradient.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/AbstractGradient.java deleted file mode 100644 index 5a94abc2cb4e42846ee0cb8886c528cf6420084a..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/AbstractGradient.java +++ /dev/null @@ -1,280 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import java.awt.Color; -import java.awt.MultipleGradientPaint.CycleMethod; -import java.awt.Paint; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.ArrayList; -import java.util.Collections; -import java.util.Comparator; -import java.util.List; - -/** @author rbair */ -public abstract class AbstractGradient extends PaintModel { - private final Comparator sorter = new Comparator() { - public int compare(GradientStop s1, GradientStop s2) { - //since a float value may be -.001 or .001, and since casting - //this to an int will round off to 0, I have to do a more direct - //comparison - float v = s1.getPosition() - s2.getPosition(); - - if (v < 0) return -1; - else if (v == 0) return 0; - else return 1; - } - }; - private PropertyChangeListener stopListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - if (evt.getPropertyName().equals("position")) { - if (stops.contains((GradientStop) evt.getSource())) { - resortModel(true); - } else { - System.err.println("[WARNING] The position of an orphaned stop was changed."); - } - } else { - firePropertyChange("paint", null, getPaint()); - } - } - }; - - private List stops = new ArrayList(); - private List unmodifiable; - private CycleMethod cycleMethod; - - protected AbstractGradient() { - unmodifiable = Collections.unmodifiableList(stops); - cycleMethod = CycleMethod.NO_CYCLE; - setStops(new GradientStop(0, new Matte(Color.BLUE, null)), - new GradientStop(1, new Matte(Color.WHITE, null))); - } - - /** - * Copy stops and cycleMethod from src to dst - * - * @param dst The gradient to update to same stops and cycle method as this gradient - */ - protected void copyTo(AbstractGradient dst) { - dst.stops.clear(); - List stops = new ArrayList(); - for (GradientStop stop : this.stops) { - stops.add(stop.clone()); - } - dst.setStops(stops); - dst.cycleMethod = this.cycleMethod; - } - - - public PaintControlType getPaintControlType() { - return PaintControlType.control_line; - } - - public void setCycleMethod(CycleMethod method) { - CycleMethod old = cycleMethod; - Paint oldp = getPaint(); - cycleMethod = method == null ? CycleMethod.NO_CYCLE : method; - firePropertyChange("cycleMethod", old, cycleMethod); - firePropertyChange("paint", oldp, getPaint()); - } - - public final CycleMethod getCycleMethod() { - return cycleMethod; - } - - public void setStops(GradientStop... stops) { - if (stops == null || stops.length < 1) { - throw new IllegalArgumentException("Must have more than one stop"); - } - List old = new ArrayList(this.stops); - for (GradientStop stop : old) { - stop.removePropertyChangeListener(stopListener); - } - Paint oldp = getPaint(); - this.stops.clear(); - Collections.addAll(this.stops, stops); - for (GradientStop stop : this.stops) { - stop.addPropertyChangeListener(stopListener); - } - resortModel(false); - firePropertyChange("stops", old, getStops()); - firePropertyChange("paint", oldp, getPaint()); - } - - public final void setStops(List stops) { - setStops(stops == null ? null : stops.toArray(new GradientStop[0])); - } - - public final List getStops() { - return unmodifiable; - } - - private void resortModel(boolean fireEvent) { - Collections.sort(this.stops, sorter); - if (fireEvent) { - Paint oldp = getPaint(); - firePropertyChange("stops", null, getStops()); - firePropertyChange("paint", oldp, getPaint()); - } - } - - //adds a new stop, and interoplates the proper color to use based on - //its position - public GradientStop addStop(float position) { - GradientStop prevStop = null; - GradientStop nextStop = null; - for (GradientStop stop : stops) { - if (stop.getPosition() <= position) { - prevStop = stop; - } else if (stop.getPosition() >= position) { - nextStop = stop; - } - } - - Matte c = null; - if (prevStop != null && nextStop != null) { - //interpolate the value of c - c = interpolate(prevStop.getColor(), nextStop.getColor(), - position / (nextStop.getPosition() - prevStop.getPosition())); - } else if (prevStop != null) { - c = prevStop.getColor().clone(); - } else if (nextStop != null) { - c = nextStop.getColor().clone(); - } - - return addStop(position, c); - } - - public GradientStop addStop(float position, Matte color) { - GradientStop s = new GradientStop(position, color); - s.addPropertyChangeListener(stopListener); - List old = new ArrayList(stops); - Paint oldp = getPaint(); - stops.add(s); - resortModel(false); - firePropertyChange("stops", old, getStops()); - firePropertyChange("paint", oldp, getPaint()); - - return s; - } - - public GradientStop removeStop(GradientStop s) { - List old = new ArrayList(stops); - Paint oldp = getPaint(); - stops.remove(s); - s.removePropertyChangeListener(stopListener); - resortModel(false); - firePropertyChange("stops", old, getStops()); - firePropertyChange("paint", oldp, getPaint()); - return s; - } - - @Override public Paint getPaint() { - if (stops.size() == 0) { - return null; - } - - //there are stops.size() number of main stops. Between each is - //a fractional stop. Thus, there are: - //stops.size() + stops.size() - 1 - //number of fractions and colors. - - float[] fractions = new float[stops.size() + stops.size() - 1]; - Matte[] colors = new Matte[fractions.length]; - - //for each stop, create the stop and it's associated fraction - int index = 0; // the index into fractions and colors - for (int i = 0; i < stops.size(); i++) { - GradientStop s = stops.get(i); - //copy over the stop's data - colors[index] = s.getColor(); - fractions[index] = s.getPosition(); - - //If this isn't the last stop, then add in the fraction - if (index < fractions.length - 1) { - float f1 = s.getPosition(); - float f2 = stops.get(i + 1).getPosition(); - - index++; - fractions[index] = f1 + (f2 - f1) * s.getMidpoint(); - colors[index] = interpolate(colors[index - 1], stops.get(i + 1).getColor(), .5f); - } - - index++; - } - - for (int i = 1; i < fractions.length; i++) { - //to avoid an error with LinearGradientPaint where two fractions - //are identical, bump up the fraction value by a miniscule amount - //if it is identical to the previous one - //NOTE: The <= is critical because the previous value may already - //have been bumped up - if (fractions[i] <= fractions[i - 1]) { - fractions[i] = fractions[i - 1] + .000001f; - } - } - - //another boundary condition where multiple stops are all at the end. The - //previous loop bumped all but one of these past 1.0, which is bad. - //so remove any fractions (and their colors!) that are beyond 1.0 - int outOfBoundsIndex = -1; - for (int i = 0; i < fractions.length; i++) { - if (fractions[i] > 1) { - outOfBoundsIndex = i; - break; - } - } - - if (outOfBoundsIndex >= 0) { - float[] f = fractions; - Matte[] c = colors; - fractions = new float[outOfBoundsIndex]; - colors = new Matte[outOfBoundsIndex]; - System.arraycopy(f, 0, fractions, 0, outOfBoundsIndex); - System.arraycopy(c, 0, colors, 0, outOfBoundsIndex); - } - - return createPaint(fractions, colors, cycleMethod); - } - - protected abstract Paint createPaint(float[] fractions, Matte[] colors, CycleMethod method); - - protected static Matte interpolate(Matte v0, Matte v1, float fraction) { - return new Matte(interpolate(v0.getColor(), v1.getColor(), fraction), v0.getUiDefaults()); - } - - protected static Color interpolate(Color v0, Color v1, float fraction) { - int r = v0.getRed() + - (int) ((v1.getRed() - v0.getRed()) * fraction + 0.5f); - int g = v0.getGreen() + - (int) ((v1.getGreen() - v0.getGreen()) * fraction + 0.5f); - int b = v0.getBlue() + - (int) ((v1.getBlue() - v0.getBlue()) * fraction + 0.5f); - int a = v0.getAlpha() + - (int) ((v1.getAlpha() - v0.getAlpha()) * fraction + 0.5f); - return new Color(r, g, b, a); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Gradient.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Gradient.java deleted file mode 100644 index ed239ed370bf326d7e8e6c397b752cb11ffe1730..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Gradient.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import java.awt.Color; -import java.awt.LinearGradientPaint; -import java.awt.MultipleGradientPaint.CycleMethod; -import java.awt.Paint; - -/** - * Represents a GradientPaint or LinearGradientPaint. - * - * @author rbair - */ -public class Gradient extends AbstractGradient implements Cloneable { - protected Paint createPaint(float[] fractions, Matte[] mattes, CycleMethod method) { - Color[] colors = new Color[mattes.length]; - for (int i = 0; i < colors.length; i++) { - colors[i] = mattes[i].getColor(); - } - return new LinearGradientPaint(0, 0, 1, 0, fractions, colors, method); - } - - @Override public Gradient clone() { - Gradient gradient = new Gradient(); - copyTo(gradient); - return gradient; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/GradientStop.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/GradientStop.java deleted file mode 100644 index f462fedde7d9f28a9f7cd0fad9c107cacc50a589..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/GradientStop.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import org.jdesktop.beans.AbstractBean; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -/** Each stop is defined linearly, at positions between 0 and 1. */ -public final class GradientStop extends AbstractBean implements Cloneable { - private float position; - private Matte color; - private PropertyChangeListener matteListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("color", null, color); - } - }; - - /** - * The midpoint to the right of the stop. Must be 0 <= midpoint <= 1. The midpoint value of the last Stop is - * ignored. - */ - private float midpoint; - - public GradientStop() {} - - public GradientStop(float position, Matte color) { - if (color == null) { - throw new IllegalArgumentException("Color must not be null"); - } - - this.position = clamp(0, 1, position); - this.color = color; - this.midpoint = .5f; - - if (this.color != null) { - this.color.addPropertyChangeListener("color", matteListener); - } - } - - - public GradientStop clone() { - GradientStop clone = new GradientStop(this.position, this.color.clone()); - clone.midpoint = midpoint; - return clone; - } - - public final float getPosition() { - return position; - } - - public final void setPosition(float position) { - float old = this.position; - this.position = clamp(0, 1, position); - firePropertyChange("position", old, this.position); - } - - public final Matte getColor() { - return color; - } - - public final void setColor(Matte c) { - if (c == null) throw new IllegalArgumentException("Color must not be null"); - Matte old = this.color; - if (old != null) old.removePropertyChangeListener(matteListener); - this.color = c; - if (this.color != null) this.color.addPropertyChangeListener(matteListener); - firePropertyChange("color", old, c); - } - - public final void setOpacity(int opacity) { - int old = getOpacity(); - color.setAlpha(opacity); - firePropertyChange("opacity", old, getOpacity()); - } - - public final int getOpacity() { - return color.getAlpha(); - } - - public final float getMidpoint() { - return midpoint; - } - - public final void setMidpoint(float midpoint) { - float old = this.midpoint; - this.midpoint = clamp(0, 1, midpoint); - firePropertyChange("midpoint", old, this.midpoint); - } - - private float clamp(float lo, float hi, float value) { - if (value < lo) { - return lo; - } else if (value > hi) { - return hi; - } else { - return value; - } - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Matte.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Matte.java deleted file mode 100644 index 634909f30a14beeb478bc349bd22b92f927a4426..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Matte.java +++ /dev/null @@ -1,610 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -import javax.swing.UIDefaults; -import java.awt.Color; -import java.awt.Paint; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -/** - * Representing a single uniform color. Basically, it represents the java.awt.Color. It can either be absolute or - * derived from a UIDefault color. - * - * @author rbair & jasper potts - */ -public class Matte extends PaintModel implements HasUIDefaults { - private float[] tmpf1 = new float[3]; - private float[] tmpf2 = new float[3]; - - private int red; - private int green; - private int blue; - private int alpha; - private Color cached = null; - - /** - * The name of the ui default key to derive this color from. - */ - private String uiDefaultParentName = null; - /** - * The name of the bean property, or client property, on this component - * from which to extract a color used for painting. So for example the color - * used in a painter could be the background of the component. - */ - private String componentPropertyName = null; - private float hueOffset = 0, saturationOffset = 0, brightnessOffset = 0; - private int alphaOffset = 0; - /** - * When true this color will become a UIResource in the UIManager defaults - * table. If false, then it will not be a UIResource. This is sometimes - * required, such as with colors installed on renderers. - */ - private boolean uiResource = true; - - /** This is a local UIDefaults that contains all the UIDefaults in the Model. */ - private transient UIDefaults uiDefaults = new UIDefaults(); - private PropertyChangeListener uiDefaultsChangeListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - if (uiDefaultParentName != null && uiDefaultParentName.equals(evt.getPropertyName())) { - updateARGBFromOffsets(); - } - } - }; - - // ================================================================================================================= - // Constructors - - /** propected constructor for JIBX */ - protected Matte() {} - - public Matte(Color c, UIDefaults uiDefaults) { - if (c != null) { - this.red = c.getRed(); - this.green = c.getGreen(); - this.blue = c.getBlue(); - this.alpha = c.getAlpha(); - } - setUiDefaults(uiDefaults); - } - - // ================================================================================================================= - // JIBX Methods - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - protected void postSet(IUnmarshallingContext context) { - // walk up till we get synth model - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof HasUIDefaults) { - UIDefaults uiDefaults = ((HasUIDefaults) context.getStackObject(i)).getUiDefaults(); - if (uiDefaults != null) { - setUiDefaults(uiDefaults); - break; - } - } - } - } - - // ================================================================================================================= - // Matte methods - - /** - * Is the matte an absolute color ot derived from a parent ui default - * - * @return true if this is a absolute not uidefault derived color - */ - public boolean isAbsolute() { - return uiDefaultParentName == null; - } - - /** - * Set all properties of this matte to be the same as srcMatte and fire all the change events - * - * @param srcMatte the matte to copy properties from - */ - public void copy(Matte srcMatte) { - // keep old values - Color oldColor = getColor(); - String oldParentName = uiDefaultParentName; - String oldComponentPropertyName = componentPropertyName; - boolean oldUiResource = uiResource; - int oldR = red, oldG = green, oldB = blue, oldA = alpha; - float oldH = hueOffset, oldS = saturationOffset, oldBr = brightnessOffset; - // set properties - if (uiResource != srcMatte.uiResource) { - uiResource = srcMatte.uiResource; - firePropertyChange("uiResource", oldUiResource, isUiResource()); - } - if (red != srcMatte.red) { - red = srcMatte.red; - firePropertyChange("red", oldR, getRed()); - } - if (green != srcMatte.green) { - green = srcMatte.green; - firePropertyChange("green", oldG, getGreen()); - } - if (blue != srcMatte.blue) { - blue = srcMatte.blue; - firePropertyChange("blue", oldB, getBlue()); - } - if (alpha != srcMatte.alpha) { - alpha = srcMatte.alpha; - firePropertyChange("alpha", oldA, getAlpha()); - } - if (hueOffset != srcMatte.hueOffset) { - hueOffset = srcMatte.hueOffset; - firePropertyChange("hueOffset", oldH, getHueOffset()); - } - if (saturationOffset != srcMatte.saturationOffset) { - saturationOffset = srcMatte.saturationOffset; - firePropertyChange("saturationOffset", oldS, getSaturationOffset()); - } - if (brightnessOffset != srcMatte.brightnessOffset) { - brightnessOffset = srcMatte.brightnessOffset; - firePropertyChange("brightnessOffset", oldBr, getBrightnessOffset()); - } - if (alphaOffset != srcMatte.alphaOffset) { - alphaOffset = srcMatte.alphaOffset; - firePropertyChange("alphaOffset", oldA, getAlphaOffset()); - } - if (uiDefaultParentName != srcMatte.uiDefaultParentName) { - uiDefaultParentName = srcMatte.uiDefaultParentName; - firePropertyChange("uiDefaultParentName", oldParentName, getUiDefaultParentName()); - } - if (componentPropertyName != srcMatte.componentPropertyName) { - componentPropertyName = srcMatte.componentPropertyName; - firePropertyChange("componentPropertyName", oldComponentPropertyName, getComponentPropertyName()); - } - if (uiDefaults != srcMatte.uiDefaults) { - setUiDefaults(srcMatte.uiDefaults); - } - if (!oldColor.equals(srcMatte.getColor())) { - firePropertyChange("paint", oldColor, getColor()); - firePropertyChange("color", oldColor, getColor()); - fireHSBChange(oldR, oldG, oldB); - } - } - - // ================================================================================================================= - // PaintModel methods - - public PaintControlType getPaintControlType() { - return PaintControlType.none; - } - - // ================================================================================================================= - // Bean Methods - - /** - * Get the local UIDefaults that contains all the UIDefaults in the Model. - * - * @return The UIDefaults for the model that contains this Matte, can be null if this Matte is not part of a bigger - * model - */ - public UIDefaults getUiDefaults() { - return uiDefaults; - } - - /** - * Set the local UIDefaults that contains all the UIDefaults in the Model. - * - * @param uiDefaults The UIDefaults for the model that contains this Matte, can be null if this Matte is not part of - * a bigger model - */ - public void setUiDefaults(UIDefaults uiDefaults) { - if (uiDefaults != this.uiDefaults) { - UIDefaults old = getUiDefaults(); - if (old != null) old.removePropertyChangeListener(uiDefaultsChangeListener); - this.uiDefaults = uiDefaults; - if (uiDefaults != null) this.uiDefaults.addPropertyChangeListener(uiDefaultsChangeListener); - firePropertyChange("uiDefaults", old, getUiDefaults()); - } - } - - /** - * Get the name if the uidefault color that is the parent that this matte is derived from. If null then this is a - * absolute color. - * - * @return Parent color ui default name - */ - public String getUiDefaultParentName() { - return uiDefaultParentName; - } - - /** - * Set the name if the uidefault color that is the parent that this matte is derived from. If null then this is a - * absolute color. - * - * @param uiDefaultParentName Parent color ui default name - */ - public void setUiDefaultParentName(String uiDefaultParentName) { - String old = getUiDefaultParentName(); - this.uiDefaultParentName = uiDefaultParentName; - firePropertyChange("uiDefaultParentName", old, getUiDefaultParentName()); - if (isAbsolute()) { - // reset offsets - float oldH = hueOffset, oldS = saturationOffset, oldB = brightnessOffset; - int oldA = alphaOffset; - hueOffset = 0; - saturationOffset = 0; - brightnessOffset = 0; - alphaOffset = 0; - firePropertyChange("hueOffset", oldH, getHueOffset()); - firePropertyChange("saturationOffset", oldS, getSaturationOffset()); - firePropertyChange("brightnessOffset", oldB, getBrightnessOffset()); - firePropertyChange("alphaOffset", oldA, getAlphaOffset()); - } - updateARGBFromOffsets(); - } - - /** - * Sets the property to use for extracting the color for whatever component - * is passed to the painter. Can be a key in client properties. Can be null. - * @param name - */ - public void setComponentPropertyName(String name) { - String old = componentPropertyName; - firePropertyChange("componentPropertyName", old, componentPropertyName = name); - } - - /** - * Gets the name of the bean property, or client property, on this component - * from which to extract a color used for painting. So for example the color - * used in a painter could be the background of the component. - * - * @return - */ - public String getComponentPropertyName() { - return componentPropertyName; - } - - /** - * Sets whether this color should be represented as a UIResource in UIDefaults - * @param b true if the color should be a ui resource - */ - public void setUiResource(boolean b) { - boolean old = uiResource; - firePropertyChange("uiResource", old, uiResource = b); - } - - /** - * When false this color will become a non-UIResource in the UIManager defaults - * table. This is sometimes required to force swing to use the given color, - * such as with renderers. - * @return false if the color should not be a uiresource - */ - public boolean isUiResource() { - return uiResource; - } - - public float getHueOffset() { - return hueOffset; - } - - public void setHueOffset(float hueOffset) { - float old = getHueOffset(); - this.hueOffset = hueOffset; - firePropertyChange("hueOffset", old, getHueOffset()); - updateARGBFromOffsets(); - } - - public float getSaturationOffset() { - return saturationOffset; - } - - public void setSaturationOffset(float satOffset) { - float old = getSaturationOffset(); - this.saturationOffset = satOffset; - firePropertyChange("saturationOffset", old, getSaturationOffset()); - updateARGBFromOffsets(); - } - - public float getBrightnessOffset() { - return brightnessOffset; - } - - public void setBrightnessOffset(float brightOffset) { - float old = getBrightnessOffset(); - this.brightnessOffset = brightOffset; - firePropertyChange("brightnessOffset", old, getBrightnessOffset()); - updateARGBFromOffsets(); - } - - public int getAlphaOffset() { - return alphaOffset; - } - - public void setAlphaOffset(int alphaOffset) { - int old = getAlphaOffset(); - this.alphaOffset = alphaOffset; - firePropertyChange("alphaOffset", old, alphaOffset); - updateARGBFromOffsets(); - } - - - public void setRed(int red) { - red = clamp(red); - if (this.red != red) { - Color old = getColor(); - int oldr = this.red; - this.red = red; - firePropertyChange("paint", old, getColor()); - firePropertyChange("color", old, getColor()); - firePropertyChange("red", oldr, red); - fireHSBChange(oldr, green, blue); - updateOffsetsFromARGB(); - } - } - - public final int getRed() { - return red; - } - - public void setGreen(int green) { - green = clamp(green); - if (this.green != green) { - Color old = getColor(); - int oldg = this.green; - this.green = green; - firePropertyChange("paint", old, getColor()); - firePropertyChange("color", old, getColor()); - firePropertyChange("green", oldg, green); - fireHSBChange(red, oldg, blue); - updateOffsetsFromARGB(); - } - } - - public final int getGreen() { - return green; - } - - public void setBlue(int blue) { - blue = clamp(blue); - if (this.blue != blue) { - Color old = getColor(); - int oldb = this.blue; - this.blue = blue; - firePropertyChange("paint", old, getColor()); - firePropertyChange("color", old, getColor()); - firePropertyChange("blue", oldb, blue); - fireHSBChange(red, green, oldb); - updateOffsetsFromARGB(); - } - } - - public final int getBlue() { - return blue; - } - - public void setAlpha(int alpha) { - alpha = clamp(alpha); - if (this.alpha != alpha) { - int old = getAlpha(); - this.alpha = alpha; - firePropertyChange("alpha", old, alpha); - firePropertyChange("paint", old, getColor()); - firePropertyChange("color", old, getColor()); - updateOffsetsFromARGB(); - } - } - - public final int getAlpha() { - return alpha; - } - - public Color getColor() { - if (cached == null || red != cached.getRed() || green != cached.getGreen() || - blue != cached.getBlue() || alpha != cached.getAlpha()) { - cached = new Color(red, green, blue, alpha); - } - return cached; - } - - public void setColor(Color c) { - setColor(c, false); - } - - public void setColor(Color c, boolean dontSetAlpha) { - Color oldColor = getColor(); - int oldR = red, oldG = green, oldB = blue, oldA = alpha; - cached = c; - red = c.getRed(); - green = c.getGreen(); - blue = c.getBlue(); - if (!dontSetAlpha) alpha = c.getAlpha(); - updateOffsetsFromARGB(); - firePropertyChange("red", oldR, getRed()); - firePropertyChange("green", oldG, getGreen()); - firePropertyChange("blue", oldB, getBlue()); - fireHSBChange(oldR, oldG, oldB); - if (!dontSetAlpha) firePropertyChange("alpha", oldA, getAlpha()); - firePropertyChange("paint", oldColor, getColor()); - firePropertyChange("color", oldColor, getColor()); - } - - @Override public Paint getPaint() { - return getColor(); - } - - - @Override public String toString() { - if (isAbsolute()) { - return Matte.class.getName() + "[r=" + red + ", g=" + green + ", b=" + blue + ", a=" + alpha + "]"; - } else { - return Matte.class.getName() + "[base=" + uiDefaultParentName + ", H+" + hueOffset + - ", S+" + saturationOffset + ", B+" + brightnessOffset + ", A+" + alphaOffset + "]"; - } - } - - public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - Matte matte = (Matte) o; - if (alpha != matte.alpha) return false; - if (alphaOffset != matte.alphaOffset) return false; - if (Float.compare(matte.alpha, alpha) != 0) return false; - if (blue != matte.blue) return false; - if (Float.compare(matte.brightnessOffset, brightnessOffset) != 0) - return false; - if (green != matte.green) return false; - if (Float.compare(matte.hueOffset, hueOffset) != 0) return false; - if (red != matte.red) return false; - if (uiResource != matte.uiResource) return false; - if (Float.compare(matte.saturationOffset, saturationOffset) != 0) - return false; - if (componentPropertyName != null ? - !componentPropertyName.equals(componentPropertyName) : - matte.componentPropertyName != null) return false; - - if (uiDefaultParentName != null ? - !uiDefaultParentName.equals(matte.uiDefaultParentName) : - matte.uiDefaultParentName != null) return false; - return true; - } - - public int hashCode() { - int result; - result = red; - result = 31 * result + green; - result = 31 * result + blue; - result = 31 * result + alpha; - result = 31 * result + (uiDefaultParentName != null ? - uiDefaultParentName.hashCode() : 0); - result = 31 * result + (componentPropertyName != null ? - componentPropertyName.hashCode() : 0); - result = 31 * result + hueOffset != +0.0f ? - Float.floatToIntBits(hueOffset) : 0; - result = 31 * result + saturationOffset != +0.0f ? - Float.floatToIntBits(saturationOffset) : 0; - result = 31 * result + brightnessOffset != +0.0f ? - Float.floatToIntBits(brightnessOffset) : 0; - result = 31 * result + (uiResource ? 1 : 0); - return result; - } - - @Override public Matte clone() { - Matte m = new Matte(); - m.red = red; - m.green = green; - m.blue = blue; - m.alpha = alpha; - m.brightnessOffset = brightnessOffset; - m.hueOffset = hueOffset; - m.saturationOffset = saturationOffset; - m.alphaOffset = alphaOffset; - m.uiDefaultParentName = uiDefaultParentName; - m.componentPropertyName = componentPropertyName; - m.uiResource = uiResource; - m.setUiDefaults(uiDefaults); - return m; - } - - // ================================================================================================================= - // Private Helper Methods - - private void updateOffsetsFromARGB() { - if (!isAbsolute()) { - tmpf1 = Color.RGBtoHSB(red, green, blue, tmpf1); - Color parentColor = uiDefaults.getColor(uiDefaultParentName); - tmpf2 = Color.RGBtoHSB(parentColor.getRed(), parentColor.getGreen(), parentColor.getBlue(), tmpf2); - // update offset properties and fire events - float oldH = hueOffset, oldS = saturationOffset, oldB = brightnessOffset; - int oldA = alphaOffset; - hueOffset = tmpf1[0] - tmpf2[0]; - saturationOffset = tmpf1[1] - tmpf2[1]; - brightnessOffset = tmpf1[2] - tmpf2[2]; - alphaOffset = alpha - parentColor.getAlpha(); - firePropertyChange("hueOffset", oldH, getHueOffset()); - firePropertyChange("saturationOffset", oldS, getSaturationOffset()); - firePropertyChange("brightnessOffset", oldB, getBrightnessOffset()); - firePropertyChange("alphaOffset", oldA, getAlphaOffset()); - } - } - - private void updateARGBFromOffsets() { - if (!isAbsolute()) { - Color oldColor = getColor(); - // get parent color HSB - Color parentColor = uiDefaults.getColor(uiDefaultParentName); - tmpf1 = Color.RGBtoHSB(parentColor.getRed(), parentColor.getGreen(), parentColor.getBlue(), tmpf1); - // apply offsets - tmpf1[0] = clamp(tmpf1[0] + hueOffset); - tmpf1[1] = clamp(tmpf1[1] + saturationOffset); - tmpf1[2] = clamp(tmpf1[2] + brightnessOffset); - int oldA = getAlpha(); - alpha = clamp(parentColor.getAlpha() + alphaOffset); - updateRGB(tmpf1); - // update fire events - firePropertyChange("alpha", oldA, getAlpha()); - firePropertyChange("paint", oldColor, getColor()); - firePropertyChange("color", oldColor, getColor()); - } - } - - private void updateRGB(float[] hsb) { - int oldR = red, oldG = green, oldB = blue; - int rgb = Color.HSBtoRGB(hsb[0], hsb[1], hsb[2]); - red = (rgb >> 16) & 0xFF; - green = (rgb >> 8) & 0xFF; - blue = rgb & 0xFF; - firePropertyChange("red", oldR, getRed()); - firePropertyChange("green", oldG, getGreen()); - firePropertyChange("blue", oldB, getBlue()); - } - - private void fireHSBChange(int oldR, int oldG, int oldB) { - tmpf1 = Color.RGBtoHSB(oldR, oldG, oldB, tmpf1); - tmpf2 = Color.RGBtoHSB(red, green, blue, tmpf2); - firePropertyChange("hue", tmpf1[0], tmpf2[0]); - firePropertyChange("saturation", tmpf1[1], tmpf2[1]); - firePropertyChange("brightness", tmpf1[2], tmpf2[2]); - } - - private float clamp(float value) { - if (value < 0) { - value = 0; - } else if (value > 1) { - value = 1; - } - return value; - } - - private int clamp(int value) { - if (value < 0) { - value = 0; - } else if (value > 255) { - value = 255; - } - return value; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/PaintModel.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/PaintModel.java deleted file mode 100644 index 15b67f55a2eefab37c30d6fa87797822c482e859..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/PaintModel.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import org.jdesktop.beans.AbstractBean; - -import java.awt.Paint; - -/** - * I'd have just called it Paint, but sadly, that name was already taken, and would have been too confusing. - *

- * Whenever size or position values are required (for example with Texture or Gradient), they are specified in the unit - * square: that is, between 0 and 1 inclusive. They can then later be scaled as necessary by any painting code. - * - * @author rbair - */ -public abstract class PaintModel extends AbstractBean implements Cloneable { - public static enum PaintControlType { - none, control_line, control_rect - } - - protected PaintModel() { } - - /** - * @return an instance of Paint that is represented by this PaintModel. This is often not a reversable operation, - * and hence there is no "setPaint" method. Rather, tweaking the exposed properties of the PaintModel fires, - * when necessary, property change events for the "paint" property, and results in different values returned - * from this method. - */ - public abstract Paint getPaint(); - - /** - * Get the type of controls for this paint model - * - * @return The type of paint controls, one of PaintControlType.none, PaintControlType.control_line or - * PaintControlType.control_rect - */ - public abstract PaintControlType getPaintControlType(); - - - public abstract PaintModel clone(); -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/RadialGradient.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/RadialGradient.java deleted file mode 100644 index 3e66092320b60d7d99af08ca81b96ee88bcebc58..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/RadialGradient.java +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import java.awt.Color; -import java.awt.MultipleGradientPaint.CycleMethod; -import java.awt.Paint; -import java.awt.RadialGradientPaint; - -/** - * Represents a RadialGradientPaint. - * - * @author rbair - */ -public class RadialGradient extends AbstractGradient { - protected Paint createPaint(float[] fractions, Matte[] mattes, CycleMethod method) { - Color[] colors = new Color[mattes.length]; - for (int i = 0; i < colors.length; i++) { - colors[i] = mattes[i].getColor(); - } - return new RadialGradientPaint(.5f, .5f, 1, fractions, colors, method); - } - - @Override public RadialGradient clone() { - RadialGradient gradient = new RadialGradient(); - copyTo(gradient); - return gradient; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Texture.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Texture.java deleted file mode 100644 index 8fd4b2a7b3935830588923f02e9f7a80700f6a2a..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/paint/Texture.java +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.paint; - -import java.awt.Paint; -import java.awt.TexturePaint; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; - -/** - * Represents a TexturePaint. - * - * @author rbair - */ -public class Texture extends PaintModel { - private static final Rectangle2D RECT = new Rectangle2D.Double(0, 0, 1, 1); - private BufferedImage img; - - public Texture() { - } - - public PaintControlType getPaintControlType() { - return PaintControlType.control_rect; - } - - public void setImage(BufferedImage img) { - BufferedImage old = this.img; - this.img = img; - firePropertyChange("paint", old, this.img); - firePropertyChange("image", old, this.img); - } - - public final BufferedImage getImage() { - return img; - } - - public Paint getPaint() { - return new TexturePaint(img, RECT); - } - - - public Texture clone() { - Texture newTexture = new Texture(); - newTexture.img = this.img; - return newTexture; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasUIDefaults.java b/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasUIDefaults.java deleted file mode 100644 index c774d796c1c1008094e457c5866ef43970e00db2..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasUIDefaults.java +++ /dev/null @@ -1,36 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.swingx.designer.utils; - -import javax.swing.UIDefaults; - -/** - * HasUIDefaults - A tagging interface for any class that has UIDefaults - * - * @author Created by Jasper Potts (Jun 22, 2007) - */ -public interface HasUIDefaults { - public UIDefaults getUiDefaults(); -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/DefaultsGenerator.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/DefaultsGenerator.java deleted file mode 100644 index 948686cb0244dd465ebb895a0aaaf617545ac212..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/DefaultsGenerator.java +++ /dev/null @@ -1,726 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.generator; - -import org.jdesktop.swingx.designer.Canvas; -import org.jdesktop.swingx.designer.font.Typeface; -import org.jdesktop.swingx.designer.paint.Matte; -import org.jdesktop.swingx.designer.paint.PaintModel; -import static org.jdesktop.synthdesigner.generator.GeneratorUtils.makePretty; -import static org.jdesktop.synthdesigner.generator.GeneratorUtils.toConstantName; -import static org.jdesktop.synthdesigner.generator.ObjectCodeConvertors.convert; -import static org.jdesktop.synthdesigner.generator.TemplateWriter.read; -import static org.jdesktop.synthdesigner.generator.TemplateWriter.writeSrcFile; -import org.jdesktop.synthdesigner.synthmodel.SynthModel; -import org.jdesktop.synthdesigner.synthmodel.UIComponent; -import org.jdesktop.synthdesigner.synthmodel.UIFont; -import org.jdesktop.synthdesigner.synthmodel.UIIconRegion; -import org.jdesktop.synthdesigner.synthmodel.UIPaint; -import org.jdesktop.synthdesigner.synthmodel.UIProperty; -import org.jdesktop.synthdesigner.synthmodel.UIRegion; -import org.jdesktop.synthdesigner.synthmodel.UIState; -import org.jdesktop.synthdesigner.synthmodel.UIStateType; -import org.jdesktop.synthdesigner.synthmodel.UIStyle; - -import javax.swing.border.BevelBorder; -import javax.swing.border.Border; -import javax.swing.border.CompoundBorder; -import javax.swing.border.EmptyBorder; -import javax.swing.border.EtchedBorder; -import javax.swing.border.LineBorder; -import javax.swing.border.MatteBorder; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Insets; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import org.jdesktop.synthdesigner.synthmodel.PainterBorder; - -/** - * DefaultsGenerator - *

- * There are two main sets of defaults that must be configured. The first is - * the actual UI defaults tree. The second is a map of components + regions, which - * are used to decide what SynthStyle to use. - * - * @author Jasper Potts - * @author Richard Bair - */ -public class DefaultsGenerator { - private static String stateTypeImplTemplate; - - private static String getStateTypeTemplate() { - if (stateTypeImplTemplate == null) { - //load the painter template file into an in-memory string to improve performance - //when generating a lot of classes - try { - stateTypeImplTemplate = read("resources/StateImpl.template"); - } catch (IOException e) { - System.err.println("Failed to read template files."); - throw new RuntimeException(e); - } - } - return stateTypeImplTemplate; - } - - /** - * Generate the defaults file and all painter files for a SynthModel. This method - * is the main entry point, called by the Generator class. - * - * @param uiDefaultInit The buffer to write ui default put methods of the form d.put("activeCaption", new - * ColorUIResource(123, 45, 200)); - * @param styleInit The buffer to write out code to generate Synth Style populating the styles map m - * = new HashMap() - * @param model The Synth Model we are writing out defaults class for - * @param variables The variables map pre populated with "PACKAGE" and "LAF_NAME" - * @param packageNamePrefix The package name associated with this synth look and feel. For example, - * org.mypackage.mylaf - * @param painterPackageRoot The directory to write painters out to - */ - public static void generateDefaults(StringBuilder uiDefaultInit, StringBuilder styleInit, SynthModel model, - Map variables, String packageNamePrefix, - File painterPackageRoot) { - // write color palette - uiDefaultInit.append(" //Color palette\n"); - writeColorPalette(uiDefaultInit, model.getColorPalette()); - uiDefaultInit.append("\n"); - // write fonts palette - uiDefaultInit.append(" //Font palette\n"); - uiDefaultInit.append(" d.put(\"defaultFont\", new FontUIResource(defaultFont));\n"); - writeFontPalette(uiDefaultInit, model.getFontPalette()); - uiDefaultInit.append("\n"); - // TODO: Other palettes - uiDefaultInit.append(" //Border palette\n"); - uiDefaultInit.append("\n"); - // write global style - uiDefaultInit.append(" //The global style definition\n"); - writeStyle(model.getStyle(), uiDefaultInit, ""); - uiDefaultInit.append("\n"); - // write components - for (UIComponent c : model.getComponents()) { - String prefix = escape(c.getKey()); - uiDefaultInit.append(" //Initialize ").append(prefix) - .append("\n"); - writeRegion(c, c, prefix, uiDefaultInit, - styleInit, variables, packageNamePrefix, painterPackageRoot); - uiDefaultInit.append("\n"); - } - } - - private static void writeColorPalette(StringBuilder uiDefaultInit, List colors) { - for (UIPaint color : colors) { - uiDefaultInit.append(" d.put(\"") - .append(color.getName()) - .append("\",") - .append(convertPaint(color.getValue())) - .append(");\n"); - } - } - - private static void writeFontPalette(StringBuilder uiDefaultInit, List fonts) { - for (UIFont font : fonts) { - // We have no way of doing CSS style font lists yet so will just - // just the first font - if (!font.getFonts().isEmpty()){ - Typeface t = font.getFonts().get(0); - if (t.isAbsolute()){ - Font f = t.getFont(); - uiDefaultInit.append(" d.put(\"") - .append(font.getName()) - .append("\", new javax.swing.plaf.FontUIResource(\"") - .append(f.getName()) - .append("\", ") - .append(f.getStyle()) - .append(", ") - .append(f.getSize()) - .append("));\n"); - } else { - uiDefaultInit.append(" d.put(\"") - .append(font.getName()) - .append("\", new DerivedFont(\"") - .append(t.getUiDefaultParentName()) - .append("\", ") - .append(t.getSizeOffset()) - .append("f, "); - switch (t.getBold()){ - case Default: - uiDefaultInit.append("null"); - break; - case On: - uiDefaultInit.append("true"); - break; - case Off: - uiDefaultInit.append("false"); - break; - } - uiDefaultInit.append(", "); - switch (t.getItalic()){ - case Default: - uiDefaultInit.append("null"); - break; - case On: - uiDefaultInit.append("true"); - break; - case Off: - uiDefaultInit.append("false"); - break; - } - uiDefaultInit.append("));\n"); - } - } - } - } - - /** - * Write out the UIDefaults entries for a style - * - * @param style The style to write defaults entries for - * @param uiDefaultInit The buffer to write ui default put methods of the form d.put("activeCaption", new - * ColorUIResource(123, 45, 200)); - * @param prefix The prefix for the style property names, for the model path where the style is from, should - * end with a "." - */ - private static void writeStyle(UIStyle style, StringBuilder uiDefaultInit, String prefix) { - if (!style.isTextForegroundInherited()) writeMatte(prefix + "textForeground", style.getTextForeground(), uiDefaultInit); - if (!style.isTextBackgroundInherited()) writeMatte(prefix + "textBackground", style.getTextBackground(), uiDefaultInit); - if (!style.isBackgroundInherited()) writeMatte(prefix + "background", style.getBackground(), uiDefaultInit); - if (!style.isFontInherited()) writeTypeFace(prefix + "font", style.getFont(), uiDefaultInit); - for (UIProperty property : style.getUiProperties()) { - switch (property.getType()) { - case BOOLEAN: - Boolean b = ((Boolean)property.getValue()); - if (b != null) { - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", ") - .append(b ? "Boolean.TRUE" : "Boolean.FALSE") - .append(");\n"); - } - break; - case STRING: - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", \"") - .append(property.getValue().toString()) - .append("\");\n"); - break; - case INT: - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", new Integer(") - .append(((Integer) property.getValue()).intValue()) - .append("));\n"); - break; - case FLOAT: - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", new Float(") - .append(((Float) property.getValue()).floatValue()) - .append("f));\n"); - break; - case DOUBLE: - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", new Double(") - .append(((Double) property.getValue()).doubleValue()) - .append("));\n"); - break; - case COLOR: - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", ") - .append(convertPaint((Matte)property.getValue())) - .append(");\n"); - break; - case FONT: - writeTypeFace(prefix.replace("\"", "\\\"") + property.getName(), - (Typeface) property.getValue(), uiDefaultInit); - break; - case INSETS: - Insets i = (Insets) property.getValue(); - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", new InsetsUIResource(") - .append(i.top).append(", ").append(i.left).append(", ").append(i.bottom).append(", ") - .append(i.right) - .append("));\n"); - break; - case DIMENSION: - Dimension d = (Dimension) property.getValue(); - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", new DimensionUIResource(") - .append(d.width).append(", ").append(d.height) - .append("));\n"); - break; - case BORDER: - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(property.getName()) - .append("\", new BorderUIResource("); - uiDefaultInit.append(convertBorder( - (Border)property.getValue())); - uiDefaultInit.append("));\n"); - break; - } - } - } - - private static void writeMatte(String propertyName, Matte matte, StringBuilder uiDefaultInit) { - if (matte==null) System.err.println("Error matte is NULL for ["+propertyName+"]"); - uiDefaultInit.append(" d.put(\"") - .append(propertyName) - .append("\", ") - .append(convertPaint(matte)) - .append(");\n"); - } - - private static void writeTypeFace(String propertyName, Typeface typeface, StringBuilder uiDefaultInit) { - uiDefaultInit.append(" d.put(\"") - .append(propertyName) - .append("\", new DerivedFont(\"") - .append(typeface.getUiDefaultParentName()) - .append("\", ") - .append(typeface.getSizeOffset()) - .append("f, "); - switch (typeface.getBold()) { - case Default: - uiDefaultInit.append("null,"); - break; - case Off: - uiDefaultInit.append("Boolean.FALSE,"); - break; - case On: - uiDefaultInit.append("Boolean.TRUE,"); - break; - } - switch (typeface.getItalic()) { - case Default: - uiDefaultInit.append("null"); - break; - case Off: - uiDefaultInit.append("Boolean.FALSE"); - break; - case On: - uiDefaultInit.append("Boolean.TRUE"); - break; - } - uiDefaultInit.append("));\n"); - } - - - /** - * Write out code for a Component or Region - * - * @param comp This may be the same as the region reg or is the parent component - * containing the region - * @param region The region we are writing out - * @param prefix This is dot sperated path of component and sub regions to and including the region - * reg of the form [Comp].[Region]......[Region] path - * @param uiDefaultInit This is for inserting into org.mypackage.mylaf.MyDefaults#getDefaults() method - * @param styleInit This is for inserting into org.mypackage.mylaf.MyDefaults#initialize() method - * @param variables The variables map pre populated with "PACKAGE" and "LAF_NAME" - * @param packageNamePrefix The package name associated with this synth look and feel. For example, - * org.mypackage.mylaf - * @param painterPackageRoot The directory to write painters out to - */ - private static void writeRegion(UIComponent comp, UIRegion region, String prefix, StringBuilder uiDefaultInit, - StringBuilder styleInit, Map variables, - String packageNamePrefix, File painterPackageRoot) { - // register component with LAF - String regionCode = GeneratorUtils.getRegionNameCaps(region.getName()); - if (regionCode == null) { - throw new IllegalStateException("We were asked to encode a region we know nothing about: " + region.getName()); - } else { - regionCode = "Region." + regionCode; - } - - //construct the list of States that accompany this registration. - StringBuffer regString = new StringBuffer(); //like: Enabled,Disabled,Foo,Default,Etc - List types = comp.getStateTypes(); //state types are only defined on the UIComponent level - if (types != null && types.size() > 0) { - for (UIStateType type : types) { - regString.append(type.getKey()); - regString.append(","); - } - //remove the last "," - regString.deleteCharAt(regString.length()-1); - } - - styleInit.append(" register(") - .append(regionCode) - .append(", \"") - .append(prefix); - styleInit.append("\""); - styleInit.append(");\n"); - - // write content margins - Insets i = (Insets) region.getContentMargins(); - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(".contentMargins") - .append("\", new InsetsUIResource(") - .append(i.top).append(", ").append(i.left).append(", ").append(i.bottom).append(", ").append(i.right) - .append("));\n"); - // write opaque if true - if (region instanceof UIComponent && ((UIComponent)region).isOpaque()) { - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(".opaque") - .append("\", Boolean.TRUE);\n"); - } - //write the State, if necessary - if (!regString.equals("Enabled,MouseOver,Pressed,Disabled,Focused,Selected,Default") && types.size() > 0) { - //there were either custom states, or the normal states were in a custom order - //so go ahead and write out prefix.State - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(".States") - .append("\", \"") - .append(regString) - .append("\");\n"); - } - //write out any custom states, if necessary - for (UIStateType type : types) { - String synthState = type.getKey(); - if (!"Enabled".equals(synthState) && - !"MouseOver".equals(synthState) && - !"Pressed".equals(synthState) && - !"Disabled".equals(synthState) && - !"Focused".equals(synthState) && - !"Selected".equals(synthState) && - !"Default".equals(synthState)) { - //what we have here, gentlemen, is a bona-fide custom state. - try { - //if the type is not one of the standard types, then construct a name for - //the new type, and write out a new subclass of State. - java.lang.String className = makePretty(prefix) + synthState + "State"; - java.lang.String body = type.getCodeSnippet(); - variables.put("STATE_NAME", className); - variables.put("STATE_KEY", synthState); - variables.put("BODY", body); - - writeSrcFile(getStateTypeTemplate(), variables, new java.io.File(painterPackageRoot, className + ".java")); - - variables.remove("STATE_NAME"); - variables.remove("STATE_KEY"); - variables.remove("BODY"); - - uiDefaultInit.append(" d.put(\"") - .append(prefix) - .append(".") - .append(synthState) - .append("\", new ") - .append(className) - .append("());\n"); - } catch (IOException ex) { - ex.printStackTrace(); - } - } - } - // write region style - writeStyle(region.getStyle(), uiDefaultInit, prefix + "."); - - try { - boolean hasCanvas = hasCanvas(region); - if (hasCanvas) { - PainterGenerator.writePainter(region, variables, painterPackageRoot, prefix); - } - String fileNamePrefix = makePretty(prefix) + "Painter"; - // write states ui defaults - for (UIState state : region.getBackgroundStates()) { - String statePrefix = prefix + "[" + state.getName() + "]"; - // write state style - writeStyle(state.getStyle(), uiDefaultInit, statePrefix + "."); - // write painter - if (hasCanvas) { - writeLazyPainter(state, uiDefaultInit, statePrefix, packageNamePrefix, fileNamePrefix, "background"); - } - } - for (UIState state : region.getForegroundStates()) { - String statePrefix = prefix + "[" + state.getName() + "]"; - // write state style - writeStyle(state.getStyle(), uiDefaultInit, statePrefix + "."); - // write painter - if (hasCanvas) { - writeLazyPainter(state, uiDefaultInit, statePrefix, packageNamePrefix, fileNamePrefix, "foreground"); - } - } - for (UIState state : region.getBorderStates()) { - String statePrefix = prefix + "[" + state.getName() + "]"; - // write state style - writeStyle(state.getStyle(), uiDefaultInit, statePrefix + "."); - // write painter - if (hasCanvas) { - writeLazyPainter(state, uiDefaultInit, statePrefix, packageNamePrefix, fileNamePrefix, "border"); - } - } - } catch (Exception e) { - e.printStackTrace(); - } - - // handle sub regions - for (UIRegion subRegion : region.getSubRegions()) { - String subregionName = prefix + ":" + escape(subRegion.getKey()); - if (subRegion instanceof UIIconRegion) { - writeIconRegion(comp, (UIIconRegion) subRegion, prefix, uiDefaultInit, - variables, packageNamePrefix, painterPackageRoot); - } else if (subRegion instanceof UIComponent) { - // inner named component - UIComponent subComponent = (UIComponent) subRegion; - writeRegion(subComponent, subRegion, subregionName, - uiDefaultInit, styleInit, variables, packageNamePrefix, painterPackageRoot); - } else { - writeRegion(comp, subRegion, subregionName, uiDefaultInit, styleInit, variables, - packageNamePrefix, painterPackageRoot); - } - } - } - - private static void writeLazyPainter(UIState state, StringBuilder uiDefaultInit, String statePrefix, String packageNamePrefix, String fileNamePrefix, String painterSuffix) { - Canvas canvas = state.getCanvas(); - if (!canvas.isBlank()) { - Insets si = canvas.getStretchingInsets(); - boolean inverted = state.isInverted(); - UIStyle.CacheMode cache = state.getStyle().getCacheMode(); - String cacheModeString = null; - switch (cache) { - case NO_CACHING: cacheModeString = "AbstractRegionPainter.PaintContext.CacheMode.NO_CACHING"; break; - case FIXED_SIZES: cacheModeString = "AbstractRegionPainter.PaintContext.CacheMode.FIXED_SIZES"; break; - case NINE_SQUARE_SCALE: cacheModeString = "AbstractRegionPainter.PaintContext.CacheMode.NINE_SQUARE_SCALE"; break; - } - double maxH = state.getStyle().getMaxHozCachedImgScaling(); - double maxV = state.getStyle().getMaxVertCachedImgScaling(); - String stateConstant = toConstantName(painterSuffix + "_" + UIState.keysToString(state.getStateKeys())); - - uiDefaultInit.append(" d.put(\"") - .append(statePrefix) - .append(".").append(painterSuffix).append("Painter\", new LazyPainter(\"") - .append(packageNamePrefix).append(".").append(fileNamePrefix) - .append("\", ") - .append(fileNamePrefix).append(".").append(stateConstant).append(", ") - .append(convert(si)).append(", ") - .append(convert(canvas.getSize())).append(", ") - .append(inverted).append(", ") - .append(cacheModeString).append(", ") - .append(maxH == Double.POSITIVE_INFINITY ? "Double.POSITIVE_INFINITY" : maxH).append(", ") - .append(maxV == Double.POSITIVE_INFINITY ? "Double.POSITIVE_INFINITY" : maxV).append("));\n"); - } - } - - - /** - * Write out code for a IconRegion - * - * @param comp This may be the same as the region region or is the parent component - * containing the region - * @param region The region we are writing out - * @param prefix This is [Comp][Region]......[Region] path - * @param key The key for this icon. - * @param uiDefaultInit This is for inserting into org.mypackage.mylaf.MyDefaults#getDefaults() method - * @param variables The variables map pre populated with "PACKAGE" and "LAF_NAME" - * @param packageNamePrefix The package name associated with this synth look and feel. For example, - * org.mypackage.mylaf - * @param painterPackageRoot The directory to write painters out to - */ - private static void writeIconRegion(UIComponent comp, UIIconRegion region, String prefix, - StringBuilder uiDefaultInit, Map variables, - String packageNamePrefix, File painterPackageRoot) { - - Dimension size = null; - String fileNamePrefix = makePretty(prefix) + "Painter"; - // write states ui defaults - for (UIState state : region.getBackgroundStates()) {// TODO: Handle Background,Foreground and Borders States Lists? Actually not sure that IconRegions need support borders or foregrounds - Canvas canvas = state.getCanvas(); - if (!canvas.isBlank()) { - String statePrefix = prefix + "[" + state.getName() + "]"; - // Put Painter in UiDefaults - writeLazyPainter(state, uiDefaultInit, statePrefix, packageNamePrefix, fileNamePrefix, region.getKey()); - size = canvas.getSize(); - } - } - - if (size != null) { - // Put SynthIconImpl wrapper in UiDefaults - String key = region.getBasicKey() == null ? prefix + "." + region.getKey() : region.getBasicKey(); - uiDefaultInit.append(" d.put(\"") - .append(key) - .append("\", new NimbusIcon(\"") //TODO should this be wrapped in an IconUIResource? - .append(prefix) - .append("\", \"") - .append(region.getKey()) - .append("Painter") - .append("\", ") - .append(size.width) - .append(", ") - .append(size.height) - .append("));\n"); - } - - // handle sub regions - if (region.getSubRegions().length > 0) { - // there is no meaning to a sub region inside a IconRegion - throw new IllegalStateException("You can not have sub regions inside UiIconRegions. \"" + - comp.getSubRegions()[0].getName() + "\" is inside \"" - + prefix.substring(0, prefix.length() - 1) + "\""); - } - } - - /** - * Utility method for escaping all double quotes with backslash double-quote. - */ - private static String escape(String s) { - return s.replace("\"", "\\\""); - } - - private static String convertPaint(PaintModel paint){ - if (paint instanceof Matte){ - Matte matte = (Matte)paint; - if (matte.isAbsolute()){ - String colorParams = convert(matte.getColor()); - if (matte.isUiResource()) { - return "new ColorUIResource(" + colorParams + ")"; - } else { - return colorParams; - } - } else { - String s = "getDerivedColor(\"" + - matte.getUiDefaultParentName()+"\","+ - matte.getHueOffset()+"f,"+matte.getSaturationOffset()+ - "f,"+matte.getBrightnessOffset()+"f,"+ - matte.getAlphaOffset(); - if (matte.isUiResource()) { - return s + ")"; - } else { - return s + ",false)"; - } - } - } else { - //TODO: What about gradients etc here? - System.err.println("Error: Could not write paint in " + - "DefaultsGenerator as it was not a Matte. = "+ - paint.getClass().getName()); - return ""; - } - } - - private static String convertBorder(Border val) { - StringBuilder uiDefaultInit = new StringBuilder(); - Insets i; - if (val instanceof PainterBorder) { - PainterBorder pb = (PainterBorder) val; - i = pb.getBorderInsets(); - uiDefaultInit.append("new PainterBorder(\"") - .append(pb.getPainterName()) - .append("\", new Insets(") - .append(i.top).append(", ") - .append(i.left).append(", ") - .append(i.bottom).append(", ") - .append(i.right) - .append("))"); - } else if (val instanceof EmptyBorder) { - i = ((EmptyBorder) val).getBorderInsets(); - uiDefaultInit.append("BorderFactory.createEmptyBorder(") - .append(i.top).append(", ") - .append(i.left).append(", ") - .append(i.bottom).append(", ") - .append(i.right) - .append(")"); - } else if (val instanceof LineBorder) { - LineBorder border = (LineBorder) val; - uiDefaultInit.append("BorderFactory.createLineBorder(") - .append(convert(border.getLineColor())) - .append(",") - .append(border.getThickness()) - .append(")"); - } else if (val instanceof EtchedBorder) { - EtchedBorder border = (EtchedBorder) val; - uiDefaultInit.append("BorderFactory.createEtchedBorder(") - .append(border.getEtchType()) - .append(",") - .append(convert(border.getHighlightColor())) - .append(",") - .append(convert(border.getShadowColor())) - .append(")"); - } else if (val instanceof BevelBorder) { - BevelBorder border = (BevelBorder) val; - uiDefaultInit.append("BorderFactory.createEtchedBorder(") - .append(border.getBevelType()) - .append(",") - .append(convert(border.getHighlightOuterColor())) - .append(",") - .append(convert(border.getHighlightInnerColor())) - .append(",") - .append(convert(border.getShadowOuterColor())) - .append(",") - .append(convert(border.getShadowInnerColor())) - .append(")"); - } else if (val instanceof MatteBorder) { - MatteBorder border = (MatteBorder) val; - i = border.getBorderInsets(); - uiDefaultInit.append("BorderFactory.createEmptyBorder(") - .append(i.top).append(", ") - .append(i.left).append(", ") - .append(i.bottom).append(", ") - .append(i.right).append(", ") - .append(convert(border.getMatteColor())) - .append(")"); - } else if (val instanceof CompoundBorder) { - CompoundBorder border = (CompoundBorder) val; - uiDefaultInit.append("BorderFactory.createEmptyBorder(") - .append(convertBorder(border.getOutsideBorder())) - .append(",") - .append(convertBorder(border.getInsideBorder())) - .append(")"); - } - return uiDefaultInit.toString(); - } - - private static boolean hasCanvas(UIRegion region) { - for (UIState s : region.getBackgroundStates()) { - if (!s.getCanvas().isBlank()) return true; - } - for (UIState s : region.getBorderStates()) { - if (!s.getCanvas().isBlank()) return true; - } - for (UIState s : region.getForegroundStates()) { - if (!s.getCanvas().isBlank()) return true; - } - for (UIRegion subregion : region.getSubRegions()) { - if (hasCanvas(subregion)) return true; - } - return false; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/ObjectCodeConvertors.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/ObjectCodeConvertors.java deleted file mode 100644 index 88b1e9baff69884e4b3ce25c5712001c6e159671..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/ObjectCodeConvertors.java +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.generator; - -import java.awt.*; - -/** - * ObjectCodeConvertors - * - * @author Richard Bair - * @author Jasper Potts - */ -public class ObjectCodeConvertors { - static java.math.MathContext ctx = new java.math.MathContext(3); - - /** - * Given a value (x), encode it such that 0 -> 1 is to the left of a, 1 -> 2 is between a and b, and 2 -> 3 - * is to the right of b. - * - * @param w width in the case of the x axis, height in the case of the y axis. - */ - static float encode(float x, float a, float b, float w) { - float r = 0; - if (x < a) { - r = (x / a); - } else if (x > b) { - r = 2 + ((x - b) / (w - b)); - } else if (x == a && x == b) { - return 1.5f; - } else { - r = 1 + ((x - a) / (b - a)); - } - - if (Float.isNaN(r)) { - System.err.println("[Error] Encountered NaN: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); - return 0; - } else if (Float.isInfinite(r)) { - System.err.println("[Error] Encountered Infinity: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); - return 0; - } else if (r < 0) { - System.err.println("[Error] encoded value was less than 0: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); - return 0; - } else if (r > 3) { - System.err.println("[Error] encoded value was greater than 3: encode(" + x + ", " + a + ", " + b + ", " + w + ")"); - return 3; - } else { - //for prettyness sake (and since we aren't really going to miss - //any accuracy here) I'm rounding this to 3 decimal places -// return java.math.BigDecimal.valueOf(r).round(ctx).doubleValue(); - return r; - } - } - - static String convert(Paint paint) { - //TODO need to support writing out other Paints, such as gradients - if (paint instanceof Color) { - return convert((Color) paint); - } else { - System.err.println("[WARNING] Unable to encode a paint in the encode(Paint) method: " + paint); - return "null"; - } - } - - /** - * Given a Color, write out the java code required to create a new Color. - * - * @param color The color to convert - * @return String of the code for the color - */ - static String convert(Color color) { - return "new Color(" + - color.getRed() + ", " + - color.getGreen() + ", " + - color.getBlue() + ", " + - color.getAlpha() + ")"; - } - - static String convert(Insets i) { - return "new Insets(" + i.top + ", " + i.left + ", " + i.bottom + ", " + i.right + ")"; - } - - static String convert(Dimension d) { - return "new Dimension(" + d.width + ", " + d.height + ")"; - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/TemplateWriter.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/TemplateWriter.java deleted file mode 100644 index 9a76c80a7847ec6a9a9a0b0364bb61ed8a390682..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/generator/TemplateWriter.java +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.generator; - -import java.io.BufferedReader; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.PrintWriter; -import java.io.StringReader; -import java.util.Map; - -/** - * TemplateWriter - Class for writing Java Source files using a src template and variable subsitution - * - * @author Richard Bair - * @author Jasper Potts - */ -public class TemplateWriter { - - /** - * Write a Java source file by taking a template file and applying variable substitution and writing to the output - * file. - * - * @param template The template to use - * @param variables Map of the variable names and values to substitute in the template - * @param output The file to write to - * @throws IOException If there was a problem writing the Java source file - */ - static void writeSrcFile(String template, Map variables, File output) throws IOException { - TemplateReader in = new TemplateReader(variables, template); - PrintWriter out = - new PrintWriter(new FileWriter(output)); - - String line = in.readLine(); - while (line != null) { - out.println(line); - line = in.readLine(); - } - - out.close(); - } - - /** - * Read a template file into a string - * - * @param name The template file path relative to Generator class - * @return The contents of the template file as string - * @throws IOException If there was a problem reading the template file - */ - static String read(String name) throws IOException { - InputStream in = Generator.class.getResourceAsStream(name); - if (in==null) throw new IOException("Could not find template ["+name+ - "] relative to class ["+Generator.class.getName()+"]"); - byte[] data = new byte[4096]; - int length = -1; - StringBuilder buffer = new StringBuilder(); - while ((length = in.read(data)) != -1) { - buffer.append(new String(data, 0, length)); - } - return buffer.toString(); - } - - /** A BufferedReader implementation that automatically performs string replacements as needed. */ - private static final class TemplateReader extends BufferedReader { - private Map variables; - - TemplateReader(Map variables, String template) { - super(new StringReader(template)); - this.variables = variables; - } - - /** - * @return a line of text from the template but with variables substituted. Other methods will return the text - * sans substitution. Call this method. - * @throws java.io.IOException - */ - public String readLine() throws IOException { - return substituteVariables(super.readLine()); - } - - private String substituteVariables(String input) { - if (input == null) return null; - for (Map.Entry variable : variables.entrySet()) { - input = input.replace("${" + variable.getKey() + "}", variable.getValue()); - } - return input; - } - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/PainterBorder.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/PainterBorder.java deleted file mode 100644 index b3e53db3c948275889933cfdfb4497127c839cf5..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/PainterBorder.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import javax.swing.border.EmptyBorder; - -/** - * Represents a border that refers to a Painter to do it's work. This border - * doesn't actually render -- it is just used as part of the model. - * - * @author Richard Bair - */ -public class PainterBorder extends EmptyBorder { - private String painterName; - public PainterBorder(String painterName, int top, int left, int bottom, int right) { - super(top, left, bottom, right); - this.painterName = painterName; - } - - public String getPainterName() { return painterName; } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/SynthModel.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/SynthModel.java deleted file mode 100644 index 70a18c50ea505499d6cff16366370a7d317c157f..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/SynthModel.java +++ /dev/null @@ -1,530 +0,0 @@ -/* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.utils.HasResources; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JCheckBoxMenuItem; -import javax.swing.JColorChooser; -import javax.swing.JComboBox; -import javax.swing.JDesktopPane; -import javax.swing.JEditorPane; -import javax.swing.JFileChooser; -import javax.swing.JFormattedTextField; -import javax.swing.JInternalFrame; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JMenu; -import javax.swing.JMenuBar; -import javax.swing.JMenuItem; -import javax.swing.JOptionPane; -import javax.swing.JPanel; -import javax.swing.JPasswordField; -import javax.swing.JPopupMenu; -import javax.swing.JProgressBar; -import javax.swing.JRadioButton; -import javax.swing.JRadioButtonMenuItem; -import javax.swing.JRootPane; -import javax.swing.JScrollBar; -import javax.swing.JScrollPane; -import javax.swing.JSeparator; -import javax.swing.JSlider; -import javax.swing.JSpinner; -import javax.swing.JSplitPane; -import javax.swing.JTabbedPane; -import javax.swing.JTable; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.JTextPane; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.JToolTip; -import javax.swing.JTree; -import javax.swing.JViewport; -import javax.swing.UIDefaults; -import javax.swing.plaf.basic.BasicLookAndFeel; -import javax.swing.plaf.metal.MetalLookAndFeel; -import static javax.swing.plaf.synth.SynthConstants.*; -import javax.swing.table.JTableHeader; -import java.awt.Insets; -import java.io.File; -import java.util.ArrayList; -import java.util.List; - -/** - * Models a Synth look and feel. Contains all of the colors, fonts, painters, states, etc that compose a synth look and - * feel. - *

- * To model Synth properly, I need to both Model the way Synth works (with styles, and so forth) and the way a look and - * feel works (UIDefaults table, etc) since both of these are supported ways of doing things in Synth. - *

- * One important (but non-visual) thing that needs to be configurable is the support for InputMaps per component. In - * Synth, an input map can be associated with the main Synth element, meaning it applies to everything. Or it can be - * associated with a single style. An Inputmap can have an id, and it can contain multiple key/action pairs (where - * actions are denoted by name). - *

- * It looks like Regions can have InputMaps? Sounds fishy to me. I think only Components really have input maps. - *

- * I would like some way of denoting special keys between mac and other platforms. For example, cut, copy, paste etc - * should be different. In general, the ctrl key and apple (meta) key are reversed from what is typically on windows. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class SynthModel extends AbstractBean implements HasUIDefaults, HasUIStyle, HasResources { - //I'm going to want: - //entries related to the Control color, and other colors of the Basic LAF - //entries related to fonts (standard fonts) used in the Basic LAF - //entries related to standard insets, borders, dimensions, icons - //entries related to component specific entries in the LAF - private List colors; - private List fonts; - private List insets; - private List borders; - private List dimensions; - private List icons; - private List components; - /** - * This is a local UIDefaults that contains all the UIDefaults in this synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - */ - private transient UIDefaults modelDefaults = new UIDefaults(); - private transient UIStyle globalStyle = new UIStyle(); - - private transient File resourcesDir; - private transient File imagesDir; - private transient File templatesDir; - - /** Default constructor used by JIBX to create new empty SynthModel */ - protected SynthModel() { - this(false); - } - - public SynthModel(boolean populateWithDefaults) { - // create observable lists that fire changes on as property changes - colors = new ArrayList(); - fonts = new ArrayList(); - insets = new ArrayList(); - borders = new ArrayList(); - dimensions = new ArrayList(); - icons = new ArrayList(); - components = new ArrayList(); - - if (populateWithDefaults) { - //get the ui defaults from the SynthLookAndFeel. Using the UIDefaults table, - //pre initialize everything. -// SynthLookAndFeel synth = new SynthLookAndFeel(); - BasicLookAndFeel synth = new MetalLookAndFeel(); - UIDefaults defaults = synth.getDefaults(); - - //pre-init the palettes - colors.add(new UIColor("desktop", defaults.getColor("desktop"), modelDefaults)); - colors.add(new UIColor("activeCaption", defaults.getColor("activeCaption"), modelDefaults)); - colors.add(new UIColor("activeCaptionText", defaults.getColor("activeCaptionText"), modelDefaults)); - colors.add(new UIColor("activeCaptionBorder", defaults.getColor("activeCaptionBorder"), modelDefaults)); - colors.add(new UIColor("inactiveCaption", defaults.getColor("inactiveCaption"), modelDefaults)); - colors.add(new UIColor("inactiveCaptionText", defaults.getColor("inactiveCaptionText"), modelDefaults)); - colors.add(new UIColor("inactiveCaptionBorder", defaults.getColor("inactiveCaptionBorder"), modelDefaults)); - colors.add(new UIColor("window", defaults.getColor("window"), modelDefaults)); - colors.add(new UIColor("windowBorder", defaults.getColor("windowBorder"), modelDefaults)); - colors.add(new UIColor("windowText", defaults.getColor("windowText"), modelDefaults)); - colors.add(new UIColor("menu", defaults.getColor("menu"), modelDefaults)); - colors.add(new UIColor("menuText", defaults.getColor("menuText"), modelDefaults)); - colors.add(new UIColor("text", defaults.getColor("text"), modelDefaults)); - colors.add(new UIColor("textText", defaults.getColor("textText"), modelDefaults)); - colors.add(new UIColor("textHighlight", defaults.getColor("textHighlight"), modelDefaults)); - colors.add(new UIColor("textHighlightText", defaults.getColor("textHighlightText"), modelDefaults)); - colors.add(new UIColor("textInactiveText", defaults.getColor("textInactiveText"), modelDefaults)); - colors.add(new UIColor("control", defaults.getColor("control"), modelDefaults)); - colors.add(new UIColor("controlText", defaults.getColor("controlText"), modelDefaults)); - colors.add(new UIColor("controlHighlight", defaults.getColor("controlHighlight"), modelDefaults)); - colors.add(new UIColor("controlLHighlight", defaults.getColor("controlLHighlight"), modelDefaults)); - colors.add(new UIColor("controlShadow", defaults.getColor("controlShadow"), modelDefaults)); - colors.add(new UIColor("controlDkShadow", defaults.getColor("controlDkShadow"), modelDefaults)); - colors.add(new UIColor("scrollbar", defaults.getColor("scrollbar"), modelDefaults)); - colors.add(new UIColor("info", defaults.getColor("info"), modelDefaults)); - colors.add(new UIColor("infoText", defaults.getColor("infoText"), modelDefaults)); - - fonts.add(new UIFont("dialogPlain", defaults.getFont("Button.font"), modelDefaults)); - fonts.add(new UIFont("serifPlain", defaults.getFont("TextPane.font"), modelDefaults)); - fonts.add(new UIFont("sansSerifPlain", defaults.getFont("ToolTip.font"), modelDefaults)); - fonts.add(new UIFont("monospacedPlain", defaults.getFont("TextArea.font"), modelDefaults)); - fonts.add(new UIFont("dialogBold", defaults.getFont("InternalFrame.titleFont"), modelDefaults)); - - insets.add(new UIInsets("zeroInsets", new Insets(0, 0, 0, 0))); - insets.add(new UIInsets("twoInsets", new Insets(2, 2, 2, 2))); - insets.add(new UIInsets("threeInsets", new Insets(3, 3, 3, 3))); - - borders.add(new UIBorder("marginBorder", defaults.getBorder("MenuItem.border"))); - borders.add(new UIBorder("etchedBorder", defaults.getBorder("TitledBorder.border"))); - borders.add(new UIBorder("loweredBevelBorder", defaults.getBorder("Table.scrollPaneBorder"))); - borders.add(new UIBorder("blackLineBorder", defaults.getBorder("ToolTip.border"))); - - //TODO have to deal with the special arrow button region - - //pre-init the list of UI components - UIComponent button = new UIComponent("Button", JButton.class.getName(), "ButtonUI"); - addStates(this, button, DEFAULT, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(button); - - UIComponent toggleButton = - new UIComponent("ToggleButton", JToggleButton.class.getName(), "ToggleButtonUI"); - addStates(this, toggleButton, DEFAULT, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED, SELECTED, - SELECTED | PRESSED, SELECTED | MOUSE_OVER, DISABLED | SELECTED); - components.add(toggleButton); - - UIComponent radioButton = - new UIComponent("RadioButton", JRadioButton.class.getName(), "RadioButtonUI"); - addStates(this, radioButton, DEFAULT, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED, SELECTED, - SELECTED | PRESSED, SELECTED | MOUSE_OVER, DISABLED | SELECTED); - components.add(radioButton); - - UIComponent checkBox = - new UIComponent("CheckBox", JCheckBox.class.getName(), "CheckBoxUI"); - addStates(this, checkBox, DEFAULT, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED, SELECTED, - SELECTED | PRESSED, SELECTED | MOUSE_OVER, DISABLED | SELECTED); - components.add(checkBox); - - UIComponent colorChooser = - new UIComponent("ColorChooser", JColorChooser.class.getName(), "ColorChooserUI"); - addStates(this, colorChooser, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(colorChooser); - - UIComponent comboBox = - new UIComponent("ComboBox", JComboBox.class.getName(), "ComboBoxUI"); - addStates(this, comboBox, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(comboBox); - - UIComponent fileChooser = - new UIComponent("FileChooser", JFileChooser.class.getName(), "FileChooserUI"); - addStates(this, fileChooser, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(fileChooser); - - //not represented in Synth -// UIComponent fileView = new UIComponent ("FileView", -// list(DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - - UIComponent internalFrame = - new UIComponent("InternalFrame", JInternalFrame.class.getName(), "InternalFrameUI"); - addStates(this, internalFrame, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //has an internal frame title pane region - components.add(internalFrame); - - //TODO DesktopIcon ??? - - UIComponent desktop = - new UIComponent("Desktop", JDesktopPane.class.getName(), "DesktopPaneUI"); - addStates(this, desktop, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(desktop); - - UIComponent label = new UIComponent("Label", JLabel.class.getName(), "LabelUI"); - addStates(this, label, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(label); - - UIComponent list = new UIComponent("List", JList.class.getName(), "ListUI"); - addStates(this, list, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(list); - - UIComponent menuBar = new UIComponent("MenuBar", JMenuBar.class.getName(), "MenuBarUI"); - addStates(this, menuBar, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(menuBar); - - UIComponent menuItem = - new UIComponent("MenuItem", JMenuItem.class.getName(), "MenuItemUI"); - addStates(this, menuItem, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //has a menuItemAccelerator region - components.add(menuItem); - - UIComponent radioButtonMenuItem = - new UIComponent("RadioButtonMenuItem", JRadioButtonMenuItem.class.getName(), - "RadioButtonMenuItemUI"); - addStates(this, radioButtonMenuItem, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(radioButtonMenuItem); - - UIComponent checkBoxMenuItem = - new UIComponent("CheckBoxMenuItem", JCheckBoxMenuItem.class.getName(), - "CheckBoxMenuItemUI"); - addStates(this, checkBoxMenuItem, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(checkBoxMenuItem); - - UIComponent menu = new UIComponent("Menu", JMenu.class.getName(), "MenuUI"); - addStates(this, menu, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(menu); - - UIComponent popupMenu = - new UIComponent("PopupMenu", JPopupMenu.class.getName(), "PopupMenuUI"); - addStates(this, popupMenu, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //has a popupMenuSeparator region - components.add(popupMenu); - - UIComponent optionPane = - new UIComponent("OptionPane", JOptionPane.class.getName(), "OptionPaneUI"); - addStates(this, optionPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(optionPane); - - UIComponent panel = new UIComponent("Panel", JPanel.class.getName(), "PanelUI"); - addStates(this, panel, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(panel); - - UIComponent progressBar = - new UIComponent("ProgressBar", JProgressBar.class.getName(), "ProgressBarUI"); - addStates(this, progressBar, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(progressBar); - - UIComponent separator = - new UIComponent("Separator", JSeparator.class.getName(), "SeparatorUI"); - addStates(this, separator, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(separator); - - UIRegion scrollBarThumb = new UIRegion("ScrollBar.Thumb"); - addStates(this, scrollBarThumb, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - UIRegion scrollBarTrack = new UIRegion("ScrollBar.Track"); - addStates(this, scrollBarTrack, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - UIComponent scrollBar = - new UIComponent("ScrollBar", JScrollBar.class.getName(), "ScrollBarUI", scrollBarThumb, - scrollBarTrack); - addStates(this, scrollBar, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(scrollBar); - - UIComponent scrollPane = - new UIComponent("ScrollPane", JScrollPane.class.getName(), "ScrollPaneUI"); - addStates(this, scrollPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(scrollPane); - - UIComponent viewport = - new UIComponent("Viewport", JViewport.class.getName(), "ViewportUI"); - addStates(this, viewport, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(viewport); - - UIComponent slider = new UIComponent("Slider", JSlider.class.getName(), "SliderUI"); - addStates(this, slider, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //has sliderThumb and sliderTrack sub regions - components.add(slider); - - UIComponent spinner = new UIComponent("Spinner", JSpinner.class.getName(), "SpinnerUI"); - addStates(this, spinner, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(spinner); - - UIComponent splitPane = - new UIComponent("SplitPane", JSplitPane.class.getName(), "SplitPaneUI"); - addStates(this, splitPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //has splitPaneDivider sub region - components.add(splitPane); - - UIComponent tabbedPane = - new UIComponent("TabbedPane", JTabbedPane.class.getName(), "TabbedPaneUI"); - addStates(this, tabbedPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //has tabbedPaneContent and tabbedPaneTab and TabbedPaneTabArea sub regions - components.add(tabbedPane); - - UIComponent table = new UIComponent("Table", JTable.class.getName(), "TableUI"); - addStates(this, table, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(table); - - UIComponent tableHeader = - new UIComponent("TableHeader", JTableHeader.class.getName(), "TableHeaderUI"); - addStates(this, tableHeader, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(tableHeader); - - UIComponent textField = - new UIComponent("TextField", JTextField.class.getName(), "TextFieldUI"); - addStates(this, textField, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(textField); - - UIComponent formattedTextField = - new UIComponent("FormattedTextField", JFormattedTextField.class.getName(), - "FormattedTextFieldUI"); - addStates(this, formattedTextField, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(formattedTextField); - - UIComponent passwordField = - new UIComponent("PasswordField", JPasswordField.class.getName(), "PasswordFieldUI"); - addStates(this, passwordField, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(passwordField); - - UIComponent textArea = - new UIComponent("TextArea", JTextArea.class.getName(), "TextAreaUI"); - addStates(this, textArea, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(textArea); - - UIComponent textPane = - new UIComponent("TextPane", JTextPane.class.getName(), "TextPaneUI"); - addStates(this, textPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(textPane); - - UIComponent editorPane = - new UIComponent("EditorPane", JEditorPane.class.getName(), "EditorPaneUI"); - addStates(this, editorPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(editorPane); - - /* - * The only thing not represented in Synth as a region. I suppose we'll have - * to make it a CustomUIComponent - */ -// UIComponent titledBorder = new UIComponent ("TitledBorder", -// list(DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - - UIComponent toolBar = new UIComponent("ToolBar", JToolBar.class.getName(), "ToolBarUI"); - addStates(this, toolBar, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //toolBarContent, toolBarDragWindow, toolBarSeparator sub regions - components.add(toolBar); - - UIComponent toolTip = new UIComponent("ToolTip", JToolTip.class.getName(), "ToolTipUI"); - addStates(this, toolTip, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(toolTip); - - //tooltip manager - - UIComponent tree = new UIComponent("Tree", JTree.class.getName(), "TreeUI"); - addStates(this, tree, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - //treeCell sub region - components.add(tree); - - UIComponent rootPane = - new UIComponent("RootPane", JRootPane.class.getName(), "RootPaneUI"); - addStates(this, rootPane, DISABLED, ENABLED, FOCUSED, MOUSE_OVER, PRESSED); - components.add(rootPane); - } - } - - public List getColorPalette() { - return colors; - } - - public List getFontPalette() { - return fonts; - } - - public List getInsetPalette() { - return insets; - } - - public List getBorderPalette() { - return borders; - } - - public List getDimensionPalette() { - return dimensions; - } - - public List getIconPalette() { - return icons; - } - - public List getComponents() { - return components; - } - - /** - * Get the local UIDefaults that contains all the UIDefaults in this synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - * - * @return The UIDefaults for the synth model - */ - public UIDefaults getUiDefaults() { - return modelDefaults; - } - - public UIStyle getStyle() { - return globalStyle; - } - - // by default there are no painters assigned to the various states - private static void addStates(SynthModel model, UIRegion parentRegion, int... states) { - for (int state : states) { - List stateList = new ArrayList(); - if ((state & ENABLED) != 0) { - stateList.add(UIStateType.ENABLED_KEY); - } - if ((state & MOUSE_OVER) != 0) { - stateList.add(UIStateType.MOUSE_OVER_KEY); - } - if ((state & PRESSED) != 0) { - stateList.add(UIStateType.PRESSED_KEY); - } - if ((state & DISABLED) != 0) { - stateList.add(UIStateType.DISABLED_KEY); - } - if ((state & FOCUSED) != 0) { - stateList.add(UIStateType.FOCUSED_KEY); - } - if ((state & SELECTED) != 0) { - stateList.add(UIStateType.SELECTED_KEY); - } - if ((state & DEFAULT) != 0) { - stateList.add(UIStateType.DEFAULT_KEY); - } - parentRegion.addBackgroundState(new UIState(model, parentRegion, stateList.toArray(new String[stateList.size()]))); - } - } - - public File getResourcesDir() { - return resourcesDir; - } - - public void setResourcesDir(File resourcesDir) { - System.out.println("SynthModel.setResourcesDir(" + resourcesDir + ")"); - File old = getResourcesDir(); - this.resourcesDir = resourcesDir; - firePropertyChange("resourcesDir", old, getResourcesDir()); - } - - public File getImagesDir() { - return imagesDir; - } - - public void setImagesDir(File imagesDir) { - System.out.println("SynthModel.setImagesDir(" + imagesDir + ")"); - File old = getImagesDir(); - this.imagesDir = imagesDir; - firePropertyChange("imagesDir", old, getImagesDir()); - } - - public File getTemplatesDir() { - return templatesDir; - } - - public void setTemplatesDir(File templatesDir) { - System.out.println("SynthModel.setTemplatesDir(" + templatesDir + ")"); - File old = getTemplatesDir(); - this.templatesDir = templatesDir; - firePropertyChange("templatesDir", old, getTemplatesDir()); - } - - // ================================================================================================================= - // JIBX Methods - - public void preSet(IUnmarshallingContext context) { - File resourcesDir = (File) context.getUserContext(); - this.resourcesDir = resourcesDir; - this.imagesDir = new File(resourcesDir, "images"); - this.templatesDir = new File(resourcesDir, "templates"); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/SynthModel.jibx.xml b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/SynthModel.jibx.xml deleted file mode 100644 index 981772abc2b0d573210d446763e712a78bc52948..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/SynthModel.jibx.xml +++ /dev/null @@ -1,181 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIBorder.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIBorder.java deleted file mode 100644 index 46c35ed1b082d3cab4386f168f45b7e5ac8063eb..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIBorder.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import javax.swing.border.Border; - -/** - * UIBorder - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIBorder extends UIDefault { - - public UIBorder() { - } - - public UIBorder(String id, Border b) { - super(id, b); - } - - public Border getBorder() { - return super.getValue(); - } - - public void setBorder(Border b) { - Border old = getBorder(); - super.setValue(b); - firePropertyChange("border", old, b); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIColor.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIColor.java deleted file mode 100644 index 572d346132515b2b60a3a91a524b6ea88ce49f85..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIColor.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.swingx.designer.paint.Matte; - -import javax.swing.UIDefaults; -import java.awt.Color; - -/** - * UIColor - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIColor extends UIPaint { - - public UIColor() { - } - - public UIColor(String id, Matte value) { - super(id, value); - } - - public UIColor(String id, Color color, UIDefaults modelDefaults) { - this(id, new Matte(color, modelDefaults)); - } - - public Matte getPaint() { - return (Matte) super.getPaint(); - } - - public void setPaint(Matte c) { - super.setPaint(c); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIComponent.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIComponent.java deleted file mode 100644 index 028124ab36371ec3295b39cf877e07b406aa1585..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIComponent.java +++ /dev/null @@ -1,138 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.swingx.designer.utils.HasUIDefaults; - -import java.util.List; -import java.util.ArrayList; - -/** - * UIComponent - model node that represents the designs for a single swing component - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIComponent extends UIRegion implements HasUIDefaults { - - /** The classname of the swing component that this UIComponent represents */ - private String type; - /** The name of the component if its a named component or null if its a generic component */ - private String componentName = null; - /** If this components is opaque which means that when it is painted all of its bounds are filled */ - private boolean opaque = false; - /** - * A list of state types that are available to this region and sub regions of this component but not subcomponents - * of this component. If this list is empty then the standard synth set of state types are assumed. - */ - private List stateTypes; - - // ================================================================================================================= - // Contructors - - /** no-args contructor for JIBX */ - protected UIComponent() { - super(); - // create new observable list for state types so we get events for when the model changes - stateTypes = new ArrayList(); - } - - public UIComponent(String name, String type, String ui, UIRegion... subRegions) { - super(name, ui, subRegions); - this.type = type; - for (UIRegion r : subRegions) { - r.setRegion(this); - } - // create new observable list for state types so we get events for when the model changes - stateTypes = new ArrayList(); - } - - // ================================================================================================================= - // Bean Methods - - public String getComponentName() { - return componentName; - } - - public void setComponentName(String componentName) { - String old = getComponentName(); - this.componentName = componentName; - firePropertyChange("componentName", old, getComponentName()); - } - - public boolean isOpaque() { - return opaque; - } - - public void setOpaque(boolean opaque) { - boolean old = isOpaque(); - this.opaque = opaque; - firePropertyChange("opaque", old, isOpaque()); - } - - public String getType() { - return type; - } - - public void setType(String type) { - String old = getType(); - this.type = type; - firePropertyChange("type", old, getType()); - } - - /** - * Get the list of state types that are available to this region and sub regions of this component but not - * subcomponents of this component. If this list is empty then the standard synth set of state types are assumed. - * - * @return List of available state types - */ - public List getStateTypes() { - return stateTypes; - } - - @Override public String getKey() { - if (key == null || "".equals(key)) { - if (componentName == null || "".equals(componentName)) { - return getName(); - } else { - return "\"" + componentName + "\""; - } - } else { - return key; - } - } - - @Override public String getTitle() { - if (title == null || "".equals(title)) { - if (componentName == null || "".equals(componentName)) { - return getName(); - } else { - return componentName; - } - } else { - return title; - } - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIDefault.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIDefault.java deleted file mode 100644 index 2f0bf09a8d6584407782641a936ffa6b856cdc93..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIDefault.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -import javax.swing.UIDefaults; - -/** - * Represents an entry in the UI defaults table. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIDefault extends AbstractBean implements HasUIDefaults { - private String name; - private T value; - /** - * This is a local UIDefaults that contains all the UIDefaults in the synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - */ - private transient UIDefaults modelDefaults = null; - - public UIDefault() { - } - - public UIDefault(String name, T value) { - this.name = name; - this.value = value; - } - - public UIDefault(String name, T value, UIDefaults modelDefaults) { - this.name = name; - this.value = value; - this.modelDefaults = modelDefaults; - } - - // ================================================================================================================= - // JIBX Methods - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - private void postSet(IUnmarshallingContext context) { - // walk up till we get synth model - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof HasUIDefaults) { - modelDefaults = ((HasUIDefaults) context.getStackObject(i)).getUiDefaults(); - if (modelDefaults != null) break; - } - } - } - - // ================================================================================================================= - // Bean Methods - - /** - * Get the local UIDefaults that contains all the UIDefaults in the synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - * - * @return The UIDefaults for the synth model - */ - public UIDefaults getUiDefaults() { - return modelDefaults; - } - - public void setValue(T t) { - T old = this.value; - this.value = t; - firePropertyChange("value", old, getValue()); - } - - public T getValue() { - return value; - } - - public final String getName() { - return name; - } - - public void setName(String name) { - String old = this.name; - firePropertyChange("name", old, name); - this.name = name; - // update model defaults - if (old != null) modelDefaults.remove(old); - modelDefaults.put(getName(), getValue()); - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIFont.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIFont.java deleted file mode 100644 index efb6fdba35c5212f2d7359c45ad9c516b4b1a834..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIFont.java +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import java.awt.Font; -import org.jdesktop.swingx.designer.font.Typeface; -import java.util.Arrays; -import java.util.List; -import java.util.ArrayList; -import javax.swing.UIDefaults; - -/** - * Represents a single font entry in the UIDefaults table. Each UIFont takes a - * list of Typefaces. These typefaces are listed by order of preference. Thus, - * when putting a font into UIDefaults, the code can check whether each font - * exists, and when it finds the first font that does, insert it. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIFont extends UIDefault> implements Cloneable { - - private void updateUIDefaults() { - if (getUiDefaults() != null) { - for (Typeface t : getFonts()) { - if (t.isFontSupported()) { - getUiDefaults().put(getName(), t.getFont()); - return; - } - } - } - - //TODO must not have found any. Default to the Default platform font - getUiDefaults().put(getName(), new Font("Arial", Font.PLAIN, 12)); - } - - public UIFont() { - setValue(new ArrayList()); - } - - public UIFont(String id, List values, UIDefaults defaults) { - super(id, values, defaults); - updateUIDefaults(); - } - - public UIFont(String id, Font font, UIDefaults modelDefaults) { - this(id, Arrays.asList(new Typeface(font, modelDefaults)), modelDefaults); - } - - public List getFonts() { - return super.getValue(); - } - - private void setFonts(List values) { - super.setValue(values); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIIcon.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIIcon.java deleted file mode 100644 index d1a25833de121f19701c7d9a7df943a3de39d177..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIIcon.java +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import javax.swing.Icon; - -/** - * UIIcon - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIIcon extends UIDefault { - - public UIIcon() { - } - - public Icon getIcon() { - return super.getValue(); - } - - public void setIcon(Icon i) { - Icon old = getIcon(); - super.setValue(i); - firePropertyChange("icon", old, i); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIIconRegion.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIIconRegion.java deleted file mode 100644 index 74590ee9789bdbc6d8d464614c13a6b0ac573ffc..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIIconRegion.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -/** - * A UIRegion subclass which is used for generating icons. For example, JRadioButton and JCheckBox represent themselves - * mainly via their icons. However, from the designers perspective, the main design isn't an "icon", but just a region - * on the button. - *

- * That type of region is represented by a UIIconRegion. UIIconRegion contains a string which references the UIDefault - * value associated with this icon. For example, RadioButton.icon. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIIconRegion extends UIRegion { - /** The UiDefaults key which this icon should be stored for basic LaF to find it. This is absolute */ - private String basicKey = null; - - public UIIconRegion() { - super(); - } - - public String getBasicKey() { - return basicKey; - } - - public void setBasicKey(String basicKey) { - String old = getBasicKey(); - this.basicKey = basicKey; - firePropertyChange("basicKey",old,getBasicKey()); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIInsets.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIInsets.java deleted file mode 100644 index 3e320de6682c7bbd0c77dab7f59ee67cca430510..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIInsets.java +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import java.awt.Insets; - -/** - * UIInsets - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIInsets extends UIDefault { - - public UIInsets() { - } - - public UIInsets(String id, Insets value) { - super(id, value); - } - - public Insets getInsets() { - return super.getValue(); - } - - public void setInsets(Insets i) { - Insets old = getInsets(); - super.setValue(i); - firePropertyChange("insets", old, i); - // update model defaults - getUiDefaults().put(getName(), i); - } - - - public String toString() { - return "UiInset(" + getName() + ")" + - ((getInsets() == null) ? " NONE" : "(" + getInsets().top + "," + getInsets().left + "," + - getInsets().bottom + "," + getInsets().right + ")"); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIPaint.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIPaint.java deleted file mode 100644 index 931b3f41feea7262dbed1a0d2f73366b769e80a8..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIPaint.java +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.swingx.designer.paint.Matte; -import org.jdesktop.swingx.designer.paint.PaintModel; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; - -/** - * UIPaint - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIPaint extends UIDefault { - - /** Listener to keep model UiDefaults up to date for this UiPaint */ - private PropertyChangeListener matteListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - PaintModel paintModel = getValue(); - if (paintModel instanceof Matte) { - getUiDefaults().put(getName(), ((Matte) paintModel).getColor()); - } - // propogate the paint change up as PaintModel is a mutable object - if (evt.getPropertyName().equals("paint")) { - firePropertyChange("paint", null, getPaint()); - firePropertyChange("value", null, getPaint()); - } - } - }; - - public UIPaint() {} - - public UIPaint(String id, PaintModel value) { - super(id, value, (value instanceof Matte) ? ((Matte) value).getUiDefaults() : null); - // update model defaults - if (value instanceof Matte) { - Matte matte = (Matte) value; - if (getUiDefaults() != null) getUiDefaults().put(getName(), matte.getColor()); - matte.addPropertyChangeListener(matteListener); - } - } - - public PaintModel getPaint() { - return super.getValue(); - } - - public void setPaint(PaintModel c) { - PaintModel old = getPaint(); - if (old instanceof Matte) old.removePropertyChangeListener(matteListener); - super.setValue(c); - firePropertyChange("paint", old, c); - // update model defaults - if (c instanceof Matte) { - Matte matte = (Matte) c; - getUiDefaults().put(getName(), matte.getColor()); - matte.addPropertyChangeListener(matteListener); - } - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIProperty.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIProperty.java deleted file mode 100644 index 1a57a58f816adf9211d4a541ed89f860904adc9c..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIProperty.java +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; - -/** - * UIProperty - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIProperty extends AbstractBean { - public static enum PropertyType { - BOOLEAN, INT, FLOAT, DOUBLE, STRING, FONT, COLOR, INSETS, DIMENSION, BORDER - } - - private String name; - private PropertyType type; - private Object value; - - protected UIProperty() { - } - - public UIProperty(String name, PropertyType type, Object value) { - this.name = name; - this.type = type; - this.value = value; - } - - // ================================================================================================================= - // Bean Methods - - public String getName() { - return name; - } - - public void setName(String name) { - String old = getName(); - this.name = name; - firePropertyChange("name", old, getName()); - } - - public PropertyType getType() { - return type; - } - - public void setType(PropertyType type) { - PropertyType old = getType(); - this.type = type; - firePropertyChange("type", old, getType()); - } - - public Object getValue() { - return value; - } - - public void setValue(Object value) { - Object old = getValue(); - this.value = value; - firePropertyChange("value", old, getValue()); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIRegion.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIRegion.java deleted file mode 100644 index 1ee4f35653a3af119323ef2dc65f54020cfeb6de..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIRegion.java +++ /dev/null @@ -1,253 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -import javax.swing.UIDefaults; -import java.awt.Insets; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.List; -import java.util.ArrayList; - -/** - * Represents a "Region" in synth, which also includes entire components. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIRegion extends AbstractBean implements HasUIDefaults, HasUIStyle { - private String name;//the code-wise name of the region - protected String key; //the UIdefaults key for this region - protected String title; //the user friendly name/title of this region - /** List of background states */ - private List backgroundStates; - /** List of foreground states */ - private List foregroundStates; - /** List of border states */ - private List borderStates; - private UIStyle style = new UIStyle(); - protected Insets contentMargins = new Insets(0, 0, 0, 0); - /** Sub regions, if any */ - private List subRegions; - - //together with name, these two fields allow me to reconstruct, in - //code, a synth Region, including a custom Region, if you make one. - private String ui; - private boolean subregion; - /** - * This is a local UIDefaults that contains all the UIDefaults in the synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - */ - private transient UIDefaults modelDefaults = null; - - private UIRegion region; //the region that this region belongs to - - // ================================================================================================================= - // Constructors - - /** no-args contructor for JIBX */ - protected UIRegion() { - subRegions = new ArrayList(); - backgroundStates = new ArrayList(); - foregroundStates = new ArrayList(); - borderStates = new ArrayList(); - style.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("style." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }); - } - - public UIRegion(String name, UIRegion... subRegions) { - this(name, null, true, subRegions); - } - - public UIRegion(String name, String ui, UIRegion... subRegions) { - this(name, ui, false, subRegions); - } - - public UIRegion(String name, String ui, boolean subregion, UIRegion... subRegions) { - this(); - this.name = name; - this.ui = ui; - this.subregion = subregion; - if (subRegions != null) { - for (UIRegion r : subRegions) { - if (r != null) { - this.subRegions.add(r); - r.getStyle().setParentStyle(getStyle()); - } - } - } - } - - // ================================================================================================================= - // JIBX Methods - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - private void preSet(IUnmarshallingContext context) { - // walk up till we get synth model - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof HasUIDefaults) { - modelDefaults = ((HasUIDefaults) context.getStackObject(i)).getUiDefaults(); - if (modelDefaults != null) break; - } - } - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof UIRegion && context.getStackObject(i) != this) { - region = (UIRegion) context.getStackObject(i); - break; - } - } - } - - // ================================================================================================================= - // Bean Methods - - public Insets getContentMargins() { - return contentMargins; - } - - public void setContentMargins(Insets contentMargins) { - Insets old = getContentMargins(); - this.contentMargins = contentMargins; - firePropertyChange("contentMargins", old, getContentMargins()); - } - - void setRegion(UIRegion r) { - this.region = r; - } - - public UIRegion getRegion() { - return region; - } - - /** - * Get the local UIDefaults that contains all the UIDefaults in the synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - * - * @return The UIDefaults for the synth model - */ - public UIDefaults getUiDefaults() { - return modelDefaults; - } - - public String getName() { - return name; - } - - public final UIRegion[] getSubRegions() { - return subRegions.toArray(new UIRegion[0]); - } - - public final UIState[] getBackgroundStates() { - return backgroundStates.toArray(new UIState[0]); - } - - public final UIState[] getForegroundStates() { - return foregroundStates.toArray(new UIState[0]); - } - - public final UIState[] getBorderStates() { - return borderStates.toArray(new UIState[0]); - } - - public UIStyle getStyle() { - return style; - } - - public final boolean isSubRegion() { - return subregion; - } - - public final String getUi() { - return ui; - } - - public void addBackgroundState(UIState state) { - // check if we already have that state - for (UIState uiState : backgroundStates) { - if (uiState.getName().equals(state.getName())) return; - } - backgroundStates.add(state); - state.setRegion(this); - firePropertyChange("backgroundStates", null, backgroundStates); - } - - public void removeBackgroundState(UIState state) { - if (backgroundStates.remove(state)) { - firePropertyChange("backgroundStates", null, backgroundStates); - } - } - - public void addForegroundState(UIState state) { - // check if we already have that state - for (UIState uiState : foregroundStates) { - if (uiState.getName().equals(state.getName())) return; - } - foregroundStates.add(state); - state.setRegion(this); - firePropertyChange("foregroundStates", null, foregroundStates); - } - - public void removeForegroundState(UIState state) { - if (foregroundStates.remove(state)) { - firePropertyChange("foregroundStates", null, foregroundStates); - } - } - - public void addBorderState(UIState state) { - // check if we already have that state - for (UIState uiState : borderStates) { - if (uiState.getName().equals(state.getName())) return; - } - borderStates.add(state); - state.setRegion(this); - firePropertyChange("borderStates", null, borderStates); - } - - public void removeBorderState(UIState state) { - if (borderStates.remove(state)) { - firePropertyChange("borderStates", null, borderStates); - } - } - - - public String getKey() { - return key == null || "".equals(key) ? name : key; - } - - public String getTitle() { - return title == null || "".equals(title) ? name : title; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIState.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIState.java deleted file mode 100644 index 4d747a4e2d4a0c090d53e5b6a57cd009205a8662..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIState.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.Canvas; -import org.jdesktop.swingx.designer.utils.HasPath; -import org.jdesktop.swingx.designer.utils.HasUIDefaults; -import org.jibx.runtime.IUnmarshallingContext; - -import javax.swing.UIDefaults; -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.Iterator; -import java.util.List; - -/** - * Represents a State in the Synth LAF. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIState extends AbstractBean implements HasUIStyle, HasPath { - - private List stateKeys; - private boolean inverted; //indicates whether to invert the meaning of the 9-square stretching insets - /** A cached string representing the list of stateKeys deliminated with "+" */ - private String cachedName = null; - private Canvas canvas; - private UIStyle style; - /** the region that this state belongs to */ - private UIRegion region; - /** - * This is a local UIDefaults that contains all the UIDefaults in the synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - */ - private transient UIDefaults modelDefaults = null; - - // ================================================================================================================= - // Contructors - - public UIState() { - // Create state keys as event list so model changes are propogated - stateKeys = new ArrayList(); - } - - public UIState(SynthModel model, UIRegion parentRegion, String... stateTypeKeys) { - // Create state keys as event list so model changes are propogated - stateKeys = new ArrayList(); - this.stateKeys.addAll(Arrays.asList(stateTypeKeys)); - // - modelDefaults = model.getUiDefaults(); - region = parentRegion; - // create new canvas - canvas = new Canvas(100, 30); - canvas.setUiDefaults(modelDefaults); - String canvasPath = getPath(); - canvas.setResourcesDir(new File(model.getResourcesDir(), canvasPath)); - canvas.setTemplatesDir(new File(model.getTemplatesDir(), canvasPath)); - canvas.setImagesDir(new File(model.getImagesDir(), canvasPath)); - canvas.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("canvas." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }); - // create new style - style = new UIStyle(); - style.setParentStyle(region.getStyle()); - style.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("style." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }); - } - - // ================================================================================================================= - // JIBX Methods - - /** - * JIBX needs this - * - * @param stateKeys The new list of states - */ - private void setStateKeys(List stateKeys) { - if (stateKeys != this.stateKeys) { - this.stateKeys.clear(); - this.stateKeys.addAll(stateKeys); - } - } - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - private void preSet(IUnmarshallingContext context) { - // walk up till we get synth model - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof HasUIDefaults) { - modelDefaults = ((HasUIDefaults) context.getStackObject(i)).getUiDefaults(); - if (modelDefaults != null) break; - } - } - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof UIRegion) { - region = (UIRegion) context.getStackObject(i); - break; - } - } - } - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - private void postSet(IUnmarshallingContext context) { - // add listeners to pass canvas and style events up tree - canvas.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("canvas." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }); - style.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("style." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }); - } - - // ================================================================================================================= - // Bean Methods - - /** - * Get path to this UI State of the form /RegionA/RegionB/StateName - * - * @return Path to this state - */ - public String getPath() { - StringBuilder buf = new StringBuilder(getName()); - UIRegion region = getRegion(); - // check if we are foreground background or border - boolean found = false; - for (UIState state : region.getBackgroundStates()) { - if (state == this) { - buf.insert(0, "Background/"); - found = true; - break; - } - } - if (!found) { - for (UIState state : region.getForegroundStates()) { - if (state == this) { - buf.insert(0, "Foreground/"); - found = true; - break; - } - } - } - if (!found) { - for (UIState state : region.getBorderStates()) { - if (state == this) { - buf.insert(0, "Border/"); - found = true; - break; - } - } - } - // add parent regions - while (region != null) { - buf.insert(0, '/'); - if (region instanceof UIComponent && ((UIComponent) region).getComponentName() != null) { - buf.insert(0, ((UIComponent) region).getComponentName()); - } else { - buf.insert(0, region.getName()); - } - region = region.getRegion(); - } - return buf.toString(); - } - - void setRegion(UIRegion r) { - this.region = r; - this.style.setParentStyle(r.getStyle()); - } - - public UIRegion getRegion() { - return region; - } - - /** - * Get the local UIDefaults that contains all the UIDefaults in the synth model. It is kept uptodate by the - * indervidual UIDefaults nodes - * - * @return The UIDefaults for the synth model - */ - public UIDefaults getUIDefaults() { - return modelDefaults; - } - - - /** - * Get the list of state type keys for this state. This state is applied when the current component state matches as - * many as possible of these state types. - * - * @return List of state types that need to be true for this state. This is direct access to the data and changes to - * the returned list will effect this UiState. - */ - public List getStateKeys() { - return stateKeys; - } - - public void setInverted(boolean b) { - boolean old = inverted; - inverted = b; - firePropertyChange("invert", old, b); - } - - public final boolean isInverted() { - return inverted; - } - - /** - * Get the name of this state - * - * @return - */ - public String getName() { - if (cachedName == null) { - StringBuilder buf = new StringBuilder(); - List keys = new ArrayList(stateKeys); - Collections.sort(keys); - for (Iterator iter = keys.iterator(); iter.hasNext();) { - buf.append(iter.next()); - if (iter.hasNext()) buf.append('+'); - } - cachedName = buf.toString(); - } - return cachedName; - } - - public final Canvas getCanvas() { - return canvas; - } - - public void setCanvas(Canvas c) { - Canvas old = canvas; - canvas = c; - firePropertyChange("canvas", old, c); - } - - public UIStyle getStyle() { - return style; - } - - // ================================================================================================================= - // JIBX Helper Methods - - public static String keysToString(List keys) { - StringBuilder buf = new StringBuilder(); - for (Iterator iter = keys.iterator(); iter.hasNext();) { - buf.append(iter.next()); - if (iter.hasNext()) buf.append('+'); - } - return buf.toString(); - } - - public static List stringToKeys(String keysString) { - return Arrays.asList(keysString.split("\\+")); - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIStateType.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIStateType.java deleted file mode 100644 index 811ca8fa17c15792ab2bbfe73137ce7b388e1046..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIStateType.java +++ /dev/null @@ -1,129 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; - -/** - * UIStateType - A UIComponents has a collection of these which constitute the avilables states which can be chosen in - * the components regions. A UIStateType can be either a custom state or one of the predefined standard states. - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIStateType extends AbstractBean { - /* Keys for standard synth states */ - public static final String ENABLED_KEY = "Enabled"; - public static final String MOUSE_OVER_KEY = "MouseOver"; - public static final String PRESSED_KEY = "Pressed"; - public static final String DISABLED_KEY = "Disabled"; - public static final String FOCUSED_KEY = "Focused"; - public static final String SELECTED_KEY = "Selected"; - public static final String DEFAULT_KEY = "Default"; - public static final String[] STANDARD_SYNTH_STATE_KEYS = new String[]{ - ENABLED_KEY, MOUSE_OVER_KEY, PRESSED_KEY, DISABLED_KEY, FOCUSED_KEY, SELECTED_KEY, DEFAULT_KEY - }; - public static final UIStateType[] STANDARD_SYNTH_STATES = new UIStateType[]{ - new UIStateType(ENABLED_KEY), - new UIStateType(MOUSE_OVER_KEY), - new UIStateType(PRESSED_KEY), - new UIStateType(DISABLED_KEY), - new UIStateType(FOCUSED_KEY), - new UIStateType(SELECTED_KEY), - new UIStateType(DEFAULT_KEY) - }; - - /** Unique string for the ui key for this state, must be unique within a components set of UiStateTypes */ - private String key; - /** - * Snippet of java code that defines calculates the value of this state for a particular component. The varaiable - * c is the component. You end with a return statement returning boolean true/false for the current - * value of this state for this component. This can be null if the key is one of that standard synth states defined - * in constants in this class. - */ - private String codeSnippet; - - /** JIBX no-args contructor */ - private UIStateType() {} - - private UIStateType(String key) { - this.key = key; - this.codeSnippet = null; - } - - public UIStateType(String key, String codeSnippet) { - this.key = key; - this.codeSnippet = codeSnippet; - } - - // ================================================================================================================= - // Bean Methods - - /** - * Get the ui defaults key for this state type. Unique string for the ui key for this state, must be unique within a - * components set of UiStateTypes. - * - * @return Unique ui default key - */ - public String getKey() { - return key; - } - - /** - * Get the snippet of java code that defines calculates the value of this state for a particular component. The - * varaiable c is the component. You end with a return statement returning boolean true/false for the - * current value of this state for this component. This can be null if the key is one of that standard synth states - * defined in constants in this class. - * - * @return Snippet of java code or null if this is a synth standard state - */ - public String getCodeSnippet() { - return codeSnippet; - } - - /** - * Set the snippet of java code that defines calculates the value of this state for a particular component. The - * varaiable c is the component. You end with a return statement returning boolean true/false for the - * current value of this state for this component. This can be null if the key is one of that standard synth states - * defined in constants in this class. - * - * @param codeSnippet Snippet of java code or null if this is a synth standard state - */ - public void setCodeSnippet(String codeSnippet) { - this.codeSnippet = codeSnippet; - } - - /** - * Returns if this state type is a standard synth type and has no code snippet or a custom type that has a code - * snippet. It is used by JIBX to determin if the code snippet should be written to XML. - * - * @return true if codeSnippet is non null - */ - public boolean hasCodeSnippet() { - return codeSnippet != null; - } - - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIStyle.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIStyle.java deleted file mode 100644 index 3e926bf8e4a077101d93952735e55a2384ceafe0..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIStyle.java +++ /dev/null @@ -1,467 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel; - -import org.jdesktop.beans.AbstractBean; -import org.jdesktop.swingx.designer.font.Typeface; -import org.jdesktop.swingx.designer.paint.Matte; -import org.jibx.runtime.IUnmarshallingContext; - -import java.beans.PropertyChangeEvent; -import java.beans.PropertyChangeListener; -import java.util.List; -import java.util.ArrayList; - -/** - * UIStyle - * - * @author Richard Bair - * @author Jasper Potts - */ -public class UIStyle extends AbstractBean { - public static enum CacheMode {NO_CACHING,FIXED_SIZES,NINE_SQUARE_SCALE} - public static enum HintAlphaInterpolation { - DEFAULT, QUALITY, SPEED - } - - public static enum HintAntialiasing { - DEFAULT, ON, OFF - } - - public static enum HintColorRendering { - DEFAULT, QUALITY, SPEED - } - - public static enum HintDithering { - DEFAULT, DISABLE, ENABLE - } - - public static enum HintFractionalMetrics { - DEFAULT, ON, OFF - } - - public static enum HintInterpolation { - NEAREST_NEIGHBOR, BILINEAR, BICUBIC - } - - public static enum HintRendering { - DEFAULT, QUALITY, SPEED - } - - public static enum HintStrokeControl { - DEFAULT, NORMALIZE, PURE - } - - public static enum HintTextAntialiasing { - DEFAULT, ON, OFF, GASP, LCD_HBGR, LCD_HRGB, LCD_VBGR, LCD_VRGB - } - - private Typeface font = null; - private boolean fontInherited = true; - private Matte textForeground = null; - private boolean textForegroundInherited = true; - private Matte textBackground = null; - private boolean textBackgroundInherited = true; - private Matte background = null; - private boolean backgroundInherited = true; - - private boolean cacheSettingsInherited = true; - private CacheMode cacheMode = CacheMode.FIXED_SIZES; - private double maxHozCachedImgScaling = 1; - private double maxVertCachedImgScaling = 1; - - private HintAlphaInterpolation hintAlphaInterpolation = null; - private HintAntialiasing hintAntialiasing = null; - private HintColorRendering hintColorRendering = null; - private HintDithering hintDithering = null; - private HintFractionalMetrics hintFractionalMetrics = null; - private HintInterpolation hintInterpolation = null; - private HintRendering hintRendering = null; - private HintStrokeControl hintStrokeControl = null; - private HintTextAntialiasing hintTextAntialiasing = null; - private List uiProperties; - private UIStyle parentStyle = null; - - private PropertyChangeListener textForegoundListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("textForeground." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }; - private PropertyChangeListener textBackgroundListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("textBackground." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }; - private PropertyChangeListener backgroundListener = new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent evt) { - firePropertyChange("background." + evt.getPropertyName(), evt.getOldValue(), evt.getNewValue()); - } - }; - - // ================================================================================================================= - // Constructors - - public UIStyle() { - uiProperties = new ArrayList(); - } - - // ================================================================================================================= - // JIBX Methods - - /** - * Called by JIBX after all fields have been set - * - * @param context The JIBX Unmarshalling Context - */ - private void postSet(IUnmarshallingContext context) { - // walk up till we get a parent style - for (int i = 0; i < context.getStackDepth(); i++) { - if (context.getStackObject(i) instanceof HasUIStyle) { - HasUIStyle hasStyle = (HasUIStyle) context.getStackObject(i); - if (hasStyle.getStyle() != this) { - parentStyle = hasStyle.getStyle(); - if (parentStyle != null) break; - } - } - } - } - - // ================================================================================================================= - // Bean Methods - - public UIStyle getParentStyle() { - return parentStyle; - } - - public void setParentStyle(UIStyle parentStyle) { - UIStyle old = getParentStyle(); - this.parentStyle = parentStyle; - firePropertyChange("parentStyle", old, getParentStyle()); - } - - public List getUiProperties() { - return uiProperties; - } - - public void addUiProperty(UIProperty uiProperty) { - uiProperties.add(uiProperty); - // todo not quite sure what events we want here - fireIndexedPropertyChange("uiProperties", uiProperties.size(), null, uiProperty); -// firePropertyChange("uiProperties", null, uiProperties); - } - - public void removeUiProperty(UIProperty uiProperty) { - int index = uiProperties.indexOf(uiProperty); - if (index != -1) { - uiProperties.remove(uiProperty); - // todo not quite sure what events we want here - fireIndexedPropertyChange("uiProperties", index, null, uiProperty); -// firePropertyChange("uiProperties", null, uiProperties); - } - } - - public Typeface getFont() { - if (isFontInherited()) { - return parentStyle == null ? font : parentStyle.getFont(); - } else { - return font; - } - } - - public void setFont(Typeface font) { - Typeface old = getFont(); - this.font = font; - firePropertyChange("font", old, font); - } - - public boolean isFontInherited() { - return fontInherited; - } - - public void setFontInherited(boolean b) { - boolean old = isFontInherited(); - fontInherited = b; - firePropertyChange("fontInherited", old, b); - - if (!fontInherited && font == null && parentStyle != null && parentStyle.getFont() != null) { - font = parentStyle.getFont().clone(); - firePropertyChange("font", null, font); - } - } - - public Matte getTextForeground() { - if (isTextForegroundInherited()) { - return parentStyle == null ? null : parentStyle.getTextForeground(); - } else { - return textForeground; - } - } - - public boolean isTextForegroundInherited() { - return textForegroundInherited; - } - - public void setTextForegroundInherited(boolean b) { - boolean old = isTextForegroundInherited(); - textForegroundInherited = b; - firePropertyChange("foregroundInherited", old, b); - - if (!textForegroundInherited && textForeground == null && parentStyle != null && - parentStyle.getTextForeground() != null) { - textForeground = parentStyle.getTextForeground().clone(); - firePropertyChange("textForeground", null, textForeground); - } - } - - public void setTextForeground(Matte textForeground) { - Matte old = this.textForeground; - if (old != null) old.removePropertyChangeListener(textForegoundListener); - this.textForeground = textForeground; - if (this.textForeground != null) this.textForeground.addPropertyChangeListener(textForegoundListener); - firePropertyChange("textForeground", old, this.textForeground); - } - - public Matte getTextBackground() { - if (isTextBackgroundInherited()) { - return parentStyle == null ? null : parentStyle.getBackground(); - } else { - return textBackground; - } - } - - public boolean isTextBackgroundInherited() { - return textBackgroundInherited; - } - - public void setTextBackgroundInherited(boolean b) { - boolean old = isBackgroundInherited(); - textBackgroundInherited = b; - firePropertyChange("textBackgroundInherited", old, b); - - if (!textBackgroundInherited && textBackground == null && parentStyle != null && - parentStyle.getTextBackground() != null) { - textBackground = parentStyle.getTextBackground().clone(); - firePropertyChange("textBackground", null, textBackground); - } - } - - public void setTextBackground(Matte textBackground) { - Matte old = this.textBackground; - if (old != null) old.removePropertyChangeListener(textBackgroundListener); - this.textBackground = textBackground; - if (this.textBackground != null) this.textBackground.addPropertyChangeListener(textBackgroundListener); - firePropertyChange("textBackground", old, this.textBackground); - } - - public Matte getBackground() { - if (isBackgroundInherited()) { - return parentStyle == null ? null : parentStyle.getBackground(); - } else { - return background; - } - } - - public boolean isBackgroundInherited() { - return backgroundInherited; - } - - public void setBackgroundInherited(boolean b) { - boolean old = isBackgroundInherited(); - backgroundInherited = b; - firePropertyChange("backgroundInherited", old, b); - - if (!backgroundInherited && background == null && parentStyle != null && parentStyle.getBackground() != null) { - background = parentStyle.getBackground().clone(); - firePropertyChange("background", null, background); - } - } - - public void setBackground(Matte background) { - Matte old = this.background; - if (old != null) old.removePropertyChangeListener(backgroundListener); - this.background = background; - if (this.background != null) this.background.addPropertyChangeListener(backgroundListener); - firePropertyChange("background", old, this.background); - } - - public HintAlphaInterpolation getHintAlphaInterpolation() { - return hintAlphaInterpolation; - } - - public void setHintAlphaInterpolation(HintAlphaInterpolation hintAlphaInterpolation) { - HintAlphaInterpolation old = getHintAlphaInterpolation(); - this.hintAlphaInterpolation = hintAlphaInterpolation; - firePropertyChange("hintAlphaInterpolation", old, getHintAlphaInterpolation()); - } - - public HintAntialiasing getHintAntialiasing() { - return hintAntialiasing; - } - - public void setHintAntialiasing(HintAntialiasing hintAntialiasing) { - HintAntialiasing old = getHintAntialiasing(); - this.hintAntialiasing = hintAntialiasing; - firePropertyChange("hintAntialiasing", old, getHintAntialiasing()); - } - - public HintColorRendering getHintColorRendering() { - return hintColorRendering; - } - - public void setHintColorRendering(HintColorRendering hintColorRendering) { - HintColorRendering old = getHintColorRendering(); - this.hintColorRendering = hintColorRendering; - firePropertyChange("hintColorRendering", old, getHintColorRendering()); - } - - public HintDithering getHintDithering() { - return hintDithering; - } - - public void setHintDithering(HintDithering hintDithering) { - HintDithering old = getHintDithering(); - this.hintDithering = hintDithering; - firePropertyChange("hintDithering", old, getHintDithering()); - } - - public HintFractionalMetrics getHintFractionalMetrics() { - return hintFractionalMetrics; - } - - public void setHintFractionalMetrics(HintFractionalMetrics hintFractionalMetrics) { - HintFractionalMetrics old = getHintFractionalMetrics(); - this.hintFractionalMetrics = hintFractionalMetrics; - firePropertyChange("hintFractionalMetrics", old, getHintFractionalMetrics()); - } - - public HintInterpolation getHintInterpolation() { - return hintInterpolation; - } - - public void setHintInterpolation(HintInterpolation hintInterpolation) { - HintInterpolation old = getHintInterpolation(); - this.hintInterpolation = hintInterpolation; - firePropertyChange("hintInterpolation", old, getHintInterpolation()); - } - - public HintRendering getHintRendering() { - return hintRendering; - } - - public void setHintRendering(HintRendering hintRendering) { - HintRendering old = getHintRendering(); - this.hintRendering = hintRendering; - firePropertyChange("hintRendering", old, getHintRendering()); - } - - public HintStrokeControl getHintStrokeControl() { - return hintStrokeControl; - } - - public void setHintStrokeControl(HintStrokeControl hintStrokeControl) { - HintStrokeControl old = getHintStrokeControl(); - this.hintStrokeControl = hintStrokeControl; - firePropertyChange("hintStrokeControl", old, getHintStrokeControl()); - } - - public HintTextAntialiasing getHintTextAntialiasing() { - return hintTextAntialiasing; - } - - public void setHintTextAntialiasing(HintTextAntialiasing hintTextAntialiasing) { - HintTextAntialiasing old = getHintTextAntialiasing(); - this.hintTextAntialiasing = hintTextAntialiasing; - firePropertyChange("hintTextAntialiasing", old, getHintTextAntialiasing()); - } - - public boolean isCacheSettingsInherited() { - return cacheSettingsInherited; - } - - public void setCacheSettingsInherited(boolean cacheSettingsInherited) { - boolean old = isCacheSettingsInherited(); - this.cacheSettingsInherited = cacheSettingsInherited; - firePropertyChange("cacheSettingsInherited", old, isCacheSettingsInherited()); - } - - public CacheMode getCacheMode() { - if (isCacheSettingsInherited()) { - return (parentStyle == null)?CacheMode.FIXED_SIZES : parentStyle.getCacheMode(); - } else { - return cacheMode; - } - } - - public void setCacheMode(CacheMode cacheMode) { - CacheMode old = this.cacheMode; - this.cacheMode = cacheMode; - if (isCacheSettingsInherited()) { - setCacheSettingsInherited(false); - UIStyle parent = getParentStyle(); - setMaxHozCachedImgScaling(parent == null ? 1 : parent.getMaxHozCachedImgScaling()); - setMaxVertCachedImgScaling(parent == null ? 1 : parent.getMaxVertCachedImgScaling()); - } - firePropertyChange("cacheMode",old,cacheMode); - } - - public double getMaxHozCachedImgScaling() { - if (isCacheSettingsInherited()) { - return parentStyle == null ? 1 : parentStyle.getMaxHozCachedImgScaling(); - } else { - return maxHozCachedImgScaling; - } - } - - public void setMaxHozCachedImgScaling(double maxHozCachedImgScaling) { - double old = getMaxHozCachedImgScaling(); - this.maxHozCachedImgScaling = maxHozCachedImgScaling; - if (isCacheSettingsInherited()) { - setCacheSettingsInherited(false); - setCacheMode((parentStyle == null)?CacheMode.FIXED_SIZES : parentStyle.getCacheMode()); - setMaxVertCachedImgScaling(parentStyle == null ? 1 : parentStyle.getMaxVertCachedImgScaling()); - } - firePropertyChange("maxHozCachedImgScaling", old, getMaxHozCachedImgScaling()); - } - - public double getMaxVertCachedImgScaling() { - if (isCacheSettingsInherited()) { - return parentStyle == null ? 1 : parentStyle.getMaxVertCachedImgScaling(); - } else { - return maxVertCachedImgScaling; - } - } - - public void setMaxVertCachedImgScaling(double maxVertCachedImgScaling) { - double old = getMaxVertCachedImgScaling(); - this.maxVertCachedImgScaling = maxVertCachedImgScaling; - if (isCacheSettingsInherited()) { - setCacheSettingsInherited(false); - setCacheMode((parentStyle == null)?CacheMode.FIXED_SIZES : parentStyle.getCacheMode()); - setMaxHozCachedImgScaling(parentStyle == null ? 1 : parentStyle.getMaxHozCachedImgScaling()); - } - firePropertyChange("maxVertCachedImgScaling", old, getMaxVertCachedImgScaling()); - } -} - diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/BorderMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/BorderMapper.java deleted file mode 100644 index da35f401bc42879c82ed5835e665e297da58ff31..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/BorderMapper.java +++ /dev/null @@ -1,285 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel.jibxhelpers; - -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IAliasable; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; -import org.jdesktop.swingx.designer.jibxhelpers.ColorMapper; - -import javax.swing.border.LineBorder; -import javax.swing.border.EmptyBorder; -import javax.swing.border.EtchedBorder; -import javax.swing.border.BevelBorder; -import javax.swing.border.MatteBorder; -import javax.swing.border.CompoundBorder; -import javax.swing.border.Border; -import javax.swing.BorderFactory; -import java.awt.Insets; -import java.awt.Color; -import org.jdesktop.synthdesigner.synthmodel.PainterBorder; - -/** - * BorderMapper - JIBX xml mapper for swing standard borders - * - * @author Jasper Potts - */ -public class BorderMapper implements IMarshaller, IUnmarshaller, IAliasable { - private static enum BorderType { - empty, line, etched, bevel, matte, compound, painter - } - private static enum SubType { - raised(EtchedBorder.RAISED), lowered(EtchedBorder.LOWERED); - private int subtype; - - SubType(int type) { - this.subtype = type; - } - - public int getSubType() { - return subtype; - } - } - private static final String ELEMENT_NAME = "border"; - private static final String TYPE_NAME = "type"; - private static final String SUB_TYPE_NAME = "subtype"; - private static final String TOP_NAME = "top"; - private static final String BOTTOM_NAME = "bottom"; - private static final String LEFT_NAME = "left"; - private static final String RIGHT_NAME = "right"; - private static final String THICKNESS_NAME = "thickness"; - private static final String INSIDE_NAME = "inside"; - private static final String OUTSIDE_NAME = "outside"; - private static final String PAINTER_NAME = "painter"; - - private String uri; - private int index; - private String name; - - public BorderMapper() { - uri = null; - index = 0; - name = ELEMENT_NAME; - } - - public BorderMapper(String uri, int index, String name) { - this.uri = uri; - this.index = index; - this.name = name; - } - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws - JiBXException { - return iUnmarshallingContext.isAt(uri, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) - throws JiBXException { - if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - if (object instanceof PainterBorder) { - PainterBorder border = (PainterBorder) object; - Insets insets = border.getBorderInsets(); - ctx.startTagAttributes(index, name) - .attribute(index, TYPE_NAME, BorderType.painter.toString()) - .attribute(index, PAINTER_NAME, border.getPainterName()) - .attribute(index, TOP_NAME, insets.top) - .attribute(index, BOTTOM_NAME, insets.bottom) - .attribute(index, LEFT_NAME, insets.left) - .attribute(index, RIGHT_NAME, insets.right) - .closeStartContent(); - ctx.endTag(index, name); - } else if (object instanceof EmptyBorder) { - Insets insets = ((EmptyBorder) object).getBorderInsets(); - ctx.startTagAttributes(index, name) - .attribute(index, TYPE_NAME, - BorderType.empty.toString()) - .attribute(index, TOP_NAME, insets.top) - .attribute(index, BOTTOM_NAME, insets.bottom) - .attribute(index, LEFT_NAME, insets.left) - .attribute(index, RIGHT_NAME, insets.right) - .closeStartEmpty(); - } else if (object instanceof LineBorder) { - LineBorder border = (LineBorder) object; - ctx.startTagAttributes(index, name). - attribute(index, TYPE_NAME, BorderType.line.toString()). - attribute(index, THICKNESS_NAME, border.getThickness()). - closeStartContent(); - new ColorMapper().marshal(border.getLineColor(), ctx); - ctx.endTag(index, name); - } else if (object instanceof EtchedBorder) { - EtchedBorder border = (EtchedBorder) object; - ctx.startTagAttributes(index, name). - attribute(index, TYPE_NAME, - BorderType.etched.toString()). - attribute(index, SUB_TYPE_NAME, - border.getEtchType()==EtchedBorder.RAISED? - SubType.raised.toString(): - SubType.lowered.toString()). - closeStartContent(); - new ColorMapper().marshal(border.getHighlightColor(), ctx); - new ColorMapper().marshal(border.getShadowColor(), ctx); - ctx.endTag(index, name); - } else if (object instanceof BevelBorder) { - BevelBorder border = (BevelBorder) object; - ctx.startTagAttributes(index, name). - attribute(index, TYPE_NAME, - BorderType.bevel.toString()). - attribute(index, SUB_TYPE_NAME, - border.getBevelType()==BevelBorder.RAISED? - SubType.raised.toString(): - SubType.lowered.toString()). - closeStartContent(); - new ColorMapper().marshal(border.getHighlightInnerColor(), ctx); - new ColorMapper().marshal(border.getHighlightOuterColor(), ctx); - new ColorMapper().marshal(border.getShadowInnerColor(), ctx); - new ColorMapper().marshal(border.getHighlightOuterColor(), ctx); - ctx.endTag(index, name); - } else if (object instanceof MatteBorder) { - MatteBorder border = (MatteBorder) object; - Insets insets = ((EmptyBorder) object).getBorderInsets(); - ctx.startTagAttributes(index, name) - .attribute(index, TYPE_NAME, - BorderType.matte.toString()) - .attribute(index, TOP_NAME, insets.top) - .attribute(index, BOTTOM_NAME, insets.bottom) - .attribute(index, LEFT_NAME, insets.left) - .attribute(index, RIGHT_NAME, insets.right) - .closeStartContent(); - new ColorMapper().marshal(border.getMatteColor(), ctx); - // todo: we should support tiled icons here to be 100% complete - ctx.endTag(index, name); - } else if (object instanceof CompoundBorder) { - CompoundBorder border = (CompoundBorder) object; - ctx.startTagAttributes(index, name) - .attribute(index, TYPE_NAME, - BorderType.compound.toString()) - .closeStartContent(); - new BorderMapper(null,0, INSIDE_NAME).marshal(border.getInsideBorder(),ctx); - new BorderMapper(null,0, OUTSIDE_NAME).marshal(border.getOutsideBorder(),ctx); - ctx.endTag(index, name); - } else { - throw new JiBXException("Invalid object type for marshaller"); - } - } - } - - public Object unmarshal(Object object, - IUnmarshallingContext iUnmarshallingContext) - throws JiBXException { - Border border = null; - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(uri, name)) { - ctx.throwStartTagNameError(uri, name); - } - // get type - BorderType type = BorderType.valueOf(ctx.attributeText(uri, TYPE_NAME) - .toLowerCase()); - int top,bottom,left,right; - Color color; - switch(type){ - case empty: - top = ctx.attributeInt(uri, TOP_NAME, index); - bottom = ctx.attributeInt(uri, BOTTOM_NAME, index); - left = ctx.attributeInt(uri, LEFT_NAME, index); - right = ctx.attributeInt(uri, RIGHT_NAME, index); - border = BorderFactory.createEmptyBorder(top,left,bottom,right); - break; - case line: - int thickness = ctx.attributeInt(uri, THICKNESS_NAME, index); - ctx.parsePastStartTag(uri,name); - color = (Color)new ColorMapper().unmarshal(null,ctx); - border = BorderFactory.createLineBorder(color,thickness); - break; - case etched: - SubType etchedType = SubType.valueOf( - ctx.attributeText(uri, SUB_TYPE_NAME).toLowerCase()); - ctx.parsePastStartTag(uri,name); - Color highColor = (Color)new ColorMapper() - .unmarshal(null,ctx); - Color shadowColor = (Color)new ColorMapper() - .unmarshal(null,ctx); - border = BorderFactory.createEtchedBorder( - etchedType.getSubType(),highColor,shadowColor); - break; - case bevel: - SubType bevelType = SubType.valueOf( - ctx.attributeText(uri, SUB_TYPE_NAME).toLowerCase()); - ctx.parsePastStartTag(uri,name); - Color innerHighColor = (Color)new ColorMapper() - .unmarshal(null,ctx); - Color outerHighColor = (Color)new ColorMapper() - .unmarshal(null,ctx); - Color innerShadowColor = (Color)new ColorMapper() - .unmarshal(null,ctx); - Color outerShadowColor = (Color)new ColorMapper() - .unmarshal(null,ctx); - border = BorderFactory.createBevelBorder( - bevelType.getSubType(),outerHighColor,innerHighColor, - outerShadowColor,innerShadowColor); - break; - case matte: - top = ctx.attributeInt(uri, TOP_NAME, index); - bottom = ctx.attributeInt(uri, BOTTOM_NAME, index); - left = ctx.attributeInt(uri, LEFT_NAME, index); - right = ctx.attributeInt(uri, RIGHT_NAME, index); - ctx.parsePastStartTag(uri,name); - color = (Color)new ColorMapper().unmarshal(null,ctx); - border = BorderFactory.createMatteBorder(top,left,bottom,right, - color); - break; - case compound: - ctx.parsePastStartTag(uri,name); - Border inside = (Border) new BorderMapper(null,0, INSIDE_NAME) - .unmarshal(null,ctx); - Border outside = (Border) new BorderMapper(null,0, OUTSIDE_NAME) - .unmarshal(null,ctx); - border = BorderFactory.createCompoundBorder(outside, inside); - break; - case painter: - String painterName = ctx.attributeText(uri, PAINTER_NAME); - top = ctx.attributeInt(uri, TOP_NAME, index); - bottom = ctx.attributeInt(uri, BOTTOM_NAME, index); - left = ctx.attributeInt(uri, LEFT_NAME, index); - right = ctx.attributeInt(uri, RIGHT_NAME, index); - border = new PainterBorder(painterName, top, left, bottom, right); - } - ctx.parsePastEndTag(uri, name); - return border; - } -} - diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/ClassConverter.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/ClassConverter.java deleted file mode 100644 index ca59d1aac7f0cedfc280e6daca6a0d8b4c842e03..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/ClassConverter.java +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel.jibxhelpers; - -/** - * ClassConverter - * - * @author Created by Jasper Potts (Jul 16, 2007) - */ -public class ClassConverter { - - public static String classToString(Class c) { - return c == null ? "" : c.getName(); - } - - public static Class stringToClass(String className) { - if (className == null || className.length() == 0) { - return null; - } - try { - ClassLoader classLoader = Thread.currentThread().getContextClassLoader(); - if (classLoader == null) classLoader = ClassConverter.class.getClassLoader(); - return classLoader.loadClass(className); - } catch (ClassNotFoundException e) { - System.err.println("Failed to find class with name [" + className + "] in ClassConverter"); - e.printStackTrace(); - return null; - } - } - -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/ClassMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/ClassMapper.java deleted file mode 100644 index 5d3d7650fbc5b2a43feb243946f6fd358b982a4f..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/ClassMapper.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel.jibxhelpers; - -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - - -public class ClassMapper implements IMarshaller, IUnmarshaller { - private static final String ELEMENT_NAME = "type"; - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(null, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof Class)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - Class clazz = (Class) object; - ctx.startTagAttributes(0, ELEMENT_NAME). - attribute(0, "value", clazz.getName()). - closeStartEmpty(); - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(null, ELEMENT_NAME)) { - ctx.throwStartTagNameError(null, ELEMENT_NAME); - } - // get values - String value = ctx.attributeText(null, "value", null); - ctx.parsePastEndTag(null, ELEMENT_NAME); - // create - try { - return Class.forName(value); - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/FontMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/FontMapper.java deleted file mode 100644 index b815c0c4b97c5425aad8ab5705accf88c00f48f5..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/FontMapper.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel.jibxhelpers; - -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - -import java.awt.Font; - -/** - * FontMapper - * - * @author Created by Jasper Potts (Jun 8, 2007) - */ -public class FontMapper implements IMarshaller, IUnmarshaller { - private static final String ELEMENT_NAME = "font"; - private static final String FAMILY_NAME = "family"; - private static final String STYLE_NAME = "style"; - private static final String SIZE_NAME = "size"; - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(null, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof Font)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - Font font = (Font) object; - ctx.startTagAttributes(0, ELEMENT_NAME). - attribute(0, FAMILY_NAME, font.getFamily()). - attribute(0, STYLE_NAME, font.getStyle()). - attribute(0, SIZE_NAME, font.getSize()). - closeStartEmpty(); - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(null, ELEMENT_NAME)) { - ctx.throwStartTagNameError(null, ELEMENT_NAME); - } - // get values - String name = ctx.attributeText(null, FAMILY_NAME, null); - int style = ctx.attributeInt(null, STYLE_NAME, 0); - int size = ctx.attributeInt(null, SIZE_NAME, 0); - ctx.parsePastEndTag(null, ELEMENT_NAME); - // create - return new Font(name, style, size); - } -} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/UIPropertyMapper.java b/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/UIPropertyMapper.java deleted file mode 100644 index 002ab6b9defbc5d9186fd21d75a3ea8d24f51651..0000000000000000000000000000000000000000 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/jibxhelpers/UIPropertyMapper.java +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. - * - * This code 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 - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, - * CA 95054 USA or visit www.sun.com if you need additional information or - * have any questions. - */ -package org.jdesktop.synthdesigner.synthmodel.jibxhelpers; - -import org.jdesktop.swingx.designer.jibxhelpers.DimensionMapper; -import org.jdesktop.swingx.designer.jibxhelpers.InsetsMapper; -import org.jdesktop.synthdesigner.synthmodel.UIProperty; -import org.jibx.runtime.IMarshallable; -import org.jibx.runtime.IMarshaller; -import org.jibx.runtime.IMarshallingContext; -import org.jibx.runtime.IUnmarshaller; -import org.jibx.runtime.IUnmarshallingContext; -import org.jibx.runtime.JiBXException; -import org.jibx.runtime.impl.MarshallingContext; -import org.jibx.runtime.impl.UnmarshallingContext; - -/** - * UIPropertyMapper - * - * @author Created by Jasper Potts (Jul 10, 2007) - */ -public class UIPropertyMapper implements IMarshaller, IUnmarshaller { - private static final String ELEMENT_NAME = "uiProperty"; - private static final String NAME_NAME = "name"; - private static final String TYPE_NAME = "type"; - private static final String VALUE_NAME = "value"; - - public boolean isExtension(int i) { - return false; - } - - public boolean isPresent(IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - return iUnmarshallingContext.isAt(null, ELEMENT_NAME); - } - - public void marshal(Object object, IMarshallingContext iMarshallingContext) throws JiBXException { - if (!(object instanceof UIProperty)) { - throw new JiBXException("Invalid object type for marshaller"); - } else if (!(iMarshallingContext instanceof MarshallingContext)) { - throw new JiBXException("Invalid object type for marshaller"); - } else { - MarshallingContext ctx = (MarshallingContext) iMarshallingContext; - UIProperty property = (UIProperty) object; - ctx.startTagAttributes(0, ELEMENT_NAME); - ctx.attribute(0, NAME_NAME, property.getName()); - ctx.attribute(0, TYPE_NAME, property.getType().toString()); - switch (property.getType()) { - case BOOLEAN: - case DOUBLE: - case INT: - case FLOAT: - case STRING: - ctx.attribute(0, VALUE_NAME, property.getValue().toString()); - ctx.closeStartEmpty(); - break; - case INSETS: - ctx.closeStartContent(); - new InsetsMapper().marshal(property.getValue(), ctx); - ctx.endTag(0, ELEMENT_NAME); - break; - case COLOR: - case FONT: - ctx.closeStartContent(); - if (property.getValue() instanceof IMarshallable) { - ((IMarshallable) property.getValue()).marshal(ctx); - } else { - throw new JiBXException("Mapped value is not marshallable"); - } - ctx.endTag(0, ELEMENT_NAME); - break; - case DIMENSION: - ctx.closeStartContent(); - new DimensionMapper().marshal(property.getValue(), ctx); - ctx.endTag(0, ELEMENT_NAME); - break; - case BORDER: - ctx.closeStartContent(); - new BorderMapper().marshal(property.getValue(), ctx); - ctx.endTag(0, ELEMENT_NAME); - break; - } - } - } - - public Object unmarshal(Object object, IUnmarshallingContext iUnmarshallingContext) throws JiBXException { - // make sure we're at the appropriate start tag - UnmarshallingContext ctx = (UnmarshallingContext) iUnmarshallingContext; - if (!ctx.isAt(null, ELEMENT_NAME)) { - ctx.throwStartTagNameError(null, ELEMENT_NAME); - } - // get values - Object value = null; - String name = ctx.attributeText(null, NAME_NAME, null); - UIProperty.PropertyType type = UIProperty.PropertyType.valueOf(ctx.attributeText(null, TYPE_NAME, null)); - switch (type) { - case BOOLEAN: - value = Boolean.parseBoolean(ctx.attributeText(null, VALUE_NAME, null)); - break; - case DOUBLE: - value = Double.parseDouble(ctx.attributeText(null, VALUE_NAME, null)); - break; - case INT: - value = Integer.parseInt(ctx.attributeText(null, VALUE_NAME, null)); - break; - case FLOAT: - value = Float.parseFloat(ctx.attributeText(null, VALUE_NAME, null)); - break; - case STRING: - value = ctx.attributeText(null, VALUE_NAME, null); - break; - case INSETS: - ctx.parsePastStartTag(null, ELEMENT_NAME); - value = new InsetsMapper().unmarshal(value, ctx); - break; - case COLOR: - case FONT: - ctx.parsePastStartTag(null, ELEMENT_NAME); - value = ctx.unmarshalElement(); - break; - case DIMENSION: - ctx.parsePastStartTag(null, ELEMENT_NAME); - value = new DimensionMapper().unmarshal(value, ctx); - break; - case BORDER: - ctx.parsePastStartTag(null, ELEMENT_NAME); - value = new BorderMapper().unmarshal(value, ctx); - break; - } - ctx.parsePastEndTag(null, ELEMENT_NAME); - // create - return new UIProperty(name, type, value); - } -} diff --git a/src/share/bin/java.h b/src/share/bin/java.h index fe039cdcc88452d2562c88e475e3478309432f79..cebdb5fc81afad84d0c6415886636434d03ab0f6 100644 --- a/src/share/bin/java.h +++ b/src/share/bin/java.h @@ -187,9 +187,6 @@ void InitLauncher(jboolean javaw); * */ typedef jclass (JNICALL FindClassFromBootLoader_t(JNIEnv *env, - const char *name, - jboolean init, - jobject loader, - jboolean throwError)); + const char *name)); jclass FindBootStrapClass(JNIEnv *env, const char *classname); #endif /* _JAVA_H_ */ diff --git a/src/share/bin/parse_manifest.c b/src/share/bin/parse_manifest.c index 6dcca091a4bb3c6be3324cda7217ad54f00342fc..a59540213c2dc4ce20585b000b725cbe5cff25c7 100644 --- a/src/share/bin/parse_manifest.c +++ b/src/share/bin/parse_manifest.c @@ -59,7 +59,7 @@ inflate_file(int fd, zentry *entry, int *size_out) char *out; z_stream zs; - if (entry->csize == 0xffffffff || entry->isize == 0xffffffff) + if (entry->csize == (size_t) -1 || entry->isize == (size_t) -1 ) return (NULL); if (lseek(fd, entry->offset, SEEK_SET) < (off_t)0) return (NULL); diff --git a/src/share/classes/com/sun/beans/finder/BeanInfoFinder.java b/src/share/classes/com/sun/beans/finder/BeanInfoFinder.java index faab85cafa99eb84bd8e1f56ae5bd365775f8755..5dda4dfa1a3d982af6e56c5f3c440558c16b8855 100644 --- a/src/share/classes/com/sun/beans/finder/BeanInfoFinder.java +++ b/src/share/classes/com/sun/beans/finder/BeanInfoFinder.java @@ -52,8 +52,14 @@ public final class BeanInfoFinder } @Override - protected BeanInfo instantiate(Class type, String name) { - BeanInfo info = super.instantiate(type, name); + protected BeanInfo instantiate(Class type, String prefix, String name) { + // this optimization will only use the BeanInfo search path + // if is has changed from the original + // or trying to get the ComponentBeanInfo + BeanInfo info = !DEFAULT.equals(prefix) || "ComponentBeanInfo".equals(name) + ? super.instantiate(type, prefix, name) + : null; + if (info != null) { // make sure that the returned BeanInfo matches the class BeanDescriptor bd = info.getBeanDescriptor(); @@ -89,14 +95,4 @@ public final class BeanInfoFinder } return null; } - - @Override - protected BeanInfo instantiate(Class type, String prefix, String name) { - // this optimization will only use the BeanInfo search path - // if is has changed from the original - // or trying to get the ComponentBeanInfo - return !DEFAULT.equals(prefix) || "ComponentBeanInfo".equals(name) - ? super.instantiate(type, prefix, name) - : null; - } } diff --git a/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java b/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java index 11807239c34286d895921a308feb5d6430b30062..cfcf6194ec35cecfb4ee00c344cb982b9830f382 100644 --- a/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java +++ b/src/share/classes/com/sun/java/swing/plaf/windows/DesktopProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -49,7 +49,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue { /** * ReferenceQueue of unreferenced WeakPCLs. */ - private static ReferenceQueue queue; + private static final ReferenceQueue queue = new ReferenceQueue(); /** * PropertyChangeListener attached to the Toolkit. @@ -58,7 +58,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue { /** * Key used to lookup value from desktop. */ - private String key; + private final String key; /** * Value to return. */ @@ -66,17 +66,8 @@ public class DesktopProperty implements UIDefaults.ActiveValue { /** * Fallback value in case we get null from desktop. */ - private Object fallback; + private final Object fallback; - /** - * Toolkit. - */ - private Toolkit toolkit; - - - static { - queue = new ReferenceQueue(); - } /** * Cleans up any lingering state held by unrefeernced @@ -138,13 +129,10 @@ public class DesktopProperty implements UIDefaults.ActiveValue { * * @param key Key used in looking up desktop value. * @param fallback Value used if desktop property is null. - * @param toolkit Toolkit used to fetch property from, can be null - * in which default will be used. */ - public DesktopProperty(String key, Object fallback, Toolkit toolkit) { + public DesktopProperty(String key, Object fallback) { this.key = key; this.fallback = fallback; - this.toolkit = toolkit; // The only sure fire way to clear our references is to create a // Thread and wait for a reference to be added to the queue. // Because it is so rare that you will actually change the look @@ -175,13 +163,14 @@ public class DesktopProperty implements UIDefaults.ActiveValue { * Returns the value from the desktop. */ protected Object getValueFromDesktop() { - if (this.toolkit == null) { - this.toolkit = Toolkit.getDefaultToolkit(); + Toolkit toolkit = Toolkit.getDefaultToolkit(); + + if (pcl == null) { + pcl = new WeakPCL(this, getKey(), UIManager.getLookAndFeel()); + toolkit.addPropertyChangeListener(getKey(), pcl); } - Object value = toolkit.getDesktopProperty(getKey()); - pcl = new WeakPCL(this, toolkit, getKey(), UIManager.getLookAndFeel()); - toolkit.addPropertyChangeListener(getKey(), pcl); - return value; + + return toolkit.getDesktopProperty(getKey()); } /** @@ -205,12 +194,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue { * createValue will ask for the property again. */ public void invalidate() { - if (pcl != null) { - toolkit.removePropertyChangeListener(getKey(), pcl); - toolkit = null; - pcl = null; - value = null; - } + value = null; } /** @@ -271,13 +255,11 @@ public class DesktopProperty implements UIDefaults.ActiveValue { */ private static class WeakPCL extends WeakReference implements PropertyChangeListener { - private Toolkit kit; private String key; private LookAndFeel laf; - WeakPCL(DesktopProperty target, Toolkit kit, String key, LookAndFeel laf) { + WeakPCL(DesktopProperty target, String key, LookAndFeel laf) { super(target, queue); - this.kit = kit; this.key = key; this.laf = laf; } @@ -297,7 +279,7 @@ public class DesktopProperty implements UIDefaults.ActiveValue { } void dispose() { - kit.removePropertyChangeListener(key, this); + Toolkit.getDefaultToolkit().removePropertyChangeListener(key, this); } } } diff --git a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java index 79d06782e8b4b3cdabae0464904dedb89915b982..f1657cc27c173c3f4ca1a2552a1f7d8d8cf729b1 100644 --- a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java +++ b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsFileChooserUI.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -43,7 +43,6 @@ import java.security.AccessController; import java.security.PrivilegedAction; import sun.awt.shell.ShellFolder; -import sun.awt.OSInfo; import sun.swing.*; import javax.accessibility.*; @@ -58,8 +57,6 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { // The following are private because the implementation of the // Windows FileChooser L&F is not complete yet. - private static final OSInfo.WindowsVersion OS_VERSION = OSInfo.getWindowsVersion(); - private JPanel centerPanel; private JLabel lookInLabel; @@ -118,18 +115,9 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { private String upFolderToolTipText = null; private String upFolderAccessibleName = null; - private String homeFolderToolTipText = null; - private String homeFolderAccessibleName = null; - private String newFolderToolTipText = null; private String newFolderAccessibleName = null; - private String listViewButtonToolTipText = null; - private String listViewButtonAccessibleName = null; - - private String detailsViewButtonToolTipText = null; - private String detailsViewButtonAccessibleName = null; - private String viewMenuButtonToolTipText = null; private String viewMenuButtonAccessibleName = null; @@ -231,9 +219,7 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { // Directory manipulation buttons JToolBar topPanel = new JToolBar(); topPanel.setFloatable(false); - if (OS_VERSION.compareTo(OSInfo.WINDOWS_ME) >= 0) { - topPanel.putClientProperty("JToolBar.isRollover", Boolean.TRUE); - } + topPanel.putClientProperty("JToolBar.isRollover", Boolean.TRUE); // Add the top panel to the fileChooser fc.add(topPanel, BorderLayout.NORTH); @@ -287,218 +273,103 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { topPanel.add(Box.createRigidArea(hstrut10)); // Up Button - JButton upFolderButton = new JButton(getChangeToParentDirectoryAction()); - upFolderButton.setText(null); - upFolderButton.setIcon(upFolderIcon); - upFolderButton.setToolTipText(upFolderToolTipText); - upFolderButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, - upFolderAccessibleName); - upFolderButton.putClientProperty(WindowsLookAndFeel.HI_RES_DISABLED_ICON_CLIENT_KEY, - Boolean.TRUE); - upFolderButton.setAlignmentX(JComponent.LEFT_ALIGNMENT); - upFolderButton.setAlignmentY(JComponent.CENTER_ALIGNMENT); - upFolderButton.setMargin(shrinkwrap); - upFolderButton.setFocusPainted(false); + JButton upFolderButton = createToolButton(getChangeToParentDirectoryAction(), upFolderIcon, + upFolderToolTipText, upFolderAccessibleName); topPanel.add(upFolderButton); - if (OS_VERSION.compareTo(OSInfo.WINDOWS_ME) < 0) { - topPanel.add(Box.createRigidArea(hstrut10)); - } - - JButton b; - - if (OS_VERSION == OSInfo.WINDOWS_98) { - // Desktop Button - File homeDir = fsv.getHomeDirectory(); - String toolTipText = homeFolderToolTipText; - if (fsv.isRoot(homeDir)) { - toolTipText = getFileView(fc).getName(homeDir); // Probably "Desktop". - } - b = new JButton(getFileView(fc).getIcon(homeDir)); - b.setToolTipText(toolTipText); - b.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, - toolTipText); - b.setAlignmentX(JComponent.LEFT_ALIGNMENT); - b.setAlignmentY(JComponent.CENTER_ALIGNMENT); - b.setMargin(shrinkwrap); - b.setFocusPainted(false); - b.addActionListener(getGoHomeAction()); - topPanel.add(b); - topPanel.add(Box.createRigidArea(hstrut10)); - } // New Directory Button if (!UIManager.getBoolean("FileChooser.readOnly")) { - b = new JButton(filePane.getNewFolderAction()); - b.setText(null); - b.setIcon(newFolderIcon); - b.setToolTipText(newFolderToolTipText); - b.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, - newFolderAccessibleName); - b.putClientProperty(WindowsLookAndFeel.HI_RES_DISABLED_ICON_CLIENT_KEY, - Boolean.TRUE); - b.setAlignmentX(JComponent.LEFT_ALIGNMENT); - b.setAlignmentY(JComponent.CENTER_ALIGNMENT); - b.setMargin(shrinkwrap); - b.setFocusPainted(false); - topPanel.add(b); + JButton newFolderButton = createToolButton(filePane.getNewFolderAction(), newFolderIcon, + newFolderToolTipText, newFolderAccessibleName); + topPanel.add(newFolderButton); } - if (OS_VERSION.compareTo(OSInfo.WINDOWS_ME) < 0) { - topPanel.add(Box.createRigidArea(hstrut10)); - - // View button group - ButtonGroup viewButtonGroup = new ButtonGroup(); - - // List Button - final JToggleButton listViewButton = new JToggleButton(listViewIcon); - listViewButton.setToolTipText(listViewButtonToolTipText); - listViewButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, - listViewButtonAccessibleName); - listViewButton.putClientProperty(WindowsLookAndFeel.HI_RES_DISABLED_ICON_CLIENT_KEY, - Boolean.TRUE); - listViewButton.setFocusPainted(false); - listViewButton.setSelected(true); - listViewButton.setAlignmentX(JComponent.LEFT_ALIGNMENT); - listViewButton.setAlignmentY(JComponent.CENTER_ALIGNMENT); - listViewButton.setMargin(shrinkwrap); - listViewButton.addActionListener(filePane.getViewTypeAction(FilePane.VIEWTYPE_LIST)); - topPanel.add(listViewButton); - viewButtonGroup.add(listViewButton); - - // Details Button - final JToggleButton detailsViewButton = new JToggleButton(detailsViewIcon); - detailsViewButton.setToolTipText(detailsViewButtonToolTipText); - detailsViewButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, - detailsViewButtonAccessibleName); - detailsViewButton.putClientProperty(WindowsLookAndFeel.HI_RES_DISABLED_ICON_CLIENT_KEY, - Boolean.TRUE); - detailsViewButton.setFocusPainted(false); - detailsViewButton.setAlignmentX(JComponent.LEFT_ALIGNMENT); - detailsViewButton.setAlignmentY(JComponent.CENTER_ALIGNMENT); - detailsViewButton.setMargin(shrinkwrap); - detailsViewButton.addActionListener(filePane.getViewTypeAction(FilePane.VIEWTYPE_DETAILS)); - topPanel.add(detailsViewButton); - viewButtonGroup.add(detailsViewButton); - - topPanel.add(Box.createRigidArea(new Dimension(60, 0))); - - filePane.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent e) { - if ("viewType".equals(e.getPropertyName())) { - int viewType = filePane.getViewType(); - - switch (viewType) { - case FilePane.VIEWTYPE_LIST: - listViewButton.setSelected(true); - break; - - case FilePane.VIEWTYPE_DETAILS: - detailsViewButton.setSelected(true); - break; - } - } + + // View button group + ButtonGroup viewButtonGroup = new ButtonGroup(); + + // Popup Menu + final JPopupMenu viewTypePopupMenu = new JPopupMenu(); + + final JRadioButtonMenuItem listViewMenuItem = new JRadioButtonMenuItem( + filePane.getViewTypeAction(FilePane.VIEWTYPE_LIST)); + listViewMenuItem.setSelected(filePane.getViewType() == FilePane.VIEWTYPE_LIST); + viewTypePopupMenu.add(listViewMenuItem); + viewButtonGroup.add(listViewMenuItem); + + final JRadioButtonMenuItem detailsViewMenuItem = new JRadioButtonMenuItem( + filePane.getViewTypeAction(FilePane.VIEWTYPE_DETAILS)); + detailsViewMenuItem.setSelected(filePane.getViewType() == FilePane.VIEWTYPE_DETAILS); + viewTypePopupMenu.add(detailsViewMenuItem); + viewButtonGroup.add(detailsViewMenuItem); + + // Create icon for viewMenuButton + BufferedImage image = new BufferedImage(viewMenuIcon.getIconWidth() + 7, viewMenuIcon.getIconHeight(), + BufferedImage.TYPE_INT_ARGB); + Graphics graphics = image.getGraphics(); + viewMenuIcon.paintIcon(filePane, graphics, 0, 0); + int x = image.getWidth() - 5; + int y = image.getHeight() / 2 - 1; + graphics.setColor(Color.BLACK); + graphics.fillPolygon(new int[]{x, x + 5, x + 2}, new int[]{y, y, y + 3}, 3); + + // Details Button + final JButton viewMenuButton = createToolButton(null, new ImageIcon(image), viewMenuButtonToolTipText, + viewMenuButtonAccessibleName); + + viewMenuButton.addMouseListener(new MouseAdapter() { + public void mousePressed(MouseEvent e) { + if (SwingUtilities.isLeftMouseButton(e) && !viewMenuButton.isSelected()) { + viewMenuButton.setSelected(true); + + viewTypePopupMenu.show(viewMenuButton, 0, viewMenuButton.getHeight()); } - }); - } else { // After Windows Me - // View button group - ButtonGroup viewButtonGroup = new ButtonGroup(); - - // Popup Menu - final JPopupMenu viewTypePopupMenu = new JPopupMenu(); - - final JRadioButtonMenuItem listViewMenuItem = new JRadioButtonMenuItem( - filePane.getViewTypeAction(FilePane.VIEWTYPE_LIST)); - listViewMenuItem.setSelected(filePane.getViewType() == FilePane.VIEWTYPE_LIST); - viewTypePopupMenu.add(listViewMenuItem); - viewButtonGroup.add(listViewMenuItem); - - final JRadioButtonMenuItem detailsViewMenuItem = new JRadioButtonMenuItem( - filePane.getViewTypeAction(FilePane.VIEWTYPE_DETAILS)); - detailsViewMenuItem.setSelected(filePane.getViewType() == FilePane.VIEWTYPE_DETAILS); - viewTypePopupMenu.add(detailsViewMenuItem); - viewButtonGroup.add(detailsViewMenuItem); - - // Create icon for viewMenuButton - BufferedImage image = new BufferedImage(viewMenuIcon.getIconWidth() + 7, viewMenuIcon.getIconHeight(), - BufferedImage.TYPE_INT_ARGB); - Graphics graphics = image.getGraphics(); - viewMenuIcon.paintIcon(filePane, graphics, 0, 0); - int x = image.getWidth() - 5; - int y = image.getHeight() / 2 - 1; - graphics.setColor(Color.BLACK); - graphics.fillPolygon(new int[]{x, x + 5, x + 2}, new int[]{y, y, y + 3}, 3); - - // Details Button - final JButton viewMenuButton = new JButton(new ImageIcon(image)); - viewMenuButton.setToolTipText(viewMenuButtonToolTipText); - viewMenuButton.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, viewMenuButtonAccessibleName); - viewMenuButton.putClientProperty(WindowsLookAndFeel.HI_RES_DISABLED_ICON_CLIENT_KEY, Boolean.TRUE); - viewMenuButton.setFocusable(false); - viewMenuButton.setAlignmentX(JComponent.LEFT_ALIGNMENT); - viewMenuButton.setAlignmentY(JComponent.CENTER_ALIGNMENT); - viewMenuButton.setMargin(shrinkwrap); - viewMenuButton.setModel(new DefaultButtonModel() { - public void setPressed(boolean b) { + } + }); + viewMenuButton.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + // Forbid keyboard actions if the button is not in rollover state + if (e.getKeyCode() == KeyEvent.VK_SPACE && viewMenuButton.getModel().isRollover()) { + viewMenuButton.setSelected(true); + + viewTypePopupMenu.show(viewMenuButton, 0, viewMenuButton.getHeight()); } + } + }); + viewTypePopupMenu.addPopupMenuListener(new PopupMenuListener() { + public void popupMenuWillBecomeVisible(PopupMenuEvent e) { + } - public void setArmed(boolean b) { - } + public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { + SwingUtilities.invokeLater(new Runnable() { + public void run() { + viewMenuButton.setSelected(false); + } + }); + } - public void setSelected(boolean b) { - super.setSelected(b); + public void popupMenuCanceled(PopupMenuEvent e) { + } + }); - if (b) { - stateMask |= PRESSED | ARMED; - } else { - stateMask &= ~(PRESSED | ARMED); - } - } - }); - viewMenuButton.addMouseListener(new MouseAdapter() { - public void mousePressed(MouseEvent e) { - if (SwingUtilities.isLeftMouseButton(e)) { - viewMenuButton.setSelected(!viewMenuButton.isSelected()); - - if (viewMenuButton.isSelected()) { - viewTypePopupMenu.show(viewMenuButton, 0, viewMenuButton.getHeight()); - } - } - } - }); - viewTypePopupMenu.addPopupMenuListener(new PopupMenuListener() { - public void popupMenuWillBecomeVisible(PopupMenuEvent e) { - } + topPanel.add(viewMenuButton); - public void popupMenuWillBecomeInvisible(PopupMenuEvent e) { - SwingUtilities.invokeLater(new Runnable() { - public void run() { - viewMenuButton.setSelected(false); - } - }); - } + topPanel.add(Box.createRigidArea(new Dimension(80, 0))); - public void popupMenuCanceled(PopupMenuEvent e) { - } - }); - topPanel.add(viewMenuButton); - - topPanel.add(Box.createRigidArea(new Dimension(80, 0))); - - filePane.addPropertyChangeListener(new PropertyChangeListener() { - public void propertyChange(PropertyChangeEvent e) { - if ("viewType".equals(e.getPropertyName())) { - switch (filePane.getViewType()) { - case FilePane.VIEWTYPE_LIST: - listViewMenuItem.setSelected(true); - break; - - case FilePane.VIEWTYPE_DETAILS: - detailsViewMenuItem.setSelected(true); - break; - } + filePane.addPropertyChangeListener(new PropertyChangeListener() { + public void propertyChange(PropertyChangeEvent e) { + if ("viewType".equals(e.getPropertyName())) { + switch (filePane.getViewType()) { + case FilePane.VIEWTYPE_LIST: + listViewMenuItem.setSelected(true); + break; + + case FilePane.VIEWTYPE_DETAILS: + detailsViewMenuItem.setSelected(true); + break; } } - }); - } + } + }); // ************************************** // // ******* Add the directory pane ******* // @@ -622,19 +493,18 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { // Decide whether to use the ShellFolder class to populate shortcut // panel and combobox. JFileChooser fc = getFileChooser(); - if (OS_VERSION.compareTo(OSInfo.WINDOWS_ME) >= 0) { - if (FilePane.usesShellFolder(fc)) { - if (placesBar == null && !UIManager.getBoolean("FileChooser.noPlacesBar")) { - placesBar = new WindowsPlacesBar(fc, XPStyle.getXP() != null); - fc.add(placesBar, BorderLayout.BEFORE_LINE_BEGINS); - fc.addPropertyChangeListener(placesBar); - } - } else { - if (placesBar != null) { - fc.remove(placesBar); - fc.removePropertyChangeListener(placesBar); - placesBar = null; - } + + if (FilePane.usesShellFolder(fc)) { + if (placesBar == null && !UIManager.getBoolean("FileChooser.noPlacesBar")) { + placesBar = new WindowsPlacesBar(fc, XPStyle.getXP() != null); + fc.add(placesBar, BorderLayout.BEFORE_LINE_BEGINS); + fc.addPropertyChangeListener(placesBar); + } + } else { + if (placesBar != null) { + fc.remove(placesBar); + fc.removePropertyChangeListener(placesBar); + placesBar = null; } } } @@ -673,18 +543,9 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { upFolderToolTipText = UIManager.getString("FileChooser.upFolderToolTipText",l); upFolderAccessibleName = UIManager.getString("FileChooser.upFolderAccessibleName",l); - homeFolderToolTipText = UIManager.getString("FileChooser.homeFolderToolTipText",l); - homeFolderAccessibleName = UIManager.getString("FileChooser.homeFolderAccessibleName",l); - newFolderToolTipText = UIManager.getString("FileChooser.newFolderToolTipText",l); newFolderAccessibleName = UIManager.getString("FileChooser.newFolderAccessibleName",l); - listViewButtonToolTipText = UIManager.getString("FileChooser.listViewButtonToolTipText",l); - listViewButtonAccessibleName = UIManager.getString("FileChooser.listViewButtonAccessibleName",l); - - detailsViewButtonToolTipText = UIManager.getString("FileChooser.detailsViewButtonToolTipText",l); - detailsViewButtonAccessibleName = UIManager.getString("FileChooser.detailsViewButtonAccessibleName",l); - viewMenuButtonToolTipText = UIManager.getString("FileChooser.viewMenuButtonToolTipText",l); viewMenuButtonAccessibleName = UIManager.getString("FileChooser.viewMenuButtonAccessibleName",l); } @@ -1052,6 +913,65 @@ public class WindowsFileChooserUI extends BasicFileChooserUI { return new DirectoryComboBoxRenderer(); } + private static JButton createToolButton(Action a, Icon defaultIcon, String toolTipText, String accessibleName) { + final JButton result = new JButton(a); + + result.setText(null); + result.setIcon(defaultIcon); + result.setToolTipText(toolTipText); + result.setRequestFocusEnabled(false); + result.putClientProperty(AccessibleContext.ACCESSIBLE_NAME_PROPERTY, accessibleName); + result.putClientProperty(WindowsLookAndFeel.HI_RES_DISABLED_ICON_CLIENT_KEY, Boolean.TRUE); + result.setAlignmentX(JComponent.LEFT_ALIGNMENT); + result.setAlignmentY(JComponent.CENTER_ALIGNMENT); + result.setMargin(shrinkwrap); + result.setFocusPainted(false); + + result.setModel(new DefaultButtonModel() { + public void setPressed(boolean b) { + // Forbid keyboard actions if the button is not in rollover state + if (!b || isRollover()) { + super.setPressed(b); + } + } + + public void setRollover(boolean b) { + if (b && !isRollover()) { + // Reset other buttons + for (Component component : result.getParent().getComponents()) { + if (component instanceof JButton && component != result) { + ((JButton) component).getModel().setRollover(false); + } + } + } + + super.setRollover(b); + } + + public void setSelected(boolean b) { + super.setSelected(b); + + if (b) { + stateMask |= PRESSED | ARMED; + } else { + stateMask &= ~(PRESSED | ARMED); + } + } + }); + + result.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + result.getModel().setRollover(true); + } + + public void focusLost(FocusEvent e) { + result.getModel().setRollover(false); + } + }); + + return result; + } + // // Renderer for DirectoryComboBox // diff --git a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java index e24067efad15f4c3492d5fe5d654ed24bbd46fad..c388f80e6a45cf522ee92db4f7831e9f98f4c4f1 100644 --- a/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java +++ b/src/share/classes/com/sun/java/swing/plaf/windows/WindowsLookAndFeel.java @@ -1,5 +1,5 @@ /* - * Copyright 1997-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1997-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -104,7 +104,6 @@ public class WindowsLookAndFeel extends BasicLookAndFeel new StringUIClientPropertyKey( "WindowsLookAndFeel.generateHiResDisabledIcon"); - private Toolkit toolkit; private boolean updatePending = false; private boolean useSystemFontSettings = true; @@ -149,7 +148,6 @@ public class WindowsLookAndFeel extends BasicLookAndFeel public void initialize() { super.initialize(); - toolkit = Toolkit.getDefaultToolkit(); // Set the flag which determines which version of Windows should // be rendered. This flag only need to be set once. @@ -470,80 +468,61 @@ public class WindowsLookAndFeel extends BasicLookAndFeel Object ControlBackgroundColor = new DesktopProperty( "win.3d.backgroundColor", - table.get("control"), - toolkit); + table.get("control")); Object ControlLightColor = new DesktopProperty( "win.3d.lightColor", - table.get("controlHighlight"), - toolkit); + table.get("controlHighlight")); Object ControlHighlightColor = new DesktopProperty( "win.3d.highlightColor", - table.get("controlLtHighlight"), - toolkit); + table.get("controlLtHighlight")); Object ControlShadowColor = new DesktopProperty( "win.3d.shadowColor", - table.get("controlShadow"), - toolkit); + table.get("controlShadow")); Object ControlDarkShadowColor = new DesktopProperty( "win.3d.darkShadowColor", - table.get("controlDkShadow"), - toolkit); + table.get("controlDkShadow")); Object ControlTextColor = new DesktopProperty( "win.button.textColor", - table.get("controlText"), - toolkit); + table.get("controlText")); Object MenuBackgroundColor = new DesktopProperty( "win.menu.backgroundColor", - table.get("menu"), - toolkit); + table.get("menu")); Object MenuBarBackgroundColor = new DesktopProperty( "win.menubar.backgroundColor", - table.get("menu"), - toolkit); + table.get("menu")); Object MenuTextColor = new DesktopProperty( "win.menu.textColor", - table.get("menuText"), - toolkit); + table.get("menuText")); Object SelectionBackgroundColor = new DesktopProperty( "win.item.highlightColor", - table.get("textHighlight"), - toolkit); + table.get("textHighlight")); Object SelectionTextColor = new DesktopProperty( "win.item.highlightTextColor", - table.get("textHighlightText"), - toolkit); + table.get("textHighlightText")); Object WindowBackgroundColor = new DesktopProperty( "win.frame.backgroundColor", - table.get("window"), - toolkit); + table.get("window")); Object WindowTextColor = new DesktopProperty( "win.frame.textColor", - table.get("windowText"), - toolkit); + table.get("windowText")); Object WindowBorderWidth = new DesktopProperty( "win.frame.sizingBorderWidth", - Integer.valueOf(1), - toolkit); + Integer.valueOf(1)); Object TitlePaneHeight = new DesktopProperty( "win.frame.captionHeight", - Integer.valueOf(18), - toolkit); + Integer.valueOf(18)); Object TitleButtonWidth = new DesktopProperty( "win.frame.captionButtonWidth", - Integer.valueOf(16), - toolkit); + Integer.valueOf(16)); Object TitleButtonHeight = new DesktopProperty( "win.frame.captionButtonHeight", - Integer.valueOf(16), - toolkit); + Integer.valueOf(16)); Object InactiveTextColor = new DesktopProperty( "win.text.grayedTextColor", - table.get("textInactiveText"), - toolkit); + table.get("textInactiveText")); Object ScrollbarBackgroundColor = new DesktopProperty( "win.scrollbar.backgroundColor", - table.get("scrollbar"), - toolkit); + table.get("scrollbar")); Object TextBackground = new XPColorValue(Part.EP_EDIT, null, Prop.FILLCOLOR, WindowBackgroundColor); @@ -566,32 +545,22 @@ public class WindowsLookAndFeel extends BasicLookAndFeel Object ToolTipFont = sansSerifPlain12; Object IconFont = ControlFont; - Object scrollBarWidth = new DesktopProperty("win.scrollbar.width", - Integer.valueOf(16), toolkit); + Object scrollBarWidth = new DesktopProperty("win.scrollbar.width", Integer.valueOf(16)); - Object menuBarHeight = new DesktopProperty("win.menu.height", - null, toolkit); + Object menuBarHeight = new DesktopProperty("win.menu.height", null); - Object hotTrackingOn = new DesktopProperty("win.item.hotTrackingOn", - true, toolkit); + Object hotTrackingOn = new DesktopProperty("win.item.hotTrackingOn", true); - Object showMnemonics = new DesktopProperty("win.menu.keyboardCuesOn", - Boolean.TRUE, toolkit); + Object showMnemonics = new DesktopProperty("win.menu.keyboardCuesOn", Boolean.TRUE); if (useSystemFontSettings) { - MenuFont = getDesktopFontValue("win.menu.font", MenuFont, toolkit); - FixedControlFont = getDesktopFontValue("win.ansiFixed.font", - FixedControlFont, toolkit); - ControlFont = getDesktopFontValue("win.defaultGUI.font", - ControlFont, toolkit); - MessageFont = getDesktopFontValue("win.messagebox.font", - MessageFont, toolkit); - WindowFont = getDesktopFontValue("win.frame.captionFont", - WindowFont, toolkit); - IconFont = getDesktopFontValue("win.icon.font", - IconFont, toolkit); - ToolTipFont = getDesktopFontValue("win.tooltip.font", ToolTipFont, - toolkit); + MenuFont = getDesktopFontValue("win.menu.font", MenuFont); + FixedControlFont = getDesktopFontValue("win.ansiFixed.font", FixedControlFont); + ControlFont = getDesktopFontValue("win.defaultGUI.font", ControlFont); + MessageFont = getDesktopFontValue("win.messagebox.font", MessageFont); + WindowFont = getDesktopFontValue("win.frame.captionFont", WindowFont); + IconFont = getDesktopFontValue("win.icon.font", IconFont); + ToolTipFont = getDesktopFontValue("win.tooltip.font", ToolTipFont); /* Put the desktop AA settings in the defaults. * JComponent.setUI() retrieves this and makes it available @@ -605,26 +574,14 @@ public class WindowsLookAndFeel extends BasicLookAndFeel new FontDesktopProperty(SunToolkit.DESKTOPFONTHINTS); } if (useSystemFontSizeSettings) { - MenuFont = new WindowsFontSizeProperty("win.menu.font.height", - toolkit, Font.DIALOG, Font.PLAIN, 12); - FixedControlFont = new WindowsFontSizeProperty( - "win.ansiFixed.font.height", toolkit, Font.MONOSPACED, + MenuFont = new WindowsFontSizeProperty("win.menu.font.height", Font.DIALOG, Font.PLAIN, 12); + FixedControlFont = new WindowsFontSizeProperty("win.ansiFixed.font.height", Font.MONOSPACED, Font.PLAIN, 12); - ControlFont = new WindowsFontSizeProperty( - "win.defaultGUI.font.height", toolkit, Font.DIALOG, - Font.PLAIN, 12); - MessageFont = new WindowsFontSizeProperty( - "win.messagebox.font.height", - toolkit, Font.DIALOG, Font.PLAIN, 12); - WindowFont = new WindowsFontSizeProperty( - "win.frame.captionFont.height", toolkit, - Font.DIALOG, Font.BOLD, 12); - ToolTipFont = new WindowsFontSizeProperty( - "win.tooltip.font.height", toolkit, Font.SANS_SERIF, - Font.PLAIN, 12); - IconFont = new WindowsFontSizeProperty( - "win.icon.font.height", toolkit, Font.DIALOG, - Font.PLAIN, 12); + ControlFont = new WindowsFontSizeProperty("win.defaultGUI.font.height", Font.DIALOG, Font.PLAIN, 12); + MessageFont = new WindowsFontSizeProperty("win.messagebox.font.height", Font.DIALOG, Font.PLAIN, 12); + WindowFont = new WindowsFontSizeProperty("win.frame.captionFont.height", Font.DIALOG, Font.BOLD, 12); + ToolTipFont = new WindowsFontSizeProperty("win.tooltip.font.height", Font.SANS_SERIF, Font.PLAIN, 12); + IconFont = new WindowsFontSizeProperty("win.icon.font.height", Font.DIALOG, Font.PLAIN, 12); } @@ -752,8 +709,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel // DeskTop. "Desktop.background", new DesktopProperty( "win.desktop.backgroundColor", - table.get("desktop"), - toolkit), + table.get("desktop")), "Desktop.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ctrl F5", "restore", @@ -819,7 +775,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "FileChooser.filesOfTypeLabelMnemonic", Integer.valueOf(KeyEvent.VK_T), "FileChooser.usesSingleFilePane", Boolean.TRUE, "FileChooser.noPlacesBar", new DesktopProperty("win.comdlg.noPlacesBar", - Boolean.FALSE, toolkit), + Boolean.FALSE), "FileChooser.ancestorInputMap", new UIDefaults.LazyInputMap(new Object[] { "ESCAPE", "cancelSelection", @@ -861,36 +817,28 @@ public class WindowsLookAndFeel extends BasicLookAndFeel "InternalFrame.resizeIconShadow", ControlShadowColor, "InternalFrame.activeBorderColor", new DesktopProperty( "win.frame.activeBorderColor", - table.get("windowBorder"), - toolkit), + table.get("windowBorder")), "InternalFrame.inactiveBorderColor", new DesktopProperty( "win.frame.inactiveBorderColor", - table.get("windowBorder"), - toolkit), + table.get("windowBorder")), "InternalFrame.activeTitleBackground", new DesktopProperty( "win.frame.activeCaptionColor", - table.get("activeCaption"), - toolkit), + table.get("activeCaption")), "InternalFrame.activeTitleGradient", new DesktopProperty( "win.frame.activeCaptionGradientColor", - table.get("activeCaption"), - toolkit), + table.get("activeCaption")), "InternalFrame.activeTitleForeground", new DesktopProperty( "win.frame.captionTextColor", - table.get("activeCaptionText"), - toolkit), + table.get("activeCaptionText")), "InternalFrame.inactiveTitleBackground", new DesktopProperty( "win.frame.inactiveCaptionColor", - table.get("inactiveCaption"), - toolkit), + table.get("inactiveCaption")), "InternalFrame.inactiveTitleGradient", new DesktopProperty( "win.frame.inactiveCaptionGradientColor", - table.get("inactiveCaption"), - toolkit), + table.get("inactiveCaption")), "InternalFrame.inactiveTitleForeground", new DesktopProperty( "win.frame.inactiveCaptionTextColor", - table.get("inactiveCaptionText"), - toolkit), + table.get("inactiveCaptionText")), "InternalFrame.maximizeIcon", WindowsIconFactory.createFrameMaximizeIcon(), @@ -1529,12 +1477,8 @@ public class WindowsLookAndFeel extends BasicLookAndFeel // *** ToolTip "ToolTip.font", ToolTipFont, - "ToolTip.background", new DesktopProperty( - "win.tooltip.backgroundColor", - table.get("info"), toolkit), - "ToolTip.foreground", new DesktopProperty( - "win.tooltip.textColor", - table.get("infoText"), toolkit), + "ToolTip.background", new DesktopProperty("win.tooltip.backgroundColor", table.get("info")), + "ToolTip.foreground", new DesktopProperty("win.tooltip.textColor", table.get("infoText")), // *** ToolTipManager "ToolTipManager.enableToolTipMode", "activeApplication", @@ -1798,10 +1742,9 @@ public class WindowsLookAndFeel extends BasicLookAndFeel * represented in the current encoding this will return null and * turn off the use of system fonts. */ - private Object getDesktopFontValue(String fontName, Object backup, - Toolkit kit) { + private Object getDesktopFontValue(String fontName, Object backup) { if (useSystemFontSettings) { - return new WindowsFontProperty(fontName, backup, kit); + return new WindowsFontProperty(fontName, backup); } return null; } @@ -1989,7 +1932,6 @@ public class WindowsLookAndFeel extends BasicLookAndFeel public void uninitialize() { super.uninitialize(); - toolkit = null; if (WindowsPopupMenuUI.mnemonicListener != null) { MenuSelectionManager.defaultManager(). @@ -2309,8 +2251,8 @@ public class WindowsLookAndFeel extends BasicLookAndFeel * is returned, it is mapped to 'Microsoft Sans Serif'. */ private static class WindowsFontProperty extends DesktopProperty { - WindowsFontProperty(String key, Object backup, Toolkit kit) { - super(key, backup, kit); + WindowsFontProperty(String key, Object backup) { + super(key, backup); } public void invalidate(LookAndFeel laf) { @@ -2372,9 +2314,9 @@ public class WindowsLookAndFeel extends BasicLookAndFeel private int fontSize; private int fontStyle; - WindowsFontSizeProperty(String key, Toolkit toolkit, String fontName, + WindowsFontSizeProperty(String key, String fontName, int fontStyle, int fontSize) { - super(key, null, toolkit); + super(key, null); this.fontName = fontName; this.fontSize = fontSize; this.fontStyle = fontStyle; @@ -2508,7 +2450,7 @@ public class WindowsLookAndFeel extends BasicLookAndFeel private class TriggerDesktopProperty extends DesktopProperty { TriggerDesktopProperty(String key) { - super(key, null, toolkit); + super(key, null); // This call adds a property change listener for the property, // which triggers a call to updateUI(). The value returned // is not interesting here. diff --git a/src/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java b/src/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java index 7192405745f5261cd7dd4dc80dbccbaa73227e78..e0512a33b875585fa751173dff388e795469bc92 100644 --- a/src/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java +++ b/src/share/classes/com/sun/net/ssl/internal/www/protocol/https/DelegateHttpsURLConnection.java @@ -1,5 +1,5 @@ /* - * Copyright 2001-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -116,7 +116,10 @@ class VerifierWrapper implements javax.net.ssl.HostnameVerifier { try { String serverName; Principal principal = getPeerPrincipal(session); - if (principal instanceof KerberosPrincipal) { + // X.500 principal or Kerberos principal. + // (Use ciphersuite check to determine whether Kerberos is present.) + if (session.getCipherSuite().startsWith("TLS_KRB5") && + principal instanceof KerberosPrincipal) { serverName = HostnameChecker.getServerName((KerberosPrincipal)principal); } else { diff --git a/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java b/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java index 002d20785ff45dcc52fff642db6f4e5406d6f0da..1ebeb565ddbc651bb48351df81ec105bd060c799 100644 --- a/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java +++ b/src/share/classes/com/sun/rowset/JdbcRowSetResourceBundle.java @@ -133,7 +133,7 @@ public class JdbcRowSetResourceBundle implements Serializable { * This method returns an enumerated handle of the keys * which correspond to values translated to various locales. * - * @returns an enumerated keys which have messages tranlated to + * @return an enumeration of keys which have messages tranlated to * corresponding locales. */ public Enumeration getKeys() { @@ -146,7 +146,7 @@ public class JdbcRowSetResourceBundle implements Serializable { * returns the corresponding value reading it * from the Resource Bundle loaded earlier. * - * @returns value in locale specific language + * @return value in locale specific language * according to the key passed. */ public Object handleGetObject(String key) { diff --git a/src/share/classes/com/sun/rowset/JoinRowSetImpl.java b/src/share/classes/com/sun/rowset/JoinRowSetImpl.java index 7908848b2974be904947a15f01fc3c05ccc29f7d..d301c605cdb829526a5c902d1e12c374467a5530 100644 --- a/src/share/classes/com/sun/rowset/JoinRowSetImpl.java +++ b/src/share/classes/com/sun/rowset/JoinRowSetImpl.java @@ -3737,7 +3737,6 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet { * Returns a result set containing the original value of the current * row only. * - * @return the original result set of the row * @throws SQLException if there is no current row * @see #setOriginalRow */ diff --git a/src/share/classes/com/sun/rowset/internal/WebRowSetXmlReader.java b/src/share/classes/com/sun/rowset/internal/WebRowSetXmlReader.java index 8db17537187b108c21780b6d9db789a500f6ed51..f25cec7e62e0fae47927ac9c3686e17745b885d7 100644 --- a/src/share/classes/com/sun/rowset/internal/WebRowSetXmlReader.java +++ b/src/share/classes/com/sun/rowset/internal/WebRowSetXmlReader.java @@ -46,6 +46,17 @@ import javax.sql.rowset.spi.*; */ public class WebRowSetXmlReader implements XmlReader, Serializable { + + private JdbcRowSetResourceBundle resBundle; + + public WebRowSetXmlReader(){ + try { + resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle(); + } catch(IOException ioe) { + throw new RuntimeException(ioe); + } + } + /** * Parses the given WebRowSet object, getting its input from * the given java.io.Reader object. The parser will send @@ -69,17 +80,6 @@ public class WebRowSetXmlReader implements XmlReader, Serializable { * reader for the given rowset * @see XmlReaderContentHandler */ - - private JdbcRowSetResourceBundle resBundle; - - public WebRowSetXmlReader(){ - try { - resBundle = JdbcRowSetResourceBundle.getJdbcRowSetResourceBundle(); - } catch(IOException ioe) { - throw new RuntimeException(ioe); - } - } - public void readXML(WebRowSet caller, java.io.Reader reader) throws SQLException { try { // Crimson Parser(as in J2SE 1.4.1 is NOT able to handle diff --git a/src/share/classes/java/awt/Component.java b/src/share/classes/java/awt/Component.java index 3ecf30c51d5f01d504fe0cdfefc45bc5a2f5717a..7c73f27ee6108286b89c45a447d59bb1b1727bed 100644 --- a/src/share/classes/java/awt/Component.java +++ b/src/share/classes/java/awt/Component.java @@ -6665,6 +6665,9 @@ public abstract class Component implements ImageObserver, MenuContainer, Container parent = this.parent; if (parent != null && parent.peer instanceof LightweightPeer) { relocateComponent(); + if (!isRecursivelyVisible()) { + peer.setVisible(false); + } } } invalidate(); @@ -9572,6 +9575,13 @@ public abstract class Component implements ImageObserver, MenuContainer, return comp.getPeer(); } } + // traversing the hierarchy up to the closest HW container; + // further traversing may return a component that is not actually + // a native sibling of this component and this kind of z-order + // request may not be allowed by the underlying system (6852051). + if (!cont.isLightweight()) { + break; + } indexAbove = cont.getSiblingIndexAbove(); cont = cont.getContainer(); diff --git a/src/share/classes/java/awt/Dialog.java b/src/share/classes/java/awt/Dialog.java index 4660e6ea07c5b60f6bdbe86a6816ee2729b2ecc5..b897183ca8b4cfaee2b4a13e86cd0f78032b0a14 100644 --- a/src/share/classes/java/awt/Dialog.java +++ b/src/share/classes/java/awt/Dialog.java @@ -856,7 +856,7 @@ public class Dialog extends Window { if (type == ModalityType.TOOLKIT_MODAL) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(SecurityConstants.TOOLKIT_MODALITY_PERMISSION); + sm.checkPermission(SecurityConstants.AWT.TOOLKIT_MODALITY_PERMISSION); } } modalityType = type; diff --git a/src/share/classes/java/awt/MouseInfo.java b/src/share/classes/java/awt/MouseInfo.java index dce20bc0b84bce09108f7aee96f9a79ab0376b07..8905ecaee9cf959d2b992b2a6d60981b296342e2 100644 --- a/src/share/classes/java/awt/MouseInfo.java +++ b/src/share/classes/java/awt/MouseInfo.java @@ -76,7 +76,7 @@ public class MouseInfo { SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.WATCH_MOUSE_PERMISSION); + security.checkPermission(SecurityConstants.AWT.WATCH_MOUSE_PERMISSION); } Point point = new Point(0, 0); diff --git a/src/share/classes/java/awt/Robot.java b/src/share/classes/java/awt/Robot.java index c9a32e2d01d542239076df0a2ad0fec063149ccb..d262910a22040fbd00b226fa7a29b831cb5104ca 100644 --- a/src/share/classes/java/awt/Robot.java +++ b/src/share/classes/java/awt/Robot.java @@ -167,7 +167,7 @@ public class Robot { private void checkRobotAllowed() { SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.CREATE_ROBOT_PERMISSION); + security.checkPermission(SecurityConstants.AWT.CREATE_ROBOT_PERMISSION); } } @@ -466,7 +466,7 @@ public class Robot { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkPermission( - SecurityConstants.READ_DISPLAY_PIXELS_PERMISSION); + SecurityConstants.AWT.READ_DISPLAY_PIXELS_PERMISSION); } } diff --git a/src/share/classes/java/awt/SystemTray.java b/src/share/classes/java/awt/SystemTray.java index 2aa172108b1c71c5940d9369ffa396afe5c2bd1e..91cffdce9f23e3ad85670d0e36ea90bd6ff3d14a 100644 --- a/src/share/classes/java/awt/SystemTray.java +++ b/src/share/classes/java/awt/SystemTray.java @@ -490,7 +490,7 @@ public class SystemTray { static void checkSystemTrayAllowed() { SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.ACCESS_SYSTEM_TRAY_PERMISSION); + security.checkPermission(SecurityConstants.AWT.ACCESS_SYSTEM_TRAY_PERMISSION); } } diff --git a/src/share/classes/java/awt/Toolkit.java b/src/share/classes/java/awt/Toolkit.java index aaa6afdd5a08993f1956ad5425c4651ea49340ef..129b1f0102da64b902cb04dc3c6309f58e8b5213 100644 --- a/src/share/classes/java/awt/Toolkit.java +++ b/src/share/classes/java/awt/Toolkit.java @@ -2025,7 +2025,7 @@ public abstract class Toolkit { } SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION); + security.checkPermission(SecurityConstants.AWT.ALL_AWT_EVENTS_PERMISSION); } synchronized (this) { SelectiveAWTEventListener selectiveListener = @@ -2094,7 +2094,7 @@ public abstract class Toolkit { } SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION); + security.checkPermission(SecurityConstants.AWT.ALL_AWT_EVENTS_PERMISSION); } synchronized (this) { @@ -2165,7 +2165,7 @@ public abstract class Toolkit { public AWTEventListener[] getAWTEventListeners() { SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION); + security.checkPermission(SecurityConstants.AWT.ALL_AWT_EVENTS_PERMISSION); } synchronized (this) { EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class); @@ -2217,7 +2217,7 @@ public abstract class Toolkit { public AWTEventListener[] getAWTEventListeners(long eventMask) { SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.ALL_AWT_EVENTS_PERMISSION); + security.checkPermission(SecurityConstants.AWT.ALL_AWT_EVENTS_PERMISSION); } synchronized (this) { EventListener[] la = ToolkitEventMulticaster.getListeners(eventListener,AWTEventListener.class); diff --git a/src/share/classes/java/awt/Window.java b/src/share/classes/java/awt/Window.java index a342f37879f06ba3196c7bcc003df82227101c2b..c526107f4e80e1388bb3f7ddbf8ab4809d57a606 100644 --- a/src/share/classes/java/awt/Window.java +++ b/src/share/classes/java/awt/Window.java @@ -1581,7 +1581,7 @@ public class Window extends Container implements Accessible { if (exclusionType == Dialog.ModalExclusionType.TOOLKIT_EXCLUDE) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { - sm.checkPermission(SecurityConstants.TOOLKIT_MODALITY_PERMISSION); + sm.checkPermission(SecurityConstants.AWT.TOOLKIT_MODALITY_PERMISSION); } } modalExclusionType = exclusionType; @@ -2129,7 +2129,7 @@ public class Window extends Container implements Accessible { public final void setAlwaysOnTop(boolean alwaysOnTop) throws SecurityException { SecurityManager security = System.getSecurityManager(); if (security != null) { - security.checkPermission(SecurityConstants.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); + security.checkPermission(SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); } boolean oldAlwaysOnTop; diff --git a/src/share/classes/java/awt/color/ICC_Profile.java b/src/share/classes/java/awt/color/ICC_Profile.java index 84b8a8c63d3150e373bed1bb606ac693bc99d533..488e6f4d29925e7cb737ac3489ad792c472c5597 100644 --- a/src/share/classes/java/awt/color/ICC_Profile.java +++ b/src/share/classes/java/awt/color/ICC_Profile.java @@ -58,6 +58,8 @@ import java.util.StringTokenizer; import java.security.AccessController; import java.security.PrivilegedAction; +import sun.misc.BootClassLoaderHook; + /** * A representation of color profile data for device independent and * device dependent color spaces based on the International Color @@ -1830,8 +1832,19 @@ public class ICC_Profile implements Serializable { dir = st.nextToken(); fullPath = dir + File.separatorChar + fileName; f = new File(fullPath); - if (!isChildOf(f, dir)) { - f = null; + } + } + + if (!f.isFile()) { /* try the directory of built-in profiles */ + dir = System.getProperty("java.home") + + File.separatorChar + "lib" + File.separatorChar + "cmm"; + fullPath = dir + File.separatorChar + fileName; + f = new File(fullPath); + if (!f.isFile()) { + //make sure file was installed in the kernel mode + BootClassLoaderHook hook = BootClassLoaderHook.getHook(); + if (hook.getHook() != null) { + hook.prefetchFile("lib/cmm/"+fileName); } } } diff --git a/src/share/classes/java/lang/Boolean.java b/src/share/classes/java/lang/Boolean.java index b614dafdaae0bac7e9ec5bc86c88bd8f9f096e1d..8a3d6ab996ed3f07eeeec42a5ecc69829e32482f 100644 --- a/src/share/classes/java/lang/Boolean.java +++ b/src/share/classes/java/lang/Boolean.java @@ -255,7 +255,25 @@ public final class Boolean implements java.io.Serializable, * @since 1.5 */ public int compareTo(Boolean b) { - return (b.value == value ? 0 : (value ? 1 : -1)); + return compare(this.value, b.value); + } + + /** + * Compares two {@code boolean} values. + * The value returned is identical to what would be returned by: + *

+     *    Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
+     * 
+ * + * @param x the first {@code boolean} to compare + * @param y the second {@code boolean} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code !x && y}; and + * a value greater than {@code 0} if {@code x && !y} + * @since 1.7 + */ + public static int compare(boolean x, boolean y) { + return (x == y) ? 0 : (x ? 1 : -1); } private static boolean toBoolean(String name) { diff --git a/src/share/classes/java/lang/Byte.java b/src/share/classes/java/lang/Byte.java index 459c2237a18ca7aea65a86421d93207a8e265b3e..4725f3278b79750c31cc8b8f83bf95c8119a51ee 100644 --- a/src/share/classes/java/lang/Byte.java +++ b/src/share/classes/java/lang/Byte.java @@ -378,7 +378,10 @@ public final class Byte extends Number implements Comparable { } /** - * Returns a hash code for this {@code Byte}. + * Returns a hash code for this {@code Byte}; equal to the result + * of invoking {@code intValue()}. + * + * @return a hash code value for this {@code Byte} */ public int hashCode() { return (int)value; @@ -415,7 +418,25 @@ public final class Byte extends Number implements Comparable { * @since 1.2 */ public int compareTo(Byte anotherByte) { - return this.value - anotherByte.value; + return compare(this.value, anotherByte.value); + } + + /** + * Compares two {@code byte} values numerically. + * The value returned is identical to what would be returned by: + *
+     *    Byte.valueOf(x).compareTo(Byte.valueOf(y))
+     * 
+ * + * @param x the first {@code byte} to compare + * @param y the second {@code byte} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(byte x, byte y) { + return x - y; } /** diff --git a/src/share/classes/java/lang/Character.java b/src/share/classes/java/lang/Character.java index bc4284c20df9695b0a43d8f808b3b60b31a5c593..8f106a473ddce87dc0e620b8e52fc3d687a71f7d 100644 --- a/src/share/classes/java/lang/Character.java +++ b/src/share/classes/java/lang/Character.java @@ -2612,8 +2612,10 @@ class Character extends Object implements java.io.Serializable, ComparableCharacter. - * @return a hash code value for this object. + * Returns a hash code for this {@code Character}; equal to the result + * of invoking {@code charValue()}. + * + * @return a hash code value for this {@code Character} */ public int hashCode() { return (int)value; @@ -4962,7 +4964,25 @@ class Character extends Object implements java.io.Serializable, Comparable + * Character.valueOf(x).compareTo(Character.valueOf(y)) + *
+ * + * @param x the first {@code char} to compare + * @param y the second {@code char} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(char x, char y) { + return x - y; } /** diff --git a/src/share/classes/java/lang/Class.java b/src/share/classes/java/lang/Class.java index ddf5763179019e8e521c68bb76252f55a3328730..46414ad849164d034cbebf9d8de9a8cc64bbd090 100644 --- a/src/share/classes/java/lang/Class.java +++ b/src/share/classes/java/lang/Class.java @@ -565,8 +565,9 @@ public final * represented by this object. */ public String getName() { + String name = this.name; if (name == null) - name = getName0(); + this.name = name = getName0(); return name; } diff --git a/src/share/classes/java/lang/ClassLoader.java b/src/share/classes/java/lang/ClassLoader.java index 33236c00ff6c4e826650dfe11e66203ede8bb32c..323240b395c0f491ba40359ca3f729bd87892f5a 100644 --- a/src/share/classes/java/lang/ClassLoader.java +++ b/src/share/classes/java/lang/ClassLoader.java @@ -51,6 +51,7 @@ import java.util.Vector; import java.util.Hashtable; import java.util.WeakHashMap; import java.util.concurrent.ConcurrentHashMap; +import sun.misc.BootClassLoaderHook; import sun.misc.ClassFileTransformer; import sun.misc.CompoundEnumeration; import sun.misc.Resource; @@ -58,7 +59,6 @@ import sun.misc.URLClassPath; import sun.misc.VM; import sun.reflect.Reflection; import sun.security.util.SecurityConstants; -import sun.jkernel.DownloadManager; /** * A class loader is an object that is responsible for loading classes. The @@ -364,16 +364,28 @@ public abstract class ClassLoader { // First, check if the class has already been loaded Class c = findLoadedClass(name); if (c == null) { + long t0 = System.nanoTime(); try { if (parent != null) { c = parent.loadClass(name, false); } else { - c = findBootstrapClass0(name); + c = findBootstrapClassOrNull(name); } } catch (ClassNotFoundException e) { + // ClassNotFoundException thrown if class not found + // from the non-null parent class loader + } + + if (c == null) { // If still not found, then invoke findClass in order // to find the class. + long t1 = System.nanoTime(); c = findClass(name); + + // this is the defining class loader; record the stats + sun.misc.PerfCounter.getParentDelegationTime().addTime(t1 - t0); + sun.misc.PerfCounter.getFindClassTime().addElapsedTimeFrom(t1); + sun.misc.PerfCounter.getFindClasses().increment(); } } if (resolve) { @@ -987,21 +999,28 @@ public abstract class ClassLoader { if (system == null) { if (!checkName(name)) throw new ClassNotFoundException(name); - return findBootstrapClass(name); + Class cls = findBootstrapClass(name); + if (cls == null) { + throw new ClassNotFoundException(name); + } + return cls; } return system.loadClass(name); } - private Class findBootstrapClass0(String name) - throws ClassNotFoundException + /** + * Returns a class loaded by the bootstrap class loader; + * or return null if not found. + */ + private Class findBootstrapClassOrNull(String name) { - if (!checkName(name)) - throw new ClassNotFoundException(name); + if (!checkName(name)) return null; + return findBootstrapClass(name); } - private native Class findBootstrapClass(String name) - throws ClassNotFoundException; + // return null if not found + private native Class findBootstrapClass(String name); /** * Returns the class with the given binary name if this @@ -1250,21 +1269,7 @@ public abstract class ClassLoader { * Find resources from the VM's built-in classloader. */ private static URL getBootstrapResource(String name) { - try { - // If this is a known JRE resource, ensure that its bundle is - // downloaded. If it isn't known, we just ignore the download - // failure and check to see if we can find the resource anyway - // (which is possible if the boot class path has been modified). - if (sun.misc.VM.isBootedKernelVM()) { - sun.jkernel.DownloadManager.getBootClassPathEntryForResource( - name); - } - } catch (NoClassDefFoundError e) { - // This happens while Java itself is being compiled; DownloadManager - // isn't accessible when this code is first invoked. It isn't an - // issue, as if we can't find DownloadManager, we can safely assume - // that additional code is not available for download. - } + BootClassLoaderHook.preLoadResource(name); URLClassPath ucp = getBootstrapClassPath(); Resource res = ucp.getResource(name); return res != null ? res.getURL() : null; @@ -1781,24 +1786,7 @@ public abstract class ClassLoader { // Invoked in the java.lang.Runtime class to implement load and loadLibrary. static void loadLibrary(Class fromClass, String name, boolean isAbsolute) { - try { - if (VM.isBootedKernelVM() && !DownloadManager.isJREComplete() && - !DownloadManager.isCurrentThreadDownloading()) { - DownloadManager.downloadFile("bin/" + - System.mapLibraryName(name)); - // it doesn't matter if the downloadFile call returns false -- - // it probably just means that this is a user library, as - // opposed to a JRE library - } - } catch (IOException e) { - throw new UnsatisfiedLinkError("Error downloading library " + - name + ": " + e); - } catch (NoClassDefFoundError e) { - // This happens while Java itself is being compiled; DownloadManager - // isn't accessible when this code is first invoked. It isn't an - // issue, as if we can't find DownloadManager, we can safely assume - // that additional code is not available for download. - } + BootClassLoaderHook.preLoadLibrary(name); ClassLoader loader = (fromClass == null) ? null : fromClass.getClassLoader(); if (sys_paths == null) { @@ -2186,3 +2174,4 @@ class SystemClassLoaderAction return sys; } } + diff --git a/src/share/classes/java/lang/Integer.java b/src/share/classes/java/lang/Integer.java index a66a8fae792c27abc67035f81c4db4c56f4339c5..1c457c548e71f721ccbaa811c768819ee396c67f 100644 --- a/src/share/classes/java/lang/Integer.java +++ b/src/share/classes/java/lang/Integer.java @@ -1010,9 +1010,25 @@ public final class Integer extends Number implements Comparable { * @since 1.2 */ public int compareTo(Integer anotherInteger) { - int thisVal = this.value; - int anotherVal = anotherInteger.value; - return (thisVal + * Integer.valueOf(x).compareTo(Integer.valueOf(y)) + *
+ * + * @param x the first {@code int} to compare + * @param y the second {@code int} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(int x, int y) { + return (x < y) ? -1 : ((x == y) ? 0 : 1); } diff --git a/src/share/classes/java/lang/Long.java b/src/share/classes/java/lang/Long.java index 58014997f35862cf6c189a0afba3faa8d8131300..c5fd7ee5e298a7de9e9fc8040c95353aba7dc17e 100644 --- a/src/share/classes/java/lang/Long.java +++ b/src/share/classes/java/lang/Long.java @@ -950,9 +950,25 @@ public final class Long extends Number implements Comparable { * @since 1.2 */ public int compareTo(Long anotherLong) { - long thisVal = this.value; - long anotherVal = anotherLong.value; - return (thisVal + * Long.valueOf(x).compareTo(Long.valueOf(y)) + *
+ * + * @param x the first {@code long} to compare + * @param y the second {@code long} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(long x, long y) { + return (x < y) ? -1 : ((x == y) ? 0 : 1); } diff --git a/src/share/classes/java/lang/SecurityManager.java b/src/share/classes/java/lang/SecurityManager.java index ea0dd5ea998228da1ebef49e3cb90ac2ba8d35ad..9006588fa085bbbea2cf3bd80f5b670fa0f22298 100644 --- a/src/share/classes/java/lang/SecurityManager.java +++ b/src/share/classes/java/lang/SecurityManager.java @@ -1341,7 +1341,7 @@ class SecurityManager { throw new NullPointerException("window can't be null"); } try { - checkPermission(SecurityConstants.TOPLEVEL_WINDOW_PERMISSION); + checkPermission(SecurityConstants.AWT.TOPLEVEL_WINDOW_PERMISSION); return true; } catch (SecurityException se) { // just return false @@ -1391,7 +1391,7 @@ class SecurityManager { * @see #checkPermission(java.security.Permission) checkPermission */ public void checkSystemClipboardAccess() { - checkPermission(SecurityConstants.ACCESS_CLIPBOARD_PERMISSION); + checkPermission(SecurityConstants.AWT.ACCESS_CLIPBOARD_PERMISSION); } /** @@ -1412,7 +1412,7 @@ class SecurityManager { * @see #checkPermission(java.security.Permission) checkPermission */ public void checkAwtEventQueueAccess() { - checkPermission(SecurityConstants.CHECK_AWT_EVENTQUEUE_PERMISSION); + checkPermission(SecurityConstants.AWT.CHECK_AWT_EVENTQUEUE_PERMISSION); } /* diff --git a/src/share/classes/java/lang/Short.java b/src/share/classes/java/lang/Short.java index a2d98b277ee2357b47360444953d4a7fc417d1f5..cf1551da8e5d46a6128b4c6f82b77799254753e3 100644 --- a/src/share/classes/java/lang/Short.java +++ b/src/share/classes/java/lang/Short.java @@ -383,7 +383,10 @@ public final class Short extends Number implements Comparable { } /** - * Returns a hash code for this {@code Short}. + * Returns a hash code for this {@code Short}; equal to the result + * of invoking {@code intValue()}. + * + * @return a hash code value for this {@code Short} */ public int hashCode() { return (int)value; @@ -420,7 +423,25 @@ public final class Short extends Number implements Comparable { * @since 1.2 */ public int compareTo(Short anotherShort) { - return this.value - anotherShort.value; + return compare(this.value, anotherShort.value); + } + + /** + * Compares two {@code short} values numerically. + * The value returned is identical to what would be returned by: + *
+     *    Short.valueOf(x).compareTo(Short.valueOf(y))
+     * 
+ * + * @param x the first {@code short} to compare + * @param y the second {@code short} to compare + * @return the value {@code 0} if {@code x == y}; + * a value less than {@code 0} if {@code x < y}; and + * a value greater than {@code 0} if {@code x > y} + * @since 1.7 + */ + public static int compare(short x, short y) { + return x - y; } /** diff --git a/src/share/classes/java/lang/reflect/Constructor.java b/src/share/classes/java/lang/reflect/Constructor.java index bdd158a3eb8b167b2b068afc8ac68fe44b7c3377..ae812ad72f512f566ee4ec6a0f30535562c9e13b 100644 --- a/src/share/classes/java/lang/reflect/Constructor.java +++ b/src/share/classes/java/lang/reflect/Constructor.java @@ -275,10 +275,6 @@ public final * Returns an array of length 0 if the underlying method declares * no exceptions in its {@code throws} clause. * - *

If an exception type is a parameterized type, the {@code Type} - * object returned for it must accurately reflect the actual type - * parameters used in the source code. - * *

If an exception type is a type variable or a parameterized * type, it is created. Otherwise, it is resolved. * diff --git a/src/share/classes/java/lang/reflect/Method.java b/src/share/classes/java/lang/reflect/Method.java index 1c660f2dca8bc695fc29eb211faff2f8d5b51388..fc9e467ae48b3ee053046b8669b685075b789a47 100644 --- a/src/share/classes/java/lang/reflect/Method.java +++ b/src/share/classes/java/lang/reflect/Method.java @@ -317,10 +317,6 @@ public final * Returns an array of length 0 if the underlying method declares * no exceptions in its {@code throws} clause. * - *

If an exception type is a parameterized type, the {@code Type} - * object returned for it must accurately reflect the actual type - * parameters used in the source code. - * *

If an exception type is a type variable or a parameterized * type, it is created. Otherwise, it is resolved. * diff --git a/src/share/classes/java/net/CookieManager.java b/src/share/classes/java/net/CookieManager.java index 32790a8f185197b377903cb1c24bc837eb448a88..95de8c0db3bb9a40be2e0354f03c64da27a5a1bc 100644 --- a/src/share/classes/java/net/CookieManager.java +++ b/src/share/classes/java/net/CookieManager.java @@ -157,7 +157,7 @@ public class CookieManager extends CookieHandler // if not specify CookieStore to use, use default one if (store == null) { - cookieJar = new sun.net.www.protocol.http.InMemoryCookieStore(); + cookieJar = new InMemoryCookieStore(); } else { cookieJar = store; } diff --git a/src/share/classes/sun/net/www/protocol/http/InMemoryCookieStore.java b/src/share/classes/java/net/InMemoryCookieStore.java similarity index 99% rename from src/share/classes/sun/net/www/protocol/http/InMemoryCookieStore.java rename to src/share/classes/java/net/InMemoryCookieStore.java index 2e7b54f70c00577e24960d21531bb4a64db1a635..697ca88d7107d1f47efaa0ab51faa18afbbc1487 100644 --- a/src/share/classes/sun/net/www/protocol/http/InMemoryCookieStore.java +++ b/src/share/classes/java/net/InMemoryCookieStore.java @@ -23,7 +23,7 @@ * have any questions. */ -package sun.net.www.protocol.http; +package java.net; import java.net.URI; import java.net.CookieStore; @@ -43,7 +43,7 @@ import java.util.concurrent.locks.ReentrantLock; * @author Edward Wang * @since 1.6 */ -public class InMemoryCookieStore implements CookieStore { +class InMemoryCookieStore implements CookieStore { // the in-memory representation of cookies private List cookieJar = null; diff --git a/src/share/classes/java/net/URLClassLoader.java b/src/share/classes/java/net/URLClassLoader.java index 22be20b7ecd5fc43cfcc377d0060dc2a13edf661..c4f775db71a18703a81e4f0d6ec482a727bd95e2 100644 --- a/src/share/classes/java/net/URLClassLoader.java +++ b/src/share/classes/java/net/URLClassLoader.java @@ -340,6 +340,7 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { * used. */ private Class defineClass(String name, Resource res) throws IOException { + long t0 = System.nanoTime(); int i = name.lastIndexOf('.'); URL url = res.getCodeSourceURL(); if (i != -1) { @@ -370,12 +371,14 @@ public class URLClassLoader extends SecureClassLoader implements Closeable { // Use (direct) ByteBuffer: CodeSigner[] signers = res.getCodeSigners(); CodeSource cs = new CodeSource(url, signers); + sun.misc.PerfCounter.getReadClassBytesTime().addElapsedTimeFrom(t0); return defineClass(name, bb, cs); } else { byte[] b = res.getBytes(); // must read certificates AFTER reading bytes. CodeSigner[] signers = res.getCodeSigners(); CodeSource cs = new CodeSource(url, signers); + sun.misc.PerfCounter.getReadClassBytesTime().addElapsedTimeFrom(t0); return defineClass(name, b, 0, b.length, cs); } } diff --git a/src/share/classes/java/net/doc-files/net-properties.html b/src/share/classes/java/net/doc-files/net-properties.html index e6b6330ba42aa3e00ae63ca478b1ca523fc809e6..384abd8d93fce0b9a3f1f53f33574c78d0c6706d 100644 --- a/src/share/classes/java/net/doc-files/net-properties.html +++ b/src/share/classes/java/net/doc-files/net-properties.html @@ -71,12 +71,12 @@ of proxies.

  • HTTP

    The following proxy settings are used by the HTTP protocol handler.

      -
    • http.proxyHost (default: <none>)
      +

    • http.proxyHost (default: <none>)
      The hostname, or address, of the proxy server

    • http.proxyPort (default: 80)
      The port number of the proxy server.

      -
    • http.nonProxyHosts (default: <none>)
      +

    • http.nonProxyHosts (default: localhost|127.*|[::1])
      Indicates the hosts that should be accessed without going through the proxy. Typically this defines internal hosts. The value of this property is a list of hosts, @@ -86,7 +86,8 @@ of proxies.

      will indicate that every hosts in the foo.com domain and the localhost should be accessed directly even if a proxy server is specified.

      -
    +

    The default value excludes all common variations of the loopback address.

    +
  • HTTPS
    This is HTTP over SSL, a secure version of HTTP mainly used when confidentiality (like on payment sites) is needed.

    The following proxy settings are used by the HTTPS protocol handler.

    @@ -107,7 +108,7 @@ of proxies.

  • ftp.proxyPort (default: 80)
    The port number of the proxy server.

    -
  • ftp.nonProxyHosts (default: <none>)
    +

  • ftp.nonProxyHosts (default: localhost|127.*|[::1])
    Indicates the hosts that should be accessed without going through the proxy. Typically this defines internal hosts. The value of this property is a list of hosts, separated by @@ -117,6 +118,7 @@ of proxies.

    will indicate that every hosts in the foo.com domain and the localhost should be accessed directly even if a proxy server is specified.

    +

    The default value excludes all common variations of the loopback address.

  • SOCKS
    This is another type of proxy. It allows for lower level type of tunneling since it works at the TCP level. In effect, diff --git a/src/share/classes/java/nio/file/FileTreeWalker.java b/src/share/classes/java/nio/file/FileTreeWalker.java index 71cb86eb88a883606900dbb906b9f62086626694..1452bd66b2aa96dc2ad4ba190d947849493e17cf 100644 --- a/src/share/classes/java/nio/file/FileTreeWalker.java +++ b/src/share/classes/java/nio/file/FileTreeWalker.java @@ -41,8 +41,12 @@ class FileTreeWalker { private final boolean detectCycles; private final LinkOption[] linkOptions; private final FileVisitor visitor; + private final int maxDepth; - FileTreeWalker(Set options, FileVisitor visitor) { + FileTreeWalker(Set options, + FileVisitor visitor, + int maxDepth) + { boolean fl = false; boolean dc = false; for (FileVisitOption option: options) { @@ -58,18 +62,15 @@ class FileTreeWalker { this.linkOptions = (fl) ? new LinkOption[0] : new LinkOption[] { LinkOption.NOFOLLOW_LINKS }; this.visitor = visitor; + this.maxDepth = maxDepth; } /** * Walk file tree starting at the given file */ - void walk(Path start, int maxDepth) { - // don't use attributes of starting file as they may be stale - if (start instanceof BasicFileAttributesHolder) { - ((BasicFileAttributesHolder)start).invalidate(); - } + void walk(Path start) { FileVisitResult result = walk(start, - maxDepth, + 0, new ArrayList()); if (result == null) { throw new NullPointerException("Visitor returned 'null'"); @@ -89,12 +90,15 @@ class FileTreeWalker { List ancestors) { // depth check - if (depth-- < 0) + if (depth > maxDepth) return FileVisitResult.CONTINUE; // if attributes are cached then use them if possible BasicFileAttributes attrs = null; - if (file instanceof BasicFileAttributesHolder) { + if ((depth > 0) && + (file instanceof BasicFileAttributesHolder) && + (System.getSecurityManager() == null)) + { BasicFileAttributes cached = ((BasicFileAttributesHolder)file).get(); if (!followLinks || !cached.isSymbolicLink()) attrs = cached; @@ -120,6 +124,10 @@ class FileTreeWalker { } } } catch (SecurityException x) { + // If access to starting file is denied then SecurityException + // is thrown, otherwise the file is ignored. + if (depth == 0) + throw x; return FileVisitResult.CONTINUE; } } @@ -196,7 +204,7 @@ class FileTreeWalker { try { for (Path entry: stream) { inAction = true; - result = walk(entry, depth, ancestors); + result = walk(entry, depth+1, ancestors); inAction = false; // returning null will cause NPE to be thrown diff --git a/src/share/classes/java/nio/file/Files.java b/src/share/classes/java/nio/file/Files.java index 00e1014526c617b4335d2514ccd1d3fb8af35915..ca5bc5698e1db19ea601a3cd6bc6f4ca48c4bdfa 100644 --- a/src/share/classes/java/nio/file/Files.java +++ b/src/share/classes/java/nio/file/Files.java @@ -133,10 +133,11 @@ public final class Files { *

    This method walks a file tree rooted at a given starting file. The * file tree traversal is depth-first with the given {@link * FileVisitor} invoked for each file encountered. File tree traversal - * completes when all accessible files in the tree have been visited, a - * visitor returns a result of {@link FileVisitResult#TERMINATE TERMINATE}, - * or the visitor terminates due to an uncaught {@code Error} or {@code - * RuntimeException}. + * completes when all accessible files in the tree have been visited, or a + * visit method returns a result of {@link FileVisitResult#TERMINATE + * TERMINATE}. Where a visit method terminates due an uncaught error or + * runtime exception then the traversal is terminated and the error or + * exception is propagated to the caller of this method. * *

    For each file encountered this method attempts to gets its {@link * java.nio.file.attribute.BasicFileAttributes}. If the file is not a @@ -222,7 +223,7 @@ public final class Files { { if (maxDepth < 0) throw new IllegalArgumentException("'maxDepth' is negative"); - new FileTreeWalker(options, visitor).walk(start, maxDepth); + new FileTreeWalker(options, visitor, maxDepth).walk(start); } /** diff --git a/src/share/classes/java/nio/file/SimpleFileVisitor.java b/src/share/classes/java/nio/file/SimpleFileVisitor.java index 761773513ede4781cf42f56bb77384543c48383b..f252ef03eea8e7a8d777381bf251be0dbc11f043 100644 --- a/src/share/classes/java/nio/file/SimpleFileVisitor.java +++ b/src/share/classes/java/nio/file/SimpleFileVisitor.java @@ -124,8 +124,8 @@ public class SimpleFileVisitor implements FileVisitor { * cause. * * @throws IOError - * if iteration of the directory completed prematurely due to an - * I/O error + * with the I/O exception thrown when iteration of the directory + * completed prematurely due to an I/O error */ @Override public FileVisitResult postVisitDirectory(T dir, IOException exc) { diff --git a/src/share/classes/java/util/Currency.java b/src/share/classes/java/util/Currency.java index 5c9124a90c87797e052fe9beb7cf75d64d9c4f2c..714bd3b2363b4eedc156f8c8b445127a511cdc64 100644 --- a/src/share/classes/java/util/Currency.java +++ b/src/share/classes/java/util/Currency.java @@ -35,12 +35,12 @@ import java.io.Serializable; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.logging.Level; -import java.util.logging.Logger; import java.util.regex.Pattern; import java.util.regex.Matcher; import java.util.spi.CurrencyNameProvider; import java.util.spi.LocaleServiceProvider; import sun.util.LocaleServiceProviderPool; +import sun.util.logging.PlatformLogger; import sun.util.resources.LocaleData; import sun.util.resources.OpenListResourceBundle; @@ -244,7 +244,7 @@ public final class Currency implements Serializable { } } } catch (IOException e) { - log(Level.INFO, "currency.properties is ignored because of an IOException", e); + info("currency.properties is ignored because of an IOException", e); } return null; } @@ -686,7 +686,7 @@ public final class Currency implements Serializable { .append("The entry in currency.properties for ") .append(ctry).append(" is ignored because of the invalid country code.") .toString(); - log(Level.INFO, message, null); + info(message, null); return; } @@ -698,7 +698,7 @@ public final class Currency implements Serializable { .append(ctry) .append(" is ignored because the value format is not recognized.") .toString(); - log(Level.INFO, message, null); + info(message, null); return; } @@ -726,13 +726,13 @@ public final class Currency implements Serializable { setMainTableEntry(ctry.charAt(0), ctry.charAt(1), entry); } - private static void log(Level level, String message, Throwable t) { - Logger logger = Logger.getLogger("java.util.Currency"); - if (logger.isLoggable(level)) { + private static void info(String message, Throwable t) { + PlatformLogger logger = PlatformLogger.getLogger("java.util.Currency"); + if (logger.isLoggable(PlatformLogger.INFO)) { if (t != null) { - logger.log(level, message, t); + logger.info(message, t); } else { - logger.log(level, message); + logger.info(message); } } } diff --git a/src/share/classes/java/util/SimpleTimeZone.java b/src/share/classes/java/util/SimpleTimeZone.java index b0fd57de8df8e9b9b5c4dfc131b33fff043e4e31..d97d6f59a03d8bced3dc4f98b215b7982b9ee230 100644 --- a/src/share/classes/java/util/SimpleTimeZone.java +++ b/src/share/classes/java/util/SimpleTimeZone.java @@ -1372,7 +1372,7 @@ public class SimpleTimeZone extends TimeZone { throw new IllegalArgumentException( "Illegal start month " + startMonth); } - if (startTime < 0 || startTime >= millisPerDay) { + if (startTime < 0 || startTime > millisPerDay) { throw new IllegalArgumentException( "Illegal start time " + startTime); } @@ -1419,7 +1419,7 @@ public class SimpleTimeZone extends TimeZone { throw new IllegalArgumentException( "Illegal end month " + endMonth); } - if (endTime < 0 || endTime >= millisPerDay) { + if (endTime < 0 || endTime > millisPerDay) { throw new IllegalArgumentException( "Illegal end time " + endTime); } diff --git a/src/share/classes/java/util/jar/Attributes.java b/src/share/classes/java/util/jar/Attributes.java index 27a2aba8ef98596120d6a1c06e847932b6210ceb..e9a9e6e6f691707680aede942c7bf94a5d6c9941 100644 --- a/src/share/classes/java/util/jar/Attributes.java +++ b/src/share/classes/java/util/jar/Attributes.java @@ -34,7 +34,7 @@ import java.util.Set; import java.util.Collection; import java.util.AbstractSet; import java.util.Iterator; -import java.util.logging.Logger; +import sun.util.logging.PlatformLogger; import java.util.Comparator; import sun.misc.ASCIICaseInsensitiveComparator; @@ -419,7 +419,7 @@ public class Attributes implements Map, Cloneable { } try { if ((putValue(name, value) != null) && (!lineContinued)) { - Logger.getLogger("java.util.jar").warning( + PlatformLogger.getLogger("java.util.jar").warning( "Duplicate name in Manifest: " + name + ".\n" + "Ensure that the manifest does not " diff --git a/src/share/classes/java/util/logging/ErrorManager.java b/src/share/classes/java/util/logging/ErrorManager.java index 39c215151fc2180de3033f000c45c88884293d9c..8a6d935dea3456f626297738a464236a10a49faf 100644 --- a/src/share/classes/java/util/logging/ErrorManager.java +++ b/src/share/classes/java/util/logging/ErrorManager.java @@ -28,7 +28,7 @@ package java.util.logging; /** * ErrorManager objects can be attached to Handlers to process - * any error that occur on a Handler during Logging. + * any error that occurs on a Handler during Logging. *

    * When processing logging output, if a Handler encounters problems * then rather than throwing an Exception back to the issuer of @@ -72,7 +72,7 @@ public class ErrorManager { /** * The error method is called when a Handler failure occurs. *

    - * This method may be overriden in subclasses. The default + * This method may be overridden in subclasses. The default * behavior in this base class is that the first call is * reported to System.err, and subsequent calls are ignored. * diff --git a/src/share/classes/java/util/logging/FileHandler.java b/src/share/classes/java/util/logging/FileHandler.java index a4f18bd2130c8705c21d27204a4253980912f396..23031a010c8bf8b5b8d43a341d51900bf08730da 100644 --- a/src/share/classes/java/util/logging/FileHandler.java +++ b/src/share/classes/java/util/logging/FileHandler.java @@ -39,7 +39,7 @@ import java.security.*; * For a rotating set of files, as each file reaches a given size * limit, it is closed, rotated out, and a new file opened. * Successively older files are named by adding "0", "1", "2", - * etc into the base filename. + * etc. into the base filename. *

    * By default buffering is enabled in the IO libraries but each log * record is flushed out when it is complete. @@ -391,7 +391,7 @@ public class FileHandler extends StreamHandler { // Generate a lock file name from the "unique" int. lockFileName = generate(pattern, 0, unique).toString() + ".lck"; // Now try to lock that filename. - // Because some systems (e.g. Solaris) can only do file locks + // Because some systems (e.g., Solaris) can only do file locks // between processes (and not within a process), we first check // if we ourself already have the file locked. synchronized(locks) { diff --git a/src/share/classes/java/util/logging/Formatter.java b/src/share/classes/java/util/logging/Formatter.java index 7e7030ba6b0bef63a0bde0c8914dd8aac5db96d9..7cf5c1764a1b3500b247e12a4d0a74796753d786 100644 --- a/src/share/classes/java/util/logging/Formatter.java +++ b/src/share/classes/java/util/logging/Formatter.java @@ -52,7 +52,7 @@ public abstract class Formatter { * Format the given log record and return the formatted string. *

    * The resulting formatted String will normally include a - * localized and formated version of the LogRecord's message field. + * localized and formatted version of the LogRecord's message field. * It is recommended to use the {@link Formatter#formatMessage} * convenience method to localize and format the message field. * @@ -66,7 +66,7 @@ public abstract class Formatter { * Return the header string for a set of formatted records. *

    * This base class returns an empty string, but this may be - * overriden by subclasses. + * overridden by subclasses. * * @param h The target handler (can be null) * @return header string @@ -79,7 +79,7 @@ public abstract class Formatter { * Return the tail string for a set of formatted records. *

    * This base class returns an empty string, but this may be - * overriden by subclasses. + * overridden by subclasses. * * @param h The target handler (can be null) * @return tail string diff --git a/src/share/classes/java/util/logging/Handler.java b/src/share/classes/java/util/logging/Handler.java index 2643c73471489332498d7f15a0b3aeaf5719071d..7c1c6268b00bc795eaf796d918494b207ddfb3c0 100644 --- a/src/share/classes/java/util/logging/Handler.java +++ b/src/share/classes/java/util/logging/Handler.java @@ -274,7 +274,7 @@ public abstract class Handler { * Level and whether it satisfies any Filter. It also * may make other Handler specific checks that might prevent a * handler from logging the LogRecord. It will return false if - * the LogRecord is Null. + * the LogRecord is null. *

    * @param record a LogRecord * @return true if the LogRecord would be logged. diff --git a/src/share/classes/java/util/logging/Level.java b/src/share/classes/java/util/logging/Level.java index 910a50d1ebba75aee5f7725cfb5ee1ef465cf080..173201f80eee201a02e4fdb10745ae6271d0f0a2 100644 --- a/src/share/classes/java/util/logging/Level.java +++ b/src/share/classes/java/util/logging/Level.java @@ -110,7 +110,7 @@ public class Level implements java.io.Serializable { * Typically INFO messages will be written to the console * or its equivalent. So the INFO level should only be * used for reasonably significant messages that will - * make sense to end users and system admins. + * make sense to end users and system administrators. * This level is initialized to 800. */ public static final Level INFO = new Level("INFO", 800, defaultBundle); @@ -245,6 +245,8 @@ public class Level implements java.io.Serializable { } /** + * Returns a string representation of this Level. + * * @return the non-localized name of the Level, for example "INFO". */ public final String toString() { @@ -299,14 +301,14 @@ public class Level implements java.io.Serializable { * @throws IllegalArgumentException if the value is not valid. * Valid values are integers between Integer.MIN_VALUE * and Integer.MAX_VALUE, and all known level names. - * Known names are the levels defined by this class (i.e. FINE, + * Known names are the levels defined by this class (e.g., FINE, * FINER, FINEST), or created by this class with * appropriate package access, or new levels defined or created * by subclasses. * * @return The parsed value. Passing an integer that corresponds to a known name - * (eg 700) will return the associated name (eg CONFIG). - * Passing an integer that does not (eg 1) will return a new level name + * (e.g., 700) will return the associated name (e.g., CONFIG). + * Passing an integer that does not (e.g., 1) will return a new level name * initialized to that value. */ public static synchronized Level parse(String name) throws IllegalArgumentException { diff --git a/src/share/classes/java/util/logging/LogManager.java b/src/share/classes/java/util/logging/LogManager.java index e6412565a87ec94d238428c958204c674f84c1e3..4faea17d79e5e9689ed01c79660429524b287d15 100644 --- a/src/share/classes/java/util/logging/LogManager.java +++ b/src/share/classes/java/util/logging/LogManager.java @@ -283,6 +283,10 @@ public class LogManager { AccessController.doPrivileged(new PrivilegedExceptionAction() { public Object run() throws Exception { readConfiguration(); + + // Platform loggers begin to delegate to java.util.logging.Logger + sun.util.logging.PlatformLogger.redirectPlatformLoggers(); + return null; } }); diff --git a/src/share/classes/java/util/logging/LogRecord.java b/src/share/classes/java/util/logging/LogRecord.java index 2610316a5e38b7e1a08d2d5c11dd90f7c63d84b7..e6706319ffadf4d728aef54045767712cbf5500b 100644 --- a/src/share/classes/java/util/logging/LogRecord.java +++ b/src/share/classes/java/util/logging/LogRecord.java @@ -188,7 +188,7 @@ public class LogRecord implements java.io.Serializable { } /** - * Get the source Logger name's + * Get the source Logger's name. * * @return source logger name (may be null) */ @@ -197,7 +197,7 @@ public class LogRecord implements java.io.Serializable { } /** - * Set the source Logger name. + * Set the source Logger's name. * * @param name the source logger name (may be null) */ @@ -530,6 +530,7 @@ public class LogRecord implements java.io.Serializable { int depth = access.getStackTraceDepth(throwable); String logClassName = "java.util.logging.Logger"; + String plogClassName = "sun.util.logging.PlatformLogger"; boolean lookingForLogger = true; for (int ix = 0; ix < depth; ix++) { // Calling getStackTraceElement directly prevents the VM @@ -539,15 +540,18 @@ public class LogRecord implements java.io.Serializable { String cname = frame.getClassName(); if (lookingForLogger) { // Skip all frames until we have found the first logger frame. - if (cname.equals(logClassName)) { + if (cname.equals(logClassName) || cname.startsWith(plogClassName)) { lookingForLogger = false; } } else { - if (!cname.equals(logClassName)) { - // We've found the relevant frame. - setSourceClassName(cname); - setSourceMethodName(frame.getMethodName()); - return; + if (!cname.equals(logClassName) && !cname.startsWith(plogClassName)) { + // skip reflection call + if (!cname.startsWith("java.lang.reflect.") && !cname.startsWith("sun.reflect.")) { + // We've found the relevant frame. + setSourceClassName(cname); + setSourceMethodName(frame.getMethodName()); + return; + } } } } diff --git a/src/share/classes/java/util/logging/Logger.java b/src/share/classes/java/util/logging/Logger.java index 5ae2b42713361f38875dd8141a1c172ebb1861e4..cd9f4d90568cbc7371762e1a206d4eb8daf1eea7 100644 --- a/src/share/classes/java/util/logging/Logger.java +++ b/src/share/classes/java/util/logging/Logger.java @@ -66,7 +66,7 @@ import java.lang.ref.WeakReference; * effective level from its parent. *

    * On each logging call the Logger initially performs a cheap - * check of the request level (e.g. SEVERE or FINE) against the + * check of the request level (e.g., SEVERE or FINE) against the * effective log level of the logger. If the request level is * lower than the log level, the logging call returns immediately. *

    @@ -230,7 +230,7 @@ public class Logger { * Protected method to construct a logger for a named subsystem. *

    * The logger will be initially configured with a null Level - * and with useParentHandlers true. + * and with useParentHandlers set to true. * * @param name A name for the logger. This should * be a dot-separated name and should normally @@ -240,7 +240,7 @@ public class Logger { * @param resourceBundleName name of ResourceBundle to be used for localizing * messages for this logger. May be null if none * of the messages require localization. - * @throws MissingResourceException if the ResourceBundleName is non-null and + * @throws MissingResourceException if the resourceBundleName is non-null and * no corresponding resource can be found. */ protected Logger(String name, String resourceBundleName) { @@ -285,7 +285,7 @@ public class Logger { *

    * If a new logger is created its log level will be configured * based on the LogManager configuration and it will configured - * to also send logging output to its parent's handlers. It will + * to also send logging output to its parent's Handlers. It will * be registered in the LogManager global namespace. * * @param name A name for the logger. This should @@ -308,7 +308,7 @@ public class Logger { *

    * If a new logger is created its log level will be configured * based on the LogManager and it will configured to also send logging - * output to its parent loggers Handlers. It will be registered in + * output to its parent's Handlers. It will be registered in * the LogManager global namespace. *

    * If the named Logger already exists and does not yet have a @@ -326,7 +326,8 @@ public class Logger { * messages for this logger. May be null if none of * the messages require localization. * @return a suitable Logger - * @throws MissingResourceException if the named ResourceBundle cannot be found. + * @throws MissingResourceException if the resourceBundleName is non-null and + * no corresponding resource can be found. * @throws IllegalArgumentException if the Logger already exists and uses * a different resource bundle name. * @throws NullPointerException if the name is null. @@ -395,7 +396,8 @@ public class Logger { * messages for this logger. * May be null if none of the messages require localization. * @return a newly created private Logger - * @throws MissingResourceException if the named ResourceBundle cannot be found. + * @throws MissingResourceException if the resourceBundleName is non-null and + * no corresponding resource can be found. */ public static synchronized Logger getAnonymousLogger(String resourceBundleName) { LogManager manager = LogManager.getLogManager(); @@ -514,7 +516,7 @@ public class Logger { * level then the given message is forwarded to all the * registered output Handler objects. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) */ public void log(Level level, String msg) { @@ -532,7 +534,7 @@ public class Logger { * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param param1 parameter to the message */ @@ -553,7 +555,7 @@ public class Logger { * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param params array of parameters to the message */ @@ -578,7 +580,7 @@ public class Logger { * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param msg The string message (or a key in the message catalog) * @param thrown Throwable associated with log message. */ @@ -603,7 +605,7 @@ public class Logger { * level then the given message is forwarded to all the * registered output Handler objects. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) @@ -626,7 +628,7 @@ public class Logger { * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) @@ -653,7 +655,7 @@ public class Logger { * level then a corresponding LogRecord is created and forwarded * to all the registered output Handler objects. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) @@ -684,7 +686,7 @@ public class Logger { * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param msg The string message (or a key in the message catalog) @@ -731,7 +733,7 @@ public class Logger { * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, @@ -762,7 +764,7 @@ public class Logger { * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, @@ -795,7 +797,7 @@ public class Logger { * resource bundle name is null, or an empty String or invalid * then the msg string is not localized. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, @@ -832,7 +834,7 @@ public class Logger { * processed specially by output Formatters and is not treated * as a formatting parameter to the LogRecord message property. *

    - * @param level One of the message level identifiers, e.g. SEVERE + * @param level One of the message level identifiers, e.g., SEVERE * @param sourceClass name of class that issued the logging request * @param sourceMethod name of method that issued the logging request * @param bundleName name of resource bundle to localize msg, @@ -1214,7 +1216,7 @@ public class Logger { /** * Specify whether or not this logger should send its output - * to it's parent Logger. This means that any LogRecords will + * to its parent Logger. This means that any LogRecords will * also be written to the parent's Handlers, and potentially * to its parent, recursively up the namespace. * diff --git a/src/share/classes/java/util/logging/LoggingMXBean.java b/src/share/classes/java/util/logging/LoggingMXBean.java index cb67d7b4fb071c410615b21956750df0c50a5d6e..a3abe3c69b16fc4cc0c848c1ca5940e9625b0fa8 100644 --- a/src/share/classes/java/util/logging/LoggingMXBean.java +++ b/src/share/classes/java/util/logging/LoggingMXBean.java @@ -105,8 +105,8 @@ public interface LoggingMXBean extends PlatformManagedObject { * * @param loggerName The name of the Logger to be set. * Must be non-null. - * @param levelName The name of the level to set the specified logger to, - * or null if to set the level to inherit + * @param levelName The name of the level to set on the specified logger, + * or null if setting the level to inherit * from its nearest ancestor. * * @throws IllegalArgumentException if the specified logger diff --git a/src/share/classes/java/util/logging/MemoryHandler.java b/src/share/classes/java/util/logging/MemoryHandler.java index d812e3bf64f82cdb02afd4e94b5d53ee3c8fc9f2..aa632223667fd0b8e10ab36e252dd830883b391e 100644 --- a/src/share/classes/java/util/logging/MemoryHandler.java +++ b/src/share/classes/java/util/logging/MemoryHandler.java @@ -136,7 +136,7 @@ public class MemoryHandler extends Handler { * @param size the number of log records to buffer (must be greater than zero) * @param pushLevel message level to push on * - * @throws IllegalArgumentException is size is <= 0 + * @throws IllegalArgumentException if size is <= 0 */ public MemoryHandler(Handler target, int size, Level pushLevel) { if (target == null || pushLevel == null) { @@ -258,7 +258,7 @@ public class MemoryHandler extends Handler { * This method checks if the LogRecord has an appropriate level and * whether it satisfies any Filter. However it does not * check whether the LogRecord would result in a "push" of the - * buffer contents. It will return false if the LogRecord is Null. + * buffer contents. It will return false if the LogRecord is null. *

    * @param record a LogRecord * @return true if the LogRecord would be logged. diff --git a/src/share/classes/java/util/logging/StreamHandler.java b/src/share/classes/java/util/logging/StreamHandler.java index 766142a1a58883c1ae758bcd998cfbe6e9b241ab..ce47fe904272f39e6778cefc72a9f9ef4717d6bd 100644 --- a/src/share/classes/java/util/logging/StreamHandler.java +++ b/src/share/classes/java/util/logging/StreamHandler.java @@ -220,7 +220,7 @@ public class StreamHandler extends Handler { *

    * This method checks if the LogRecord has an appropriate level and * whether it satisfies any Filter. It will also return false if - * no output stream has been assigned yet or the LogRecord is Null. + * no output stream has been assigned yet or the LogRecord is null. *

    * @param record a LogRecord * @return true if the LogRecord would be logged. diff --git a/src/share/classes/java/util/zip/ZipEntry.java b/src/share/classes/java/util/zip/ZipEntry.java index cba69b0c1a2e37cbdc15562fbf2b8f78c469be77..8da5a4f54ade3ed09855e9615560b1010f454cc6 100644 --- a/src/share/classes/java/util/zip/ZipEntry.java +++ b/src/share/classes/java/util/zip/ZipEntry.java @@ -26,6 +26,7 @@ package java.util.zip; import java.util.Date; +import sun.misc.BootClassLoaderHook; /** * This class is used to represent a ZIP file entry. @@ -109,12 +110,16 @@ class ZipEntry implements ZipConstants, Cloneable { * @see #getTime() */ public void setTime(long time) { - // fix for bug 6625963: we bypass time calculations while Kernel is - // downloading bundles, since they aren't necessary and would cause - // the Kernel core to depend upon the (very large) time zone data - if (sun.misc.VM.isBootedKernelVM() && - sun.jkernel.DownloadManager.isCurrentThreadDownloading()) { - this.time = sun.jkernel.DownloadManager.KERNEL_STATIC_MODTIME; + // Same value as defined in sun.jkernel.DownloadManager.KERNEL_STATIC_MODTIME + // to avoid direct reference to DownoadManager class. Need to revisit + // if this is needed any more (see comment in the DownloadManager class) + final int KERNEL_STATIC_MODTIME = 10000000; + BootClassLoaderHook hook = BootClassLoaderHook.getHook(); + if (hook != null && hook.isCurrentThreadPrefetching()) { + // fix for bug 6625963: we bypass time calculations while Kernel is + // downloading bundles, since they aren't necessary and would cause + // the Kernel core to depend upon the (very large) time zone data + this.time = KERNEL_STATIC_MODTIME; } else { this.time = javaToDosTime(time); } @@ -253,14 +258,10 @@ class ZipEntry implements ZipConstants, Cloneable { * the first 0xFFFF bytes are output to the ZIP file entry. * * @param comment the comment string - * @exception IllegalArgumentException if the length of the specified - * comment string is greater than 0xFFFF bytes + * * @see #getComment() */ public void setComment(String comment) { - if (comment != null && comment.length() > 0xffff) { - throw new IllegalArgumentException("invalid entry comment length"); - } this.comment = comment; } diff --git a/src/share/classes/java/util/zip/ZipFile.java b/src/share/classes/java/util/zip/ZipFile.java index 76c270c1b1019561548c503dbf65ecd1323206a6..583d7dcfe1aa7d250eecf439a51fb258eec1f503 100644 --- a/src/share/classes/java/util/zip/ZipFile.java +++ b/src/share/classes/java/util/zip/ZipFile.java @@ -195,7 +195,10 @@ class ZipFile implements ZipConstants, Closeable { if (charset == null) throw new NullPointerException("charset is null"); this.zc = ZipCoder.get(charset); + long t0 = System.nanoTime(); jzfile = open(name, mode, file.lastModified()); + sun.misc.PerfCounter.getZipFileOpenTime().addElapsedTimeFrom(t0); + sun.misc.PerfCounter.getZipFileCount().increment(); this.name = name; this.total = getTotal(jzfile); } diff --git a/src/share/classes/javax/sql/rowset/BaseRowSet.java b/src/share/classes/javax/sql/rowset/BaseRowSet.java index 2d13d835c1ba3989f727b71422aa23fc4e8d96d9..f3e79555ba1d80d3890ccf398ef0ba6f692d1afc 100644 --- a/src/share/classes/javax/sql/rowset/BaseRowSet.java +++ b/src/share/classes/javax/sql/rowset/BaseRowSet.java @@ -168,8 +168,8 @@ import javax.sql.rowset.serial.*; * The majority of methods for setting placeholder parameters take two parameters, * with the first parameter * indicating which placeholder parameter is to be set, and the second parameter - * giving the value to be set. Methods such as getInt, - * getString, getBoolean, and getLong fall into + * giving the value to be set. Methods such as setInt, + * setString, setBoolean, and setLong fall into * this category. After these methods have been called, a call to the method * getParams will return an array with the values that have been set. Each * element in the array is an Object instance representing the @@ -3259,9 +3259,9 @@ public static final int ASCII_STREAM_PARAM = 2; * @param x the parameter value * @exception SQLException if a database access error occurs or * this method is called on a closed CallableStatement - * @see #getBoolean * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method + * @see #getParams * @since 1.4 */ public void setBoolean(String parameterName, boolean x) throws SQLException{ @@ -3281,7 +3281,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getByte + * @see #getParams * @since 1.4 */ public void setByte(String parameterName, byte x) throws SQLException{ @@ -3301,7 +3301,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getShort + * @see #getParams * @since 1.4 */ public void setShort(String parameterName, short x) throws SQLException{ @@ -3320,7 +3320,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getInt + * @see #getParams * @since 1.4 */ public void setInt(String parameterName, int x) throws SQLException{ @@ -3339,7 +3339,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getLong + * @see #getParams * @since 1.4 */ public void setLong(String parameterName, long x) throws SQLException{ @@ -3358,7 +3358,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getFloat + * @see #getParams * @since 1.4 */ public void setFloat(String parameterName, float x) throws SQLException{ @@ -3377,7 +3377,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getDouble + * @see #getParams * @since 1.4 */ public void setDouble(String parameterName, double x) throws SQLException{ @@ -3398,7 +3398,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getBigDecimal + * @see #getParams * @since 1.4 */ public void setBigDecimal(String parameterName, BigDecimal x) throws SQLException{ @@ -3421,7 +3421,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getString + * @see #getParams * @since 1.4 */ public void setString(String parameterName, String x) throws SQLException{ @@ -3443,7 +3443,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getBytes + * @see #getParams * @since 1.4 */ public void setBytes(String parameterName, byte x[]) throws SQLException{ @@ -3464,7 +3464,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getTimestamp + * @see #getParams * @since 1.4 */ public void setTimestamp(String parameterName, java.sql.Timestamp x) @@ -3712,7 +3712,7 @@ public static final int ASCII_STREAM_PARAM = 2; * or STRUCT data type and the JDBC driver does not support * this data type * @see Types - * @see #getObject + * @see #getParams * @since 1.4 */ public void setObject(String parameterName, Object x, int targetSqlType, int scale) @@ -3740,7 +3740,7 @@ public static final int ASCII_STREAM_PARAM = 2; * REF, ROWID, SQLXML * or STRUCT data type and the JDBC driver does not support * this data type - * @see #getObject + * @see #getParams * @since 1.4 */ public void setObject(String parameterName, Object x, int targetSqlType) @@ -3782,7 +3782,7 @@ public static final int ASCII_STREAM_PARAM = 2; * Object parameter is ambiguous * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getObject + * @see #getParams * @since 1.4 */ public void setObject(String parameterName, Object x) throws SQLException{ @@ -4064,7 +4064,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getDate + * @see #getParams * @since 1.4 */ public void setDate(String parameterName, java.sql.Date x) @@ -4091,7 +4091,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getDate + * @see #getParams * @since 1.4 */ public void setDate(String parameterName, java.sql.Date x, Calendar cal) @@ -4111,7 +4111,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getTime + * @see #getParams * @since 1.4 */ public void setTime(String parameterName, java.sql.Time x) @@ -4138,7 +4138,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getTime + * @see #getParams * @since 1.4 */ public void setTime(String parameterName, java.sql.Time x, Calendar cal) @@ -4165,7 +4165,7 @@ public static final int ASCII_STREAM_PARAM = 2; * this method is called on a closed CallableStatement * @exception SQLFeatureNotSupportedException if the JDBC driver does not support * this method - * @see #getTimestamp + * @see #getParams * @since 1.4 */ public void setTimestamp(String parameterName, java.sql.Timestamp x, Calendar cal) diff --git a/src/share/classes/javax/swing/JEditorPane.java b/src/share/classes/javax/swing/JEditorPane.java index 21528752fd5f1c5c5f9ff9503443aacb9c4c05f5..4dfbf92488ea19183bbf62437b4d7899ee382e56 100644 --- a/src/share/classes/javax/swing/JEditorPane.java +++ b/src/share/classes/javax/swing/JEditorPane.java @@ -24,6 +24,8 @@ */ package javax.swing; +import sun.swing.SwingUtilities2; + import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; @@ -1123,6 +1125,7 @@ public class JEditorPane extends JTextComponent { * @param content the content to replace the selection with. This * value can be null */ + @Override public void replaceSelection(String content) { if (! isEditable()) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); @@ -1133,6 +1136,7 @@ public class JEditorPane extends JTextComponent { try { Document doc = getDocument(); Caret caret = getCaret(); + boolean composedTextSaved = saveComposedText(caret.getDot()); int p0 = Math.min(caret.getDot(), caret.getMark()); int p1 = Math.max(caret.getDot(), caret.getMark()); if (doc instanceof AbstractDocument) { @@ -1148,6 +1152,9 @@ public class JEditorPane extends JTextComponent { getInputAttributes()); } } + if (composedTextSaved) { + restoreComposedText(); + } } catch (BadLocationException e) { UIManager.getLookAndFeel().provideErrorFeedback(JEditorPane.this); } @@ -1323,8 +1330,8 @@ public class JEditorPane extends JTextComponent { */ public Dimension getPreferredSize() { Dimension d = super.getPreferredSize(); - if (getParent() instanceof JViewport) { - JViewport port = (JViewport)getParent(); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { TextUI ui = getUI(); int prefWidth = d.width; int prefHeight = d.height; @@ -1445,8 +1452,8 @@ public class JEditorPane extends JTextComponent { * match its own, false otherwise */ public boolean getScrollableTracksViewportWidth() { - if (getParent() instanceof JViewport) { - JViewport port = (JViewport)getParent(); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { TextUI ui = getUI(); int w = port.getWidth(); Dimension min = ui.getMinimumSize(this); @@ -1467,8 +1474,8 @@ public class JEditorPane extends JTextComponent { * false otherwise */ public boolean getScrollableTracksViewportHeight() { - if (getParent() instanceof JViewport) { - JViewport port = (JViewport)getParent(); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { TextUI ui = getUI(); int h = port.getHeight(); Dimension min = ui.getMinimumSize(this); diff --git a/src/share/classes/javax/swing/JLayer.java b/src/share/classes/javax/swing/JLayer.java index b8cc69e9bcd1086dccd072b7ad82838310ac60ef..1ce679bc02d7238c6502cec4f18eb0b1975c7299 100644 --- a/src/share/classes/javax/swing/JLayer.java +++ b/src/share/classes/javax/swing/JLayer.java @@ -1,6 +1,26 @@ /* - * Copyright 2009 Sun Microsystems, Inc. All rights reserved. - * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. */ package javax.swing; @@ -158,7 +178,7 @@ public final class JLayer * @return the {@code JLayer}'s view component * or {@code null} if none exists * - * @see #setView(V) + * @see #setView(Component) */ public V getView() { return view; @@ -259,7 +279,7 @@ public final class JLayer * @throws UnsupportedOperationException this method is not supported * * @see #setView(Component) - * @see #setGlassPane(Component) + * @see #setGlassPane(JPanel) */ protected void addImpl(Component comp, Object constraints, int index) { throw new UnsupportedOperationException( @@ -319,7 +339,7 @@ public final class JLayer * @return false if {@code JLayer}'s {@code glassPane} is visible */ public boolean isOptimizedDrawingEnabled() { - return !glassPane.isVisible(); + return glassPane == null || !glassPane.isVisible(); } /** @@ -388,7 +408,10 @@ public final class JLayer if (layerEventMask != oldEventMask) { disableEvents(oldEventMask); enableEvents(eventMask); - eventController.updateAWTEventListener(this); + if (isDisplayable()) { + eventController.updateAWTEventListener( + oldEventMask, layerEventMask); + } } } @@ -475,9 +498,6 @@ public final class JLayer if (getUI() != null) { return getUI().getScrollableTracksViewportHeight(this); } - if (getParent() instanceof JViewport) { - return ((getParent()).getHeight() > getPreferredSize().height); - } return false; } @@ -498,9 +518,6 @@ public final class JLayer if (getUI() != null) { return getUI().getScrollableTracksViewportWidth(this); } - if (getParent() instanceof JViewport) { - return ((getParent()).getWidth() > getPreferredSize().width); - } return false; } @@ -535,20 +552,36 @@ public final class JLayer private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); - if (getUI() != null) { - setUI(getUI()); + if (layerUI != null) { + setUI(layerUI); } - if (getLayerEventMask() != 0) { - eventController.updateAWTEventListener(this); + if (eventMask != 0) { + eventController.updateAWTEventListener(0, eventMask); } } + /** + * {@inheritDoc} + */ + public void addNotify() { + super.addNotify(); + eventController.updateAWTEventListener(0, eventMask); + } + + /** + * {@inheritDoc} + */ + public void removeNotify() { + super.removeNotify(); + eventController.updateAWTEventListener(eventMask, 0); + } + /** * static AWTEventListener to be shared with all AbstractLayerUIs */ private static class LayerEventController implements AWTEventListener { - private ArrayList> layerList = - new ArrayList>(); + private ArrayList layerMaskList = + new ArrayList(); private long currentEventMask; @@ -572,37 +605,24 @@ public final class JLayer } } - private boolean layerListContains(JLayer l) { - for (WeakReference layerWeakReference : layerList) { - if (layerWeakReference.get() == l) { - return true; - } + private void updateAWTEventListener(long oldEventMask, long newEventMask) { + if (oldEventMask != 0) { + layerMaskList.remove(oldEventMask); } - return false; - } - - private void updateAWTEventListener(JLayer layer) { - if (!layerListContains(layer) && layer.getLayerEventMask() != 0) { - layerList.add(new WeakReference(layer)); + if (newEventMask != 0) { + layerMaskList.add(newEventMask); } long combinedMask = 0; - Iterator> it = layerList.iterator(); - while (it.hasNext()) { - WeakReference weakRef = it.next(); - JLayer currLayer = weakRef.get(); - if (currLayer == null) { - it.remove(); - } else { - combinedMask |= currLayer.getLayerEventMask(); - } + for (Long mask : layerMaskList) { + combinedMask |= mask; } if (combinedMask == 0) { removeAWTEventListener(); - layerList.clear(); } else if (getCurrentEventMask() != combinedMask) { removeAWTEventListener(); addAWTEventListener(combinedMask); } + currentEventMask = combinedMask; } private long getCurrentEventMask() { @@ -617,7 +637,7 @@ public final class JLayer return null; } }); - currentEventMask = eventMask; + } private void removeAWTEventListener() { @@ -628,7 +648,6 @@ public final class JLayer return null; } }); - currentEventMask = 0; } private boolean isEventEnabled(long eventMask, int id) { @@ -785,4 +804,4 @@ public final class JLayer public void removeLayoutComponent(Component comp) { } } -} \ No newline at end of file +} diff --git a/src/share/classes/javax/swing/JList.java b/src/share/classes/javax/swing/JList.java index 772c7554056dd27892f44f76fa5b2f664e858a09..796ac11ba6c91060e7f016179cae6bbef3cc9f00 100644 --- a/src/share/classes/javax/swing/JList.java +++ b/src/share/classes/javax/swing/JList.java @@ -2722,8 +2722,9 @@ public class JList extends JComponent implements Scrollable, Accessible getVisibleRowCount() <= 0) { return true; } - if (getParent() instanceof JViewport) { - return (getParent().getWidth() > getPreferredSize().width); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + return port.getWidth() > getPreferredSize().width; } return false; } @@ -2747,8 +2748,9 @@ public class JList extends JComponent implements Scrollable, Accessible getVisibleRowCount() <= 0) { return true; } - if (getParent() instanceof JViewport) { - return (getParent().getHeight() > getPreferredSize().height); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + return port.getHeight() > getPreferredSize().height; } return false; } diff --git a/src/share/classes/javax/swing/JPopupMenu.java b/src/share/classes/javax/swing/JPopupMenu.java index 8f90a02a2a9670157c51d98fe92d20cb36db1938..78715b886bed96c2d795578d2d3f3df72b54942b 100644 --- a/src/share/classes/javax/swing/JPopupMenu.java +++ b/src/share/classes/javax/swing/JPopupMenu.java @@ -412,7 +412,7 @@ public class JPopupMenu extends JComponent implements Accessible,MenuElement { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission( - SecurityConstants.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); + SecurityConstants.AWT.SET_WINDOW_ALWAYS_ON_TOP_PERMISSION); } } catch (SecurityException se) { // There is no permission to show popups over the task bar diff --git a/src/share/classes/javax/swing/JTable.java b/src/share/classes/javax/swing/JTable.java index dc9adebc4d47947eb2e445552d2176f8370df7cb..521f17ab8a5d9bf4b6451c08452d8d8a941e58e4 100644 --- a/src/share/classes/javax/swing/JTable.java +++ b/src/share/classes/javax/swing/JTable.java @@ -718,9 +718,9 @@ public class JTable extends JComponent implements TableModelListener, Scrollable * @see #addNotify */ protected void configureEnclosingScrollPane() { - Container p = getParent(); - if (p instanceof JViewport) { - Container gp = p.getParent(); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + Container gp = port.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane)gp; // Make certain we are the viewPort's view and not, for @@ -750,9 +750,9 @@ public class JTable extends JComponent implements TableModelListener, Scrollable * from configureEnclosingScrollPane() and updateUI() in a safe manor. */ private void configureEnclosingScrollPaneUI() { - Container p = getParent(); - if (p instanceof JViewport) { - Container gp = p.getParent(); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + Container gp = port.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane)gp; // Make certain we are the viewPort's view and not, for @@ -819,9 +819,9 @@ public class JTable extends JComponent implements TableModelListener, Scrollable * @since 1.3 */ protected void unconfigureEnclosingScrollPane() { - Container p = getParent(); - if (p instanceof JViewport) { - Container gp = p.getParent(); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + Container gp = port.getParent(); if (gp instanceof JScrollPane) { JScrollPane scrollPane = (JScrollPane)gp; // Make certain we are the viewPort's view and not, for @@ -5215,9 +5215,10 @@ public class JTable extends JComponent implements TableModelListener, Scrollable * @see #getFillsViewportHeight */ public boolean getScrollableTracksViewportHeight() { + JViewport port = SwingUtilities2.getViewport(this); return getFillsViewportHeight() - && getParent() instanceof JViewport - && (getParent().getHeight() > getPreferredSize().height); + && port != null + && port.getHeight() > getPreferredSize().height; } /** diff --git a/src/share/classes/javax/swing/JTextField.java b/src/share/classes/javax/swing/JTextField.java index c104f36ec98763b9e4e44ff2dc4b75b73a6c7193..de408914d2222c156ba4530bda43237b00b3f4af 100644 --- a/src/share/classes/javax/swing/JTextField.java +++ b/src/share/classes/javax/swing/JTextField.java @@ -24,6 +24,8 @@ */ package javax.swing; +import sun.swing.SwingUtilities2; + import java.awt.*; import java.awt.event.*; import java.beans.*; @@ -288,11 +290,7 @@ public class JTextField extends JTextComponent implements SwingConstants { * @see JComponent#isValidateRoot */ public boolean isValidateRoot() { - Component parent = getParent(); - if (parent instanceof JViewport) { - return false; - } - return true; + return SwingUtilities2.getViewport(this) == null; } diff --git a/src/share/classes/javax/swing/JTextPane.java b/src/share/classes/javax/swing/JTextPane.java index efb339bd59fc247b7fcbd2cc350b2fb69e288fdf..7f113ddd59c1f0385c7fcb48275c7a1b58aac2e3 100644 --- a/src/share/classes/javax/swing/JTextPane.java +++ b/src/share/classes/javax/swing/JTextPane.java @@ -170,6 +170,7 @@ public class JTextPane extends JEditorPane { * * @param content the content to replace the selection with */ + @Override public void replaceSelection(String content) { replaceSelection(content, true); } @@ -183,6 +184,7 @@ public class JTextPane extends JEditorPane { if (doc != null) { try { Caret caret = getCaret(); + boolean composedTextSaved = saveComposedText(caret.getDot()); int p0 = Math.min(caret.getDot(), caret.getMark()); int p1 = Math.max(caret.getDot(), caret.getMark()); AttributeSet attr = getInputAttributes().copyAttributes(); @@ -197,6 +199,9 @@ public class JTextPane extends JEditorPane { doc.insertString(p0, content, attr); } } + if (composedTextSaved) { + restoreComposedText(); + } } catch (BadLocationException e) { UIManager.getLookAndFeel().provideErrorFeedback(JTextPane.this); } diff --git a/src/share/classes/javax/swing/JTree.java b/src/share/classes/javax/swing/JTree.java index 639dd45e8f99f2a4b81db3257134a1a84757a70c..1b200f78591a476b0e10f1555af558fe08ae57b7 100644 --- a/src/share/classes/javax/swing/JTree.java +++ b/src/share/classes/javax/swing/JTree.java @@ -3498,8 +3498,9 @@ public class JTree extends JComponent implements Scrollable, Accessible * @see Scrollable#getScrollableTracksViewportWidth */ public boolean getScrollableTracksViewportWidth() { - if (getParent() instanceof JViewport) { - return getParent().getWidth() > getPreferredSize().width; + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + return port.getWidth() > getPreferredSize().width; } return false; } @@ -3514,8 +3515,9 @@ public class JTree extends JComponent implements Scrollable, Accessible * @see Scrollable#getScrollableTracksViewportHeight */ public boolean getScrollableTracksViewportHeight() { - if (getParent() instanceof JViewport) { - return getParent().getHeight() > getPreferredSize().height; + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + return port.getHeight() > getPreferredSize().height; } return false; } diff --git a/src/share/classes/javax/swing/SwingUtilities.java b/src/share/classes/javax/swing/SwingUtilities.java index 21a75ce1d9772c569b9cef7996c08370b42b361a..d7a26a0dd729555011a93a6ead80acf5c54f6b87 100644 --- a/src/share/classes/javax/swing/SwingUtilities.java +++ b/src/share/classes/javax/swing/SwingUtilities.java @@ -999,24 +999,20 @@ public class SwingUtilities implements SwingConstants textR.height = (int) v.getPreferredSpan(View.Y_AXIS); } else { textR.width = SwingUtilities2.stringWidth(c, fm, text); - - // Take into account the left and right side bearings. - // This gives more space than it is actually needed, - // but there are two reasons: - // 1. If we set the width to the actual bounds, - // all callers would have to account for the bearings - // themselves. NOTE: all pref size calculations don't do it. - // 2. You can do a drawString at the returned location - // and the text won't be clipped. lsb = SwingUtilities2.getLeftSideBearing(c, fm, text); if (lsb < 0) { + // If lsb is negative, add it to the width and later + // adjust the x location. This gives more space than is + // actually needed. + // This is done like this for two reasons: + // 1. If we set the width to the actual bounds all + // callers would have to account for negative lsb + // (pref size calculations ONLY look at width of + // textR) + // 2. You can do a drawString at the returned location + // and the text won't be clipped. textR.width -= lsb; } - rsb = SwingUtilities2.getRightSideBearing(c, fm, text); - if (rsb > 0) { - textR.width += rsb; - } - if (textR.width > availTextWidth) { text = SwingUtilities2.clipString(c, fm, text, availTextWidth); diff --git a/src/share/classes/javax/swing/plaf/LayerUI.java b/src/share/classes/javax/swing/plaf/LayerUI.java index 44c57ce3cad0ec6fca7c6f0d00ab1d243a81c202..cf64687421a9606add6adcc07102eef7bc9bc45a 100644 --- a/src/share/classes/javax/swing/plaf/LayerUI.java +++ b/src/share/classes/javax/swing/plaf/LayerUI.java @@ -1,6 +1,26 @@ /* - * Copyright 2009 Sun Microsystems, Inc. All rights reserved. - * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. */ package javax.swing.plaf; @@ -202,6 +222,7 @@ public class LayerUI * Returns an array of all the listeners which have been associated * with the named property. * + * @param propertyName The name of the property being listened to * @return all of the {@code PropertyChangeListener}s associated with * the named property; if no such listeners have been added or * if {@code propertyName} is {@code null}, an empty @@ -242,6 +263,7 @@ public class LayerUI /** * Returns the preferred size of the viewport for a view component. * + * @param l the {@code JLayer} component where this UI delegate is being installed * @return the preferred size of the viewport for a view component * @see Scrollable#getPreferredScrollableViewportSize() */ @@ -257,6 +279,10 @@ public class LayerUI * that display logical rows or columns in order to completely expose * one block of rows or columns, depending on the value of orientation. * + * @param l the {@code JLayer} component where this UI delegate is being installed + * @param visibleRect The view area visible within the viewport + * @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL. + * @param direction Less than zero to scroll up/left, greater than zero for down/right. * @return the "block" increment for scrolling in the specified direction * @see Scrollable#getScrollableBlockIncrement(Rectangle, int, int) */ @@ -276,6 +302,7 @@ public class LayerUI * determine the height of the layer, unless the preferred height * of the layer is smaller than the height of the viewport. * + * @param l the {@code JLayer} component where this UI delegate is being installed * @return whether the layer should track the height of the viewport * @see Scrollable#getScrollableTracksViewportHeight() */ @@ -283,9 +310,6 @@ public class LayerUI if (l.getView() instanceof Scrollable) { return ((Scrollable)l.getView()).getScrollableTracksViewportHeight(); } - if (l.getParent() instanceof JViewport) { - return (((JViewport)l.getParent()).getHeight() > l.getPreferredSize().height); - } return false; } @@ -294,6 +318,7 @@ public class LayerUI * determine the width of the layer, unless the preferred width * of the layer is smaller than the width of the viewport. * + * @param l the {@code JLayer} component where this UI delegate is being installed * @return whether the layer should track the width of the viewport * @see Scrollable * @see LayerUI#getScrollableTracksViewportWidth(JLayer) @@ -302,9 +327,6 @@ public class LayerUI if (l.getView() instanceof Scrollable) { return ((Scrollable)l.getView()).getScrollableTracksViewportWidth(); } - if (l.getParent() instanceof JViewport) { - return (((JViewport)l.getParent()).getWidth() > l.getPreferredSize().width); - } return false; } @@ -318,6 +340,10 @@ public class LayerUI * Scrolling containers, like JScrollPane, will use this method * each time the user requests a unit scroll. * + * @param l the {@code JLayer} component where this UI delegate is being installed + * @param visibleRect The view area visible within the viewport + * @param orientation Either SwingConstants.VERTICAL or SwingConstants.HORIZONTAL. + * @param direction Less than zero to scroll up/left, greater than zero for down/right. * @return The "unit" increment for scrolling in the specified direction. * This value should always be positive. * @see Scrollable#getScrollableUnitIncrement(Rectangle, int, int) @@ -367,4 +393,4 @@ public class LayerUI } return super.getBaselineResizeBehavior(c); } -} \ No newline at end of file +} diff --git a/src/share/classes/javax/swing/plaf/basic/BasicSliderUI.java b/src/share/classes/javax/swing/plaf/basic/BasicSliderUI.java index 97e2f60f52b2b8ac6949e40fef910b47795786a4..02bb547d318d318ef4cbe8489f0662123271f5c6 100644 --- a/src/share/classes/javax/swing/plaf/basic/BasicSliderUI.java +++ b/src/share/classes/javax/swing/plaf/basic/BasicSliderUI.java @@ -1507,7 +1507,8 @@ public class BasicSliderUI extends SliderUI{ propertyName == "paintTicks" || propertyName == "paintTrack" || propertyName == "font" || - propertyName == "paintLabels") { + propertyName == "paintLabels" || + propertyName == "Slider.paintThumbArrowShape") { checkedLabelBaselines = false; calculateGeometry(); slider.repaint(); diff --git a/src/share/classes/javax/swing/plaf/metal/MetalFontDesktopProperty.java b/src/share/classes/javax/swing/plaf/metal/MetalFontDesktopProperty.java index 8893782d95195305a02af683f4c08985b49abfb4..831221d57f95ad66538c877afc56ac9a557a915e 100644 --- a/src/share/classes/javax/swing/plaf/metal/MetalFontDesktopProperty.java +++ b/src/share/classes/javax/swing/plaf/metal/MetalFontDesktopProperty.java @@ -1,5 +1,5 @@ /* - * Copyright 2001 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,8 +25,6 @@ package javax.swing.plaf.metal; import java.awt.*; -import java.beans.*; -import javax.swing.*; /** * DesktopProperty that only uses font height in configuring font. This @@ -60,7 +58,7 @@ class MetalFontDesktopProperty extends com.sun.java.swing.plaf.windows.DesktopPr * @param type MetalTheme font type. */ MetalFontDesktopProperty(int type) { - this(propertyMapping[type], Toolkit.getDefaultToolkit(), type); + this(propertyMapping[type], type); } /** @@ -72,8 +70,8 @@ class MetalFontDesktopProperty extends com.sun.java.swing.plaf.windows.DesktopPr * @param type Type of font being used, corresponds to MetalTheme font * type. */ - MetalFontDesktopProperty(String key, Toolkit kit, int type) { - super(key, null, kit); + MetalFontDesktopProperty(String key, int type) { + super(key, null); this.type = type; } diff --git a/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java b/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java index 0743284196124bfcd82062f64e009574dbb58e0c..76eb24df0407dea0448861c09c0793de434b0aab 100644 --- a/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java +++ b/src/share/classes/javax/swing/plaf/metal/MetalLookAndFeel.java @@ -1,5 +1,5 @@ /* - * Copyright 1998-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 1998-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1541,10 +1541,8 @@ public class MetalLookAndFeel extends BasicLookAndFeel table.putDefaults(defaults); if (isWindows() && useSystemFonts() && theme.isSystemTheme()) { - Toolkit kit = Toolkit.getDefaultToolkit(); Object messageFont = new MetalFontDesktopProperty( - "win.messagebox.font.height", kit, MetalTheme. - CONTROL_TEXT_FONT); + "win.messagebox.font.height", MetalTheme.CONTROL_TEXT_FONT); defaults = new Object[] { "OptionPane.messageFont", messageFont, diff --git a/src/share/classes/javax/swing/plaf/nimbus/Defaults.template b/src/share/classes/javax/swing/plaf/nimbus/Defaults.template index 492b53583ed4a5f18f911301996eefedc691a40b..7f4250bc5313b26defcfbd2df5e406d643ad478a 100644 --- a/src/share/classes/javax/swing/plaf/nimbus/Defaults.template +++ b/src/share/classes/javax/swing/plaf/nimbus/Defaults.template @@ -101,14 +101,7 @@ final class ${LAF_NAME}Defaults { */ private FontUIResource defaultFont; - /** - * Map of lists of derived colors keyed by the DerivedColorKeys - */ - private Map derivedColorsMap = - new HashMap(); - - /** Tempory key used for fetching from the derivedColorsMap */ - private final DerivedColorKey tmpDCKey = new DerivedColorKey(); + private ColorTree colorTree = new ColorTree(); /** Listener for changes to user defaults table */ private DefaultsListener defaultsListener = new DefaultsListener(); @@ -117,14 +110,14 @@ final class ${LAF_NAME}Defaults { void initialize() { // add listener for derived colors UIManager.addPropertyChangeListener(defaultsListener); - UIManager.getDefaults().addPropertyChangeListener(defaultsListener); + UIManager.getDefaults().addPropertyChangeListener(colorTree); } /** Called by UIManager when this look and feel is uninstalled. */ void uninitialize() { // remove listener for derived colors - UIManager.getDefaults().removePropertyChangeListener(defaultsListener); UIManager.removePropertyChangeListener(defaultsListener); + UIManager.getDefaults().removePropertyChangeListener(colorTree); } /** @@ -663,22 +656,23 @@ ${UI_DEFAULT_INIT} } } - /** - * Get a derived color, derived colors are shared instances and will be - * updated when its parent UIDefault color changes. - * - * @param uiDefaultParentName The parent UIDefault key - * @param hOffset The hue offset - * @param sOffset The saturation offset - * @param bOffset The brightness offset - * @param aOffset The alpha offset - * @return The stored derived color - */ - public DerivedColor getDerivedColor(String uiDefaultParentName, - float hOffset, float sOffset, - float bOffset, int aOffset){ - return getDerivedColor(uiDefaultParentName, hOffset, sOffset, - bOffset, aOffset, true); + private void addColor(UIDefaults d, String uin, int r, int g, int b, int a) { + Color color = new ColorUIResource(new Color(r, g, b, a)); + colorTree.addColor(uin, color); + d.put(uin, color); + } + + private void addColor(UIDefaults d, String uin, String parentUin, + float hOffset, float sOffset, float bOffset, int aOffset) { + addColor(d, uin, parentUin, hOffset, sOffset, bOffset, aOffset, true); + } + + private void addColor(UIDefaults d, String uin, String parentUin, + float hOffset, float sOffset, float bOffset, + int aOffset, boolean uiResource) { + Color color = getDerivedColor(uin, parentUin, + hOffset, sOffset, bOffset, aOffset, uiResource); + d.put(uin, color); } /** @@ -694,89 +688,110 @@ ${UI_DEFAULT_INIT} * false if it should not be a UIResource * @return The stored derived color */ - public DerivedColor getDerivedColor(String uiDefaultParentName, + public DerivedColor getDerivedColor(String parentUin, float hOffset, float sOffset, float bOffset, int aOffset, boolean uiResource){ - tmpDCKey.set(uiDefaultParentName, hOffset, sOffset, bOffset, aOffset, - uiResource); - DerivedColor color = derivedColorsMap.get(tmpDCKey); - if (color == null){ - if (uiResource) { - color = new DerivedColor.UIResource(uiDefaultParentName, - hOffset, sOffset, bOffset, aOffset); - } else { - color = new DerivedColor(uiDefaultParentName, hOffset, sOffset, - bOffset, aOffset); - } - // calculate the initial value - color.rederiveColor(); - // add the listener so that if the color changes we'll propogate it - color.addPropertyChangeListener(defaultsListener); - // add to the derived colors table - derivedColorsMap.put(new DerivedColorKey(uiDefaultParentName, - hOffset, sOffset, bOffset, aOffset, uiResource),color); + return getDerivedColor(null, parentUin, + hOffset, sOffset, bOffset, aOffset, uiResource); + } + + private DerivedColor getDerivedColor(String uin, String parentUin, + float hOffset, float sOffset, + float bOffset, int aOffset, + boolean uiResource) { + DerivedColor color; + if (uiResource) { + color = new DerivedColor.UIResource(parentUin, + hOffset, sOffset, bOffset, aOffset); + } else { + color = new DerivedColor(parentUin, hOffset, sOffset, + bOffset, aOffset); + } + + if (derivedColors.containsKey(color)) { + return derivedColors.get(color); + } else { + derivedColors.put(color, color); + color.rederiveColor(); /// move to ARP.decodeColor() ? + colorTree.addColor(uin, color); + return color; } - return color; } - /** - * Key class for derived colors - */ - private class DerivedColorKey { - private String uiDefaultParentName; - private float hOffset, sOffset, bOffset; - private int aOffset; - private boolean uiResource; - - DerivedColorKey(){} - - DerivedColorKey(String uiDefaultParentName, float hOffset, - float sOffset, float bOffset, int aOffset, - boolean uiResource) { - set(uiDefaultParentName, hOffset, sOffset, bOffset, aOffset, uiResource); + private Map derivedColors = + new HashMap(); + + private class ColorTree implements PropertyChangeListener { + private Node root = new Node(null, null); + private Map nodes = new HashMap(); + + public Color getColor(String uin) { + return nodes.get(uin).color; } - void set (String uiDefaultParentName, float hOffset, - float sOffset, float bOffset, int aOffset, - boolean uiResource) { - this.uiDefaultParentName = uiDefaultParentName; - this.hOffset = hOffset; - this.sOffset = sOffset; - this.bOffset = bOffset; - this.aOffset = aOffset; - this.uiResource = uiResource; + public void addColor(String uin, Color color) { + Node parent = getParentNode(color); + Node node = new Node(color, parent); + parent.children.add(node); + if (uin != null) { + nodes.put(uin, node); + } } - @Override - public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof DerivedColorKey)) return false; - DerivedColorKey that = (DerivedColorKey) o; - if (aOffset != that.aOffset) return false; - if (Float.compare(that.bOffset, bOffset) != 0) return false; - if (Float.compare(that.hOffset, hOffset) != 0) return false; - if (Float.compare(that.sOffset, sOffset) != 0) return false; - if (uiDefaultParentName != null ? - !uiDefaultParentName.equals(that.uiDefaultParentName) : - that.uiDefaultParentName != null) return false; - if (this.uiResource != that.uiResource) return false; - return true; + private Node getParentNode(Color color) { + Node parent = root; + if (color instanceof DerivedColor) { + String parentUin = ((DerivedColor)color).getUiDefaultParentName(); + Node p = nodes.get(parentUin); + if (p != null) { + parent = p; + } + } + return parent; + } + + public void update() { + root.update(); } @Override - public int hashCode() { - int result = super.hashCode(); - result = 31 * result + uiDefaultParentName.hashCode(); - result = 31 * result + hOffset != +0.0f ? - Float.floatToIntBits(hOffset) : 0; - result = 31 * result + sOffset != +0.0f ? - Float.floatToIntBits(sOffset) : 0; - result = 31 * result + bOffset != +0.0f ? - Float.floatToIntBits(bOffset) : 0; - result = 31 * result + aOffset; - result = 31 * result + (uiResource ? 1 : 0); - return result; + public void propertyChange(PropertyChangeEvent ev) { + String name = ev.getPropertyName(); + Node node = nodes.get(name); + if (node != null) { + // this is a registered color + node.parent.children.remove(node); + Color color = (Color) ev.getNewValue(); + Node parent = getParentNode(color); + node.set(color, parent); + parent.children.add(node); + node.update(); + } + } + + class Node { + Color color; + Node parent; + List children = new LinkedList(); + + Node(Color color, Node parent) { + set(color, parent); + } + + public void set(Color color, Node parent) { + this.color = color; + this.parent = parent; + } + + public void update() { + if (color instanceof DerivedColor) { + ((DerivedColor)color).rederiveColor(); + } + for (Node child: children) { + child.update(); + } + } } } @@ -786,49 +801,12 @@ ${UI_DEFAULT_INIT} private class DefaultsListener implements PropertyChangeListener { @Override public void propertyChange(PropertyChangeEvent evt) { - Object src = evt.getSource(); - String key = evt.getPropertyName(); - if (key.equals("lookAndFeel")){ + if ("lookAndFeel".equals(evt.getPropertyName())) { // LAF has been installed, this is the first point at which we // can access our defaults table via UIManager so before now // all derived colors will be incorrect. // First we need to update - for (DerivedColor color : derivedColorsMap.values()) { - color.rederiveColor(); - } - } else if (src instanceof DerivedColor && key.equals("rgb")) { - // derived color that is in UIManager defaults has changed - // update all its dependent colors. Don't worry about doing - // this recursively since calling rederiveColor will cause - // another PCE to be fired, ending up here and essentially - // recursing - DerivedColor parentColor = (DerivedColor)src; - String parentKey = null; - Set> entries = - UIManager.getDefaults().entrySet(); - - for (Map.Entry entry : entries) { - Object value = entry.getValue(); - if (value == parentColor) { - parentKey = entry.getKey().toString(); - } - } - - if (parentKey == null) { - //couldn't find the DerivedColor in the UIDefaults map, - //so we just bail. - return; - } - - for (Map.Entry entry : entries) { - Object value = entry.getValue(); - if (value instanceof DerivedColor) { - DerivedColor color = (DerivedColor)entry.getValue(); - if (parentKey.equals(color.getUiDefaultParentName())) { - color.rederiveColor(); - } - } - } + colorTree.update(); } } } @@ -875,4 +853,3 @@ ${UI_DEFAULT_INIT} } } } - diff --git a/src/share/classes/javax/swing/plaf/nimbus/DerivedColor.java b/src/share/classes/javax/swing/plaf/nimbus/DerivedColor.java index 20b7b1aacec0faeddc320c44707baed27dbb870a..56bac5f4fb67737491bfbb8346914506c184e7c4 100644 --- a/src/share/classes/javax/swing/plaf/nimbus/DerivedColor.java +++ b/src/share/classes/javax/swing/plaf/nimbus/DerivedColor.java @@ -39,8 +39,6 @@ import java.beans.PropertyChangeListener; * @author Jasper Potts */ class DerivedColor extends Color { - private final PropertyChangeSupport changeSupport = - new PropertyChangeSupport(this); private final String uiDefaultParentName; private final float hOffset, sOffset, bOffset; private final int aOffset; @@ -79,7 +77,6 @@ class DerivedColor extends Color { * Recalculate the derived color from the UIManager parent color and offsets */ public void rederiveColor() { - int old = argbValue; Color src = UIManager.getColor(uiDefaultParentName); if (src != null) { float[] tmp = Color.RGBtoHSB(src.getRed(), src.getGreen(), src.getBlue(), null); @@ -97,7 +94,6 @@ class DerivedColor extends Color { int alpha = clamp(aOffset); argbValue = (Color.HSBtoRGB(tmp[0], tmp[1], tmp[2]) & 0xFFFFFF) | (alpha << 24); } - changeSupport.firePropertyChange("rgb", old, argbValue); } /** @@ -141,35 +137,6 @@ class DerivedColor extends Color { return result; } - /** - * Add a PropertyChangeListener to the listener list. - * The listener is registered for all properties. - * The same listener object may be added more than once, and will be called - * as many times as it is added. - * If listener is null, no exception is thrown and no action - * is taken. - * - * @param listener The PropertyChangeListener to be added - */ - public void addPropertyChangeListener(PropertyChangeListener listener) { - changeSupport.addPropertyChangeListener(listener); - } - - /** - * Remove a PropertyChangeListener from the listener list. - * This removes a PropertyChangeListener that was registered - * for all properties. - * If listener was added more than once to the same event - * source, it will be notified one less time after being removed. - * If listener is null, or was never added, no exception is - * thrown and no action is taken. - * - * @param listener The PropertyChangeListener to be removed - */ - public void removePropertyChangeListener(PropertyChangeListener listener) { - changeSupport.removePropertyChangeListener(listener); - } - private float clamp(float value) { if (value < 0) { value = 0; @@ -211,5 +178,15 @@ class DerivedColor extends Color { float bOffset, int aOffset) { super(uiDefaultParentName, hOffset, sOffset, bOffset, aOffset); } + + @Override + public boolean equals(Object o) { + return (o instanceof UIResource) && super.equals(o); + } + + @Override + public int hashCode() { + return super.hashCode() + 7; + } } } diff --git a/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java b/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java index 8c5d121b7e1aa8bd95a4d72abb8e7395a96043e1..3f100bc811b1ce75da4080d4d7fcc6b16463d5ee 100644 --- a/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java +++ b/src/share/classes/javax/swing/plaf/nimbus/NimbusLookAndFeel.java @@ -40,6 +40,9 @@ import java.awt.Container; import java.awt.Graphics2D; import java.awt.LayoutManager; import java.awt.image.BufferedImage; +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import java.util.*; import javax.swing.GrayFilter; import javax.swing.Icon; import javax.swing.JToolBar; @@ -87,6 +90,8 @@ public class NimbusLookAndFeel extends SynthLookAndFeel { */ private UIDefaults uiDefaults; + private DefaultsListener defaultsListener = new DefaultsListener(); + /** * Create a new NimbusLookAndFeel. */ @@ -115,8 +120,7 @@ public class NimbusLookAndFeel extends SynthLookAndFeel { defaults.uninitialize(); // clear all cached images to free memory ImageCache.getInstance().flush(); - // remove the listeners and things installed by NimbusStyle - NimbusStyle.uninitialize(); + UIManager.getDefaults().removePropertyChangeListener(defaultsListener); } /** @@ -515,4 +519,62 @@ public class NimbusLookAndFeel extends SynthLookAndFeel { return obj; } } + + private Map> compiledDefaults = null; + private boolean defaultListenerAdded = false; + + static String parsePrefix(String key) { + if (key == null) { + return null; + } + boolean inquotes = false; + for (int i = 0; i < key.length(); i++) { + char c = key.charAt(i); + if (c == '"') { + inquotes = !inquotes; + } else if ((c == '[' || c == '.') && !inquotes) { + return key.substring(0, i); + } + } + return null; + } + + Map getDefaultsForPrefix(String prefix) { + if (compiledDefaults == null) { + compiledDefaults = new HashMap>(); + for (Map.Entry entry: UIManager.getDefaults().entrySet()) { + if (entry.getKey() instanceof String) { + addDefault((String) entry.getKey(), entry.getValue()); + } + } + if (! defaultListenerAdded) { + UIManager.getDefaults().addPropertyChangeListener(defaultsListener); + defaultListenerAdded = true; + } + } + return compiledDefaults.get(prefix); + } + + private void addDefault(String key, Object value) { + String prefix = parsePrefix(key); + if (prefix != null) { + Map keys = compiledDefaults.get(prefix); + if (keys == null) { + keys = new HashMap(); + compiledDefaults.put(prefix, keys); + } + keys.put(key, value); + } + } + + private class DefaultsListener implements PropertyChangeListener { + @Override public void propertyChange(PropertyChangeEvent ev) { + String key = ev.getPropertyName(); + if ("UIDefaults".equals(key)) { + compiledDefaults = null; + } else { + addDefault(key, ev.getNewValue()); + } + } + } } diff --git a/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java b/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java index 04efc91cf018f42a67e0cee2bfc7b4a39be2d890..a8f8b3fc5b67cb620cc21a0981dfcdc0f00601ca 100644 --- a/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java +++ b/src/share/classes/javax/swing/plaf/nimbus/NimbusStyle.java @@ -26,7 +26,6 @@ package javax.swing.plaf.nimbus; import javax.swing.Painter; -import java.beans.PropertyChangeEvent; import javax.swing.JComponent; import javax.swing.UIDefaults; import javax.swing.UIManager; @@ -39,16 +38,13 @@ import javax.swing.plaf.synth.SynthStyle; import java.awt.Color; import java.awt.Font; import java.awt.Insets; -import java.beans.PropertyChangeListener; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; -import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.TreeMap; -import sun.awt.AppContext; /** *

    A SynthStyle implementation used by Nimbus. Each Region that has been @@ -232,42 +228,6 @@ public final class NimbusStyle extends SynthStyle { super.installDefaults(ctx); } - static String parsePrefix(String key) { - if (key == null) return null; - boolean inquotes = false; - for (int i=0; i> compiledDefaults = - (Map>) - ctx.get("NimbusStyle.defaults"); - - if (compiledDefaults == null) { - // the entire UIDefaults tables are parsed and compiled into - // this map of maps. The key of the compiledDefaults is the - // prefix for each style, while the value is a map of - // keys->values for that prefix. - compiledDefaults = new HashMap>(); - - // get all the defaults from UIManager.getDefaults() and put them - // into the compiledDefaults - compileDefaults(compiledDefaults, UIManager.getDefaults()); - - // This second statement pulls defaults from the laf defaults - UIDefaults lafDefaults = UIManager.getLookAndFeelDefaults(); - compileDefaults(compiledDefaults, lafDefaults); - - // if it has not already been done, add a listener to both - // UIManager.getDefaults() and UIManager.getLookAndFeelDefaults(). - PropertyChangeListener pcl = (PropertyChangeListener) - ctx.get("NimbusStyle.defaults.pcl"); - - // if pcl is null, then it has not yet been registered with - // the UIManager defaults for this app context - if (pcl == null) { - // create a PCL which will simply clear out the compiled - // defaults from the app context, causing it to be recomputed - // on subsequent passes - pcl = new DefaultsListener(); - // add the PCL to both defaults tables that we pay attention - // to, so that if the UIDefaults are updated, then the - // precompiled defaults will be cleared from the app context - // and recomputed on subsequent passes - UIManager.getDefaults().addPropertyChangeListener(pcl); - UIManager.getLookAndFeelDefaults().addPropertyChangeListener(pcl); - // save the PCL to the app context as a marker indicating - // that the PCL has been registered so we don't end up adding - // more than one listener to the UIDefaults tables. - ctx.put("NimbusStyle.defaults.pcl", pcl); - } - - // store the defaults for reuse - ctx.put("NimbusStyle.defaults", compiledDefaults); - } - - TreeMap defaults = compiledDefaults.get(prefix); + Map defaults = + ((NimbusLookAndFeel) UIManager.getLookAndFeel()). + getDefaultsForPrefix(prefix); // inspect the client properties for the key "Nimbus.Overrides". If the // value is an instance of UIDefaults, then these defaults are used @@ -371,52 +274,6 @@ public final class NimbusStyle extends SynthStyle { } } - // Now that I've accumulated all the defaults pertaining to this - // style, call init which will read these defaults and configure - // the default "values". - init(values, defaults); - } - - /** - * Iterates over all the keys in the specified UIDefaults and compiles - * those keys into the comiledDefaults data structure. It relies on - * parsing the "prefix" out of the key. If the key is not a String or is - * null then it is ignored. In all other cases a prefix is parsed out - * (even if that prefix is the empty String or is a "fake" prefix. That - * is, suppose you had a key Foo~~MySpecial.KeyThing~~. In this case this - * is not a Nimbus formatted key, but we don't care, we treat it as if it - * is. This doesn't pose any harm, it will simply never be used). - * - * @param compiledDefaults - * @param d - */ - private void compileDefaults( - Map> compiledDefaults, - UIDefaults d) { - for (Object obj : new HashSet(d.keySet())) { - if (obj instanceof String) { - String key = (String)obj; - String kp = parsePrefix(key); - if (kp == null) continue; - TreeMap map = compiledDefaults.get(kp); - if (map == null) { - map = new TreeMap(); - compiledDefaults.put(kp, map); - } - map.put(key, d.get(key)); - } - } - } - - /** - * Initializes the given Values object with the defaults - * contained in the given TreeMap. - * - * @param v The Values object to be initialized - * @param myDefaults a map of UIDefaults to use in initializing the Values. - * This map must contain only keys associated with this Style. - */ - private void init(Values v, TreeMap myDefaults) { //a list of the different types of states used by this style. This //list may contain only "standard" states (those defined by Synth), //or it may contain custom states, or it may contain only "standard" @@ -433,7 +290,7 @@ public final class NimbusStyle extends SynthStyle { //"values" stateTypes to be a non-null array. //Otherwise, let the "values" stateTypes be null to indicate that //there are no custom states or custom state ordering - String statesString = (String)myDefaults.get(prefix + ".States"); + String statesString = (String)defaults.get(prefix + ".States"); if (statesString != null) { String s[] = statesString.split(","); for (int i=0; i 0) { - v.stateTypes = states.toArray(new State[states.size()]); + values.stateTypes = states.toArray(new State[states.size()]); } //assign codes for each of the state types @@ -490,7 +347,7 @@ public final class NimbusStyle extends SynthStyle { } //Now iterate over all the keys in the defaults table - for (String key : myDefaults.keySet()) { + for (String key : defaults.keySet()) { //The key is something like JButton.Enabled.backgroundPainter, //or JButton.States, or JButton.background. //Remove the "JButton." portion of the key @@ -528,11 +385,11 @@ public final class NimbusStyle extends SynthStyle { //otherwise, assume it is a property and install it on the //values object if ("contentMargins".equals(property)) { - v.contentMargins = (Insets)myDefaults.get(key); + values.contentMargins = (Insets)defaults.get(key); } else if ("States".equals(property)) { //ignore } else { - v.defaults.put(property, myDefaults.get(key)); + values.defaults.put(property, defaults.get(key)); } } else { //it is possible that the developer has a malformed UIDefaults @@ -582,13 +439,13 @@ public final class NimbusStyle extends SynthStyle { //so put it in the UIDefaults associated with that runtime //state if ("backgroundPainter".equals(property)) { - rs.backgroundPainter = (Painter)myDefaults.get(key); + rs.backgroundPainter = getPainter(defaults, key); } else if ("foregroundPainter".equals(property)) { - rs.foregroundPainter = (Painter) myDefaults.get(key); + rs.foregroundPainter = getPainter(defaults, key); } else if ("borderPainter".equals(property)) { - rs.borderPainter = (Painter) myDefaults.get(key); + rs.borderPainter = getPainter(defaults, key); } else { - rs.defaults.put(property, myDefaults.get(key)); + rs.defaults.put(property, defaults.get(key)); } } } @@ -598,7 +455,15 @@ public final class NimbusStyle extends SynthStyle { Collections.sort(runtimeStates, STATE_COMPARATOR); //finally, set the array of runtime states on the values object - v.states = runtimeStates.toArray(new RuntimeState[runtimeStates.size()]); + values.states = runtimeStates.toArray(new RuntimeState[runtimeStates.size()]); + } + + private Painter getPainter(Map defaults, String key) { + Object p = defaults.get(key); + if (p instanceof UIDefaults.LazyValue) { + p = ((UIDefaults.LazyValue)p).createValue(UIManager.getDefaults()); + } + return (p instanceof Painter ? (Painter)p : null); } /** @@ -1245,15 +1110,4 @@ public final class NimbusStyle extends SynthStyle { return hash; } } - - /** - * This listener is used to listen to the UIDefaults tables and clear out - * the cached-precompiled map of defaults in that case. - */ - private static final class DefaultsListener implements PropertyChangeListener { - @Override - public void propertyChange(PropertyChangeEvent evt) { - AppContext.getAppContext().put("NimbusStyle.defaults", null); - } - } } diff --git a/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java b/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java index 4ca139a709d190f13fd0e04440bf364e2ebec8a1..4dd5ddc29e2367111db7a5c1ce46cf29ab60ccaf 100644 --- a/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java +++ b/src/share/classes/javax/swing/plaf/synth/SynthMenuItemLayoutHelper.java @@ -195,7 +195,7 @@ class SynthMenuItemLayoutHelper extends MenuItemLayoutHelper { getHorizontalAlignment(), getVerticalAlignment(), getHorizontalTextPosition(), getVerticalTextPosition(), getViewRect(), iconRect, textRect, getGap()); - textRect.width += getLeftTextExtraWidth() + getRightTextExtraWidth(); + textRect.width += getLeftTextExtraWidth(); Rectangle labelRect = iconRect.union(textRect); getLabelSize().setHeight(labelRect.height); getLabelSize().setWidth(labelRect.width); diff --git a/src/share/classes/javax/swing/text/JTextComponent.java b/src/share/classes/javax/swing/text/JTextComponent.java index fc24214a844309b417de08bc90d0aa6c2e62bc31..371afda48b049020ac985b62b64e7417acf7abd9 100644 --- a/src/share/classes/javax/swing/text/JTextComponent.java +++ b/src/share/classes/javax/swing/text/JTextComponent.java @@ -2069,8 +2069,9 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A * width to match its own */ public boolean getScrollableTracksViewportWidth() { - if (getParent() instanceof JViewport) { - return (getParent().getWidth() > getPreferredSize().width); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + return port.getWidth() > getPreferredSize().width; } return false; } @@ -2089,8 +2090,9 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A * to match its own */ public boolean getScrollableTracksViewportHeight() { - if (getParent() instanceof JViewport) { - return (getParent().getHeight() > getPreferredSize().height); + JViewport port = SwingUtilities2.getViewport(this); + if (port != null) { + return (port.getHeight() > getPreferredSize().height); } return false; } @@ -4813,7 +4815,18 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A new AttributedString(text, composedIndex, text.getEndIndex())); } - private boolean saveComposedText(int pos) { + /** + * Saves composed text around the specified position. + * + * The composed text (if any) around the specified position is saved + * in a backing store and removed from the document. + * + * @param pos document position to identify the composed text location + * @return {@code true} if the composed text exists and is saved, + * {@code false} otherwise + * @see #restoreComposedText + */ + protected boolean saveComposedText(int pos) { if (composedTextExists()) { int start = composedTextStart.getOffset(); int len = composedTextEnd.getOffset() - @@ -4828,7 +4841,15 @@ public abstract class JTextComponent extends JComponent implements Scrollable, A return false; } - private void restoreComposedText() { + /** + * Restores composed text previously saved by {@code saveComposedText}. + * + * The saved composed text is inserted back into the document. This method + * should be invoked only if {@code saveComposedText} returns {@code true}. + * + * @see #saveComposedText + */ + protected void restoreComposedText() { Document doc = getDocument(); try { doc.insertString(caret.getDot(), diff --git a/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java b/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java index 2eb24e84616c2cd3962a16cebd4eb924a2481d58..0225fac4a039f3ad4f1cf7a5d438023c09ca75f0 100644 --- a/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java +++ b/src/share/classes/javax/swing/tree/DefaultTreeSelectionModel.java @@ -1067,10 +1067,13 @@ public class DefaultTreeSelectionModel implements Cloneable, Serializable, TreeS } /** - * Notifies listeners of a change in path. changePaths should contain - * instances of PathPlaceHolder. - */ - protected void notifyPathChange(Vector changedPaths, + * Notifies listeners of a change in path. changePaths should contain + * instances of PathPlaceHolder. + * + * @deprecated As of JDK version 1.7 + */ + @Deprecated + protected void notifyPathChange(Vector changedPaths, TreePath oldLeadSelection) { int cPathCount = changedPaths.size(); boolean[] newness = new boolean[cPathCount]; @@ -1078,7 +1081,7 @@ public class DefaultTreeSelectionModel implements Cloneable, Serializable, TreeS PathPlaceHolder placeholder; for(int counter = 0; counter < cPathCount; counter++) { - placeholder = changedPaths.elementAt(counter); + placeholder = (PathPlaceHolder) changedPaths.elementAt(counter); newness[counter] = placeholder.isNew; paths[counter] = placeholder.path; } diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasResources.java b/src/share/classes/sun/awt/AWTPermissionFactory.java similarity index 74% rename from make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasResources.java rename to src/share/classes/sun/awt/AWTPermissionFactory.java index 82f9c0dd8a93c0f9e9b645207d37463a8e25175f..73d7e2c5cac3e96915a29333ad22d272664c344a 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasResources.java +++ b/src/share/classes/sun/awt/AWTPermissionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,21 +22,21 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.swingx.designer.utils; -import java.io.File; +package sun.awt; + +import java.awt.AWTPermission; +import sun.security.util.PermissionFactory; /** - * HasResources - interface for model nodes that have resources - * - * @author Created by Jasper Potts (Jul 2, 2007) + * A factory object for AWTPermission objects. */ -public interface HasResources { - - public File getResourcesDir(); - - public File getImagesDir(); - - public File getTemplatesDir(); +public class AWTPermissionFactory + implements PermissionFactory +{ + @Override + public AWTPermission newPermission(String name) { + return new AWTPermission(name); + } } diff --git a/src/share/classes/sun/jkernel/DownloadManager.java b/src/share/classes/sun/jkernel/DownloadManager.java index e945380ebcebef2af0f9a764ff5c2db9546fac71..b93f51c68b4487549d78906869df6ff1c9a41a67 100644 --- a/src/share/classes/sun/jkernel/DownloadManager.java +++ b/src/share/classes/sun/jkernel/DownloadManager.java @@ -31,6 +31,7 @@ import java.util.concurrent.*; import java.util.jar.*; import java.util.zip.*; import sun.misc.Launcher; +import sun.misc.BootClassLoaderHook; /** * Handles the downloading of additional JRE components. The bootstrap class @@ -39,7 +40,7 @@ import sun.misc.Launcher; * *@author Ethan Nicholas */ -public class DownloadManager { +public class DownloadManager extends BootClassLoaderHook { public static final String KERNEL_DOWNLOAD_URL_PROPERTY = "kernel.download.url"; public static final String KERNEL_DOWNLOAD_ENABLED_PROPERTY = @@ -1023,7 +1024,8 @@ public class DownloadManager { /** * Returns true if the current thread is in the process of - * downloading a bundle. This is called by ClassLoader.loadLibrary(), so + * downloading a bundle. This is called by DownloadManager.loadLibrary() + * that is called by System.loadLibrary(), so * that when we run into a library required by the download process itself, * we don't call back into DownloadManager in an attempt to download it * (which would lead to infinite recursion). @@ -1614,6 +1616,77 @@ public class DownloadManager { static native int getCurrentProcessId(); + private DownloadManager() { + } + + // Invoked by jkernel VM after the VM is initialized + static void setBootClassLoaderHook() { + if (!isJREComplete()) { + sun.misc.BootClassLoaderHook.setHook(new DownloadManager()); + } + } + + // Implementation of the BootClassLoaderHook interface + public String loadBootstrapClass(String name) { + // Check for download before we look for it. If + // DownloadManager ends up downloading it, it will add it to + // our search path before we proceed to the findClass(). + return DownloadManager.getBootClassPathEntryForClass(name); + } + + public boolean loadLibrary(String name) { + try { + if (!DownloadManager.isJREComplete() && + !DownloadManager.isCurrentThreadDownloading()) { + return DownloadManager.downloadFile("bin/" + + System.mapLibraryName(name)); + // it doesn't matter if the downloadFile call returns false -- + // it probably just means that this is a user library, as + // opposed to a JRE library + } + } catch (IOException e) { + throw new UnsatisfiedLinkError("Error downloading library " + + name + ": " + e); + } catch (NoClassDefFoundError e) { + // This happens while Java itself is being compiled; DownloadManager + // isn't accessible when this code is first invoked. It isn't an + // issue, as if we can't find DownloadManager, we can safely assume + // that additional code is not available for download. + } + return false; + } + + public boolean prefetchFile(String name) { + try { + return sun.jkernel.DownloadManager.downloadFile(name); + } catch (IOException ioe) { + return false; + } + } + + public String getBootstrapResource(String name) { + try { + // If this is a known JRE resource, ensure that its bundle is + // downloaded. If it isn't known, we just ignore the download + // failure and check to see if we can find the resource anyway + // (which is possible if the boot class path has been modified). + return DownloadManager.getBootClassPathEntryForResource(name); + } catch (NoClassDefFoundError e) { + // This happens while Java itself is being compiled; DownloadManager + // isn't accessible when this code is first invoked. It isn't an + // issue, as if we can't find DownloadManager, we can safely assume + // that additional code is not available for download. + return null; + } + } + + public File[] getAdditionalBootstrapPaths() { + return DownloadManager.getAdditionalBootStrapPaths(); + } + + public boolean isCurrentThreadPrefetching() { + return DownloadManager.isCurrentThreadDownloading(); + } public static void main(String[] arg) throws Exception { AccessController.checkPermission(new AllPermission()); diff --git a/src/share/classes/sun/misc/BootClassLoaderHook.java b/src/share/classes/sun/misc/BootClassLoaderHook.java new file mode 100644 index 0000000000000000000000000000000000000000..28c187ead7350b725591389daa24f34a0d07527b --- /dev/null +++ b/src/share/classes/sun/misc/BootClassLoaderHook.java @@ -0,0 +1,153 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.misc; + +import java.io.File; +import java.io.IOException; + +/** + * BootClassLoaderHook defines an interface for a hook to inject + * into the bootstrap class loader. + * + * In jkernel build, the sun.jkernel.DownloadManager is set as + * a BootClassLoaderHook by the jkernel VM after the VM is initialized. + * + * In other JDK builds, no hook is set. + */ +public abstract class BootClassLoaderHook { + private static BootClassLoaderHook bootLoaderHook = null; + public static synchronized BootClassLoaderHook getHook() { + return bootLoaderHook; + } + + public static synchronized void setHook(BootClassLoaderHook hook) { + if (!VM.isBooted()) { + throw new InternalError("hook can only be set after VM is booted"); + } + if (bootLoaderHook != null) { + throw new InternalError("hook should not be reinitialized"); + } + bootLoaderHook = hook; + } + + protected BootClassLoaderHook() { + } + + /** + * A method to be invoked before a class loader loads + * a bootstrap class. + * + * @param classname the binary name of the class + */ + public static void preLoadClass(String classname) { + BootClassLoaderHook hook = getHook(); + if (hook != null) { + hook.loadBootstrapClass(classname); + } + } + + /** + * A method to be invoked before a class loader loads + * a resource. + * + * @param resourcename the resource name + */ + public static void preLoadResource(String resourcename) { + BootClassLoaderHook hook = getHook(); + if (hook != null) { + hook.getBootstrapResource(resourcename); + } + } + + /** + * A method to be invoked before a library is loaded. + * + * @param libname the name of the library + */ + public static void preLoadLibrary(String libname) { + BootClassLoaderHook hook = getHook(); + if (hook != null) { + hook.loadLibrary(libname); + } + } + + private static final File[] EMPTY_FILE_ARRAY = new File[0]; + + /** + * Returns bootstrap class paths added by the hook. + */ + public static File[] getBootstrapPaths() { + BootClassLoaderHook hook = getHook(); + if (hook != null) { + return hook.getBootstrapPaths(); + } else { + return EMPTY_FILE_ARRAY; + } + } + + /** + * Returns a pathname of a JAR or class that the hook loads + * per this loadClass request; or null. + * + * @param classname the binary name of the class + */ + public abstract String loadBootstrapClass(String className); + + /** + * Returns a pathname of a resource file that the hook loads + * per this getResource request; or null. + * + * @param resourceName the resource name + */ + public abstract String getBootstrapResource(String resourceName); + + /** + * Returns true if the hook successfully performs an operation per + * this loadLibrary request; or false if it fails. + * + * @param libname the name of the library + */ + public abstract boolean loadLibrary(String libname); + + /** + * Returns additional boot class paths added by the hook that + * should be searched by the boot class loader. + */ + public abstract File[] getAdditionalBootstrapPaths(); + + /** + * Returns true if the current thread is in the process of doing + * a prefetching operation. + */ + public abstract boolean isCurrentThreadPrefetching(); + + /** + * Returns true if the hook successfully prefetches the specified file. + * + * @param name a platform independent pathname + */ + public abstract boolean prefetchFile(String name); +} diff --git a/src/share/classes/sun/misc/Launcher.java b/src/share/classes/sun/misc/Launcher.java index 2793f14f05d91f95f8d5abcb3cf0e0e69e156c83..5ebd10fbd1902aed1dc280fc8a071c0ca7677fcf 100644 --- a/src/share/classes/sun/misc/Launcher.java +++ b/src/share/classes/sun/misc/Launcher.java @@ -50,8 +50,6 @@ import java.security.CodeSource; import sun.security.action.GetPropertyAction; import sun.security.util.SecurityConstants; import sun.net.www.ParseUtil; -import sun.jkernel.Bundle; -import sun.jkernel.DownloadManager; /** * This class is used by the system to launch the main application. @@ -248,12 +246,7 @@ public class Launcher { } protected Class findClass(String name) throws ClassNotFoundException { - if (VM.isBootedKernelVM()) { - // Check for download before we look for it. If - // DownloadManager ends up downloading it, it will add it to - // our search path before we proceed to the findClass(). - DownloadManager.getBootClassPathEntryForClass(name); - } + BootClassLoaderHook.preLoadClass(name); return super.findClass(name); } @@ -321,9 +314,7 @@ public class Launcher { public Class loadClass(String name, boolean resolve) throws ClassNotFoundException { - if (VM.isBootedKernelVM()) { - DownloadManager.getBootClassPathEntryForClass(name); - } + BootClassLoaderHook.preLoadClass(name); int i = name.lastIndexOf('.'); if (i != -1) { SecurityManager sm = System.getSecurityManager(); @@ -421,19 +412,17 @@ public class Launcher { } bootstrapClassPath = new URLClassPath(urls, factory); - if (VM.isBootedKernelVM()) { - final File[] additionalBootStrapPaths = - DownloadManager.getAdditionalBootStrapPaths(); - AccessController.doPrivileged(new PrivilegedAction() { - public Object run() { - for (int i=0; i option. If there is + * insufficient memory in the jvmstat perf buffer, the C heap memory + * will be used and thus the application will continue to run if + * the counters added exceeds the buffer size but the counters + * will be missing. + * + * See HotSpot jvmstat implementation for certain circumstances + * that the jvmstat perf buffer is not supported. + * + */ +public class PerfCounter { + private static final Perf perf = + AccessController.doPrivileged(new Perf.GetPerfAction()); + + // Must match values defined in hotspot/src/share/vm/runtime/perfdata.hpp + private final static int V_Constant = 1; + private final static int V_Monotonic = 2; + private final static int V_Variable = 3; + private final static int U_None = 1; + + private final String name; + private final LongBuffer lb; + + private PerfCounter(String name, int type) { + this.name = name; + ByteBuffer bb = perf.createLong(name, U_None, type, 0L); + bb.order(ByteOrder.nativeOrder()); + this.lb = bb.asLongBuffer(); + } + + static PerfCounter newPerfCounter(String name) { + return new PerfCounter(name, V_Variable); + } + + static PerfCounter newConstantPerfCounter(String name) { + PerfCounter c = new PerfCounter(name, V_Constant); + return c; + } + + /** + * Returns the current value of the perf counter. + */ + public synchronized long get() { + return lb.get(0); + } + + /** + * Sets the value of the perf counter to the given newValue. + */ + public synchronized void set(long newValue) { + lb.put(0, newValue); + } + + /** + * Adds the given value to the perf counter. + */ + public synchronized void add(long value) { + long res = get() + value; + lb.put(0, res); + } + + /** + * Increments the perf counter with 1. + */ + public void increment() { + add(1); + } + + /** + * Adds the given interval to the perf counter. + */ + public void addTime(long interval) { + add(interval); + } + + /** + * Adds the elapsed time from the given start time (ns) to the perf counter. + */ + public void addElapsedTimeFrom(long startTime) { + add(System.nanoTime() - startTime); + } + + @Override + public String toString() { + return name + " = " + get(); + } + + static class CoreCounters { + static final PerfCounter pdt = newPerfCounter("sun.classloader.parentDelegationTime"); + static final PerfCounter lc = newPerfCounter("sun.classloader.findClasses"); + static final PerfCounter lct = newPerfCounter("sun.classloader.findClassTime"); + static final PerfCounter rcbt = newPerfCounter("sun.urlClassLoader.readClassBytesTime"); + static final PerfCounter zfc = newPerfCounter("sun.zip.zipFiles"); + static final PerfCounter zfot = newPerfCounter("sun.zip.zipFile.openTime"); + } + + static class WindowsClientCounters { + static final PerfCounter d3dAvailable = newConstantPerfCounter("sun.java2d.d3d.available"); + } + + /** + * Number of findClass calls + */ + public static PerfCounter getFindClasses() { + return CoreCounters.lc; + } + + /** + * Time (ns) spent in finding classes that includes + * lookup and read class bytes and defineClass + */ + public static PerfCounter getFindClassTime() { + return CoreCounters.lct; + } + + /** + * Time (ns) spent in finding classes + */ + public static PerfCounter getReadClassBytesTime() { + return CoreCounters.rcbt; + } + + /** + * Time (ns) spent in the parent delegation to + * the parent of the defining class loader + */ + public static PerfCounter getParentDelegationTime() { + return CoreCounters.pdt; + } + + /** + * Number of zip files opened. + */ + public static PerfCounter getZipFileCount() { + return CoreCounters.zfc; + } + + /** + * Time (ns) spent in opening the zip files that + * includes building the entries hash table + */ + public static PerfCounter getZipFileOpenTime() { + return CoreCounters.zfot; + } + + /** + * D3D graphic pipeline available + */ + public static PerfCounter getD3DAvailable() { + return WindowsClientCounters.d3dAvailable; + } +} diff --git a/src/share/classes/sun/misc/VM.java b/src/share/classes/sun/misc/VM.java index cc7f97f1c8c6e569d5c1c7b6110921026dde0c76..c0090de384a3d2b7345f23f7bca8ba92e86e44ac 100644 --- a/src/share/classes/sun/misc/VM.java +++ b/src/share/classes/sun/misc/VM.java @@ -346,11 +346,6 @@ public class VM { private native static void getThreadStateValues(int[][] vmThreadStateValues, String[][] vmThreadStateNames); - private static boolean kernelVM; - public static boolean isBootedKernelVM() { - return booted && kernelVM; - } - static { initialize(); } diff --git a/src/share/classes/sun/net/spi/DefaultProxySelector.java b/src/share/classes/sun/net/spi/DefaultProxySelector.java index 714dc4ce5c3ba133a47825a1a13ab674ead65e63..af34ada8ccff61ccbc167044c8e16424d6afe727 100644 --- a/src/share/classes/sun/net/spi/DefaultProxySelector.java +++ b/src/share/classes/sun/net/spi/DefaultProxySelector.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,9 @@ package sun.net.spi; -import sun.net.www.http.*; import sun.net.NetProperties; import java.net.*; import java.util.*; -import java.util.regex.*; import java.io.*; import sun.misc.RegexpPool; import java.security.AccessController; @@ -102,17 +100,22 @@ public class DefaultProxySelector extends ProxySelector { */ static class NonProxyInfo { + // Default value for nonProxyHosts, this provides backward compatibility + // by excluding localhost and its litteral notations. + static final String defStringVal = "localhost|127.*|[::1]"; + String hostsSource; RegexpPool hostsPool; - String property; - - static NonProxyInfo ftpNonProxyInfo = new NonProxyInfo("ftp.nonProxyHosts", null, null); - static NonProxyInfo httpNonProxyInfo = new NonProxyInfo("http.nonProxyHosts", null, null); + final String property; + final String defaultVal; + static NonProxyInfo ftpNonProxyInfo = new NonProxyInfo("ftp.nonProxyHosts", null, null, defStringVal); + static NonProxyInfo httpNonProxyInfo = new NonProxyInfo("http.nonProxyHosts", null, null, defStringVal); - NonProxyInfo(String p, String s, RegexpPool pool) { + NonProxyInfo(String p, String s, RegexpPool pool, String d) { property = p; hostsSource = s; hostsPool = pool; + defaultVal = d; } } @@ -130,7 +133,6 @@ public class DefaultProxySelector extends ProxySelector { } String protocol = uri.getScheme(); String host = uri.getHost(); - int port = uri.getPort(); if (host == null) { // This is a hack to ensure backward compatibility in two @@ -149,11 +151,6 @@ public class DefaultProxySelector extends ProxySelector { } i = auth.lastIndexOf(':'); if (i >= 0) { - try { - port = Integer.parseInt(auth.substring(i+1)); - } catch (NumberFormatException e) { - port = -1; - } auth = auth.substring(0,i); } host = auth; @@ -165,13 +162,6 @@ public class DefaultProxySelector extends ProxySelector { } List proxyl = new ArrayList(1); - // special case localhost and loopback addresses to - // not go through proxy - if (isLoopback(host)) { - proxyl.add(Proxy.NO_PROXY); - return proxyl; - } - NonProxyInfo pinfo = null; if ("http".equalsIgnoreCase(protocol)) { @@ -244,9 +234,14 @@ public class DefaultProxySelector extends ProxySelector { nphosts = NetProperties.get(nprop.property); synchronized (nprop) { if (nphosts == null) { - nprop.hostsSource = null; - nprop.hostsPool = null; - } else { + if (nprop.defaultVal != null) { + nphosts = nprop.defaultVal; + } else { + nprop.hostsSource = null; + nprop.hostsPool = null; + } + } + if (nphosts != null) { if (!nphosts.equals(nprop.hostsSource)) { RegexpPool pool = new RegexpPool(); StringTokenizer st = new StringTokenizer(nphosts, "|", false); @@ -334,107 +329,6 @@ public class DefaultProxySelector extends ProxySelector { } } - private boolean isLoopback(String host) { - if (host == null || host.length() == 0) - return false; - - if (host.equalsIgnoreCase("localhost")) - return true; - - /* The string could represent a numerical IP address. - * For IPv4 addresses, check whether it starts with 127. - * For IPv6 addresses, check whether it is ::1 or its equivalent. - * Don't check IPv4-mapped or IPv4-compatible addresses - */ - - if (host.startsWith("127.")) { - // possible IPv4 loopback address - int p = 4; - int q; - int n = host.length(); - // Per RFC2732: At most three digits per byte - // Further constraint: Each element fits in a byte - if ((q = scanByte(host, p, n)) <= p) return false; p = q; - if ((q = scan(host, p, n, '.')) <= p) return q == n && number > 0; p = q; - if ((q = scanByte(host, p, n)) <= p) return false; p = q; - if ((q = scan(host, p, n, '.')) <= p) return q == n && number > 0; p = q; - if ((q = scanByte(host, p, n)) <= p) return false; - return q == n && number > 0; - } - - if (host.endsWith(":1")) { - final Pattern p6 = Pattern.compile("::1|(0:){7}1|(0:){1,6}:1"); - return p6.matcher(host).matches(); - } - return false; - } - - // Character-class masks, in reverse order from RFC2396 because - // initializers for static fields cannot make forward references. - - // Compute a low-order mask for the characters - // between first and last, inclusive - private static long lowMask(char first, char last) { - long m = 0; - int f = Math.max(Math.min(first, 63), 0); - int l = Math.max(Math.min(last, 63), 0); - for (int i = f; i <= l; i++) - m |= 1L << i; - return m; - } - // digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | - // "8" | "9" - private static final long L_DIGIT = lowMask('0', '9'); - private static final long H_DIGIT = 0L; - - // Scan a string of decimal digits whose value fits in a byte - // - private int number; - private int scanByte(String input, int start, int n) - { - int p = start; - int q = scan(input, p, n, L_DIGIT, H_DIGIT); - if (q <= p) return q; - number = Integer.parseInt(input.substring(p, q)); - if (number > 255) return p; - return q; - } - - // Scan a specific char: If the char at the given start position is - // equal to c, return the index of the next char; otherwise, return the - // start position. - // - private int scan(String input, int start, int end, char c) { - if ((start < end) && (input.charAt(start) == c)) - return start + 1; - return start; - } - - // Scan chars that match the given mask pair - // - private int scan(String input, int start, int n, long lowMask, long highMask) - { - int p = start; - while (p < n) { - char c = input.charAt(p); - if (match(c, lowMask, highMask)) { - p++; - continue; - } - break; - } - return p; - } - - // Tell whether the given character is permitted by the given mask pair - private boolean match(char c, long lowMask, long highMask) { - if (c < 64) - return ((1L << c) & lowMask) != 0; - if (c < 128) - return ((1L << (c - 64)) & highMask) != 0; - return false; - } - private native static boolean init(); private native Proxy getSystemProxy(String protocol, String host); } diff --git a/src/share/classes/sun/net/www/http/HttpCapture.java b/src/share/classes/sun/net/www/http/HttpCapture.java index 78debed415f3253f0f557234603ed84f13af9a54..4fc59d4cacd97d5a46f6fb75b5c9b4d1c668d713 100644 --- a/src/share/classes/sun/net/www/http/HttpCapture.java +++ b/src/share/classes/sun/net/www/http/HttpCapture.java @@ -24,14 +24,12 @@ */ package sun.net.www.http; + import java.io.*; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; import java.util.ArrayList; -import java.util.logging.Level; -import java.util.logging.Logger; -import sun.net.NetProperties; import java.util.regex.*; +import sun.net.NetProperties; +import sun.util.logging.PlatformLogger; /** * Main class of the HTTP traffic capture tool. @@ -62,76 +60,6 @@ public class HttpCapture { private static boolean initialized = false; private static volatile ArrayList patterns = null; private static volatile ArrayList capFiles = null; - /* Logging is done in an ugly way so that it does not require the presence - * the java.util.logging package. If the Logger class is not available, then - * logging is turned off. This is for helping the modularization effort. - */ - private static Object logger = null; - private static boolean logging = false; - - static { - Class cl; - try { - cl = Class.forName("java.util.logging.Logger"); - } catch (ClassNotFoundException ex) { - cl = null; - } - if (cl != null) { - try { - Method m = cl.getMethod("getLogger", String.class); - logger = m.invoke(null, "sun.net.www.protocol.http.HttpURLConnection"); - logging = true; - } catch (NoSuchMethodException noSuchMethodException) { - } catch (SecurityException securityException) { - } catch (IllegalAccessException illegalAccessException) { - } catch (IllegalArgumentException illegalArgumentException) { - } catch (InvocationTargetException invocationTargetException) { - } - } - } - - public static void fine(String s) { - if (logging) { - ((Logger)logger).fine(s); - } - } - - public static void finer(String s) { - if (logging) { - ((Logger)logger).finer(s); - } - } - - public static void finest(String s) { - if (logging) { - ((Logger)logger).finest(s); - } - } - - public static void severe(String s) { - if (logging) { - ((Logger)logger).finest(s); - } - } - - public static void info(String s) { - if (logging) { - ((Logger)logger).info(s); - } - } - - public static void warning(String s) { - if (logging) { - ((Logger)logger).warning(s); - } - } - - public static boolean isLoggable(String level) { - if (!logging) { - return false; - } - return ((Logger)logger).isLoggable(Level.parse(level)); - } private static synchronized void init() { initialized = true; @@ -187,7 +115,7 @@ public class HttpCapture { out = new BufferedWriter(new FileWriter(file, true)); out.write("URL: " + url + "\n"); } catch (IOException ex) { - Logger.getLogger(HttpCapture.class.getName()).log(Level.SEVERE, null, ex); + PlatformLogger.getLogger(HttpCapture.class.getName()).severe(null, ex); } } diff --git a/src/share/classes/sun/net/www/http/HttpClient.java b/src/share/classes/sun/net/www/http/HttpClient.java index 5d269bf51ab807e058991431c61380352653597d..37ea7ada1c57f9a17c3b2739e8a9f88ded49484f 100644 --- a/src/share/classes/sun/net/www/http/HttpClient.java +++ b/src/share/classes/sun/net/www/http/HttpClient.java @@ -35,6 +35,7 @@ import sun.net.www.HeaderParser; import sun.net.www.MeteredStream; import sun.net.www.ParseUtil; import sun.net.www.protocol.http.HttpURLConnection; +import sun.util.logging.PlatformLogger; /** * @author Herb Jellinek @@ -804,8 +805,9 @@ public class HttpClient extends NetworkClient { if (isKeepingAlive()) { // Wrap KeepAliveStream if keep alive is enabled. - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("KeepAlive stream used: " + url); + PlatformLogger logger = HttpURLConnection.getHttpLogger(); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("KeepAlive stream used: " + url); } serverInput = new KeepAliveStream(serverInput, pi, cl, this); failedOnce = false; diff --git a/src/share/classes/sun/net/www/http/KeepAliveCache.java b/src/share/classes/sun/net/www/http/KeepAliveCache.java index 4ec0111651a5e4099607c8ae45526ee9366e3396..5e41c33ae1156ec833ce145bfe13a14ede95994a 100644 --- a/src/share/classes/sun/net/www/http/KeepAliveCache.java +++ b/src/share/classes/sun/net/www/http/KeepAliveCache.java @@ -25,12 +25,11 @@ package sun.net.www.http; -import java.io.InputStream; import java.io.IOException; import java.io.NotSerializableException; -import java.util.*; +import java.util.ArrayList; +import java.util.HashMap; import java.net.URL; -import java.util.concurrent.ConcurrentHashMap; /** * A class that implements a cache of idle Http connections for keep-alive @@ -39,7 +38,7 @@ import java.util.concurrent.ConcurrentHashMap; * @author Dave Brown */ public class KeepAliveCache - extends ConcurrentHashMap + extends HashMap implements Runnable { private static final long serialVersionUID = -2937172892064557949L; @@ -163,8 +162,8 @@ public class KeepAliveCache * Errs on the side of caution (leave connections idle for a relatively * short time). */ + @Override public void run() { - int total_cache; do { try { Thread.sleep(LIFETIME); @@ -311,6 +310,7 @@ class KeepAliveKey { /** * Determine whether or not two objects of this type are equal */ + @Override public boolean equals(Object obj) { if ((obj instanceof KeepAliveKey) == false) return false; @@ -325,6 +325,7 @@ class KeepAliveKey { * The hashCode() for this object is the string hashCode() of * concatenation of the protocol, host name and port. */ + @Override public int hashCode() { String str = protocol+host+port; return this.obj == null? str.hashCode() : diff --git a/src/share/classes/sun/net/www/http/KeepAliveStream.java b/src/share/classes/sun/net/www/http/KeepAliveStream.java index 3a64c465e54d3fee2a86e405d112eccbc1155b60..ff5ffada90762a92940dd33555bfc439dfd36fd4 100644 --- a/src/share/classes/sun/net/www/http/KeepAliveStream.java +++ b/src/share/classes/sun/net/www/http/KeepAliveStream.java @@ -25,10 +25,7 @@ package sun.net.www.http; -import java.net.URL; -import java.net.HttpURLConnection; import java.io.*; -import java.util.StringTokenizer; import sun.net.ProgressSource; import sun.net.www.MeteredStream; @@ -50,9 +47,8 @@ class KeepAliveStream extends MeteredStream implements Hurryable { // has this KeepAliveStream been put on the queue for asynchronous cleanup. protected boolean queuedForCleanup = false; - private static KeepAliveStreamCleaner queue = new KeepAliveStreamCleaner(); - private static Thread cleanerThread = null; - private static boolean startCleanupThread; + private static final KeepAliveStreamCleaner queue = new KeepAliveStreamCleaner(); + private static Thread cleanerThread; // null /** * Constructor @@ -155,43 +151,46 @@ class KeepAliveStream extends MeteredStream implements Hurryable { } } - private static synchronized void queueForCleanup(KeepAliveCleanerEntry kace) { - if(queue != null && !kace.getQueuedForCleanup()) { - if (!queue.offer(kace)) { - kace.getHttpClient().closeServer(); - return; - } + private static void queueForCleanup(KeepAliveCleanerEntry kace) { + synchronized(queue) { + if(!kace.getQueuedForCleanup()) { + if (!queue.offer(kace)) { + kace.getHttpClient().closeServer(); + return; + } - kace.setQueuedForCleanup(); - } + kace.setQueuedForCleanup(); + queue.notifyAll(); + } - startCleanupThread = (cleanerThread == null); - if (!startCleanupThread) { - if (!cleanerThread.isAlive()) { - startCleanupThread = true; + boolean startCleanupThread = (cleanerThread == null); + if (!startCleanupThread) { + if (!cleanerThread.isAlive()) { + startCleanupThread = true; + } } - } - if (startCleanupThread) { - java.security.AccessController.doPrivileged( - new java.security.PrivilegedAction() { - public Void run() { - // We want to create the Keep-Alive-SocketCleaner in the - // system threadgroup - ThreadGroup grp = Thread.currentThread().getThreadGroup(); - ThreadGroup parent = null; - while ((parent = grp.getParent()) != null) { - grp = parent; + if (startCleanupThread) { + java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + public Void run() { + // We want to create the Keep-Alive-SocketCleaner in the + // system threadgroup + ThreadGroup grp = Thread.currentThread().getThreadGroup(); + ThreadGroup parent = null; + while ((parent = grp.getParent()) != null) { + grp = parent; + } + + cleanerThread = new Thread(grp, queue, "Keep-Alive-SocketCleaner"); + cleanerThread.setDaemon(true); + cleanerThread.setPriority(Thread.MAX_PRIORITY - 2); + cleanerThread.start(); + return null; } - - cleanerThread = new Thread(grp, queue, "Keep-Alive-SocketCleaner"); - cleanerThread.setDaemon(true); - cleanerThread.setPriority(Thread.MAX_PRIORITY - 2); - cleanerThread.start(); - return null; - } - }); - } + }); + } + } // queue } protected long remainingToRead() { diff --git a/src/share/classes/sun/net/www/http/KeepAliveStreamCleaner.java b/src/share/classes/sun/net/www/http/KeepAliveStreamCleaner.java index 0b19b6bb88db8839f345c2da36975c3183e3b4a0..6bb28d68d9cb4b2c9539c74548b33a6462feacb2 100644 --- a/src/share/classes/sun/net/www/http/KeepAliveStreamCleaner.java +++ b/src/share/classes/sun/net/www/http/KeepAliveStreamCleaner.java @@ -25,9 +25,8 @@ package sun.net.www.http; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.TimeUnit; import java.io.IOException; +import java.util.LinkedList; import sun.net.NetProperties; import java.security.AccessController; import java.security.PrivilegedAction; @@ -44,7 +43,9 @@ import java.security.PrivilegedAction; */ @SuppressWarnings("serial") // never serialized -public class KeepAliveStreamCleaner extends LinkedBlockingQueue implements Runnable +class KeepAliveStreamCleaner + extends LinkedList + implements Runnable { // maximum amount of remaining data that we will try to cleanup protected static int MAX_DATA_REMAINING = 512; @@ -78,23 +79,39 @@ public class KeepAliveStreamCleaner extends LinkedBlockingQueue= MAX_CAPACITY) + return false; - public KeepAliveStreamCleaner(int capacity) - { - super(capacity); + return super.offer(e); } + @Override public void run() { KeepAliveCleanerEntry kace = null; do { try { - kace = poll((long)TIMEOUT, TimeUnit.MILLISECONDS); + synchronized(this) { + long before = System.currentTimeMillis(); + long timeout = TIMEOUT; + while ((kace = poll()) == null) { + this.wait(timeout); + + long after = System.currentTimeMillis(); + long elapsed = after - before; + if (elapsed > timeout) { + /* one last try */ + kace = poll(); + break; + } + before = after; + timeout -= elapsed; + } + } + if(kace == null) break; diff --git a/src/share/classes/sun/net/www/protocol/http/AuthCache.java b/src/share/classes/sun/net/www/protocol/http/AuthCache.java index 26ad1ac7bbcd70e38dade1777f492e62076fc1aa..704ca1b7f218c9d254a3a4431d4706dbd0b56900 100644 --- a/src/share/classes/sun/net/www/protocol/http/AuthCache.java +++ b/src/share/classes/sun/net/www/protocol/http/AuthCache.java @@ -25,14 +25,6 @@ package sun.net.www.protocol.http; -import java.io.IOException; -import java.net.URL; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.ListIterator; -import java.util.Enumeration; -import java.util.HashMap; - /** * @author Michael McMahon * @@ -49,7 +41,7 @@ public interface AuthCache { * A:[B:]C:D:E[:F] Between 4 and 6 fields separated by ":" * where the fields have the following meaning: * A is "s" or "p" for server or proxy authentication respectively - * B is optional and is "D", "B", or "N" for digest, basic or ntlm auth. + * B is optional and is the {@link AuthScheme}, e.g. BASIC, DIGEST, NTLM, etc * C is either "http" or "https" * D is the hostname * E is the port number diff --git a/src/share/classes/sun/net/www/protocol/http/AuthCacheValue.java b/src/share/classes/sun/net/www/protocol/http/AuthCacheValue.java index 539d483b2e41ee9c5123e4067d1065a8c74b94a4..27eca1a6dc76be2a58d330037c7e71313b39fe0c 100644 --- a/src/share/classes/sun/net/www/protocol/http/AuthCacheValue.java +++ b/src/share/classes/sun/net/www/protocol/http/AuthCacheValue.java @@ -25,15 +25,8 @@ package sun.net.www.protocol.http; -import java.io.IOException; import java.io.Serializable; -import java.net.*; -import java.util.Hashtable; -import java.util.LinkedList; -import java.util.ListIterator; -import java.util.Enumeration; -import java.util.HashMap; - +import java.net.PasswordAuthentication; /** * AuthCacheValue: interface to minimise exposure to authentication cache @@ -62,8 +55,16 @@ public abstract class AuthCacheValue implements Serializable { AuthCacheValue() {} + /** + * Proxy or Server + */ abstract Type getAuthType (); + /** + * Authentication scheme + */ + abstract AuthScheme getAuthScheme(); + /** * name of server/proxy */ diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/HasUIStyle.java b/src/share/classes/sun/net/www/protocol/http/AuthScheme.java similarity index 78% rename from make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/HasUIStyle.java rename to src/share/classes/sun/net/www/protocol/http/AuthScheme.java index e73b43405d94b05e2bdd450a0d72ba52f940aab4..bdc070fd9aa746a77885241f04e0997c367f2b5f 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/HasUIStyle.java +++ b/src/share/classes/sun/net/www/protocol/http/AuthScheme.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,15 +22,17 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.synthdesigner.synthmodel; +package sun.net.www.protocol.http; -/** - * HasUIStyle - A marker interface for all classes that have a UIStyle - * - * @author Richard Bair - * @author Jasper Potts +/* Authentication schemes supported by the http implementation. New schemes, if + * supported, should be defined here. */ -public interface HasUIStyle { - - public UIStyle getStyle(); +public enum AuthScheme { + BASIC, + DIGEST, + NTLM, + NEGOTIATE, + KERBEROS, + UNKNOWN; } + diff --git a/src/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java b/src/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java index 042ad693d5200c06ee1968d7edaf22af6496acd6..cb3362efe860dd6ea9967cb5c2c1da75bdab5a95 100644 --- a/src/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java +++ b/src/share/classes/sun/net/www/protocol/http/AuthenticationInfo.java @@ -85,6 +85,11 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { AuthCacheValue.Type.Server: AuthCacheValue.Type.Proxy; } + + AuthScheme getAuthScheme() { + return authScheme; + } + public String getHost() { return host; } @@ -151,7 +156,7 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { } //public String toString () { - //return ("{"+type+":"+authType+":"+protocol+":"+host+":"+port+":"+realm+":"+path+"}"); + //return ("{"+type+":"+authScheme+":"+protocol+":"+host+":"+port+":"+realm+":"+path+"}"); //} // REMIND: This cache just grows forever. We should put in a bounded @@ -160,8 +165,8 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { /** The type (server/proxy) of authentication this is. Used for key lookup */ char type; - /** The authentication type (basic/digest). Also used for key lookup */ - char authType; + /** The authentication scheme (basic/digest). Also used for key lookup */ + AuthScheme authScheme; /** The protocol/scheme (i.e. http or https ). Need to keep the caches * logically separate for the two protocols. This field is only used @@ -183,9 +188,9 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { String path; /** Use this constructor only for proxy entries */ - AuthenticationInfo(char type, char authType, String host, int port, String realm) { + AuthenticationInfo(char type, AuthScheme authScheme, String host, int port, String realm) { this.type = type; - this.authType = authType; + this.authScheme = authScheme; this.protocol = ""; this.host = host.toLowerCase(); this.port = port; @@ -206,9 +211,9 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { * Constructor used to limit the authorization to the path within * the URL. Use this constructor for origin server entries. */ - AuthenticationInfo(char type, char authType, URL url, String realm) { + AuthenticationInfo(char type, AuthScheme authScheme, URL url, String realm) { this.type = type; - this.authType = authType; + this.authScheme = authScheme; this.protocol = url.getProtocol().toLowerCase(); this.host = url.getHost().toLowerCase(); this.port = url.getPort(); @@ -264,12 +269,12 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { * In this case we do not use the path because the protection space * is identified by the host:port:realm only */ - static AuthenticationInfo getServerAuth(URL url, String realm, char atype) { + static AuthenticationInfo getServerAuth(URL url, String realm, AuthScheme scheme) { int port = url.getPort(); if (port == -1) { port = url.getDefaultPort(); } - String key = SERVER_AUTHENTICATION + ":" + atype + ":" + url.getProtocol().toLowerCase() + String key = SERVER_AUTHENTICATION + ":" + scheme + ":" + url.getProtocol().toLowerCase() + ":" + url.getHost().toLowerCase() + ":" + port + ":" + realm; AuthenticationInfo cached = getAuth(key, null); if ((cached == null) && requestIsInProgress (key)) { @@ -308,8 +313,8 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { * Used in response to a challenge. Note, the protocol field is always * blank for proxies. */ - static AuthenticationInfo getProxyAuth(String host, int port, String realm, char atype) { - String key = PROXY_AUTHENTICATION + ":" + atype + "::" + host.toLowerCase() + static AuthenticationInfo getProxyAuth(String host, int port, String realm, AuthScheme scheme) { + String key = PROXY_AUTHENTICATION + ":" + scheme + "::" + host.toLowerCase() + ":" + port + ":" + realm; AuthenticationInfo cached = (AuthenticationInfo) cache.get(key, null); if ((cached == null) && requestIsInProgress (key)) { @@ -393,13 +398,6 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { */ abstract boolean isAuthorizationStale (String header); - /** - * Check for any expected authentication information in the response - * from the server - */ - abstract void checkResponse (String header, String method, URL url) - throws IOException; - /** * Give a key for hash table lookups. * @param includeRealm if you want the realm considered. Preemptively @@ -409,7 +407,7 @@ abstract class AuthenticationInfo extends AuthCacheValue implements Cloneable { // This must be kept in sync with the getXXXAuth() methods in this // class. if (includeRealm) { - return type + ":" + authType + ":" + protocol + ":" + return type + ":" + authScheme + ":" + protocol + ":" + host + ":" + port + ":" + realm; } else { return type + ":" + protocol + ":" + host + ":" + port; diff --git a/src/share/classes/sun/net/www/protocol/http/BasicAuthentication.java b/src/share/classes/sun/net/www/protocol/http/BasicAuthentication.java index 22f1c28a49f0b0a702c07dc10338af996b67ace1..7a92067f050f46d6ee08d9c913a7f8286f05f9d6 100644 --- a/src/share/classes/sun/net/www/protocol/http/BasicAuthentication.java +++ b/src/share/classes/sun/net/www/protocol/http/BasicAuthentication.java @@ -44,8 +44,6 @@ class BasicAuthentication extends AuthenticationInfo { private static final long serialVersionUID = 100L; - static final char BASIC_AUTH = 'B'; - /** The authentication string for this host, port, and realm. This is a simple BASE64 encoding of "login:password". */ String auth; @@ -56,7 +54,7 @@ class BasicAuthentication extends AuthenticationInfo { public BasicAuthentication(boolean isProxy, String host, int port, String realm, PasswordAuthentication pw) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - BASIC_AUTH, host, port, realm); + AuthScheme.BASIC, host, port, realm); String plain = pw.getUserName() + ":"; byte[] nameBytes = null; try { @@ -86,7 +84,7 @@ class BasicAuthentication extends AuthenticationInfo { public BasicAuthentication(boolean isProxy, String host, int port, String realm, String auth) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - BASIC_AUTH, host, port, realm); + AuthScheme.BASIC, host, port, realm); this.auth = "Basic " + auth; } @@ -96,7 +94,7 @@ class BasicAuthentication extends AuthenticationInfo { public BasicAuthentication(boolean isProxy, URL url, String realm, PasswordAuthentication pw) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - BASIC_AUTH, url, realm); + AuthScheme.BASIC, url, realm); String plain = pw.getUserName() + ":"; byte[] nameBytes = null; try { @@ -126,7 +124,7 @@ class BasicAuthentication extends AuthenticationInfo { public BasicAuthentication(boolean isProxy, URL url, String realm, String auth) { super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, - BASIC_AUTH, url, realm); + AuthScheme.BASIC, url, realm); this.auth = "Basic " + auth; } @@ -180,13 +178,6 @@ class BasicAuthentication extends AuthenticationInfo { return false; } - /** - * For Basic Authentication, there is no security information in the - * response - */ - void checkResponse (String header, String method, URL url) { - } - /** * @return the common root path between npath and path. * This is used to detect when we have an authentication for two diff --git a/src/share/classes/sun/net/www/protocol/http/DigestAuthentication.java b/src/share/classes/sun/net/www/protocol/http/DigestAuthentication.java index 8ddaa4d87d3b83f79445527c54e1cd85c6bccf66..e62e3c2eccf23d2d4df3082f269e99ee8b57c653 100644 --- a/src/share/classes/sun/net/www/protocol/http/DigestAuthentication.java +++ b/src/share/classes/sun/net/www/protocol/http/DigestAuthentication.java @@ -38,7 +38,6 @@ import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import static sun.net.www.protocol.http.HttpURLConnection.HTTP_CONNECT; - /** * DigestAuthentication: Encapsulate an http server authentication using * the "Digest" scheme, as described in RFC2069 and updated in RFC2617 @@ -50,8 +49,6 @@ class DigestAuthentication extends AuthenticationInfo { private static final long serialVersionUID = 100L; - static final char DIGEST_AUTH = 'D'; - private String authMethod; // Authentication parameters defined in RFC2617. @@ -178,7 +175,10 @@ class DigestAuthentication extends AuthenticationInfo { public DigestAuthentication(boolean isProxy, URL url, String realm, String authMethod, PasswordAuthentication pw, Parameters params) { - super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, DIGEST_AUTH,url, realm); + super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, + AuthScheme.DIGEST, + url, + realm); this.authMethod = authMethod; this.pw = pw; this.params = params; @@ -187,7 +187,11 @@ class DigestAuthentication extends AuthenticationInfo { public DigestAuthentication(boolean isProxy, String host, int port, String realm, String authMethod, PasswordAuthentication pw, Parameters params) { - super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, DIGEST_AUTH,host, port, realm); + super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, + AuthScheme.DIGEST, + host, + port, + realm); this.authMethod = authMethod; this.pw = pw; this.params = params; @@ -287,7 +291,7 @@ class DigestAuthentication extends AuthenticationInfo { uri = HttpURLConnection.connectRequestURI(conn.getURL()); method = HTTP_CONNECT; } else { - uri = conn.getURL().getFile(); + uri = conn.getRequestURI(); method = conn.getMethod(); } @@ -381,7 +385,11 @@ class DigestAuthentication extends AuthenticationInfo { public void checkResponse (String header, String method, URL url) throws IOException { - String uri = url.getFile(); + checkResponse (header, method, url.getFile()); + } + + public void checkResponse (String header, String method, String uri) + throws IOException { char[] passwd = pw.getPassword(); String username = pw.getUserName(); boolean qop = params.authQop(); diff --git a/src/share/classes/sun/net/www/protocol/http/HttpLogFormatter.java b/src/share/classes/sun/net/www/protocol/http/HttpLogFormatter.java index 97b9be64ed17691ed1205f4041235b51fdfdfde1..b1b5a0d78212f0b5729cf37d280aadd71d7f2aee 100644 --- a/src/share/classes/sun/net/www/protocol/http/HttpLogFormatter.java +++ b/src/share/classes/sun/net/www/protocol/http/HttpLogFormatter.java @@ -49,8 +49,10 @@ public class HttpLogFormatter extends java.util.logging.SimpleFormatter { @Override public String format(LogRecord record) { - if (!"sun.net.www.http.HttpCapture".equalsIgnoreCase(record.getSourceClassName())) { - // Don't change format for stuff that doesn't concern us + String sourceClassName = record.getSourceClassName(); + if (sourceClassName == null || + !(sourceClassName.startsWith("sun.net.www.protocol.http") || + sourceClassName.startsWith("sun.net.www.http"))) { return super.format(record); } String src = record.getMessage(); diff --git a/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index d56602c50685af79515cc518ba80e29b1e602612..f1a60f85fe3befb948444b47464f96ba9b92a9a6 100644 --- a/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/src/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -57,11 +57,17 @@ import sun.net.www.http.HttpClient; import sun.net.www.http.PosterOutputStream; import sun.net.www.http.ChunkedInputStream; import sun.net.www.http.ChunkedOutputStream; -import sun.net.www.http.HttpCapture; +import sun.util.logging.PlatformLogger; import java.text.SimpleDateFormat; import java.util.TimeZone; import java.net.MalformedURLException; import java.nio.ByteBuffer; +import static sun.net.www.protocol.http.AuthScheme.BASIC; +import static sun.net.www.protocol.http.AuthScheme.DIGEST; +import static sun.net.www.protocol.http.AuthScheme.NTLM; +import static sun.net.www.protocol.http.AuthScheme.NEGOTIATE; +import static sun.net.www.protocol.http.AuthScheme.KERBEROS; +import static sun.net.www.protocol.http.AuthScheme.UNKNOWN; /** * A class to represent an HTTP connection to a remote object. @@ -231,9 +237,11 @@ public class HttpURLConnection extends java.net.HttpURLConnection { boolean needToCheck = true; private boolean doingNTLM2ndStage = false; /* doing the 2nd stage of an NTLM server authentication */ private boolean doingNTLMp2ndStage = false; /* doing the 2nd stage of an NTLM proxy authentication */ - /* try auth without calling Authenticator */ - private boolean tryTransparentNTLMServer = NTLMAuthentication.supportsTransparentAuth(); - private boolean tryTransparentNTLMProxy = NTLMAuthentication.supportsTransparentAuth(); + + /* try auth without calling Authenticator. Used for transparent NTLM authentication */ + private boolean tryTransparentNTLMServer = true; + private boolean tryTransparentNTLMProxy = true; + /* Used by Windows specific code */ Object authObj; @@ -284,6 +292,10 @@ public class HttpURLConnection extends java.net.HttpURLConnection { private int connectTimeout = -1; private int readTimeout = -1; + /* Logging support */ + private static final PlatformLogger logger = + PlatformLogger.getLogger("sun.net.www.protocol.http.HttpURLConnection"); + /* * privileged request password authentication * @@ -301,20 +313,25 @@ public class HttpURLConnection extends java.net.HttpURLConnection { return java.security.AccessController.doPrivileged( new java.security.PrivilegedAction() { public PasswordAuthentication run() { - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("Requesting Authentication: host =" + host + " url = " + url); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("Requesting Authentication: host =" + host + " url = " + url); } PasswordAuthentication pass = Authenticator.requestPasswordAuthentication( host, addr, port, protocol, prompt, scheme, url, authType); - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("Authentication returned: " + (pass != null ? pass.toString() : "null")); } return pass; } }); } + /* Logging support */ + public static PlatformLogger getHttpLogger() { + return logger; + } + /* * checks the validity of http message header and throws * IllegalArgumentException if invalid. @@ -373,7 +390,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { * request. */ if (!failedOnce) - requests.prepend(method + " " + http.getURLFile()+" " + + requests.prepend(method + " " + getRequestURI()+" " + httpVersion, null); if (!getUseCaches()) { requests.setIfNotSet ("Cache-Control", "no-cache"); @@ -463,8 +480,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { setRequests=true; } - if (HttpCapture.isLoggable("FINE")) { - HttpCapture.fine(requests.toString()); + if (logger.isLoggable(PlatformLogger.FINE)) { + logger.fine(requests.toString()); } http.writeRequests(requests, poster); if (ps.checkError()) { @@ -728,9 +745,9 @@ public class HttpURLConnection extends java.net.HttpURLConnection { && !(cachedResponse instanceof SecureCacheResponse)) { cachedResponse = null; } - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("Cache Request for " + uri + " / " + getRequestMethod()); - HttpCapture.finest("From cache: " + (cachedResponse != null ? cachedResponse.toString() : "null")); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("Cache Request for " + uri + " / " + getRequestMethod()); + logger.finest("From cache: " + (cachedResponse != null ? cachedResponse.toString() : "null")); } if (cachedResponse != null) { cachedHeaders = mapToMessageHeader(cachedResponse.getHeaders()); @@ -769,8 +786,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { }); if (sel != null) { URI uri = sun.net.www.ParseUtil.toURI(url); - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("ProxySelector Request for " + uri); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("ProxySelector Request for " + uri); } Iterator it = sel.select(uri).iterator(); Proxy p; @@ -786,9 +803,9 @@ public class HttpURLConnection extends java.net.HttpURLConnection { http = getNewHttpClient(url, p, connectTimeout, false); http.setReadTimeout(readTimeout); } - if (HttpCapture.isLoggable("FINEST")) { + if (logger.isLoggable(PlatformLogger.FINEST)) { if (p != null) { - HttpCapture.finest("Proxy used: " + p.toString()); + logger.finest("Proxy used: " + p.toString()); } } break; @@ -1018,15 +1035,15 @@ public class HttpURLConnection extends java.net.HttpURLConnection { URI uri = ParseUtil.toURI(url); if (uri != null) { - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("CookieHandler request for " + uri); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("CookieHandler request for " + uri); } Map> cookies = cookieHandler.get( uri, requests.getHeaders(EXCLUDE_HEADERS)); if (!cookies.isEmpty()) { - if (HttpCapture.isLoggable("FINEST")) { - HttpCapture.finest("Cookies retrieved: " + cookies.toString()); + if (logger.isLoggable(PlatformLogger.FINEST)) { + logger.finest("Cookies retrieved: " + cookies.toString()); } for (Map.Entry> entry : cookies.entrySet()) { @@ -1157,8 +1174,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { writeRequests(); } http.parseHTTP(responses, pi, this); - if (HttpCapture.isLoggable("FINE")) { - HttpCapture.fine(responses.toString()); + if (logger.isLoggable(PlatformLogger.FINE)) { + logger.fine(responses.toString()); } inputStream = http.getInputStream(); @@ -1270,7 +1287,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { String raw = srvHdr.raw(); if (!doingNTLM2ndStage) { if ((serverAuthentication != null)&& - !(serverAuthentication instanceof NTLMAuthentication)) { + serverAuthentication.getAuthScheme() != NTLM) { if (serverAuthentication.isAuthorizationStale (raw)) { /* we can retry with the current credentials */ disconnectInternal(); @@ -1523,16 +1540,20 @@ public class HttpURLConnection extends java.net.HttpURLConnection { */ private AuthenticationInfo resetProxyAuthentication(AuthenticationInfo proxyAuthentication, AuthenticationHeader auth) { - if ((proxyAuthentication != null )&& ! (proxyAuthentication instanceof - NTLMAuthentication)) { + if ((proxyAuthentication != null )&& + proxyAuthentication.getAuthScheme() != NTLM) { String raw = auth.raw(); if (proxyAuthentication.isAuthorizationStale (raw)) { /* we can retry with the current credentials */ String value; - if (tunnelState() == TunnelState.SETUP && - proxyAuthentication instanceof DigestAuthentication) { - value = ((DigestAuthentication)proxyAuthentication) - .getHeaderValue(connectRequestURI(url), HTTP_CONNECT); + if (proxyAuthentication instanceof DigestAuthentication) { + DigestAuthentication digestProxy = (DigestAuthentication) + proxyAuthentication; + if (tunnelState() == TunnelState.SETUP) { + value = digestProxy.getHeaderValue(connectRequestURI(url), HTTP_CONNECT); + } else { + value = digestProxy.getHeaderValue(getRequestURI(), method); + } } else { value = proxyAuthentication.getHeaderValue(url, method); } @@ -1602,8 +1623,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { http.parseHTTP(responses, null, this); /* Log the response to the CONNECT */ - if (HttpCapture.isLoggable("FINE")) { - HttpCapture.fine(responses.toString()); + if (logger.isLoggable(PlatformLogger.FINE)) { + logger.fine(responses.toString()); } statusLine = responses.getValue(0); @@ -1730,8 +1751,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { setPreemptiveProxyAuthentication(requests); /* Log the CONNECT request */ - if (HttpCapture.isLoggable("FINE")) { - HttpCapture.fine(requests.toString()); + if (logger.isLoggable(PlatformLogger.FINE)) { + logger.fine(requests.toString()); } http.writeRequests(requests, null); @@ -1748,10 +1769,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection { http.getProxyPortUsed()); if (pauth != null && pauth.supportsPreemptiveAuthorization()) { String value; - if (tunnelState() == TunnelState.SETUP && - pauth instanceof DigestAuthentication) { - value = ((DigestAuthentication)pauth) + if (pauth instanceof DigestAuthentication) { + DigestAuthentication digestProxy = (DigestAuthentication) pauth; + if (tunnelState() == TunnelState.SETUP) { + value = digestProxy .getHeaderValue(connectRequestURI(url), HTTP_CONNECT); + } else { + value = digestProxy.getHeaderValue(getRequestURI(), method); + } } else { value = pauth.getHeaderValue(url, method); } @@ -1776,28 +1801,31 @@ public class HttpURLConnection extends java.net.HttpURLConnection { HeaderParser p = authhdr.headerParser(); String realm = p.findValue("realm"); String scheme = authhdr.scheme(); - char schemeID; + AuthScheme authScheme = UNKNOWN; if ("basic".equalsIgnoreCase(scheme)) { - schemeID = BasicAuthentication.BASIC_AUTH; + authScheme = BASIC; } else if ("digest".equalsIgnoreCase(scheme)) { - schemeID = DigestAuthentication.DIGEST_AUTH; + authScheme = DIGEST; } else if ("ntlm".equalsIgnoreCase(scheme)) { - schemeID = NTLMAuthentication.NTLM_AUTH; + authScheme = NTLM; doingNTLMp2ndStage = true; } else if ("Kerberos".equalsIgnoreCase(scheme)) { - schemeID = NegotiateAuthentication.KERBEROS_AUTH; + authScheme = KERBEROS; doingNTLMp2ndStage = true; } else if ("Negotiate".equalsIgnoreCase(scheme)) { - schemeID = NegotiateAuthentication.NEGOTIATE_AUTH; + authScheme = NEGOTIATE; doingNTLMp2ndStage = true; - } else { - schemeID = 0; } + if (realm == null) realm = ""; - ret = AuthenticationInfo.getProxyAuth(host, port, realm, schemeID); + ret = AuthenticationInfo.getProxyAuth(host, + port, + realm, + authScheme); if (ret == null) { - if (schemeID == BasicAuthentication.BASIC_AUTH) { + switch (authScheme) { + case BASIC: InetAddress addr = null; try { final String finalHost = host; @@ -1818,9 +1846,9 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (a != null) { ret = new BasicAuthentication(true, host, port, realm, a); } - } else if (schemeID == DigestAuthentication.DIGEST_AUTH) { - PasswordAuthentication a = - privilegedRequestPasswordAuthentication( + break; + case DIGEST: + a = privilegedRequestPasswordAuthentication( host, null, port, url.getProtocol(), realm, scheme, url, RequestorType.PROXY); if (a != null) { @@ -1829,29 +1857,49 @@ public class HttpURLConnection extends java.net.HttpURLConnection { ret = new DigestAuthentication(true, host, port, realm, scheme, a, params); } - } else if (schemeID == NTLMAuthentication.NTLM_AUTH) { - PasswordAuthentication a = null; - if (!tryTransparentNTLMProxy) { - a = privilegedRequestPasswordAuthentication( - host, null, port, url.getProtocol(), - "", scheme, url, RequestorType.PROXY); - } - /* If we are not trying transparent authentication then - * we need to have a PasswordAuthentication instance. For - * transparent authentication (Windows only) the username - * and password will be picked up from the current logged - * on users credentials. - */ - if (tryTransparentNTLMProxy || - (!tryTransparentNTLMProxy && a != null)) { - ret = new NTLMAuthentication(true, host, port, a); - } + break; + case NTLM: + if (NTLMAuthenticationProxy.proxy.supported) { + /* tryTransparentNTLMProxy will always be true the first + * time around, but verify that the platform supports it + * otherwise don't try. */ + if (tryTransparentNTLMProxy) { + tryTransparentNTLMProxy = + NTLMAuthenticationProxy.proxy.supportsTransparentAuth; + } + a = null; + if (tryTransparentNTLMProxy) { + logger.finest("Trying Transparent NTLM authentication"); + } else { + a = privilegedRequestPasswordAuthentication( + host, null, port, url.getProtocol(), + "", scheme, url, RequestorType.PROXY); + } + /* If we are not trying transparent authentication then + * we need to have a PasswordAuthentication instance. For + * transparent authentication (Windows only) the username + * and password will be picked up from the current logged + * on users credentials. + */ + if (tryTransparentNTLMProxy || + (!tryTransparentNTLMProxy && a != null)) { + ret = NTLMAuthenticationProxy.proxy.create(true, host, port, a); + } - tryTransparentNTLMProxy = false; - } else if (schemeID == NegotiateAuthentication.NEGOTIATE_AUTH) { + /* set to false so that we do not try again */ + tryTransparentNTLMProxy = false; + } + break; + case NEGOTIATE: ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Negotiate")); - } else if (schemeID == NegotiateAuthentication.KERBEROS_AUTH) { + break; + case KERBEROS: ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos")); + break; + case UNKNOWN: + logger.finest("Unknown/Unsupported authentication scheme: " + scheme); + default: + throw new AssertionError("should not reach here"); } } // For backwards compatibility, we also try defaultAuth @@ -1875,8 +1923,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } } } - if (HttpCapture.isLoggable("FINER")) { - HttpCapture.finer("Proxy Authentication for " + authhdr.toString() +" returned " + (ret != null ? ret.toString() : "null")); + if (logger.isLoggable(PlatformLogger.FINER)) { + logger.finer("Proxy Authentication for " + authhdr.toString() +" returned " + (ret != null ? ret.toString() : "null")); } return ret; } @@ -1896,27 +1944,26 @@ public class HttpURLConnection extends java.net.HttpURLConnection { HeaderParser p = authhdr.headerParser(); String realm = p.findValue("realm"); String scheme = authhdr.scheme(); - char schemeID; + AuthScheme authScheme = UNKNOWN; if ("basic".equalsIgnoreCase(scheme)) { - schemeID = BasicAuthentication.BASIC_AUTH; + authScheme = BASIC; } else if ("digest".equalsIgnoreCase(scheme)) { - schemeID = DigestAuthentication.DIGEST_AUTH; + authScheme = DIGEST; } else if ("ntlm".equalsIgnoreCase(scheme)) { - schemeID = NTLMAuthentication.NTLM_AUTH; + authScheme = NTLM; doingNTLM2ndStage = true; } else if ("Kerberos".equalsIgnoreCase(scheme)) { - schemeID = NegotiateAuthentication.KERBEROS_AUTH; + authScheme = KERBEROS; doingNTLM2ndStage = true; } else if ("Negotiate".equalsIgnoreCase(scheme)) { - schemeID = NegotiateAuthentication.NEGOTIATE_AUTH; + authScheme = NEGOTIATE; doingNTLM2ndStage = true; - } else { - schemeID = 0; } + domain = p.findValue ("domain"); if (realm == null) realm = ""; - ret = AuthenticationInfo.getServerAuth(url, realm, schemeID); + ret = AuthenticationInfo.getServerAuth(url, realm, authScheme); InetAddress addr = null; if (ret == null) { try { @@ -1931,13 +1978,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection { port = url.getDefaultPort(); } if (ret == null) { - if (schemeID == NegotiateAuthentication.KERBEROS_AUTH) { + switch(authScheme) { + case KERBEROS: ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Kerberos")); - } - if (schemeID == NegotiateAuthentication.NEGOTIATE_AUTH) { + break; + case NEGOTIATE: ret = new NegotiateAuthentication(new HttpCallerInfo(authhdr.getHttpCallerInfo(), "Negotiate")); - } - if (schemeID == BasicAuthentication.BASIC_AUTH) { + break; + case BASIC: PasswordAuthentication a = privilegedRequestPasswordAuthentication( url.getHost(), addr, port, url.getProtocol(), @@ -1945,45 +1993,60 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (a != null) { ret = new BasicAuthentication(false, url, realm, a); } - } - - if (schemeID == DigestAuthentication.DIGEST_AUTH) { - PasswordAuthentication a = - privilegedRequestPasswordAuthentication( + break; + case DIGEST: + a = privilegedRequestPasswordAuthentication( url.getHost(), addr, port, url.getProtocol(), realm, scheme, url, RequestorType.SERVER); if (a != null) { digestparams = new DigestAuthentication.Parameters(); ret = new DigestAuthentication(false, url, realm, scheme, a, digestparams); } - } + break; + case NTLM: + if (NTLMAuthenticationProxy.proxy.supported) { + URL url1; + try { + url1 = new URL (url, "/"); /* truncate the path */ + } catch (Exception e) { + url1 = url; + } - if (schemeID == NTLMAuthentication.NTLM_AUTH) { - URL url1; - try { - url1 = new URL (url, "/"); /* truncate the path */ - } catch (Exception e) { - url1 = url; - } - PasswordAuthentication a = null; - if (!tryTransparentNTLMServer) { - a = privilegedRequestPasswordAuthentication( - url.getHost(), addr, port, url.getProtocol(), - "", scheme, url, RequestorType.SERVER); - } + /* tryTransparentNTLMServer will always be true the first + * time around, but verify that the platform supports it + * otherwise don't try. */ + if (tryTransparentNTLMServer) { + tryTransparentNTLMServer = + NTLMAuthenticationProxy.proxy.supportsTransparentAuth; + } + a = null; + if (tryTransparentNTLMServer) { + logger.finest("Trying Transparent NTLM authentication"); + } else { + a = privilegedRequestPasswordAuthentication( + url.getHost(), addr, port, url.getProtocol(), + "", scheme, url, RequestorType.SERVER); + } - /* If we are not trying transparent authentication then - * we need to have a PasswordAuthentication instance. For - * transparent authentication (Windows only) the username - * and password will be picked up from the current logged - * on users credentials. - */ - if (tryTransparentNTLMServer || - (!tryTransparentNTLMServer && a != null)) { - ret = new NTLMAuthentication(false, url1, a); - } + /* If we are not trying transparent authentication then + * we need to have a PasswordAuthentication instance. For + * transparent authentication (Windows only) the username + * and password will be picked up from the current logged + * on users credentials. + */ + if (tryTransparentNTLMServer || + (!tryTransparentNTLMServer && a != null)) { + ret = NTLMAuthenticationProxy.proxy.create(false, url1, a); + } - tryTransparentNTLMServer = false; + /* set to false so that we do not try again */ + tryTransparentNTLMServer = false; + } + break; + case UNKNOWN: + logger.finest("Unknown/Unsupported authentication scheme: " + scheme); + default: + throw new AssertionError("should not reach here"); } } @@ -2005,8 +2068,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } } } - if (HttpCapture.isLoggable("FINER")) { - HttpCapture.finer("Server Authentication for " + authhdr.toString() +" returned " + (ret != null ? ret.toString() : "null")); + if (logger.isLoggable(PlatformLogger.FINER)) { + logger.finer("Server Authentication for " + authhdr.toString() +" returned " + (ret != null ? ret.toString() : "null")); } return ret; } @@ -2020,17 +2083,23 @@ public class HttpURLConnection extends java.net.HttpURLConnection { try { if (!needToCheck) return; - if (validateProxy && currentProxyCredentials != null) { + if ((validateProxy && currentProxyCredentials != null) && + (currentProxyCredentials instanceof DigestAuthentication)) { String raw = responses.findValue ("Proxy-Authentication-Info"); if (inClose || (raw != null)) { - currentProxyCredentials.checkResponse (raw, method, url); + DigestAuthentication da = (DigestAuthentication) + currentProxyCredentials; + da.checkResponse (raw, method, getRequestURI()); currentProxyCredentials = null; } } - if (validateServer && currentServerCredentials != null) { + if ((validateServer && currentServerCredentials != null) && + (currentServerCredentials instanceof DigestAuthentication)) { String raw = responses.findValue ("Authentication-Info"); if (inClose || (raw != null)) { - currentServerCredentials.checkResponse (raw, method, url); + DigestAuthentication da = (DigestAuthentication) + currentServerCredentials; + da.checkResponse (raw, method, url); currentServerCredentials = null; } } @@ -2044,6 +2113,23 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } } + /* The request URI used in the request line for this request. + * Also, needed for digest authentication + */ + + String requestURI = null; + + String getRequestURI() { + if (requestURI == null) { + try { + requestURI = http.getURLFile(); + } catch (IOException e) { + requestURI = ""; + } + } + return requestURI; + } + /* Tells us whether to follow a redirect. If so, it * closes the connection (break any keep-alive) and * resets the url, re-connects, and resets the request @@ -2081,8 +2167,8 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (streaming()) { throw new HttpRetryException (RETRY_MSG3, stat, loc); } - if (HttpCapture.isLoggable("FINE")) { - HttpCapture.fine("Redirected from " + url + " to " + locUrl); + if (logger.isLoggable(PlatformLogger.FINE)) { + logger.fine("Redirected from " + url + " to " + locUrl); } // clear out old response headers!!!! @@ -2105,13 +2191,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection { } setProxiedClient (url, proxyHost, proxyPort); - requests.set(0, method + " " + http.getURLFile()+" " + + requests.set(0, method + " " + getRequestURI()+" " + httpVersion, null); connected = true; } else { // maintain previous headers, just change the name // of the file we're getting url = locUrl; + requestURI = null; // force it to be recalculated if (method.equals("POST") && !Boolean.getBoolean("http.strictPostRedirect") && (stat!=307)) { /* The HTTP/1.1 spec says that a redirect from a POST * *should not* be immediately turned into a GET, and @@ -2149,7 +2236,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { * CacheResponse. */ if (http != null) { - requests.set(0, method + " " + http.getURLFile()+" " + + requests.set(0, method + " " + getRequestURI()+" " + httpVersion, null); int port = url.getPort(); String host = url.getHost(); diff --git a/src/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java b/src/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java new file mode 100644 index 0000000000000000000000000000000000000000..646728fb9e6484f682e9117f0d9b5129f4b04235 --- /dev/null +++ b/src/share/classes/sun/net/www/protocol/http/NTLMAuthenticationProxy.java @@ -0,0 +1,131 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package sun.net.www.protocol.http; + +import java.net.URL; +import java.net.PasswordAuthentication; +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import sun.util.logging.PlatformLogger; + +/** + * Proxy class for loading NTLMAuthentication, so as to remove static + * dependancy. + */ +class NTLMAuthenticationProxy { + private static Method supportsTA; + private static final String clazzStr = "sun.net.www.protocol.http.NTLMAuthentication"; + private static final String supportsTAStr = "supportsTransparentAuth"; + + static final NTLMAuthenticationProxy proxy = tryLoadNTLMAuthentication(); + static final boolean supported = proxy != null ? true : false; + static final boolean supportsTransparentAuth = supported ? supportsTransparentAuth(supportsTA) : false; + + private final Constructor threeArgCtr; + private final Constructor fiveArgCtr; + + private NTLMAuthenticationProxy(Constructor threeArgCtr, + Constructor fiveArgCtr) { + this.threeArgCtr = threeArgCtr; + this.fiveArgCtr = fiveArgCtr; + } + + + AuthenticationInfo create(boolean isProxy, + URL url, + PasswordAuthentication pw) { + try { + return threeArgCtr.newInstance(isProxy, url, pw); + } catch (ReflectiveOperationException roe) { + finest(roe); + } + + return null; + } + + AuthenticationInfo create(boolean isProxy, + String host, + int port, + PasswordAuthentication pw) { + try { + return fiveArgCtr.newInstance(isProxy, host, port, pw); + } catch (ReflectiveOperationException roe) { + finest(roe); + } + + return null; + } + + /* Returns true if the NTLM implementation supports transparent + * authentication (try with the current users credentials before + * prompting for username and password, etc). + */ + private static boolean supportsTransparentAuth(Method method) { + try { + return (Boolean)method.invoke(null); + } catch (ReflectiveOperationException roe) { + finest(roe); + } + + return false; + } + + /** + * Loads the NTLM authentiation implementation through reflection. If + * the class is present, then it must have the required constructors and + * method. Otherwise, it is considered an error. + */ + @SuppressWarnings("unchecked") + private static NTLMAuthenticationProxy tryLoadNTLMAuthentication() { + Class cl; + Constructor threeArg, fiveArg; + try { + cl = (Class)Class.forName(clazzStr, true, null); + if (cl != null) { + threeArg = cl.getConstructor(boolean.class, + URL.class, + PasswordAuthentication.class); + fiveArg = cl.getConstructor(boolean.class, + String.class, + int.class, + PasswordAuthentication.class); + supportsTA = cl.getDeclaredMethod(supportsTAStr); + return new NTLMAuthenticationProxy(threeArg, + fiveArg); + } + } catch (ClassNotFoundException cnfe) { + finest(cnfe); + } catch (ReflectiveOperationException roe) { + throw new AssertionError(roe); + } + + return null; + } + + static void finest(Exception e) { + PlatformLogger logger = HttpURLConnection.getHttpLogger(); + logger.finest("NTLMAuthenticationProxy: " + e); + } +} diff --git a/src/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java b/src/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java index db5d509a3642a8232b907dbf411c7ba59e5fc3e6..6d3931d0958978705136e599902cd2baeede7636 100644 --- a/src/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java +++ b/src/share/classes/sun/net/www/protocol/http/NegotiateAuthentication.java @@ -30,11 +30,14 @@ import java.util.HashMap; import sun.net.www.HeaderParser; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; +import sun.util.logging.PlatformLogger; import java.net.URL; import java.io.IOException; import java.net.Authenticator.RequestorType; - +import java.lang.reflect.Constructor; +import static sun.net.www.protocol.http.AuthScheme.NEGOTIATE; +import static sun.net.www.protocol.http.AuthScheme.KERBEROS; /** * NegotiateAuthentication: @@ -49,9 +52,6 @@ class NegotiateAuthentication extends AuthenticationInfo { final private HttpCallerInfo hci; - static final char NEGOTIATE_AUTH = 'S'; - static final char KERBEROS_AUTH = 'K'; - // These maps are used to manage the GSS availability for diffrent // hosts. The key for both maps is the host name. // supported is set when isSupported is checked, @@ -68,11 +68,10 @@ class NegotiateAuthentication extends AuthenticationInfo { * @param hci a schemed object. */ public NegotiateAuthentication(HttpCallerInfo hci) { - super(RequestorType.PROXY==hci.authType? - PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, - hci.scheme.equalsIgnoreCase("Negotiate")? - NEGOTIATE_AUTH:KERBEROS_AUTH, - hci.url, ""); + super(RequestorType.PROXY==hci.authType ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, + hci.scheme.equalsIgnoreCase("Negotiate") ? NEGOTIATE : KERBEROS, + hci.url, + ""); this.hci = hci; } @@ -215,12 +214,6 @@ class NegotiateAuthentication extends AuthenticationInfo { return negotiator.nextToken(token); } - /** - * no-use for Negotiate - */ - public void checkResponse (String header, String method, URL url) throws IOException { - } - class B64Encoder extends BASE64Encoder { protected int bytesPerLine () { return 100000; // as big as it can be, maybe INT_MAX @@ -249,13 +242,41 @@ abstract class Negotiator { // The current implementation will make sure NegotiatorImpl is not // directly referenced when compiling, thus smooth the way of building // the J2SE platform where HttpURLConnection is a bootstrap class. + // + // Makes NegotiatorImpl, and the security classes it references, a + // runtime dependency rather than a static one. - Class clazz = Class.forName("sun.net.www.protocol.http.NegotiatorImpl"); - java.lang.reflect.Constructor c = clazz.getConstructor(HttpCallerInfo.class); - return (Negotiator) (c.newInstance(hci)); + Class clazz; + Constructor c; + try { + clazz = Class.forName("sun.net.www.protocol.http.NegotiatorImpl", true, null); + c = clazz.getConstructor(HttpCallerInfo.class); + } catch (ClassNotFoundException cnfe) { + finest(cnfe); + throw cnfe; + } catch (ReflectiveOperationException roe) { + // if the class is there then something seriously wrong if + // the constructor is not. + throw new AssertionError(roe); + } + + try { + return (Negotiator) (c.newInstance(hci)); + } catch (ReflectiveOperationException roe) { + finest(roe); + Throwable t = roe.getCause(); + if (t != null && t instanceof Exception) + finest((Exception)t); + throw roe; + } } abstract byte[] firstToken() throws IOException; abstract byte[] nextToken(byte[] in) throws IOException; + + static void finest(Exception e) { + PlatformLogger logger = HttpURLConnection.getHttpLogger(); + logger.finest("NegotiateAuthentication: " + e); + } } diff --git a/src/share/classes/sun/net/www/protocol/https/HttpsClient.java b/src/share/classes/sun/net/www/protocol/https/HttpsClient.java index d21425680c810a14b4b210b6cc46212fcf3401b6..8bbcb4de312ebdbf3e1a731634762b12da5fcc81 100644 --- a/src/share/classes/sun/net/www/protocol/https/HttpsClient.java +++ b/src/share/classes/sun/net/www/protocol/https/HttpsClient.java @@ -1,5 +1,5 @@ /* - * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -461,12 +461,16 @@ final class HttpsClient extends HttpClient } Certificate[] peerCerts = null; + String cipher = session.getCipherSuite(); try { HostnameChecker checker = HostnameChecker.getInstance( HostnameChecker.TYPE_TLS); Principal principal = getPeerPrincipal(); - if (principal instanceof KerberosPrincipal) { + // X.500 principal or Kerberos principal. + // (Use ciphersuite check to determine whether Kerberos is present.) + if (cipher.startsWith("TLS_KRB5") && + principal instanceof KerberosPrincipal) { if (!checker.match(host, (KerberosPrincipal)principal)) { throw new SSLPeerUnverifiedException("Hostname checker" + " failed for Kerberos"); @@ -499,7 +503,6 @@ final class HttpsClient extends HttpClient // ignore } - String cipher = session.getCipherSuite(); if ((cipher != null) && (cipher.indexOf("_anon_") != -1)) { return; } else if ((hostnameVerifier != null) && diff --git a/src/share/classes/sun/nio/ch/ChannelInputStream.java b/src/share/classes/sun/nio/ch/ChannelInputStream.java index 46e3e28b921f58f6085f7c193d51171396c02f4b..f7e12cf0501a86884a68e453217bbf516926d89d 100644 --- a/src/share/classes/sun/nio/ch/ChannelInputStream.java +++ b/src/share/classes/sun/nio/ch/ChannelInputStream.java @@ -109,6 +109,16 @@ public class ChannelInputStream return ChannelInputStream.read(ch, bb, true); } + public int available() throws IOException { + // special case where the channel is to a file + if (ch instanceof SeekableByteChannel) { + SeekableByteChannel sbc = (SeekableByteChannel)ch; + long rem = Math.max(0, sbc.size() - sbc.position()); + return (rem > Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)rem; + } + return 0; + } + public void close() throws IOException { ch.close(); } diff --git a/src/share/classes/sun/security/action/GetBooleanSecurityPropertyAction.java b/src/share/classes/sun/security/action/GetBooleanSecurityPropertyAction.java new file mode 100644 index 0000000000000000000000000000000000000000..3310c93e4febaf43e44ca24f45dcacc129e9be18 --- /dev/null +++ b/src/share/classes/sun/security/action/GetBooleanSecurityPropertyAction.java @@ -0,0 +1,74 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.security.action; + +import java.security.Security; + +/** + * A convenience class for retrieving the boolean value of a security property + * as a privileged action. + * + *

    An instance of this class can be used as the argument of + * AccessController.doPrivileged. + * + *

    The following code retrieves the boolean value of the security + * property named "prop" as a privileged action:

    + * + *

    + * boolean b = java.security.AccessController.doPrivileged
    + *              (new GetBooleanSecurityPropertyAction("prop")).booleanValue();
    + * 
    + * + */ +public class GetBooleanSecurityPropertyAction + implements java.security.PrivilegedAction { + private String theProp; + + /** + * Constructor that takes the name of the security property whose boolean + * value needs to be determined. + * + * @param theProp the name of the security property + */ + public GetBooleanSecurityPropertyAction(String theProp) { + this.theProp = theProp; + } + + /** + * Determines the boolean value of the security property whose name was + * specified in the constructor. + * + * @return the Boolean value of the security property. + */ + public Boolean run() { + boolean b = false; + try { + String value = Security.getProperty(theProp); + b = (value != null) && value.equalsIgnoreCase("true"); + } catch (NullPointerException e) {} + return b; + } +} diff --git a/src/share/classes/sun/security/ec/ECDHKeyAgreement.java b/src/share/classes/sun/security/ec/ECDHKeyAgreement.java index 8a61a7b1193f5395dc40ff39d505eb076be1b5d3..5ed3ffe2b006d2eaa17abf3bddfbac2a4b5a305b 100644 --- a/src/share/classes/sun/security/ec/ECDHKeyAgreement.java +++ b/src/share/classes/sun/security/ec/ECDHKeyAgreement.java @@ -39,21 +39,6 @@ import javax.crypto.spec.*; */ public final class ECDHKeyAgreement extends KeyAgreementSpi { - // flag indicating whether the native ECC implementation is present - private static boolean implementationPresent = true; - static { - try { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - System.loadLibrary("sunecc"); - return null; - } - }); - } catch (UnsatisfiedLinkError e) { - implementationPresent = false; - } - } - // private key, if initialized private ECPrivateKey privateKey; @@ -65,16 +50,12 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi { /** * Constructs a new ECDHKeyAgreement. - * - * @exception ProviderException if the native ECC library is unavailable. */ public ECDHKeyAgreement() { - if (!implementationPresent) { - throw new ProviderException("ECDH implementation is not available"); - } } // see JCE spec + @Override protected void engineInit(Key key, SecureRandom random) throws InvalidKeyException { if (!(key instanceof PrivateKey)) { @@ -86,6 +67,7 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi { } // see JCE spec + @Override protected void engineInit(Key key, AlgorithmParameterSpec params, SecureRandom random) throws InvalidKeyException, InvalidAlgorithmParameterException { @@ -97,6 +79,7 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi { } // see JCE spec + @Override protected Key engineDoPhase(Key key, boolean lastPhase) throws InvalidKeyException, IllegalStateException { if (privateKey == null) { @@ -130,6 +113,7 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi { } // see JCE spec + @Override protected byte[] engineGenerateSecret() throws IllegalStateException { if ((privateKey == null) || (publicValue == null)) { throw new IllegalStateException("Not initialized correctly"); @@ -150,6 +134,7 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi { } // see JCE spec + @Override protected int engineGenerateSecret(byte[] sharedSecret, int offset) throws IllegalStateException, ShortBufferException { if (offset + secretLen > sharedSecret.length) { @@ -162,6 +147,7 @@ public final class ECDHKeyAgreement extends KeyAgreementSpi { } // see JCE spec + @Override protected SecretKey engineGenerateSecret(String algorithm) throws IllegalStateException, NoSuchAlgorithmException, InvalidKeyException { diff --git a/src/share/classes/sun/security/ec/ECDSASignature.java b/src/share/classes/sun/security/ec/ECDSASignature.java index b2bf8936c1583da176f1852abd2f4376f3eb06b4..3c9857cd1c368af72b391012ae08278801d78ead 100644 --- a/src/share/classes/sun/security/ec/ECDSASignature.java +++ b/src/share/classes/sun/security/ec/ECDSASignature.java @@ -52,21 +52,6 @@ import sun.security.x509.AlgorithmId; */ abstract class ECDSASignature extends SignatureSpi { - // flag indicating whether the native ECC implementation is present - private static boolean implementationPresent = true; - static { - try { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - System.loadLibrary("sunecc"); - return null; - } - }); - } catch (UnsatisfiedLinkError e) { - implementationPresent = false; - } - } - // message digest implementation we use private final MessageDigest messageDigest; @@ -88,24 +73,13 @@ abstract class ECDSASignature extends SignatureSpi { * @exception ProviderException if the native ECC library is unavailable. */ ECDSASignature() { - if (!implementationPresent) { - throw new - ProviderException("ECDSA implementation is not available"); - } messageDigest = null; } /** * Constructs a new ECDSASignature. Used by subclasses. - * - * @exception ProviderException if the native ECC library is unavailable. */ ECDSASignature(String digestName) { - if (!implementationPresent) { - throw new - ProviderException("ECDSA implementation is not available"); - } - try { messageDigest = MessageDigest.getInstance(digestName); } catch (NoSuchAlgorithmException e) { @@ -299,8 +273,8 @@ abstract class ECDSASignature extends SignatureSpi { byte[] encodedParams = ECParameters.encodeParameters(params); // DER OID int keySize = params.getCurve().getField().getFieldSize(); - // seed is twice the key size (in bytes) - byte[] seed = new byte[((keySize + 7) >> 3) * 2]; + // seed is twice the key size (in bytes) plus 1 + byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2]; if (random == null) { random = JCAUtil.getSecureRandom(); } @@ -356,6 +330,7 @@ abstract class ECDSASignature extends SignatureSpi { // Convert the concatenation of R and S into their DER encoding private byte[] encodeSignature(byte[] signature) throws SignatureException { + try { int n = signature.length >> 1; diff --git a/src/share/classes/sun/security/ec/ECKeyPairGenerator.java b/src/share/classes/sun/security/ec/ECKeyPairGenerator.java index af98de60b8b87887761aa739480897a37faf88d4..99b82521293d1538f4be525e095c60f176837f2d 100644 --- a/src/share/classes/sun/security/ec/ECKeyPairGenerator.java +++ b/src/share/classes/sun/security/ec/ECKeyPairGenerator.java @@ -46,20 +46,6 @@ import sun.security.jca.JCAUtil; */ public final class ECKeyPairGenerator extends KeyPairGeneratorSpi { - // flag indicating whether the native ECC implementation is present - private static boolean implementationPresent = true; - static { - try { - AccessController.doPrivileged(new PrivilegedAction() { - public Void run() { - System.loadLibrary("sunecc"); - return null; - } - }); - } catch (UnsatisfiedLinkError e) { - implementationPresent = false; - } - } private static final int KEY_SIZE_MIN = 112; // min bits (see ecc_impl.h) private static final int KEY_SIZE_MAX = 571; // max bits (see ecc_impl.h) private static final int KEY_SIZE_DEFAULT = 256; @@ -75,13 +61,8 @@ public final class ECKeyPairGenerator extends KeyPairGeneratorSpi { /** * Constructs a new ECKeyPairGenerator. - * - * @exception ProviderException if the native ECC library is unavailable. */ public ECKeyPairGenerator() { - if (!implementationPresent) { - throw new ProviderException("EC implementation is not available"); - } // initialize to default in case the app does not call initialize() initialize(KEY_SIZE_DEFAULT, null); } @@ -133,8 +114,8 @@ public final class ECKeyPairGenerator extends KeyPairGeneratorSpi { byte[] encodedParams = ECParameters.encodeParameters((ECParameterSpec)params); - // seed is twice the key size (in bytes) - byte[] seed = new byte[2 * ((keySize + 7) >> 3)]; + // seed is twice the key size (in bytes) plus 1 + byte[] seed = new byte[(((keySize + 7) >> 3) + 1) * 2]; if (random == null) { random = JCAUtil.getSecureRandom(); } diff --git a/src/share/classes/sun/security/ec/SunEC.java b/src/share/classes/sun/security/ec/SunEC.java index 49223ca37b21e6a7755ce5799381e8b31fb960a5..69afe5bf3523668ca04d2b52cdf186da49046a42 100644 --- a/src/share/classes/sun/security/ec/SunEC.java +++ b/src/share/classes/sun/security/ec/SunEC.java @@ -39,7 +39,10 @@ import sun.security.action.PutAllAction; * via JNI to a C++ wrapper class which in turn calls C functions. * The Java classes are packaged into the signed sunec.jar in the JRE * extensions directory and the C++ and C functions are packaged into - * libsunecc.so or sunecc.dll in the JRE native libraries directory. + * libsunec.so or sunec.dll in the JRE native libraries directory. + * If the native library is not present then this provider is registered + * with support for fewer ECC algorithms (KeyPairGenerator, Signature and + * KeyAgreement are omitted). * * @since 1.7 */ @@ -47,6 +50,22 @@ public final class SunEC extends Provider { private static final long serialVersionUID = -2279741672933606418L; + // flag indicating whether the full EC implementation is present + // (when native library is absent then fewer EC algorithms are available) + private static boolean useFullImplementation = true; + static { + try { + AccessController.doPrivileged(new PrivilegedAction() { + public Void run() { + System.loadLibrary("sunec"); // check for native library + return null; + } + }); + } catch (UnsatisfiedLinkError e) { + useFullImplementation = false; + } + } + public SunEC() { super("SunEC", 1.7d, "Sun Elliptic Curve provider (EC, ECDSA, ECDH)"); @@ -54,10 +73,10 @@ public final class SunEC extends Provider { // the provider. Otherwise, create a temporary map and use a // doPrivileged() call at the end to transfer the contents if (System.getSecurityManager() == null) { - SunECEntries.putEntries(this); + SunECEntries.putEntries(this, useFullImplementation); } else { Map map = new HashMap(); - SunECEntries.putEntries(map); + SunECEntries.putEntries(map, useFullImplementation); AccessController.doPrivileged(new PutAllAction(this, map)); } } diff --git a/src/share/classes/sun/security/ec/SunECEntries.java b/src/share/classes/sun/security/ec/SunECEntries.java index 759d3007e85a202e2163ca240146fbe3d6a719b4..58e99121a25d6088a4b38c8db4369770af4d621d 100644 --- a/src/share/classes/sun/security/ec/SunECEntries.java +++ b/src/share/classes/sun/security/ec/SunECEntries.java @@ -38,7 +38,93 @@ final class SunECEntries { // empty } - static void putEntries(Map map) { + static void putEntries(Map map, + boolean useFullImplementation) { + + /* + * Key Factory engine + */ + map.put("KeyFactory.EC", "sun.security.ec.ECKeyFactory"); + map.put("Alg.Alias.KeyFactory.EllipticCurve", "EC"); + + map.put("KeyFactory.EC ImplementedIn", "Software"); + + /* + * Algorithm Parameter engine + */ + map.put("AlgorithmParameters.EC", "sun.security.ec.ECParameters"); + map.put("Alg.Alias.AlgorithmParameters.EllipticCurve", "EC"); + + map.put("AlgorithmParameters.EC KeySize", "256"); + + map.put("AlgorithmParameters.EC ImplementedIn", "Software"); + + map.put("AlgorithmParameters.EC SupportedCurves", + + // A list comprising lists of curve names and object identifiers. + // '[' ( ',' )+ ']' '|' + + // SEC 2 prime curves + "[secp112r1,1.3.132.0.6]|" + + "[secp112r2,1.3.132.0.7]|" + + "[secp128r1,1.3.132.0.28]|" + + "[secp128r2,1.3.132.0.29]|" + + "[secp160k1,1.3.132.0.9]|" + + "[secp160r1,1.3.132.0.8]|" + + "[secp160r2,1.3.132.0.30]|" + + "[secp192k1,1.3.132.0.31]|" + + "[secp192r1,NIST P-192,X9.62 prime192v1,1.2.840.10045.3.1.1]|" + + "[secp224k1,1.3.132.0.32]|" + + "[secp224r1,NIST P-224,1.3.132.0.33]|" + + "[secp256k1,1.3.132.0.10]|" + + "[secp256r1,NIST P-256,X9.62 prime256v1,1.2.840.10045.3.1.7]|" + + "[secp384r1,NIST P-384,1.3.132.0.34]|" + + "[secp521r1,NIST P-521,1.3.132.0.35]|" + + + // ANSI X9.62 prime curves + "[X9.62 prime192v2,1.2.840.10045.3.1.2]|" + + "[X9.62 prime192v3,1.2.840.10045.3.1.3]|" + + "[X9.62 prime239v1,1.2.840.10045.3.1.4]|" + + "[X9.62 prime239v2,1.2.840.10045.3.1.5]|" + + "[X9.62 prime239v3,1.2.840.10045.3.1.6]|" + + + // SEC 2 binary curves + "[sect113r1,1.3.132.0.4]|" + + "[sect113r2,1.3.132.0.5]|" + + "[sect131r1,1.3.132.0.22]|" + + "[sect131r2,1.3.132.0.23]|" + + "[sect163k1,NIST K-163,1.3.132.0.1]|" + + "[sect163r1,1.3.132.0.2]|" + + "[sect163r2,NIST B-163,1.3.132.0.15]|" + + "[sect193r1,1.3.132.0.24]|" + + "[sect193r2,1.3.132.0.25]|" + + "[sect233k1,NIST K-233,1.3.132.0.26]|" + + "[sect233r1,NIST B-233,1.3.132.0.27]|" + + "[sect239k1,1.3.132.0.3]|" + + "[sect283k1,NIST K-283,1.3.132.0.16]|" + + "[sect283r1,NIST B-283,1.3.132.0.17]|" + + "[sect409k1,NIST K-409,1.3.132.0.36]|" + + "[sect409r1,NIST B-409,1.3.132.0.37]|" + + "[sect571k1,NIST K-571,1.3.132.0.38]|" + + "[sect571r1,NIST B-571,1.3.132.0.39]|" + + + // ANSI X9.62 binary curves + "[X9.62 c2tnb191v1,1.2.840.10045.3.0.5]|" + + "[X9.62 c2tnb191v2,1.2.840.10045.3.0.6]|" + + "[X9.62 c2tnb191v3,1.2.840.10045.3.0.7]|" + + "[X9.62 c2tnb239v1,1.2.840.10045.3.0.11]|" + + "[X9.62 c2tnb239v2,1.2.840.10045.3.0.12]|" + + "[X9.62 c2tnb239v3,1.2.840.10045.3.0.13]|" + + "[X9.62 c2tnb359v1,1.2.840.10045.3.0.18]|" + + "[X9.62 c2tnb431r1,1.2.840.10045.3.0.20]"); + + /* + * Register the algorithms below only when the full ECC implementation + * is available + */ + if (!useFullImplementation) { + return; + } /* * Signature engines @@ -62,48 +148,31 @@ final class SunECEntries { map.put("Signature.SHA384withECDSA SupportedKeyClasses", ecKeyClasses); map.put("Signature.SHA512withECDSA SupportedKeyClasses", ecKeyClasses); + map.put("Signature.SHA1withECDSA KeySize", "256"); + + map.put("Signature.NONEwithECDSA ImplementedIn", "Software"); + map.put("Signature.SHA1withECDSA ImplementedIn", "Software"); + map.put("Signature.SHA256withECDSA ImplementedIn", "Software"); + map.put("Signature.SHA384withECDSA ImplementedIn", "Software"); + map.put("Signature.SHA512withECDSA ImplementedIn", "Software"); + /* * Key Pair Generator engine */ map.put("KeyPairGenerator.EC", "sun.security.ec.ECKeyPairGenerator"); map.put("Alg.Alias.KeyPairGenerator.EllipticCurve", "EC"); - /* - * Key Factory engine - */ - map.put("KeyFactory.EC", "sun.security.ec.ECKeyFactory"); - map.put("Alg.Alias.KeyFactory.EllipticCurve", "EC"); + map.put("KeyPairGenerator.EC KeySize", "256"); - /* - * Algorithm Parameter engine - */ - map.put("AlgorithmParameters.EC", "sun.security.ec.ECParameters"); - map.put("Alg.Alias.AlgorithmParameters.EllipticCurve", "EC"); + map.put("KeyPairGenerator.EC ImplementedIn", "Software"); /* * Key Agreement engine */ map.put("KeyAgreement.ECDH", "sun.security.ec.ECDHKeyAgreement"); - map.put("KeyAgreement.ECDH SupportedKeyClasses", ecKeyClasses); - /* - * Key sizes - */ - map.put("Signature.SHA1withECDSA KeySize", "256"); - map.put("KeyPairGenerator.EC KeySize", "256"); - map.put("AlgorithmParameterGenerator.ECDSA KeySize", "256"); + map.put("KeyAgreement.ECDH SupportedKeyClasses", ecKeyClasses); - /* - * Implementation type: software or hardware - */ - map.put("Signature.NONEwithECDSA ImplementedIn", "Software"); - map.put("Signature.SHA1withECDSA ImplementedIn", "Software"); - map.put("Signature.SHA256withECDSA ImplementedIn", "Software"); - map.put("Signature.SHA384withECDSA ImplementedIn", "Software"); - map.put("Signature.SHA512withECDSA ImplementedIn", "Software"); - map.put("KeyPairGenerator.EC ImplementedIn", "Software"); - map.put("KeyFactory.EC ImplementedIn", "Software"); map.put("KeyAgreement.ECDH ImplementedIn", "Software"); - map.put("AlgorithmParameters.EC ImplementedIn", "Software"); } } diff --git a/src/share/classes/sun/security/krb5/Credentials.java b/src/share/classes/sun/security/krb5/Credentials.java index 3fde713fd3c36baab64f5824fc776acc09628c7f..c003a29fa644368fd7738c31d22cc1708fea2fc7 100644 --- a/src/share/classes/sun/security/krb5/Credentials.java +++ b/src/share/classes/sun/security/krb5/Credentials.java @@ -33,16 +33,11 @@ package sun.security.krb5; import sun.security.krb5.internal.*; import sun.security.krb5.internal.ccache.CredentialsCache; -import java.util.StringTokenizer; import sun.security.krb5.internal.ktab.*; import sun.security.krb5.internal.crypto.EType; import java.io.File; import java.io.IOException; import java.util.Date; -import java.util.Vector; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.UnsupportedEncodingException; import java.net.InetAddress; /** @@ -378,9 +373,9 @@ public class Credentials { KRBError error = ke.getError(); // update salt in PrincipalName - byte[] newSalt = error.getSalt(); - if (newSalt != null && newSalt.length > 0) { - princ.setSalt(new String(newSalt)); + String newSalt = error.getSalt(); + if (newSalt != null && newSalt.length() > 0) { + princ.setSalt(newSalt); } // refresh keys diff --git a/src/share/classes/sun/security/krb5/KrbAsReq.java b/src/share/classes/sun/security/krb5/KrbAsReq.java index c493d405f51c7ebaf27b7584562ad31bf47ec350..fec6998ce3ab40ecd23d7598c516cec505e74ad3 100644 --- a/src/share/classes/sun/security/krb5/KrbAsReq.java +++ b/src/share/classes/sun/security/krb5/KrbAsReq.java @@ -1,5 +1,5 @@ /* - * Portions Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved. + * Portions Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -56,7 +56,7 @@ public class KrbAsReq extends KrbKdcReq { private boolean PA_ENC_TIMESTAMP_REQUIRED = false; private boolean pa_exists = false; private int pa_etype = 0; - private byte[] pa_salt = null; + private String pa_salt = null; private byte[] pa_s2kparams = null; // default is address-less tickets @@ -88,7 +88,7 @@ public class KrbAsReq extends KrbKdcReq { * with pre-authentication values */ KrbAsReq(PrincipalName principal, EncryptionKey[] keys, - boolean pa_exists, int etype, byte[] salt, byte[] s2kparams) + boolean pa_exists, int etype, String salt, byte[] s2kparams) throws KrbException, IOException { this(keys, // for pre-authentication pa_exists, etype, salt, s2kparams, // pre-auth values @@ -112,7 +112,7 @@ public class KrbAsReq extends KrbKdcReq { } // update with pre-auth info - public void updatePA(int etype, byte[] salt, byte[] params, PrincipalName name) { + public void updatePA(int etype, String salt, byte[] params, PrincipalName name) { // set the pre-auth values pa_exists = true; pa_etype = etype; @@ -120,9 +120,8 @@ public class KrbAsReq extends KrbKdcReq { pa_s2kparams = params; // update salt in PrincipalName - if (salt != null && salt.length > 0) { - String newSalt = new String(salt); - name.setSalt(newSalt); + if (salt != null && salt.length() > 0) { + name.setSalt(salt); if (DEBUG) { System.out.println("Updated salt from pre-auth = " + name.getSalt()); } @@ -161,7 +160,7 @@ public class KrbAsReq extends KrbKdcReq { char[] password, boolean pa_exists, int etype, - byte[] salt, + String salt, byte[] s2kparams, KDCOptions options, PrincipalName cname, @@ -246,7 +245,7 @@ public class KrbAsReq extends KrbKdcReq { EncryptionKey[] keys, boolean pa_exists, int etype, - byte[] salt, + String salt, byte[] s2kparams, KDCOptions options, PrincipalName cname, diff --git a/src/share/classes/sun/security/krb5/KrbKdcReq.java b/src/share/classes/sun/security/krb5/KrbKdcReq.java index 259aedd66fa35a848e221a065ba54cdb1b53991a..b915ff99711dd0fabf8bbf24b835dd3d0e3adce6 100644 --- a/src/share/classes/sun/security/krb5/KrbKdcReq.java +++ b/src/share/classes/sun/security/krb5/KrbKdcReq.java @@ -1,5 +1,5 @@ /* - * Portions Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Portions Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -149,6 +149,11 @@ public abstract class KrbKdcReq { send(realm,tempKdc,useTCP); break; } catch (Exception e) { + if (DEBUG) { + System.out.println(">>> KrbKdcReq send: error trying " + + tempKdc); + e.printStackTrace(System.out); + } savedException = e; } } @@ -179,10 +184,36 @@ public abstract class KrbKdcReq { /* * Get port number for this KDC. */ - StringTokenizer strTok = new StringTokenizer(tempKdc, ":"); - String kdc = strTok.nextToken(); - if (strTok.hasMoreTokens()) { - String portStr = strTok.nextToken(); + String kdc = null; + String portStr = null; + + if (tempKdc.charAt(0) == '[') { // Explicit IPv6 in [] + int pos = tempKdc.indexOf(']', 1); + if (pos == -1) { + throw new IOException("Illegal KDC: " + tempKdc); + } + kdc = tempKdc.substring(1, pos); + if (pos != tempKdc.length() - 1) { // with port number + if (tempKdc.charAt(pos+1) != ':') { + throw new IOException("Illegal KDC: " + tempKdc); + } + portStr = tempKdc.substring(pos+2); + } + } else { + int colon = tempKdc.indexOf(':'); + if (colon == -1) { // Hostname or IPv4 host only + kdc = tempKdc; + } else { + int nextColon = tempKdc.indexOf(':', colon+1); + if (nextColon > 0) { // >=2 ":", IPv6 with no port + kdc = tempKdc; + } else { // 1 ":", hostname or IPv4 with port + kdc = tempKdc.substring(0, colon); + portStr = tempKdc.substring(colon+1); + } + } + } + if (portStr != null) { int tempPort = parsePositiveIntString(portStr); if (tempPort > 0) port = tempPort; diff --git a/src/share/classes/sun/security/krb5/PrincipalName.java b/src/share/classes/sun/security/krb5/PrincipalName.java index 3761ffbb4690665ca1db10f6ebfb8a319332dc27..6705fd63e9af4c3d9cb356415368627dd71f2adb 100644 --- a/src/share/classes/sun/security/krb5/PrincipalName.java +++ b/src/share/classes/sun/security/krb5/PrincipalName.java @@ -38,6 +38,7 @@ import java.util.Vector; import java.io.IOException; import java.math.BigInteger; import sun.security.krb5.internal.ccache.CCacheOutputStream; +import sun.security.krb5.internal.util.KerberosString; /** @@ -246,7 +247,7 @@ public class PrincipalName DerValue subSubDer; while(subDer.getData().available() > 0) { subSubDer = subDer.getData().getDerValue(); - v.addElement(subSubDer.getGeneralString()); + v.addElement(new KerberosString(subSubDer).toString()); } if (v.size() > 0) { nameStrings = new String[v.size()]; @@ -554,7 +555,7 @@ public class PrincipalName temp = new DerOutputStream(); DerValue der[] = new DerValue[nameStrings.length]; for (int i = 0; i < nameStrings.length; i++) { - der[i] = new DerValue(DerValue.tag_GeneralString, nameStrings[i]); + der[i] = new KerberosString(nameStrings[i]).toDerValue(); } temp.putSequence(der); bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x01), temp); diff --git a/src/share/classes/sun/security/krb5/Realm.java b/src/share/classes/sun/security/krb5/Realm.java index bf57e7a54ceb64cec53349e35b7b80bfaa54d29e..7ba959bdcf4b98e592bcd3bb1eecd4565b2325fb 100644 --- a/src/share/classes/sun/security/krb5/Realm.java +++ b/src/share/classes/sun/security/krb5/Realm.java @@ -31,11 +31,6 @@ package sun.security.krb5; -import sun.security.krb5.Config; -import sun.security.krb5.PrincipalName; -import sun.security.krb5.KrbException; -import sun.security.krb5.Asn1Exception; -import sun.security.krb5.RealmException; import sun.security.krb5.internal.Krb5; import sun.security.util.*; import java.io.IOException; @@ -43,6 +38,7 @@ import java.util.StringTokenizer; import java.util.Vector; import java.util.Stack; import java.util.EmptyStackException; +import sun.security.krb5.internal.util.KerberosString; /** * Implements the ASN.1 Realm type. @@ -109,7 +105,7 @@ public class Realm implements Cloneable { if (encoding == null) { throw new IllegalArgumentException("encoding can not be null"); } - realm = encoding.getGeneralString(); + realm = new KerberosString(encoding).toString(); if (realm == null || realm.length() == 0) throw new RealmException(Krb5.REALM_NULL); if (!isValidRealmString(realm)) @@ -206,7 +202,7 @@ public class Realm implements Cloneable { */ public byte[] asn1Encode() throws Asn1Exception, IOException { DerOutputStream out = new DerOutputStream(); - out.putGeneralString(this.realm); + out.putDerValue(new KerberosString(this.realm).toDerValue()); return out.toByteArray(); } diff --git a/src/share/classes/sun/security/krb5/internal/ETypeInfo.java b/src/share/classes/sun/security/krb5/internal/ETypeInfo.java index 9790bb8696f14118024364c823dbf0e610427ec2..7625a6eb5d9bd8b4c0f1b6c30b21ad039997e5ce 100644 --- a/src/share/classes/sun/security/krb5/internal/ETypeInfo.java +++ b/src/share/classes/sun/security/krb5/internal/ETypeInfo.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2005-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ package sun.security.krb5.internal; import sun.security.util.*; import sun.security.krb5.Asn1Exception; import java.io.IOException; +import sun.security.krb5.internal.util.KerberosString; /** * Implements the ASN.1 ETYPE-INFO-ENTRY type. @@ -43,7 +44,7 @@ import java.io.IOException; public class ETypeInfo { private int etype; - private byte[] salt = null; + private String salt = null; private static final byte TAG_TYPE = 0; private static final byte TAG_VALUE = 1; @@ -51,21 +52,13 @@ public class ETypeInfo { private ETypeInfo() { } - public ETypeInfo(int etype, byte[] salt) { + public ETypeInfo(int etype, String salt) { this.etype = etype; - if (salt != null) { - this.salt = salt.clone(); - } + this.salt = salt; } public Object clone() { - ETypeInfo etypeInfo = new ETypeInfo(); - etypeInfo.etype = etype; - if (salt != null) { - etypeInfo.salt = new byte[salt.length]; - System.arraycopy(salt, 0, etypeInfo.salt, 0, salt.length); - } - return etypeInfo; + return new ETypeInfo(etype, salt); } /** @@ -94,7 +87,22 @@ public class ETypeInfo { if (encoding.getData().available() > 0) { der = encoding.getData().getDerValue(); if ((der.getTag() & 0x1F) == 0x01) { - this.salt = der.getData().getOctetString(); + byte[] saltBytes = der.getData().getOctetString(); + + // Although salt is defined as an OCTET STRING, it's the + // encoding from of a string. As RFC 4120 says: + // + // "The salt, ..., is also completely unspecified with respect + // to character set and is probably locale-specific". + // + // It's known that this field is using the same encoding as + // KerberosString in most implementations. + + if (KerberosString.MSNAME) { + this.salt = new String(saltBytes, "UTF8"); + } else { + this.salt = new String(saltBytes); + } } } @@ -120,7 +128,11 @@ public class ETypeInfo { if (salt != null) { temp = new DerOutputStream(); - temp.putOctetString(salt); + if (KerberosString.MSNAME) { + temp.putOctetString(salt.getBytes("UTF8")); + } else { + temp.putOctetString(salt.getBytes()); + } bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, TAG_VALUE), temp); } @@ -135,8 +147,8 @@ public class ETypeInfo { return etype; } - public byte[] getSalt() { - return ((salt == null) ? null : salt.clone()); + public String getSalt() { + return salt; } } diff --git a/src/share/classes/sun/security/krb5/internal/ETypeInfo2.java b/src/share/classes/sun/security/krb5/internal/ETypeInfo2.java index f1b657116f628a8a8ee3d72a381e08774897d829..1480774543322dc523b9958927687d6825018c2c 100644 --- a/src/share/classes/sun/security/krb5/internal/ETypeInfo2.java +++ b/src/share/classes/sun/security/krb5/internal/ETypeInfo2.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2005-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ package sun.security.krb5.internal; import sun.security.util.*; import sun.security.krb5.Asn1Exception; import java.io.IOException; +import sun.security.krb5.internal.util.KerberosString; /** * Implements the ASN.1 ETYPE-INFO-ENTRY type. @@ -54,11 +55,9 @@ public class ETypeInfo2 { private ETypeInfo2() { } - public ETypeInfo2(int etype, byte[] salt, byte[] s2kparams) { + public ETypeInfo2(int etype, String salt, byte[] s2kparams) { this.etype = etype; - if (salt != null) { - this.saltStr = new String(salt); - } + this.saltStr = salt; if (s2kparams != null) { this.s2kparams = s2kparams.clone(); } @@ -102,7 +101,8 @@ public class ETypeInfo2 { if (encoding.getData().available() > 0) { if ((encoding.getData().peekByte() & 0x1F) == 0x01) { der = encoding.getData().getDerValue(); - this.saltStr = der.getData().getGeneralString(); + this.saltStr = new KerberosString( + der.getData().getDerValue()).toString(); } } @@ -136,7 +136,7 @@ public class ETypeInfo2 { if (saltStr != null) { temp = new DerOutputStream(); - temp.putGeneralString(saltStr); + temp.putDerValue(new KerberosString(saltStr).toDerValue()); bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, TAG_VALUE1), temp); } @@ -157,8 +157,8 @@ public class ETypeInfo2 { return etype; } - public byte[] getSalt() { - return ((saltStr == null) ? null : saltStr.getBytes()); + public String getSalt() { + return saltStr; } public byte[] getParams() { diff --git a/src/share/classes/sun/security/krb5/internal/KRBError.java b/src/share/classes/sun/security/krb5/internal/KRBError.java index febc959cb805fd27745f4052064a470514108e9f..e7c73181cf7226668baae3088e48ebf18fd21817 100644 --- a/src/share/classes/sun/security/krb5/internal/KRBError.java +++ b/src/share/classes/sun/security/krb5/internal/KRBError.java @@ -1,5 +1,5 @@ /* - * Portions Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Portions Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -42,6 +42,7 @@ import java.io.IOException; import java.io.ObjectInputStream; import java.math.BigInteger; import java.util.Arrays; +import sun.security.krb5.internal.util.KerberosString; /** * Implements the ASN.1 KRBError type. * @@ -97,7 +98,7 @@ public class KRBError implements java.io.Serializable { // pre-auth info private int etype = 0; - private byte[] salt = null; + private String salt = null; private byte[] s2kparams = null; private static boolean DEBUG = Krb5.DEBUG; @@ -334,8 +335,8 @@ public class KRBError implements java.io.Serializable { } // access pre-auth info - public final byte[] getSalt() { - return ((salt == null) ? null : salt.clone()); + public final String getSalt() { + return salt; } // access pre-auth info @@ -415,7 +416,8 @@ public class KRBError implements java.io.Serializable { if (der.getData().available() >0) { if ((der.getData().peekByte() & 0x1F) == 0x0B) { subDer = der.getData().getDerValue(); - eText = subDer.getData().getGeneralString(); + eText = new KerberosString(subDer.getData().getDerValue()) + .toString(); } } if (der.getData().available() >0) { @@ -515,7 +517,7 @@ public class KRBError implements java.io.Serializable { if (eText != null) { temp = new DerOutputStream(); - temp.putGeneralString(eText); + temp.putDerValue(new KerberosString(eText).toDerValue()); bytes.write(DerValue.createTag(DerValue.TAG_CONTEXT, true, (byte)0x0B), temp); } if (eData != null) { diff --git a/src/share/classes/sun/security/krb5/internal/crypto/Des.java b/src/share/classes/sun/security/krb5/internal/crypto/Des.java index 61a03c02a94b83eec1e8fa6bc23899d4a8a53520..feaf8cf42a5ae705100e5117dd575f0a87416f21 100644 --- a/src/share/classes/sun/security/krb5/internal/crypto/Des.java +++ b/src/share/classes/sun/security/krb5/internal/crypto/Des.java @@ -34,17 +34,29 @@ import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; import javax.crypto.SecretKeyFactory; import javax.crypto.SecretKey; -import java.security.Security; -import java.security.Provider; import java.security.GeneralSecurityException; import javax.crypto.spec.IvParameterSpec; import sun.security.krb5.KrbCryptoException; -import sun.security.krb5.internal.Krb5; -import java.io.UnsupportedEncodingException; import java.util.Arrays; +import sun.security.action.GetPropertyAction; public final class Des { + // RFC 3961 demands that UTF-8 encoding be used in DES's + // string-to-key function. For historical reasons, some + // implementations use a locale-specific encoding. Even + // so, when the client and server use different locales, + // they must agree on a common value, normally the one + // used when the password is set/reset. + // + // The following system property is provided to perform the + // string-to-key encoding. When set, the specified charset + // name is used. Otherwise, the system default charset. + + private final static String CHARSET = + java.security.AccessController.doPrivileged( + new GetPropertyAction("sun.security.krb5.msinterop.des.s2kcharset")); + private static final long[] bad_keys = { 0x0101010101010101L, 0xfefefefefefefefeL, 0x1f1f1f1f1f1f1f1fL, 0xe0e0e0e0e0e0e0e0L, @@ -226,7 +238,11 @@ public final class Des { // Convert password to byte array try { - cbytes = (new String(passwdChars)).getBytes(); + if (CHARSET == null) { + cbytes = (new String(passwdChars)).getBytes(); + } else { + cbytes = (new String(passwdChars)).getBytes(CHARSET); + } } catch (Exception e) { // clear-up sensitive information if (cbytes != null) { diff --git a/src/share/classes/sun/security/krb5/internal/util/KerberosString.java b/src/share/classes/sun/security/krb5/internal/util/KerberosString.java new file mode 100644 index 0000000000000000000000000000000000000000..2c50fe601b911b4ad29a8d24016afbba3654f28e --- /dev/null +++ b/src/share/classes/sun/security/krb5/internal/util/KerberosString.java @@ -0,0 +1,82 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +package sun.security.krb5.internal.util; + +import java.io.IOException; +import java.security.AccessController; +import sun.security.action.GetBooleanAction; +import sun.security.util.DerValue; + +/** + * Implements the ASN.1 KerberosString type. + * + *
    + * KerberosString  ::= GeneralString (IA5String)
    + * 
    + * + * This definition reflects the Network Working Group RFC 4120 + * specification available at + * + * http://www.ietf.org/rfc/rfc4120.txt. + */ +public final class KerberosString { + /** + * RFC 4120 defines KerberosString as GeneralString (IA5String), which + * only includes ASCII characters. However, other implementations have been + * known to use GeneralString to contain UTF-8 encoding. To interop + * with these implementations, the following system property is defined. + * When set as true, KerberosString is encoded as UTF-8. Note that this + * only affects the byte encoding, the tag of the ASN.1 type is still + * GeneralString. + */ + public static final boolean MSNAME = AccessController.doPrivileged( + new GetBooleanAction("sun.security.krb5.msinterop.kstring")); + + private final String s; + + public KerberosString(String s) { + this.s = s; + } + + public KerberosString(DerValue der) throws IOException { + if (der.tag != DerValue.tag_GeneralString) { + throw new IOException( + "KerberosString's tag is incorrect: " + der.tag); + } + s = new String(der.getDataBytes(), MSNAME?"UTF8":"ASCII"); + } + + public String toString() { + return s; + } + + public DerValue toDerValue() throws IOException { + // No need to cache the result since this method is + // only called once. + return new DerValue(DerValue.tag_GeneralString, + s.getBytes(MSNAME?"UTF8":"ASCII")); + } +} diff --git a/src/share/classes/sun/security/provider/PolicyFile.java b/src/share/classes/sun/security/provider/PolicyFile.java index 768ddd9ce6396423fe8ccd9cbb69b5d0257457f8..324e745f375de18ba043494a1896a4fbff4a6ed5 100644 --- a/src/share/classes/sun/security/provider/PolicyFile.java +++ b/src/share/classes/sun/security/provider/PolicyFile.java @@ -54,7 +54,6 @@ import java.net.SocketPermission; import java.net.NetPermission; import java.util.PropertyPermission; import java.util.concurrent.atomic.AtomicReference; -import java.awt.AWTPermission; /* import javax.security.auth.AuthPermission; import javax.security.auth.kerberos.ServicePermission; @@ -1023,8 +1022,6 @@ public class PolicyFile extends java.security.Policy { return new NetPermission(name, actions); } else if (claz.equals(AllPermission.class)) { return SecurityConstants.ALL_PERMISSION; - } else if (claz.equals(AWTPermission.class)) { - return new AWTPermission(name, actions); /* } else if (claz.equals(ReflectPermission.class)) { return new ReflectPermission(name, actions); diff --git a/src/share/classes/sun/security/provider/certpath/Builder.java b/src/share/classes/sun/security/provider/certpath/Builder.java index 8e13fb8b777318f775cd0fdd9ce8e330adc1c7af..5892b1b328db20d953664ccd484d147133b11c32 100644 --- a/src/share/classes/sun/security/provider/certpath/Builder.java +++ b/src/share/classes/sun/security/provider/certpath/Builder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,12 +26,14 @@ package sun.security.provider.certpath; import java.io.IOException; +import java.security.AccessController; import java.security.GeneralSecurityException; import java.security.cert.*; import java.util.*; import javax.security.auth.x500.X500Principal; +import sun.security.action.GetBooleanAction; import sun.security.util.Debug; import sun.security.x509.GeneralNames; import sun.security.x509.GeneralNameInterface; @@ -64,9 +66,8 @@ public abstract class Builder { * Authority Information Access extension shall be enabled. Currently * disabled by default for compatibility reasons. */ - final static boolean USE_AIA = - DistributionPointFetcher.getBooleanProperty - ("com.sun.security.enableAIAcaIssuers", false); + final static boolean USE_AIA = AccessController.doPrivileged + (new GetBooleanAction("com.sun.security.enableAIAcaIssuers")); /** * Initialize the builder with the input parameters. diff --git a/src/share/classes/sun/security/provider/certpath/CertId.java b/src/share/classes/sun/security/provider/certpath/CertId.java index 1ee63949964452c1217897df50d2d8beaed8b2f9..20e9aa2a789a1416b5e76219250557388d5c0924 100644 --- a/src/share/classes/sun/security/provider/certpath/CertId.java +++ b/src/share/classes/sun/security/provider/certpath/CertId.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2005 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,9 +25,11 @@ package sun.security.provider.certpath; -import java.io.*; +import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.security.cert.X509Certificate; import java.util.Arrays; import sun.misc.HexDumpEncoder; import sun.security.x509.*; @@ -54,21 +56,28 @@ import sun.security.util.*; public class CertId { private static final boolean debug = false; - private AlgorithmId hashAlgId; - private byte[] issuerNameHash; - private byte[] issuerKeyHash; - private SerialNumber certSerialNumber; + private static final AlgorithmId SHA1_ALGID + = new AlgorithmId(AlgorithmId.SHA_oid); + private final AlgorithmId hashAlgId; + private final byte[] issuerNameHash; + private final byte[] issuerKeyHash; + private final SerialNumber certSerialNumber; private int myhash = -1; // hashcode for this CertId /** * Creates a CertId. The hash algorithm used is SHA-1. */ - public CertId(X509CertImpl issuerCert, SerialNumber serialNumber) - throws Exception { + public CertId(X509Certificate issuerCert, SerialNumber serialNumber) + throws IOException { // compute issuerNameHash - MessageDigest md = MessageDigest.getInstance("SHA1"); - hashAlgId = AlgorithmId.get("SHA1"); + MessageDigest md = null; + try { + md = MessageDigest.getInstance("SHA1"); + } catch (NoSuchAlgorithmException nsae) { + throw new IOException("Unable to create CertId", nsae); + } + hashAlgId = SHA1_ALGID; md.update(issuerCert.getSubjectX500Principal().getEncoded()); issuerNameHash = md.digest(); @@ -90,6 +99,7 @@ public class CertId { encoder.encode(issuerNameHash)); System.out.println("issuerKeyHash is " + encoder.encode(issuerKeyHash)); + System.out.println("SerialNumber is " + serialNumber.getNumber()); } } @@ -97,7 +107,6 @@ public class CertId { * Creates a CertId from its ASN.1 DER encoding. */ public CertId(DerInputStream derIn) throws IOException { - hashAlgId = AlgorithmId.parse(derIn.getDerValue()); issuerNameHash = derIn.getOctetString(); issuerKeyHash = derIn.getOctetString(); @@ -157,7 +166,7 @@ public class CertId { * * @return the hashcode value. */ - public int hashCode() { + @Override public int hashCode() { if (myhash == -1) { myhash = hashAlgId.hashCode(); for (int i = 0; i < issuerNameHash.length; i++) { @@ -180,8 +189,7 @@ public class CertId { * @param other the object to test for equality with this object. * @return true if the objects are considered equal, false otherwise. */ - public boolean equals(Object other) { - + @Override public boolean equals(Object other) { if (this == other) { return true; } @@ -203,7 +211,7 @@ public class CertId { /** * Create a string representation of the CertId. */ - public String toString() { + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("CertId \n"); sb.append("Algorithm: " + hashAlgId.toString() +"\n"); diff --git a/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java b/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java index b462dd5ba0870486ad0e3fe1554e82b63175a3bc..18845113edb39d7422d9b0ada49ff1d89e7b9834 100644 --- a/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java +++ b/src/share/classes/sun/security/provider/certpath/CrlRevocationChecker.java @@ -80,6 +80,7 @@ class CrlRevocationChecker extends PKIXCertPathChecker { { false, false, false, false, false, false, true }; private static final boolean[] ALL_REASONS = {true, true, true, true, true, true, true, true, true}; + private boolean mOnlyEECert = false; // Maximum clock skew in milliseconds (15 minutes) allowed when checking // validity of CRLs @@ -114,6 +115,12 @@ class CrlRevocationChecker extends PKIXCertPathChecker { CrlRevocationChecker(TrustAnchor anchor, PKIXParameters params, Collection certs) throws CertPathValidatorException { + this(anchor, params, certs, false); + } + + CrlRevocationChecker(TrustAnchor anchor, PKIXParameters params, + Collection certs, boolean onlyEECert) + throws CertPathValidatorException { mAnchor = anchor; mParams = params; mStores = new ArrayList(params.getCertStores()); @@ -133,6 +140,7 @@ class CrlRevocationChecker extends PKIXCertPathChecker { } Date testDate = params.getDate(); mCurrentTime = (testDate != null ? testDate : new Date()); + mOnlyEECert = onlyEECert; init(false); } @@ -264,6 +272,13 @@ class CrlRevocationChecker extends PKIXCertPathChecker { " ---checking " + msg + "..."); } + if (mOnlyEECert && currCert.getBasicConstraints() != -1) { + if (debug != null) { + debug.println("Skipping revocation check, not end entity cert"); + } + return; + } + // reject circular dependencies - RFC 3280 is not explicit on how // to handle this, so we feel it is safest to reject them until // the issue is resolved in the PKIX WG. diff --git a/src/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java b/src/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java index 8d94adb32cc8d6a89aefea2c97e39e0d22656e15..f1005ac7e3b5ae7178978605835e15f6620ea017 100644 --- a/src/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java +++ b/src/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java @@ -32,7 +32,7 @@ import java.security.*; import java.security.cert.*; import javax.security.auth.x500.X500Principal; -import sun.security.action.GetPropertyAction; +import sun.security.action.GetBooleanAction; import sun.security.util.Debug; import sun.security.util.DerOutputStream; import sun.security.x509.*; @@ -62,28 +62,8 @@ class DistributionPointFetcher { * extension shall be enabled. Currently disabled by default for * compatibility and legal reasons. */ - private final static boolean USE_CRLDP = - getBooleanProperty("com.sun.security.enableCRLDP", false); - - /** - * Return the value of the boolean System property propName. - */ - public static boolean getBooleanProperty(String propName, - boolean defaultValue) { - // if set, require value of either true or false - String b = AccessController.doPrivileged( - new GetPropertyAction(propName)); - if (b == null) { - return defaultValue; - } else if (b.equalsIgnoreCase("false")) { - return false; - } else if (b.equalsIgnoreCase("true")) { - return true; - } else { - throw new RuntimeException("Value of " + propName - + " must either be 'true' or 'false'"); - } - } + private final static boolean USE_CRLDP = AccessController.doPrivileged + (new GetBooleanAction("com.sun.security.enableCRLDP")); // singleton instance private static final DistributionPointFetcher INSTANCE = diff --git a/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java b/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java index 59b95dc9d1d2d2b0253d9229e44eee3762ebffa3..59ce3a9713cc888e57109f0b032e7e6fdd049668 100644 --- a/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java +++ b/src/share/classes/sun/security/provider/certpath/ForwardBuilder.java @@ -82,6 +82,7 @@ class ForwardBuilder extends Builder { TrustAnchor trustAnchor; private Comparator comparator; private boolean searchAllCertStores = true; + private boolean onlyEECert = false; /** * Initialize the builder with the input parameters. @@ -89,7 +90,8 @@ class ForwardBuilder extends Builder { * @param params the parameter set used to build a certification path */ ForwardBuilder(PKIXBuilderParameters buildParams, - X500Principal targetSubjectDN, boolean searchAllCertStores) + X500Principal targetSubjectDN, boolean searchAllCertStores, + boolean onlyEECert) { super(buildParams, targetSubjectDN); @@ -108,6 +110,7 @@ class ForwardBuilder extends Builder { } comparator = new PKIXCertComparator(trustedSubjectDNs); this.searchAllCertStores = searchAllCertStores; + this.onlyEECert = onlyEECert; } /** @@ -880,8 +883,8 @@ class ForwardBuilder extends Builder { /* Check revocation if it is enabled */ if (buildParams.isRevocationEnabled()) { try { - CrlRevocationChecker crlChecker = - new CrlRevocationChecker(anchor, buildParams); + CrlRevocationChecker crlChecker = new CrlRevocationChecker + (anchor, buildParams, null, onlyEECert); crlChecker.check(cert, anchor.getCAPublicKey(), true); } catch (CertPathValidatorException cpve) { if (debug != null) { diff --git a/src/share/classes/sun/security/provider/certpath/OCSP.java b/src/share/classes/sun/security/provider/certpath/OCSP.java new file mode 100644 index 0000000000000000000000000000000000000000..2665de6d6801c05cd8231b9c4090d5ffa69046af --- /dev/null +++ b/src/share/classes/sun/security/provider/certpath/OCSP.java @@ -0,0 +1,329 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +package sun.security.provider.certpath; + +import java.io.InputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.net.URI; +import java.net.URL; +import java.net.HttpURLConnection; +import java.security.cert.CertificateException; +import java.security.cert.CertPathValidatorException; +import java.security.cert.CRLReason; +import java.security.cert.Extension; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Collections; +import java.util.Date; +import java.util.List; +import java.util.Map; + +import static sun.security.provider.certpath.OCSPResponse.*; +import sun.security.util.Debug; +import sun.security.x509.AccessDescription; +import sun.security.x509.AuthorityInfoAccessExtension; +import sun.security.x509.GeneralName; +import sun.security.x509.GeneralNameInterface; +import sun.security.x509.URIName; +import sun.security.x509.X509CertImpl; + +/** + * This is a class that checks the revocation status of a certificate(s) using + * OCSP. It is not a PKIXCertPathChecker and therefore can be used outside of + * the CertPathValidator framework. It is useful when you want to + * just check the revocation status of a certificate, and you don't want to + * incur the overhead of validating all of the certificates in the + * associated certificate chain. + * + * @author Sean Mullan + */ +public final class OCSP { + + private static final Debug debug = Debug.getInstance("certpath"); + + private OCSP() {} + + /** + * Obtains the revocation status of a certificate using OCSP using the most + * common defaults. The OCSP responder URI is retrieved from the + * certificate's AIA extension. The OCSP responder certificate is assumed + * to be the issuer's certificate (or issued by the issuer CA). + * + * @param cert the certificate to be checked + * @param issuerCert the issuer certificate + * @return the RevocationStatus + * @throws IOException if there is an exception connecting to or + * communicating with the OCSP responder + * @throws CertPathValidatorException if an exception occurs while + * encoding the OCSP Request or validating the OCSP Response + */ + public static RevocationStatus check(X509Certificate cert, + X509Certificate issuerCert) + throws IOException, CertPathValidatorException { + CertId certId = null; + URI responderURI = null; + try { + X509CertImpl certImpl = X509CertImpl.toImpl(cert); + responderURI = getResponderURI(certImpl); + if (responderURI == null) { + throw new CertPathValidatorException + ("No OCSP Responder URI in certificate"); + } + certId = new CertId(issuerCert, certImpl.getSerialNumberObject()); + } catch (CertificateException ce) { + throw new CertPathValidatorException + ("Exception while encoding OCSPRequest", ce); + } catch (IOException ioe) { + throw new CertPathValidatorException + ("Exception while encoding OCSPRequest", ioe); + } + OCSPResponse ocspResponse = check(Collections.singletonList(certId), + responderURI, issuerCert, null); + return (RevocationStatus) ocspResponse.getSingleResponse(certId); + } + + /** + * Obtains the revocation status of a certificate using OCSP. + * + * @param cert the certificate to be checked + * @param issuerCert the issuer certificate + * @param responderURI the URI of the OCSP responder + * @param responderCert the OCSP responder's certificate + * @param date the time the validity of the OCSP responder's certificate + * should be checked against. If null, the current time is used. + * @return the RevocationStatus + * @throws IOException if there is an exception connecting to or + * communicating with the OCSP responder + * @throws CertPathValidatorException if an exception occurs while + * encoding the OCSP Request or validating the OCSP Response + */ + public static RevocationStatus check(X509Certificate cert, + X509Certificate issuerCert, URI responderURI, X509Certificate + responderCert, Date date) + throws IOException, CertPathValidatorException { + CertId certId = null; + try { + X509CertImpl certImpl = X509CertImpl.toImpl(cert); + certId = new CertId(issuerCert, certImpl.getSerialNumberObject()); + } catch (CertificateException ce) { + throw new CertPathValidatorException + ("Exception while encoding OCSPRequest", ce); + } catch (IOException ioe) { + throw new CertPathValidatorException + ("Exception while encoding OCSPRequest", ioe); + } + OCSPResponse ocspResponse = check(Collections.singletonList(certId), + responderURI, responderCert, date); + return (RevocationStatus) ocspResponse.getSingleResponse(certId); + } + + /** + * Checks the revocation status of a list of certificates using OCSP. + * + * @param certs the CertIds to be checked + * @param responderURI the URI of the OCSP responder + * @param responderCert the OCSP responder's certificate + * @param date the time the validity of the OCSP responder's certificate + * should be checked against. If null, the current time is used. + * @return the OCSPResponse + * @throws IOException if there is an exception connecting to or + * communicating with the OCSP responder + * @throws CertPathValidatorException if an exception occurs while + * encoding the OCSP Request or validating the OCSP Response + */ + static OCSPResponse check(List certIds, URI responderURI, + X509Certificate responderCert, Date date) + throws IOException, CertPathValidatorException { + + byte[] bytes = null; + try { + OCSPRequest request = new OCSPRequest(certIds); + bytes = request.encodeBytes(); + } catch (IOException ioe) { + throw new CertPathValidatorException + ("Exception while encoding OCSPRequest", ioe); + } + + InputStream in = null; + OutputStream out = null; + byte[] response = null; + try { + URL url = responderURI.toURL(); + if (debug != null) { + debug.println("connecting to OCSP service at: " + url); + } + HttpURLConnection con = (HttpURLConnection)url.openConnection(); + con.setDoOutput(true); + con.setDoInput(true); + con.setRequestMethod("POST"); + con.setRequestProperty + ("Content-type", "application/ocsp-request"); + con.setRequestProperty + ("Content-length", String.valueOf(bytes.length)); + out = con.getOutputStream(); + out.write(bytes); + out.flush(); + // Check the response + if (debug != null && + con.getResponseCode() != HttpURLConnection.HTTP_OK) { + debug.println("Received HTTP error: " + con.getResponseCode() + + " - " + con.getResponseMessage()); + } + in = con.getInputStream(); + int contentLength = con.getContentLength(); + if (contentLength == -1) { + contentLength = Integer.MAX_VALUE; + } + response = new byte[contentLength > 2048 ? 2048 : contentLength]; + int total = 0; + while (total < contentLength) { + int count = in.read(response, total, response.length - total); + if (count < 0) + break; + + total += count; + if (total >= response.length && total < contentLength) { + response = Arrays.copyOf(response, total * 2); + } + } + response = Arrays.copyOf(response, total); + } finally { + if (in != null) { + try { + in.close(); + } catch (IOException ioe) { + throw ioe; + } + } + if (out != null) { + try { + out.close(); + } catch (IOException ioe) { + throw ioe; + } + } + } + + OCSPResponse ocspResponse = null; + try { + ocspResponse = new OCSPResponse(response, date, responderCert); + } catch (IOException ioe) { + // response decoding exception + throw new CertPathValidatorException(ioe); + } + if (ocspResponse.getResponseStatus() != ResponseStatus.SUCCESSFUL) { + throw new CertPathValidatorException + ("OCSP response error: " + ocspResponse.getResponseStatus()); + } + + // Check that the response includes a response for all of the + // certs that were supplied in the request + for (CertId certId : certIds) { + SingleResponse sr = ocspResponse.getSingleResponse(certId); + if (sr == null) { + if (debug != null) { + debug.println("No response found for CertId: " + certId); + } + throw new CertPathValidatorException( + "OCSP response does not include a response for a " + + "certificate supplied in the OCSP request"); + } + if (debug != null) { + debug.println("Status of certificate (with serial number " + + certId.getSerialNumber() + ") is: " + sr.getCertStatus()); + } + } + return ocspResponse; + } + + /** + * Returns the URI of the OCSP Responder as specified in the + * certificate's Authority Information Access extension, or null if + * not specified. + * + * @param cert the certificate + * @return the URI of the OCSP Responder, or null if not specified + */ + public static URI getResponderURI(X509Certificate cert) { + try { + return getResponderURI(X509CertImpl.toImpl(cert)); + } catch (CertificateException ce) { + // treat this case as if the cert had no extension + return null; + } + } + + static URI getResponderURI(X509CertImpl certImpl) { + + // Examine the certificate's AuthorityInfoAccess extension + AuthorityInfoAccessExtension aia = + certImpl.getAuthorityInfoAccessExtension(); + if (aia == null) { + return null; + } + + List descriptions = aia.getAccessDescriptions(); + for (AccessDescription description : descriptions) { + if (description.getAccessMethod().equals( + AccessDescription.Ad_OCSP_Id)) { + + GeneralName generalName = description.getAccessLocation(); + if (generalName.getType() == GeneralNameInterface.NAME_URI) { + URIName uri = (URIName) generalName.getName(); + return uri.getURI(); + } + } + } + return null; + } + + /** + * The Revocation Status of a certificate. + */ + public static interface RevocationStatus { + public enum CertStatus { GOOD, REVOKED, UNKNOWN }; + + /** + * Returns the revocation status. + */ + CertStatus getCertStatus(); + /** + * Returns the time when the certificate was revoked, or null + * if it has not been revoked. + */ + Date getRevocationTime(); + /** + * Returns the reason the certificate was revoked, or null if it + * has not been revoked. + */ + CRLReason getRevocationReason(); + + /** + * Returns a Map of additional extensions. + */ + Map getSingleExtensions(); + } +} diff --git a/src/share/classes/sun/security/provider/certpath/OCSPChecker.java b/src/share/classes/sun/security/provider/certpath/OCSPChecker.java index 39c250257386b6455031861bdadd0ac8baa280ca..6f72c7ec185dc9e2fe5c80889dd75ff52fe52b8e 100644 --- a/src/share/classes/sun/security/provider/certpath/OCSPChecker.java +++ b/src/share/classes/sun/security/provider/certpath/OCSPChecker.java @@ -25,20 +25,20 @@ package sun.security.provider.certpath; -import java.io.*; +import java.io.IOException; import java.math.BigInteger; import java.util.*; import java.security.AccessController; -import java.security.Principal; import java.security.PrivilegedAction; import java.security.Security; import java.security.cert.*; import java.security.cert.CertPathValidatorException.BasicReason; -import java.net.*; +import java.net.URI; +import java.net.URISyntaxException; import javax.security.auth.x500.X500Principal; -import sun.misc.IOUtils; -import sun.security.util.*; +import static sun.security.provider.certpath.OCSP.*; +import sun.security.util.Debug; import sun.security.x509.*; /** @@ -51,27 +51,18 @@ import sun.security.x509.*; */ class OCSPChecker extends PKIXCertPathChecker { - public static final String OCSP_ENABLE_PROP = "ocsp.enable"; - public static final String OCSP_URL_PROP = "ocsp.responderURL"; - public static final String OCSP_CERT_SUBJECT_PROP = + static final String OCSP_ENABLE_PROP = "ocsp.enable"; + static final String OCSP_URL_PROP = "ocsp.responderURL"; + static final String OCSP_CERT_SUBJECT_PROP = "ocsp.responderCertSubjectName"; - public static final String OCSP_CERT_ISSUER_PROP = - "ocsp.responderCertIssuerName"; - public static final String OCSP_CERT_NUMBER_PROP = + static final String OCSP_CERT_ISSUER_PROP = "ocsp.responderCertIssuerName"; + static final String OCSP_CERT_NUMBER_PROP = "ocsp.responderCertSerialNumber"; private static final String HEX_DIGITS = "0123456789ABCDEFabcdef"; private static final Debug DEBUG = Debug.getInstance("certpath"); private static final boolean dump = false; - // Supported extensions - private static final int OCSP_NONCE_DATA[] = - { 1, 3, 6, 1, 5, 5, 7, 48, 1, 2 }; - private static final ObjectIdentifier OCSP_NONCE_OID; - static { - OCSP_NONCE_OID = ObjectIdentifier.newInternal(OCSP_NONCE_DATA); - } - private int remainingCerts; private X509Certificate[] certs; @@ -80,19 +71,26 @@ class OCSPChecker extends PKIXCertPathChecker { private PKIXParameters pkixParams; + private boolean onlyEECert = false; + /** * Default Constructor * * @param certPath the X509 certification path * @param pkixParams the input PKIX parameter set - * @exception CertPathValidatorException Exception thrown if cert path - * does not validate. + * @throws CertPathValidatorException if OCSPChecker can not be created */ OCSPChecker(CertPath certPath, PKIXParameters pkixParams) throws CertPathValidatorException { + this(certPath, pkixParams, false); + } + + OCSPChecker(CertPath certPath, PKIXParameters pkixParams, boolean onlyEECert) + throws CertPathValidatorException { this.cp = certPath; this.pkixParams = pkixParams; + this.onlyEECert = onlyEECert; List tmp = cp.getCertificates(); certs = tmp.toArray(new X509Certificate[tmp.size()]); init(false); @@ -102,6 +100,7 @@ class OCSPChecker extends PKIXCertPathChecker { * Initializes the internal state of the checker from parameters * specified in the constructor */ + @Override public void init(boolean forward) throws CertPathValidatorException { if (!forward) { remainingCerts = certs.length + 1; @@ -111,11 +110,11 @@ class OCSPChecker extends PKIXCertPathChecker { } } - public boolean isForwardCheckingSupported() { + @Override public boolean isForwardCheckingSupported() { return false; } - public Set getSupportedExtensions() { + @Override public Set getSupportedExtensions() { return Collections.emptySet(); } @@ -128,298 +127,233 @@ class OCSPChecker extends PKIXCertPathChecker { * @exception CertPathValidatorException Exception is thrown if the * certificate has been revoked. */ + @Override public void check(Certificate cert, Collection unresolvedCritExts) throws CertPathValidatorException { - InputStream in = null; - OutputStream out = null; - // Decrement the certificate counter remainingCerts--; + X509CertImpl currCertImpl = null; try { - X509Certificate responderCert = null; - boolean seekResponderCert = false; - X500Principal responderSubjectName = null; - X500Principal responderIssuerName = null; - BigInteger responderSerialNumber = null; - - boolean seekIssuerCert = true; - X509CertImpl issuerCertImpl = null; - X509CertImpl currCertImpl = - X509CertImpl.toImpl((X509Certificate)cert); - - /* - * OCSP security property values, in the following order: - * 1. ocsp.responderURL - * 2. ocsp.responderCertSubjectName - * 3. ocsp.responderCertIssuerName - * 4. ocsp.responderCertSerialNumber - */ - String[] properties = getOCSPProperties(); - - // Check whether OCSP is feasible before seeking cert information - URL url = getOCSPServerURL(currCertImpl, properties); - - // When responder's subject name is set then the issuer/serial - // properties are ignored - if (properties[1] != null) { - responderSubjectName = new X500Principal(properties[1]); - - } else if (properties[2] != null && properties[3] != null) { - responderIssuerName = new X500Principal(properties[2]); - // remove colon or space separators - String value = stripOutSeparators(properties[3]); - responderSerialNumber = new BigInteger(value, 16); - - } else if (properties[2] != null || properties[3] != null) { - throw new CertPathValidatorException( - "Must specify both ocsp.responderCertIssuerName and " + - "ocsp.responderCertSerialNumber properties"); - } - - // If the OCSP responder cert properties are set then the - // identified cert must be located in the trust anchors or - // in the cert stores. - if (responderSubjectName != null || responderIssuerName != null) { - seekResponderCert = true; - } + currCertImpl = X509CertImpl.toImpl((X509Certificate)cert); + } catch (CertificateException ce) { + throw new CertPathValidatorException(ce); + } - // Set the issuer certificate to the next cert in the chain - // (unless we're processing the final cert). - if (remainingCerts < certs.length) { - issuerCertImpl = X509CertImpl.toImpl(certs[remainingCerts]); - seekIssuerCert = false; // done - - // By default, the OCSP responder's cert is the same as the - // issuer of the cert being validated. - if (! seekResponderCert) { - responderCert = certs[remainingCerts]; - if (DEBUG != null) { - DEBUG.println("Responder's certificate is the same " + - "as the issuer of the certificate being validated"); - } - } + if (onlyEECert && currCertImpl.getBasicConstraints() != -1) { + if (DEBUG != null) { + DEBUG.println("Skipping revocation check, not end entity cert"); } + return; + } - // Check anchor certs for: - // - the issuer cert (of the cert being validated) - // - the OCSP responder's cert - if (seekIssuerCert || seekResponderCert) { + /* + * OCSP security property values, in the following order: + * 1. ocsp.responderURL + * 2. ocsp.responderCertSubjectName + * 3. ocsp.responderCertIssuerName + * 4. ocsp.responderCertSerialNumber + */ + // should cache these properties to avoid calling every time? + String[] properties = getOCSPProperties(); + + // Check whether OCSP is feasible before seeking cert information + URI uri = getOCSPServerURI(currCertImpl, properties[0]); + + // When responder's subject name is set then the issuer/serial + // properties are ignored + X500Principal responderSubjectName = null; + X500Principal responderIssuerName = null; + BigInteger responderSerialNumber = null; + if (properties[1] != null) { + responderSubjectName = new X500Principal(properties[1]); + } else if (properties[2] != null && properties[3] != null) { + responderIssuerName = new X500Principal(properties[2]); + // remove colon or space separators + String value = stripOutSeparators(properties[3]); + responderSerialNumber = new BigInteger(value, 16); + } else if (properties[2] != null || properties[3] != null) { + throw new CertPathValidatorException( + "Must specify both ocsp.responderCertIssuerName and " + + "ocsp.responderCertSerialNumber properties"); + } - if (DEBUG != null && seekResponderCert) { - DEBUG.println("Searching trust anchors for responder's " + - "certificate"); - } + // If the OCSP responder cert properties are set then the + // identified cert must be located in the trust anchors or + // in the cert stores. + boolean seekResponderCert = false; + if (responderSubjectName != null || responderIssuerName != null) { + seekResponderCert = true; + } - // Extract the anchor certs - Iterator anchors = pkixParams.getTrustAnchors().iterator(); - if (! anchors.hasNext()) { - throw new CertPathValidatorException( - "Must specify at least one trust anchor"); + // Set the issuer certificate to the next cert in the chain + // (unless we're processing the final cert). + X509Certificate issuerCert = null; + boolean seekIssuerCert = true; + X509Certificate responderCert = null; + if (remainingCerts < certs.length) { + issuerCert = certs[remainingCerts]; + seekIssuerCert = false; // done + + // By default, the OCSP responder's cert is the same as the + // issuer of the cert being validated. + if (!seekResponderCert) { + responderCert = issuerCert; + if (DEBUG != null) { + DEBUG.println("Responder's certificate is the same " + + "as the issuer of the certificate being validated"); } + } + } - X500Principal certIssuerName = - currCertImpl.getIssuerX500Principal(); - while (anchors.hasNext() && - (seekIssuerCert || seekResponderCert)) { + // Check anchor certs for: + // - the issuer cert (of the cert being validated) + // - the OCSP responder's cert + if (seekIssuerCert || seekResponderCert) { - TrustAnchor anchor = (TrustAnchor)anchors.next(); - X509Certificate anchorCert = anchor.getTrustedCert(); - X500Principal anchorSubjectName = - anchorCert.getSubjectX500Principal(); + if (DEBUG != null && seekResponderCert) { + DEBUG.println("Searching trust anchors for responder's " + + "certificate"); + } - if (dump) { - System.out.println("Issuer DN is " + certIssuerName); - System.out.println("Subject DN is " + - anchorSubjectName); - } + // Extract the anchor certs + Iterator anchors + = pkixParams.getTrustAnchors().iterator(); + if (!anchors.hasNext()) { + throw new CertPathValidatorException( + "Must specify at least one trust anchor"); + } - // Check if anchor cert is the issuer cert - if (seekIssuerCert && - certIssuerName.equals(anchorSubjectName)) { + X500Principal certIssuerName = + currCertImpl.getIssuerX500Principal(); + while (anchors.hasNext() && (seekIssuerCert || seekResponderCert)) { - issuerCertImpl = X509CertImpl.toImpl(anchorCert); - seekIssuerCert = false; // done + TrustAnchor anchor = anchors.next(); + X509Certificate anchorCert = anchor.getTrustedCert(); + X500Principal anchorSubjectName = + anchorCert.getSubjectX500Principal(); - // By default, the OCSP responder's cert is the same as - // the issuer of the cert being validated. - if (! seekResponderCert && responderCert == null) { - responderCert = anchorCert; - if (DEBUG != null) { - DEBUG.println("Responder's certificate is the" + - " same as the issuer of the certificate " + - "being validated"); - } - } - } + if (dump) { + System.out.println("Issuer DN is " + certIssuerName); + System.out.println("Subject DN is " + anchorSubjectName); + } - // Check if anchor cert is the responder cert - if (seekResponderCert) { - // Satisfy the responder subject name property only, or - // satisfy the responder issuer name and serial number - // properties only - if ((responderSubjectName != null && - responderSubjectName.equals(anchorSubjectName)) || - (responderIssuerName != null && - responderSerialNumber != null && - responderIssuerName.equals( - anchorCert.getIssuerX500Principal()) && - responderSerialNumber.equals( - anchorCert.getSerialNumber()))) { - - responderCert = anchorCert; - seekResponderCert = false; // done + // Check if anchor cert is the issuer cert + if (seekIssuerCert && + certIssuerName.equals(anchorSubjectName)) { + + issuerCert = anchorCert; + seekIssuerCert = false; // done + + // By default, the OCSP responder's cert is the same as + // the issuer of the cert being validated. + if (!seekResponderCert && responderCert == null) { + responderCert = anchorCert; + if (DEBUG != null) { + DEBUG.println("Responder's certificate is the" + + " same as the issuer of the certificate " + + "being validated"); } } } - if (issuerCertImpl == null) { - throw new CertPathValidatorException( - "No trusted certificate for " + - currCertImpl.getIssuerDN()); - } - // Check cert stores if responder cert has not yet been found + // Check if anchor cert is the responder cert if (seekResponderCert) { - if (DEBUG != null) { - DEBUG.println("Searching cert stores for responder's " + - "certificate"); - } - X509CertSelector filter = null; - if (responderSubjectName != null) { - filter = new X509CertSelector(); - filter.setSubject(responderSubjectName.getName()); - } else if (responderIssuerName != null && - responderSerialNumber != null) { - filter = new X509CertSelector(); - filter.setIssuer(responderIssuerName.getName()); - filter.setSerialNumber(responderSerialNumber); - } - if (filter != null) { - List certStores = pkixParams.getCertStores(); - AlgorithmChecker algChecker= - AlgorithmChecker.getInstance(); - for (CertStore certStore : certStores) { - for (Certificate selected : - certStore.getCertificates(filter)) { - try { - // don't bother to trust algorithm disabled - // certificate as responder - algChecker.check(selected); - - responderCert = (X509Certificate)selected; - seekResponderCert = false; // done - break; - } catch (CertPathValidatorException cpve) { - if (DEBUG != null) { - DEBUG.println( - "OCSP responder certificate " + - "algorithm check failed: " + cpve); - } - } - } - - if (!seekResponderCert) { - break; - } - } + // Satisfy the responder subject name property only, or + // satisfy the responder issuer name and serial number + // properties only + if ((responderSubjectName != null && + responderSubjectName.equals(anchorSubjectName)) || + (responderIssuerName != null && + responderSerialNumber != null && + responderIssuerName.equals( + anchorCert.getIssuerX500Principal()) && + responderSerialNumber.equals( + anchorCert.getSerialNumber()))) { + + responderCert = anchorCert; + seekResponderCert = false; // done } } } - - // Could not find the certificate identified in the OCSP properties - if (seekResponderCert) { + if (issuerCert == null) { throw new CertPathValidatorException( - "Cannot find the responder's certificate " + - "(set using the OCSP security properties)."); - } - - // Construct an OCSP Request - OCSPRequest ocspRequest = - new OCSPRequest(currCertImpl, issuerCertImpl); - - // Use the URL to the OCSP service that was created earlier - HttpURLConnection con = (HttpURLConnection)url.openConnection(); - if (DEBUG != null) { - DEBUG.println("connecting to OCSP service at: " + url); - } - - // Indicate that both input and output will be performed, - // that the method is POST, and that the content length is - // the length of the byte array - - con.setDoOutput(true); - con.setDoInput(true); - con.setRequestMethod("POST"); - con.setRequestProperty("Content-type", "application/ocsp-request"); - byte[] bytes = ocspRequest.encodeBytes(); - CertId certId = ocspRequest.getCertId(); - - con.setRequestProperty("Content-length", - String.valueOf(bytes.length)); - out = con.getOutputStream(); - out.write(bytes); - out.flush(); - - // Check the response - if (DEBUG != null && - con.getResponseCode() != HttpURLConnection.HTTP_OK) { - DEBUG.println("Received HTTP error: " + con.getResponseCode() + - " - " + con.getResponseMessage()); + "No trusted certificate for " + currCertImpl.getIssuerDN()); } - in = con.getInputStream(); - int contentLength = con.getContentLength(); - byte[] response = IOUtils.readFully(in, contentLength, false); - - OCSPResponse ocspResponse = new OCSPResponse(response, pkixParams, - responderCert); - // Check that response applies to the cert that was supplied - if (! certId.equals(ocspResponse.getCertId())) { - throw new CertPathValidatorException( - "Certificate in the OCSP response does not match the " + - "certificate supplied in the OCSP request."); + // Check cert stores if responder cert has not yet been found + if (seekResponderCert) { + if (DEBUG != null) { + DEBUG.println("Searching cert stores for responder's " + + "certificate"); + } + X509CertSelector filter = null; + if (responderSubjectName != null) { + filter = new X509CertSelector(); + filter.setSubject(responderSubjectName); + } else if (responderIssuerName != null && + responderSerialNumber != null) { + filter = new X509CertSelector(); + filter.setIssuer(responderIssuerName); + filter.setSerialNumber(responderSerialNumber); + } + if (filter != null) { + List certStores = pkixParams.getCertStores(); + for (CertStore certStore : certStores) { + Iterator i = null; + try { + i = certStore.getCertificates(filter).iterator(); + } catch (CertStoreException cse) { + // ignore and try next certStore + if (DEBUG != null) { + DEBUG.println("CertStore exception:" + cse); + } + continue; + } + if (i.hasNext()) { + responderCert = (X509Certificate) i.next(); + seekResponderCert = false; // done + break; + } + } + } } - SerialNumber serialNumber = currCertImpl.getSerialNumberObject(); - int certOCSPStatus = ocspResponse.getCertStatus(serialNumber); + } - if (DEBUG != null) { - DEBUG.println("Status of certificate (with serial number " + - serialNumber.getNumber() + ") is: " + - OCSPResponse.certStatusToText(certOCSPStatus)); - } + // Could not find the certificate identified in the OCSP properties + if (seekResponderCert) { + throw new CertPathValidatorException( + "Cannot find the responder's certificate " + + "(set using the OCSP security properties)."); + } - if (certOCSPStatus == OCSPResponse.CERT_STATUS_REVOKED) { - Throwable t = new CertificateRevokedException( - ocspResponse.getRevocationTime(), - ocspResponse.getRevocationReason(), - responderCert.getSubjectX500Principal(), - ocspResponse.getSingleExtensions()); - throw new CertPathValidatorException(t.getMessage(), t, - null, -1, BasicReason.REVOKED); + CertId certId = null; + OCSPResponse response = null; + try { + certId = new CertId + (issuerCert, currCertImpl.getSerialNumberObject()); + response = OCSP.check(Collections.singletonList(certId), uri, + responderCert, pkixParams.getDate()); + } catch (IOException ioe) { + // should allow this to pass if network failures are acceptable + throw new CertPathValidatorException + ("Unable to send OCSP request", ioe); + } - } else if (certOCSPStatus == OCSPResponse.CERT_STATUS_UNKNOWN) { - throw new CertPathValidatorException( - "Certificate's revocation status is unknown", null, cp, - remainingCerts, BasicReason.UNDETERMINED_REVOCATION_STATUS); - } - } catch (Exception e) { - throw new CertPathValidatorException(e); - } finally { - if (in != null) { - try { - in.close(); - } catch (IOException ioe) { - throw new CertPathValidatorException(ioe); - } - } - if (out != null) { - try { - out.close(); - } catch (IOException ioe) { - throw new CertPathValidatorException(ioe); - } - } + RevocationStatus rs = (RevocationStatus) response.getSingleResponse(certId); + RevocationStatus.CertStatus certStatus = rs.getCertStatus(); + if (certStatus == RevocationStatus.CertStatus.REVOKED) { + Throwable t = new CertificateRevokedException( + rs.getRevocationTime(), rs.getRevocationReason(), + responderCert.getSubjectX500Principal(), + rs.getSingleExtensions()); + throw new CertPathValidatorException(t.getMessage(), t, + null, -1, BasicReason.REVOKED); + } else if (certStatus == RevocationStatus.CertStatus.UNKNOWN) { + throw new CertPathValidatorException( + "Certificate's revocation status is unknown", null, cp, + remainingCerts, BasicReason.UNDETERMINED_REVOCATION_STATUS); } } @@ -430,20 +364,18 @@ class OCSPChecker extends PKIXCertPathChecker { * 3. ocsp.responderCertIssuerName * 4. ocsp.responderCertSerialNumber */ - private static URL getOCSPServerURL(X509CertImpl currCertImpl, - String[] properties) - throws CertificateParsingException, CertPathValidatorException { - - if (properties[0] != null) { - try { - return new URL(properties[0]); - } catch (java.net.MalformedURLException e) { + private static URI getOCSPServerURI(X509CertImpl currCertImpl, + String responderURL) throws CertPathValidatorException { + + if (responderURL != null) { + try { + return new URI(responderURL); + } catch (URISyntaxException e) { throw new CertPathValidatorException(e); - } + } } // Examine the certificate's AuthorityInfoAccess extension - AuthorityInfoAccessExtension aia = currCertImpl.getAuthorityInfoAccessExtension(); if (aia == null) { @@ -458,13 +390,8 @@ class OCSPChecker extends PKIXCertPathChecker { GeneralName generalName = description.getAccessLocation(); if (generalName.getType() == GeneralNameInterface.NAME_URI) { - try { - URIName uri = (URIName) generalName.getName(); - return (new URL(uri.getName())); - - } catch (java.net.MalformedURLException e) { - throw new CertPathValidatorException(e); - } + URIName uri = (URIName) generalName.getName(); + return uri.getURI(); } } } diff --git a/src/share/classes/sun/security/provider/certpath/OCSPRequest.java b/src/share/classes/sun/security/provider/certpath/OCSPRequest.java index b7350b55e9bc194541b312dccc0ae83f2aa15a79..393ac6f0e73d6bd85177d6e4196106a80a031d01 100644 --- a/src/share/classes/sun/security/provider/certpath/OCSPRequest.java +++ b/src/share/classes/sun/security/provider/certpath/OCSPRequest.java @@ -1,5 +1,5 @@ /* - * Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,9 +26,9 @@ package sun.security.provider.certpath; import java.io.IOException; -import java.security.cert.CertPathValidatorException; +import java.util.Collections; +import java.util.List; import sun.misc.HexDumpEncoder; -import sun.security.x509.*; import sun.security.util.*; /** @@ -77,47 +77,33 @@ class OCSPRequest { private static final Debug debug = Debug.getInstance("certpath"); private static final boolean dump = false; - // Serial number of the certificates to be checked for revocation - private SerialNumber serialNumber; - - // Issuer's certificate (for computing certId hash values) - private X509CertImpl issuerCert; - - // CertId of the certificate to be checked - private CertId certId = null; + // List of request CertIds + private final List certIds; /* * Constructs an OCSPRequest. This constructor is used * to construct an unsigned OCSP Request for a single user cert. */ - // used by OCSPChecker - OCSPRequest(X509CertImpl userCert, X509CertImpl issuerCert) - throws CertPathValidatorException { + OCSPRequest(CertId certId) { + this.certIds = Collections.singletonList(certId); + } - if (issuerCert == null) { - throw new CertPathValidatorException("Null IssuerCertificate"); - } - this.issuerCert = issuerCert; - serialNumber = userCert.getSerialNumberObject(); + OCSPRequest(List certIds) { + this.certIds = certIds; } - // used by OCSPChecker byte[] encodeBytes() throws IOException { // encode tbsRequest DerOutputStream tmp = new DerOutputStream(); - DerOutputStream derSingleReqList = new DerOutputStream(); - SingleRequest singleRequest = null; - - try { - singleRequest = new SingleRequest(issuerCert, serialNumber); - } catch (Exception e) { - throw new IOException("Error encoding OCSP request"); + DerOutputStream requestsOut = new DerOutputStream(); + for (CertId certId : certIds) { + DerOutputStream certIdOut = new DerOutputStream(); + certId.encode(certIdOut); + requestsOut.write(DerValue.tag_Sequence, certIdOut); } - certId = singleRequest.getCertId(); - singleRequest.encode(derSingleReqList); - tmp.write(DerValue.tag_Sequence, derSingleReqList); + tmp.write(DerValue.tag_Sequence, requestsOut); // No extensions supported DerOutputStream tbsRequest = new DerOutputStream(); tbsRequest.write(DerValue.tag_Sequence, tmp); @@ -130,35 +116,14 @@ class OCSPRequest { if (dump) { HexDumpEncoder hexEnc = new HexDumpEncoder(); - System.out.println ("OCSPRequest bytes are... "); + System.out.println("OCSPRequest bytes are... "); System.out.println(hexEnc.encode(bytes)); } - return(bytes); - } - - // used by OCSPChecker - CertId getCertId() { - return certId; + return bytes; } - private static class SingleRequest { - private CertId certId; - - // No extensions are set - - private SingleRequest(X509CertImpl cert, SerialNumber serialNo) throws Exception { - certId = new CertId(cert, serialNo); - } - - private void encode(DerOutputStream out) throws IOException { - DerOutputStream tmp = new DerOutputStream(); - certId.encode(tmp); - out.write(DerValue.tag_Sequence, tmp); - } - - private CertId getCertId() { - return certId; - } + List getCertIds() { + return certIds; } } diff --git a/src/share/classes/sun/security/provider/certpath/OCSPResponse.java b/src/share/classes/sun/security/provider/certpath/OCSPResponse.java index f7c5dbc5cada5660a0265cc8c1cf445076ade65e..e7b148fbc7cae379c925082ffd5e6fb24d77b206 100644 --- a/src/share/classes/sun/security/provider/certpath/OCSPResponse.java +++ b/src/share/classes/sun/security/provider/certpath/OCSPResponse.java @@ -28,17 +28,16 @@ package sun.security.provider.certpath; import java.io.*; import java.math.BigInteger; import java.security.*; +import java.security.cert.CertificateException; +import java.security.cert.CertificateParsingException; import java.security.cert.CertPathValidatorException; import java.security.cert.CRLReason; import java.security.cert.X509Certificate; -import java.security.cert.PKIXParameters; -import javax.security.auth.x500.X500Principal; +import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.Set; -import java.util.Iterator; import sun.misc.HexDumpEncoder; import sun.security.x509.*; import sun.security.util.*; @@ -113,32 +112,29 @@ import sun.security.util.*; * @author Ram Marti */ -class OCSPResponse { +public final class OCSPResponse { - // Certificate status CHOICE - public static final int CERT_STATUS_GOOD = 0; - public static final int CERT_STATUS_REVOKED = 1; - public static final int CERT_STATUS_UNKNOWN = 2; + public enum ResponseStatus { + SUCCESSFUL, // Response has valid confirmations + MALFORMED_REQUEST, // Illegal confirmation request + INTERNAL_ERROR, // Internal error in issuer + TRY_LATER, // Try again later + UNUSED, // is not used + SIG_REQUIRED, // Must sign the request + UNAUTHORIZED // Request unauthorized + }; + private static ResponseStatus[] rsvalues = ResponseStatus.values(); private static final Debug DEBUG = Debug.getInstance("certpath"); private static final boolean dump = false; - private static final ObjectIdentifier OCSP_BASIC_RESPONSE_OID; - private static final ObjectIdentifier OCSP_NONCE_EXTENSION_OID; - static { - ObjectIdentifier tmp1 = null; - ObjectIdentifier tmp2 = null; - try { - tmp1 = new ObjectIdentifier("1.3.6.1.5.5.7.48.1.1"); - tmp2 = new ObjectIdentifier("1.3.6.1.5.5.7.48.1.2"); - } catch (Exception e) { - // should not happen; log and exit - } - OCSP_BASIC_RESPONSE_OID = tmp1; - OCSP_NONCE_EXTENSION_OID = tmp2; - } + private static final ObjectIdentifier OCSP_BASIC_RESPONSE_OID = + ObjectIdentifier.newInternal(new int[] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 1}); + private static final ObjectIdentifier OCSP_NONCE_EXTENSION_OID = + ObjectIdentifier.newInternal(new int[] { 1, 3, 6, 1, 5, 5, 7, 48, 1, 2}); - // OCSP response status code - private static final int OCSP_RESPONSE_OK = 0; + private static final int CERT_STATUS_GOOD = 0; + private static final int CERT_STATUS_REVOKED = 1; + private static final int CERT_STATUS_UNKNOWN = 2; // ResponderID CHOICE tags private static final int NAME_TAG = 1; @@ -147,7 +143,8 @@ class OCSPResponse { // Object identifier for the OCSPSigning key purpose private static final String KP_OCSP_SIGNING_OID = "1.3.6.1.5.5.7.3.9"; - private SingleResponse singleResponse; + private final ResponseStatus responseStatus; + private final Map singleResponseMap; // Maximum clock skew in milliseconds (15 minutes) allowed when checking // validity of OCSP responses @@ -159,312 +156,300 @@ class OCSPResponse { /* * Create an OCSP response from its ASN.1 DER encoding. */ - // used by OCSPChecker - OCSPResponse(byte[] bytes, PKIXParameters params, + OCSPResponse(byte[] bytes, Date dateCheckedAgainst, X509Certificate responderCert) throws IOException, CertPathValidatorException { - try { - int responseStatus; - ObjectIdentifier responseType; - int version; - CertificateIssuerName responderName = null; - Date producedAtDate; - AlgorithmId sigAlgId; - byte[] ocspNonce; - - // OCSPResponse - if (dump) { - HexDumpEncoder hexEnc = new HexDumpEncoder(); - System.out.println("OCSPResponse bytes are..."); - System.out.println(hexEnc.encode(bytes)); - } - DerValue der = new DerValue(bytes); - if (der.tag != DerValue.tag_Sequence) { - throw new IOException("Bad encoding in OCSP response: " + - "expected ASN.1 SEQUENCE tag."); - } - DerInputStream derIn = der.getData(); + // OCSPResponse + if (dump) { + HexDumpEncoder hexEnc = new HexDumpEncoder(); + System.out.println("OCSPResponse bytes are..."); + System.out.println(hexEnc.encode(bytes)); + } + DerValue der = new DerValue(bytes); + if (der.tag != DerValue.tag_Sequence) { + throw new IOException("Bad encoding in OCSP response: " + + "expected ASN.1 SEQUENCE tag."); + } + DerInputStream derIn = der.getData(); + + // responseStatus + int status = derIn.getEnumerated(); + if (status >= 0 && status < rsvalues.length) { + responseStatus = rsvalues[status]; + } else { + // unspecified responseStatus + throw new IOException("Unknown OCSPResponse status: " + status); + } + if (DEBUG != null) { + DEBUG.println("OCSP response status: " + responseStatus); + } + if (responseStatus != ResponseStatus.SUCCESSFUL) { + // no need to continue, responseBytes are not set. + singleResponseMap = Collections.emptyMap(); + return; + } - // responseStatus - responseStatus = derIn.getEnumerated(); - if (DEBUG != null) { - DEBUG.println("OCSP response: " + - responseToText(responseStatus)); - } - if (responseStatus != OCSP_RESPONSE_OK) { - throw new CertPathValidatorException( - "OCSP Response Failure: " + - responseToText(responseStatus)); - } + // responseBytes + der = derIn.getDerValue(); + if (!der.isContextSpecific((byte)0)) { + throw new IOException("Bad encoding in responseBytes element " + + "of OCSP response: expected ASN.1 context specific tag 0."); + } + DerValue tmp = der.data.getDerValue(); + if (tmp.tag != DerValue.tag_Sequence) { + throw new IOException("Bad encoding in responseBytes element " + + "of OCSP response: expected ASN.1 SEQUENCE tag."); + } - // responseBytes - der = derIn.getDerValue(); - if (! der.isContextSpecific((byte)0)) { - throw new IOException("Bad encoding in responseBytes element " + - "of OCSP response: expected ASN.1 context specific tag 0."); - }; - DerValue tmp = der.data.getDerValue(); - if (tmp.tag != DerValue.tag_Sequence) { - throw new IOException("Bad encoding in responseBytes element " + - "of OCSP response: expected ASN.1 SEQUENCE tag."); + // responseType + derIn = tmp.data; + ObjectIdentifier responseType = derIn.getOID(); + if (responseType.equals(OCSP_BASIC_RESPONSE_OID)) { + if (DEBUG != null) { + DEBUG.println("OCSP response type: basic"); } - - // responseType - derIn = tmp.data; - responseType = derIn.getOID(); - if (responseType.equals(OCSP_BASIC_RESPONSE_OID)) { - if (DEBUG != null) { - DEBUG.println("OCSP response type: basic"); - } - } else { - if (DEBUG != null) { - DEBUG.println("OCSP response type: " + responseType); - } - throw new IOException("Unsupported OCSP response type: " + - responseType); + } else { + if (DEBUG != null) { + DEBUG.println("OCSP response type: " + responseType); } + throw new IOException("Unsupported OCSP response type: " + + responseType); + } - // BasicOCSPResponse - DerInputStream basicOCSPResponse = - new DerInputStream(derIn.getOctetString()); - - DerValue[] seqTmp = basicOCSPResponse.getSequence(2); + // BasicOCSPResponse + DerInputStream basicOCSPResponse = + new DerInputStream(derIn.getOctetString()); - if (seqTmp.length < 3) { - throw new IOException("Unexpected BasicOCSPResponse value"); - } + DerValue[] seqTmp = basicOCSPResponse.getSequence(2); + if (seqTmp.length < 3) { + throw new IOException("Unexpected BasicOCSPResponse value"); + } - DerValue responseData = seqTmp[0]; + DerValue responseData = seqTmp[0]; - // Need the DER encoded ResponseData to verify the signature later - byte[] responseDataDer = seqTmp[0].toByteArray(); + // Need the DER encoded ResponseData to verify the signature later + byte[] responseDataDer = seqTmp[0].toByteArray(); - // tbsResponseData - if (responseData.tag != DerValue.tag_Sequence) { - throw new IOException("Bad encoding in tbsResponseData " + - " element of OCSP response: expected ASN.1 SEQUENCE tag."); - } - DerInputStream seqDerIn = responseData.data; - DerValue seq = seqDerIn.getDerValue(); - - // version - if (seq.isContextSpecific((byte)0)) { - // seq[0] is version - if (seq.isConstructed() && seq.isContextSpecific()) { - //System.out.println ("version is available"); - seq = seq.data.getDerValue(); - version = seq.getInteger(); - if (seq.data.available() != 0) { - throw new IOException("Bad encoding in version " + - " element of OCSP response: bad format"); - } - seq = seqDerIn.getDerValue(); + // tbsResponseData + if (responseData.tag != DerValue.tag_Sequence) { + throw new IOException("Bad encoding in tbsResponseData " + + "element of OCSP response: expected ASN.1 SEQUENCE tag."); + } + DerInputStream seqDerIn = responseData.data; + DerValue seq = seqDerIn.getDerValue(); + + // version + if (seq.isContextSpecific((byte)0)) { + // seq[0] is version + if (seq.isConstructed() && seq.isContextSpecific()) { + //System.out.println ("version is available"); + seq = seq.data.getDerValue(); + int version = seq.getInteger(); + if (seq.data.available() != 0) { + throw new IOException("Bad encoding in version " + + " element of OCSP response: bad format"); } + seq = seqDerIn.getDerValue(); } + } - // responderID - short tag = (byte)(seq.tag & 0x1f); - if (tag == NAME_TAG) { - responderName = new CertificateIssuerName(seq.getData()); - if (DEBUG != null) { - DEBUG.println("OCSP Responder name: " + responderName); - } - } else if (tag == KEY_TAG) { - // Ignore, for now - } else { - throw new IOException("Bad encoding in responderID element " + - "of OCSP response: expected ASN.1 context specific tag 0 " + - "or 1"); + // responderID + short tag = (byte)(seq.tag & 0x1f); + if (tag == NAME_TAG) { + if (DEBUG != null) { + X500Name responderName = new X500Name(seq.getData()); + DEBUG.println("OCSP Responder name: " + responderName); } + } else if (tag == KEY_TAG) { + // Ignore, for now + } else { + throw new IOException("Bad encoding in responderID element of " + + "OCSP response: expected ASN.1 context specific tag 0 or 1"); + } - // producedAt - seq = seqDerIn.getDerValue(); - producedAtDate = seq.getGeneralizedTime(); + // producedAt + seq = seqDerIn.getDerValue(); + if (DEBUG != null) { + Date producedAtDate = seq.getGeneralizedTime(); + DEBUG.println("OCSP response produced at: " + producedAtDate); + } - // responses - DerValue[] singleResponseDer = seqDerIn.getSequence(1); - // Examine only the first response - singleResponse = new SingleResponse(singleResponseDer[0]); + // responses + DerValue[] singleResponseDer = seqDerIn.getSequence(1); + singleResponseMap + = new HashMap(singleResponseDer.length); + if (DEBUG != null) { + DEBUG.println("OCSP number of SingleResponses: " + + singleResponseDer.length); + } + for (int i = 0; i < singleResponseDer.length; i++) { + SingleResponse singleResponse + = new SingleResponse(singleResponseDer[i]); + singleResponseMap.put(singleResponse.getCertId(), singleResponse); + } - // responseExtensions - if (seqDerIn.available() > 0) { - seq = seqDerIn.getDerValue(); - if (seq.isContextSpecific((byte)1)) { - DerValue[] responseExtDer = seq.data.getSequence(3); - Extension[] responseExtension = - new Extension[responseExtDer.length]; - for (int i = 0; i < responseExtDer.length; i++) { - responseExtension[i] = new Extension(responseExtDer[i]); - if (DEBUG != null) { - DEBUG.println("OCSP extension: " + - responseExtension[i]); - } - if ((responseExtension[i].getExtensionId()).equals( - OCSP_NONCE_EXTENSION_OID)) { - ocspNonce = - responseExtension[i].getExtensionValue(); - - } else if (responseExtension[i].isCritical()) { - throw new IOException( - "Unsupported OCSP critical extension: " + - responseExtension[i].getExtensionId()); - } + // responseExtensions + if (seqDerIn.available() > 0) { + seq = seqDerIn.getDerValue(); + if (seq.isContextSpecific((byte)1)) { + DerValue[] responseExtDer = seq.data.getSequence(3); + for (int i = 0; i < responseExtDer.length; i++) { + Extension responseExtension + = new Extension(responseExtDer[i]); + if (DEBUG != null) { + DEBUG.println("OCSP extension: " + responseExtension); + } + if (responseExtension.getExtensionId().equals( + OCSP_NONCE_EXTENSION_OID)) { + /* + ocspNonce = + responseExtension[i].getExtensionValue(); + */ + } else if (responseExtension.isCritical()) { + throw new IOException( + "Unsupported OCSP critical extension: " + + responseExtension.getExtensionId()); } } } + } - // signatureAlgorithmId - sigAlgId = AlgorithmId.parse(seqTmp[1]); - - // check that the signature algorithm is not disabled. - AlgorithmChecker.check(sigAlgId); + // signatureAlgorithmId + AlgorithmId sigAlgId = AlgorithmId.parse(seqTmp[1]); - // signature - byte[] signature = seqTmp[2].getBitString(); - X509CertImpl[] x509Certs = null; + // signature + byte[] signature = seqTmp[2].getBitString(); + X509CertImpl[] x509Certs = null; - // if seq[3] is available , then it is a sequence of certificates - if (seqTmp.length > 3) { - // certs are available - DerValue seqCert = seqTmp[3]; - if (! seqCert.isContextSpecific((byte)0)) { - throw new IOException("Bad encoding in certs element " + - "of OCSP response: expected ASN.1 context specific tag 0."); - } - DerValue[] certs = (seqCert.getData()).getSequence(3); - x509Certs = new X509CertImpl[certs.length]; + // if seq[3] is available , then it is a sequence of certificates + if (seqTmp.length > 3) { + // certs are available + DerValue seqCert = seqTmp[3]; + if (!seqCert.isContextSpecific((byte)0)) { + throw new IOException("Bad encoding in certs element of " + + "OCSP response: expected ASN.1 context specific tag 0."); + } + DerValue[] certs = seqCert.getData().getSequence(3); + x509Certs = new X509CertImpl[certs.length]; + try { for (int i = 0; i < certs.length; i++) { x509Certs[i] = new X509CertImpl(certs[i].toByteArray()); } + } catch (CertificateException ce) { + throw new IOException("Bad encoding in X509 Certificate", ce); } + } - // Check whether the cert returned by the responder is trusted - if (x509Certs != null && x509Certs[0] != null) { - X509CertImpl cert = x509Certs[0]; - - // First check if the cert matches the responder cert which - // was set locally. - if (cert.equals(responderCert)) { - // cert is trusted, now verify the signed response + // Check whether the cert returned by the responder is trusted + if (x509Certs != null && x509Certs[0] != null) { + X509CertImpl cert = x509Certs[0]; - // Next check if the cert was issued by the responder cert - // which was set locally. - } else if (cert.getIssuerX500Principal().equals( - responderCert.getSubjectX500Principal())) { + // First check if the cert matches the responder cert which + // was set locally. + if (cert.equals(responderCert)) { + // cert is trusted, now verify the signed response - // check the certificate algorithm - AlgorithmChecker.check(cert); + // Next check if the cert was issued by the responder cert + // which was set locally. + } else if (cert.getIssuerX500Principal().equals( + responderCert.getSubjectX500Principal())) { - // Check for the OCSPSigning key purpose + // Check for the OCSPSigning key purpose + try { List keyPurposes = cert.getExtendedKeyUsage(); if (keyPurposes == null || !keyPurposes.contains(KP_OCSP_SIGNING_OID)) { - if (DEBUG != null) { - DEBUG.println("Responder's certificate is not " + - "valid for signing OCSP responses."); - } throw new CertPathValidatorException( "Responder's certificate not valid for signing " + "OCSP responses"); } + } catch (CertificateParsingException cpe) { + // assume cert is not valid for signing + throw new CertPathValidatorException( + "Responder's certificate not valid for signing " + + "OCSP responses", cpe); + } - // check the validity - try { - Date dateCheckedAgainst = params.getDate(); - if (dateCheckedAgainst == null) { - cert.checkValidity(); - } else { - cert.checkValidity(dateCheckedAgainst); - } - } catch (GeneralSecurityException e) { - if (DEBUG != null) { - DEBUG.println("Responder's certificate is not " + - "within the validity period."); - } - throw new CertPathValidatorException( - "Responder's certificate not within the " + - "validity period"); - } - - // check for revocation - // - // A CA may specify that an OCSP client can trust a - // responder for the lifetime of the responder's - // certificate. The CA does so by including the - // extension id-pkix-ocsp-nocheck. - // - Extension noCheck = - cert.getExtension(PKIXExtensions.OCSPNoCheck_Id); - if (noCheck != null) { - if (DEBUG != null) { - DEBUG.println("Responder's certificate includes " + - "the extension id-pkix-ocsp-nocheck."); - } + // check the validity + try { + if (dateCheckedAgainst == null) { + cert.checkValidity(); } else { - // we should do the revocating checking of the - // authorized responder in a future update. + cert.checkValidity(dateCheckedAgainst); } + } catch (GeneralSecurityException e) { + throw new CertPathValidatorException( + "Responder's certificate not within the " + + "validity period", e); + } - // verify the signature - try { - cert.verify(responderCert.getPublicKey()); - responderCert = cert; - // cert is trusted, now verify the signed response - - } catch (GeneralSecurityException e) { - responderCert = null; - } - } else { + // check for revocation + // + // A CA may specify that an OCSP client can trust a + // responder for the lifetime of the responder's + // certificate. The CA does so by including the + // extension id-pkix-ocsp-nocheck. + // + Extension noCheck = + cert.getExtension(PKIXExtensions.OCSPNoCheck_Id); + if (noCheck != null) { if (DEBUG != null) { - DEBUG.println("Responder's certificate is not " + - "authorized to sign OCSP responses."); + DEBUG.println("Responder's certificate includes " + + "the extension id-pkix-ocsp-nocheck."); } - throw new CertPathValidatorException( - "Responder's certificate not authorized to sign " + - "OCSP responses"); + } else { + // we should do the revocation checking of the + // authorized responder in a future update. } - } - // Confirm that the signed response was generated using the public - // key from the trusted responder cert - if (responderCert != null) { + // verify the signature + try { + cert.verify(responderCert.getPublicKey()); + responderCert = cert; + // cert is trusted, now verify the signed response - if (! verifyResponse(responseDataDer, responderCert, - sigAlgId, signature, params)) { - if (DEBUG != null) { - DEBUG.println("Error verifying OCSP Responder's " + - "signature"); - } - throw new CertPathValidatorException( - "Error verifying OCSP Responder's signature"); + } catch (GeneralSecurityException e) { + responderCert = null; } } else { - // Need responder's cert in order to verify the signature - if (DEBUG != null) { - DEBUG.println("Unable to verify OCSP Responder's " + - "signature"); - } throw new CertPathValidatorException( - "Unable to verify OCSP Responder's signature"); + "Responder's certificate is not authorized to sign " + + "OCSP responses"); } - } catch (CertPathValidatorException cpve) { - throw cpve; - } catch (Exception e) { - throw new CertPathValidatorException(e); + } + + // Confirm that the signed response was generated using the public + // key from the trusted responder cert + if (responderCert != null) { + if (!verifyResponse(responseDataDer, responderCert, + sigAlgId, signature)) { + throw new CertPathValidatorException( + "Error verifying OCSP Responder's signature"); + } + } else { + // Need responder's cert in order to verify the signature + throw new CertPathValidatorException( + "Unable to verify OCSP Responder's signature"); } } + /** + * Returns the OCSP ResponseStatus. + */ + ResponseStatus getResponseStatus() { + return responseStatus; + } + /* * Verify the signature of the OCSP response. * The responder's cert is implicitly trusted. */ private boolean verifyResponse(byte[] responseData, X509Certificate cert, - AlgorithmId sigAlgId, byte[] signBytes, PKIXParameters params) - throws SignatureException { + AlgorithmId sigAlgId, byte[] signBytes) + throws CertPathValidatorException { try { - Signature respSignature = Signature.getInstance(sigAlgId.getName()); respSignature.initVerify(cert); respSignature.update(responseData); @@ -483,92 +468,33 @@ class OCSPResponse { return false; } } catch (InvalidKeyException ike) { - throw new SignatureException(ike); - + throw new CertPathValidatorException(ike); } catch (NoSuchAlgorithmException nsae) { - throw new SignatureException(nsae); + throw new CertPathValidatorException(nsae); + } catch (SignatureException se) { + throw new CertPathValidatorException(se); } } - /* - * Return the revocation status code for a given certificate. - */ - // used by OCSPChecker - int getCertStatus(SerialNumber sn) { - // ignore serial number for now; if we support multiple - // requests/responses then it will be used - return singleResponse.getStatus(); - } - - // used by OCSPChecker - CertId getCertId() { - return singleResponse.getCertId(); - } - - Date getRevocationTime() { - return singleResponse.getRevocationTime(); - } - - CRLReason getRevocationReason() { - return singleResponse.getRevocationReason(); - } - - Map getSingleExtensions() { - return singleResponse.getSingleExtensions(); - } - - /* - * Map an OCSP response status code to a string. + /** + * Returns the SingleResponse of the specified CertId, or null if + * there is no response for that CertId. */ - static private String responseToText(int status) { - switch (status) { - case 0: - return "Successful"; - case 1: - return "Malformed request"; - case 2: - return "Internal error"; - case 3: - return "Try again later"; - case 4: - return "Unused status code"; - case 5: - return "Request must be signed"; - case 6: - return "Request is unauthorized"; - default: - return ("Unknown status code: " + status); - } - } - - /* - * Map a certificate's revocation status code to a string. - */ - // used by OCSPChecker - static String certStatusToText(int certStatus) { - switch (certStatus) { - case 0: - return "Good"; - case 1: - return "Revoked"; - case 2: - return "Unknown"; - default: - return ("Unknown certificate status code: " + certStatus); - } + SingleResponse getSingleResponse(CertId certId) { + return singleResponseMap.get(certId); } /* * A class representing a single OCSP response. */ - private class SingleResponse { - private CertId certId; - private int certStatus; - private Date thisUpdate; - private Date nextUpdate; - private Date revocationTime; - private CRLReason revocationReason = CRLReason.UNSPECIFIED; - private HashMap singleExtensions; + final static class SingleResponse implements OCSP.RevocationStatus { + private final CertId certId; + private final CertStatus certStatus; + private final Date thisUpdate; + private final Date nextUpdate; + private final Date revocationTime; + private final CRLReason revocationReason; + private final Map singleExtensions; private SingleResponse(DerValue der) throws IOException { if (der.tag != DerValue.tag_Sequence) { @@ -579,35 +505,48 @@ class OCSPResponse { certId = new CertId(tmp.getDerValue().data); DerValue derVal = tmp.getDerValue(); short tag = (byte)(derVal.tag & 0x1f); - if (tag == CERT_STATUS_GOOD) { - certStatus = CERT_STATUS_GOOD; - } else if (tag == CERT_STATUS_REVOKED) { - certStatus = CERT_STATUS_REVOKED; + if (tag == CERT_STATUS_REVOKED) { + certStatus = CertStatus.REVOKED; revocationTime = derVal.data.getGeneralizedTime(); if (derVal.data.available() != 0) { - int reason = derVal.getEnumerated(); - // if reason out-of-range just leave as UNSPECIFIED - if (reason >= 0 && reason < values.length) { - revocationReason = values[reason]; + DerValue dv = derVal.data.getDerValue(); + tag = (byte)(dv.tag & 0x1f); + if (tag == 0) { + int reason = dv.data.getEnumerated(); + // if reason out-of-range just leave as UNSPECIFIED + if (reason >= 0 && reason < values.length) { + revocationReason = values[reason]; + } else { + revocationReason = CRLReason.UNSPECIFIED; + } + } else { + revocationReason = CRLReason.UNSPECIFIED; } + } else { + revocationReason = CRLReason.UNSPECIFIED; } // RevokedInfo if (DEBUG != null) { DEBUG.println("Revocation time: " + revocationTime); DEBUG.println("Revocation reason: " + revocationReason); } - - } else if (tag == CERT_STATUS_UNKNOWN) { - certStatus = CERT_STATUS_UNKNOWN; - } else { - throw new IOException("Invalid certificate status"); + revocationTime = null; + revocationReason = CRLReason.UNSPECIFIED; + if (tag == CERT_STATUS_GOOD) { + certStatus = CertStatus.GOOD; + } else if (tag == CERT_STATUS_UNKNOWN) { + certStatus = CertStatus.UNKNOWN; + } else { + throw new IOException("Invalid certificate status"); + } } thisUpdate = tmp.getGeneralizedTime(); if (tmp.available() == 0) { // we are done + nextUpdate = null; } else { derVal = tmp.getDerValue(); tag = (byte)(derVal.tag & 0x1f); @@ -621,6 +560,8 @@ class OCSPResponse { derVal = tmp.getDerValue(); tag = (byte)(derVal.tag & 0x1f); } + } else { + nextUpdate = null; } } // singleExtensions @@ -638,7 +579,11 @@ class OCSPResponse { DEBUG.println("OCSP single extension: " + ext); } } + } else { + singleExtensions = Collections.emptyMap(); } + } else { + singleExtensions = Collections.emptyMap(); } long now = System.currentTimeMillis(); @@ -668,7 +613,7 @@ class OCSPResponse { /* * Return the certificate's revocation status code */ - private int getStatus() { + @Override public CertStatus getCertStatus() { return certStatus; } @@ -676,28 +621,28 @@ class OCSPResponse { return certId; } - private Date getRevocationTime() { - return revocationTime; + @Override public Date getRevocationTime() { + return (Date) revocationTime.clone(); } - private CRLReason getRevocationReason() { + @Override public CRLReason getRevocationReason() { return revocationReason; } - private Map getSingleExtensions() { - return singleExtensions; + @Override + public Map getSingleExtensions() { + return Collections.unmodifiableMap(singleExtensions); } /** * Construct a string representation of a single OCSP response. */ - public String toString() { + @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("SingleResponse: \n"); sb.append(certId); - sb.append("\nCertStatus: "+ certStatusToText(getCertStatus(null)) + - "\n"); - if (certStatus == CERT_STATUS_REVOKED) { + sb.append("\nCertStatus: "+ certStatus + "\n"); + if (certStatus == CertStatus.REVOKED) { sb.append("revocationTime is " + revocationTime + "\n"); sb.append("revocationReason is " + revocationReason + "\n"); } diff --git a/src/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java b/src/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java index 3511ad7de5431842c10d13349b281f4e867285e1..8dab2f3b26c85b8b7fb31bea250ceccdce77266a 100644 --- a/src/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java +++ b/src/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java @@ -28,8 +28,6 @@ package sun.security.provider.certpath; import java.io.IOException; import java.security.AccessController; import java.security.InvalidAlgorithmParameterException; -import java.security.PrivilegedAction; -import java.security.Security; import java.security.cert.CertPath; import java.security.cert.CertPathParameters; import java.security.cert.CertPathValidatorException; @@ -49,6 +47,7 @@ import java.util.ArrayList; import java.util.Date; import java.util.Set; import javax.security.auth.x500.X500Principal; +import sun.security.action.GetBooleanSecurityPropertyAction; import sun.security.util.Debug; /** @@ -67,7 +66,8 @@ public class PKIXCertPathValidator extends CertPathValidatorSpi { private List userCheckers; private String sigProvider; private BasicChecker basicChecker; - private String ocspProperty; + private boolean ocspEnabled = false; + private boolean onlyEECert = false; /** * Default constructor. @@ -253,13 +253,12 @@ public class PKIXCertPathValidator extends CertPathValidatorSpi { if (pkixParam.isRevocationEnabled()) { // Examine OCSP security property - ocspProperty = AccessController.doPrivileged( - new PrivilegedAction() { - public String run() { - return - Security.getProperty(OCSPChecker.OCSP_ENABLE_PROP); - } - }); + ocspEnabled = AccessController.doPrivileged( + new GetBooleanSecurityPropertyAction + (OCSPChecker.OCSP_ENABLE_PROP)); + onlyEECert = AccessController.doPrivileged( + new GetBooleanSecurityPropertyAction + ("com.sun.security.onlyCheckRevocationOfEECert")); } } @@ -303,15 +302,15 @@ public class PKIXCertPathValidator extends CertPathValidatorSpi { if (pkixParam.isRevocationEnabled()) { // Use OCSP if it has been enabled - if ("true".equalsIgnoreCase(ocspProperty)) { + if (ocspEnabled) { OCSPChecker ocspChecker = - new OCSPChecker(cpOriginal, pkixParam); + new OCSPChecker(cpOriginal, pkixParam, onlyEECert); certPathCheckers.add(ocspChecker); } // Always use CRLs - CrlRevocationChecker revocationChecker = - new CrlRevocationChecker(anchor, pkixParam, certList); + CrlRevocationChecker revocationChecker = new + CrlRevocationChecker(anchor, pkixParam, certList, onlyEECert); certPathCheckers.add(revocationChecker); } diff --git a/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java b/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java index 0c439349d3cf47d1322105adb0f9709814688ed1..6723cb8c6b896d06692297cc2887e1089b4a08b1 100644 --- a/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java +++ b/src/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java @@ -1,5 +1,5 @@ /* - * Copyright 2000-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ package sun.security.provider.certpath; import java.io.IOException; +import java.security.AccessController; import java.security.GeneralSecurityException; import java.security.InvalidAlgorithmParameterException; import java.security.Principal; @@ -44,6 +45,7 @@ import java.util.LinkedList; import java.util.Set; import javax.security.auth.x500.X500Principal; +import sun.security.action.GetBooleanSecurityPropertyAction; import sun.security.x509.X500Name; import sun.security.x509.PKIXExtensions; import sun.security.util.Debug; @@ -85,6 +87,7 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { private PublicKey finalPublicKey; private X509CertSelector targetSel; private List orderedCertStores; + private boolean onlyEECert = false; /** * Create an instance of SunCertPathBuilder. @@ -97,6 +100,9 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { } catch (CertificateException e) { throw new CertPathBuilderException(e); } + onlyEECert = AccessController.doPrivileged( + new GetBooleanSecurityPropertyAction + ("com.sun.security.onlyCheckRevocationOfEECert")); } /** @@ -256,7 +262,6 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { /* * Private build reverse method. - * */ private void buildReverse(List> adjacencyList, LinkedList certPathList) throws Exception @@ -296,7 +301,7 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { currentState.updateState(anchor); // init the crl checker currentState.crlChecker = - new CrlRevocationChecker(null, buildParams); + new CrlRevocationChecker(null, buildParams, null, onlyEECert); try { depthFirstSearchReverse(null, currentState, new ReverseBuilder(buildParams, targetSubjectDN), adjacencyList, @@ -341,10 +346,12 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { adjacencyList.add(new LinkedList()); // init the crl checker - currentState.crlChecker = new CrlRevocationChecker(null, buildParams); + currentState.crlChecker + = new CrlRevocationChecker(null, buildParams, null, onlyEECert); depthFirstSearchForward(targetSubjectDN, currentState, - new ForwardBuilder(buildParams, targetSubjectDN, searchAllCertStores), + new ForwardBuilder + (buildParams, targetSubjectDN, searchAllCertStores, onlyEECert), adjacencyList, certPathList); } @@ -486,8 +493,8 @@ public final class SunCertPathBuilder extends CertPathBuilderSpi { userCheckers.add(mustCheck, basicChecker); mustCheck++; if (buildParams.isRevocationEnabled()) { - userCheckers.add(mustCheck, - new CrlRevocationChecker(anchor, buildParams)); + userCheckers.add(mustCheck, new CrlRevocationChecker + (anchor, buildParams, null, onlyEECert)); mustCheck++; } } diff --git a/src/share/classes/sun/security/ssl/CipherSuite.java b/src/share/classes/sun/security/ssl/CipherSuite.java index bb1ffa0909d9baaa154b7c3ed2d44c876034d12d..6ca15478f8ee95fd07bd56059adfbe235e46a725 100644 --- a/src/share/classes/sun/security/ssl/CipherSuite.java +++ b/src/share/classes/sun/security/ssl/CipherSuite.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2002-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -74,7 +74,7 @@ final class CipherSuite implements Comparable { // Flag indicating if CipherSuite availability can change dynamically. // This is the case when we rely on a JCE cipher implementation that // may not be available in the installed JCE providers. - // It is true because we do not have a Java ECC implementation. + // It is true because we might not have an ECC or Kerberos implementation. final static boolean DYNAMIC_AVAILABILITY = true; private final static boolean ALLOW_ECC = Debug.getBooleanProperty @@ -278,14 +278,22 @@ final class CipherSuite implements Comparable { KeyExchange(String name, boolean allowed) { this.name = name; this.allowed = allowed; - this.alwaysAvailable = allowed && (name.startsWith("EC") == false); + this.alwaysAvailable = allowed && + (!name.startsWith("EC")) && (!name.startsWith("KRB")); } boolean isAvailable() { if (alwaysAvailable) { return true; } - return allowed && JsseJce.isEcAvailable(); + + if (name.startsWith("EC")) { + return (allowed && JsseJce.isEcAvailable()); + } else if (name.startsWith("KRB")) { + return (allowed && JsseJce.isKerberosAvailable()); + } else { + return allowed; + } } public String toString() { diff --git a/src/share/classes/sun/security/ssl/JsseJce.java b/src/share/classes/sun/security/ssl/JsseJce.java index 017efd03ac2ef1308f7cf3141a1c78fc1aa63345..779214308d3125dab292b13550a80024bcbe7ad9 100644 --- a/src/share/classes/sun/security/ssl/JsseJce.java +++ b/src/share/classes/sun/security/ssl/JsseJce.java @@ -1,5 +1,5 @@ /* - * Copyright 2001-2008 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -64,6 +64,29 @@ final class JsseJce { // If yes, then all the EC based crypto we need is available. private static volatile Boolean ecAvailable; + // Flag indicating whether Kerberos crypto is available. + // If true, then all the Kerberos-based crypto we need is available. + private final static boolean kerberosAvailable; + static { + boolean temp; + try { + AccessController.doPrivileged( + new PrivilegedExceptionAction() { + public Void run() throws Exception { + // Test for Kerberos using the bootstrap class loader + Class.forName("sun.security.krb5.PrincipalName", true, + null); + return null; + } + }); + temp = true; + + } catch (Exception e) { + temp = false; + } + kerberosAvailable = temp; + } + static { // force FIPS flag initialization // Because isFIPS() is synchronized and cryptoProvider is not modified @@ -187,6 +210,10 @@ final class JsseJce { ecAvailable = null; } + static boolean isKerberosAvailable() { + return kerberosAvailable; + } + /** * Return an JCE cipher implementation for the specified algorithm. */ diff --git a/src/share/classes/sun/security/tools/JarSigner.java b/src/share/classes/sun/security/tools/JarSigner.java index c62018c99b090b9512e0f84a62d7747f5e46f0d8..3e1d0929104dab5f55b0ec4b7384cdc0a6cbf5e8 100644 --- a/src/share/classes/sun/security/tools/JarSigner.java +++ b/src/share/classes/sun/security/tools/JarSigner.java @@ -291,13 +291,21 @@ public class JarSigner { for (n=0; n < args.length; n++) { String flags = args[n]; + String modifier = null; + if (flags.charAt(0) == '-') { + int pos = flags.indexOf(':'); + if (pos > 0) { + modifier = flags.substring(pos+1); + flags = flags.substring(0, pos); + } + } if (collator.compare(flags, "-keystore") == 0) { if (++n == args.length) usageNoArg(); keystore = args[n]; } else if (collator.compare(flags, "-storepass") ==0) { if (++n == args.length) usageNoArg(); - storepass = args[n].toCharArray(); + storepass = getPass(modifier, args[n]); } else if (collator.compare(flags, "-storetype") ==0) { if (++n == args.length) usageNoArg(); storetype = args[n]; @@ -329,7 +337,7 @@ public class JarSigner { debug = true; } else if (collator.compare(flags, "-keypass") ==0) { if (++n == args.length) usageNoArg(); - keypass = args[n].toCharArray(); + keypass = getPass(modifier, args[n]); } else if (collator.compare(flags, "-sigfile") ==0) { if (++n == args.length) usageNoArg(); sigfile = args[n]; @@ -355,13 +363,7 @@ public class JarSigner { } else if (collator.compare(flags, "-verify") ==0) { verify = true; } else if (collator.compare(flags, "-verbose") ==0) { - verbose = "all"; - } else if (collator.compare(flags, "-verbose:all") ==0) { - verbose = "all"; - } else if (collator.compare(flags, "-verbose:summary") ==0) { - verbose = "summary"; - } else if (collator.compare(flags, "-verbose:grouped") ==0) { - verbose = "grouped"; + verbose = (modifier != null) ? modifier : "all"; } else if (collator.compare(flags, "-sigalg") ==0) { if (++n == args.length) usageNoArg(); sigalg = args[n]; @@ -465,18 +467,25 @@ public class JarSigner { } } - void usageNoArg() { + static char[] getPass(String modifier, String arg) { + char[] output = KeyTool.getPassWithModifier(modifier, arg); + if (output != null) return output; + usage(); + return null; // Useless, usage() already exit + } + + static void usageNoArg() { System.out.println(rb.getString("Option lacks argument")); usage(); } - void usage() { + static void usage() { System.out.println(); System.out.println(rb.getString("Please type jarsigner -help for usage")); System.exit(1); } - void fullusage() { + static void fullusage() { System.out.println(rb.getString ("Usage: jarsigner [options] jar-file alias")); System.out.println(rb.getString diff --git a/src/share/classes/sun/security/tools/KeyTool.java b/src/share/classes/sun/security/tools/KeyTool.java index 8f9e86ee063d6ae12ba25aa78f2afc5e304547ea..d34d0bcdc485c907708a33e2e2c12cd7c5535762 100644 --- a/src/share/classes/sun/security/tools/KeyTool.java +++ b/src/share/classes/sun/security/tools/KeyTool.java @@ -76,6 +76,7 @@ import sun.security.util.DerValue; import sun.security.x509.*; import static java.security.KeyStore.*; +import static sun.security.tools.KeyTool.Command.*; /** * This tool manages keystores. @@ -92,7 +93,7 @@ import static java.security.KeyStore.*; public final class KeyTool { private boolean debug = false; - private int command = -1; + private Command command = null; private String sigAlgName = null; private String keyAlgName = null; private boolean verbose = false; @@ -146,24 +147,132 @@ public final class KeyTool { private List v3ext = new ArrayList (); - private static final int CERTREQ = 1; - private static final int CHANGEALIAS = 2; - private static final int DELETE = 3; - private static final int EXPORTCERT = 4; - private static final int GENKEYPAIR = 5; - private static final int GENSECKEY = 6; - // there is no HELP - private static final int IDENTITYDB = 7; - private static final int IMPORTCERT = 8; - private static final int IMPORTKEYSTORE = 9; - private static final int KEYCLONE = 10; - private static final int KEYPASSWD = 11; - private static final int LIST = 12; - private static final int PRINTCERT = 13; - private static final int SELFCERT = 14; - private static final int STOREPASSWD = 15; - private static final int GENCERT = 16; - private static final int PRINTCERTREQ = 17; + enum Command { + CERTREQ("Generates a certificate request", + "-alias", "-sigalg", "-file", "-keypass", "-keystore", + "-storepass", "-storetype", "-providername", "-providerclass", + "-providerarg", "-providerpath", "-v", "-protected"), + CHANGEALIAS("Changes an entry's alias", + "-alias", "-destalias", "-keypass", "-keystore", "-storepass", + "-storetype", "-providername", "-providerclass", "-providerarg", + "-providerpath", "-v", "-protected"), + DELETE("Deletes an entry", + "-alias", "-keystore", "-storepass", "-storetype", + "-providername", "-providerclass", "-providerarg", + "-providerpath", "-v", "-protected"), + EXPORTCERT("Exports certificate", + "-rfc", "-alias", "-file", "-keystore", "-storepass", + "-storetype", "-providername", "-providerclass", "-providerarg", + "-providerpath", "-v", "-protected"), + GENKEYPAIR("Generates a key pair", + "-alias", "-keyalg", "-keysize", "-sigalg", "-destalias", + "-startdate", "-ext", "-validity", "-keypass", "-keystore", + "-storepass", "-storetype", "-providername", "-providerclass", + "-providerarg", "-providerpath", "-v", "-protected"), + GENSECKEY("Generates a secret key", + "-alias", "-keypass", "-keyalg", "-keysize", "-keystore", + "-storepass", "-storetype", "-providername", "-providerclass", + "-providerarg", "-providerpath", "-v", "-protected"), + GENCERT("Generates certificate from a certificate request", + "-rfc", "-infile", "-outfile", "-alias", "-sigalg", + "-startdate", "-ext", "-validity", "-keypass", "-keystore", + "-storepass", "-storetype", "-providername", "-providerclass", + "-providerarg", "-providerpath", "-v", "-protected"), + IDENTITYDB("Imports entries from a JDK 1.1.x-style identity database", + "-file", "-storetype", "-keystore", "-storepass", "-providername", + "-providerclass", "-providerarg", "-providerpath", "-v"), + IMPORTCERT("Imports a certificate or a certificate chain", + "-noprompt", "-trustcacerts", "-protected", "-alias", "-file", + "-keypass", "-keystore", "-storepass", "-storetype", + "-providername", "-providerclass", "-providerarg", + "-providerpath", "-v"), + IMPORTKEYSTORE("Imports one or all entries from another keystore", + "-srckeystore", "-destkeystore", "-srcstoretype", + "-deststoretype", "-srcstorepass", "-deststorepass", + "-srcprotected", "-srcprovidername", "-destprovidername", + "-srcalias", "-destalias", "-srckeypass", "-destkeypass", + "-noprompt", "-providerclass", "-providerarg", "-providerpath", + "-v"), + KEYCLONE("Clones a key entry", + "-alias", "-destalias", "-keypass", "-new", "-storetype", + "-keystore", "-storepass", "-providername", "-providerclass", + "-providerarg", "-providerpath", "-v"), + KEYPASSWD("Changes the key password of an entry", + "-alias", "-keypass", "-new", "-keystore", "-storepass", + "-storetype", "-providername", "-providerclass", "-providerarg", + "-providerpath", "-v"), + LIST("Lists entries in a keystore", + "-rfc", "-alias", "-keystore", "-storepass", "-storetype", + "-providername", "-providerclass", "-providerarg", + "-providerpath", "-v", "-protected"), + PRINTCERT("Prints the content of a certificate", + "-rfc", "-file", "-sslserver", "-v"), + PRINTCERTREQ("Prints the content of a certificate request", + "-file", "-v"), + SELFCERT("Generates a self-signed certificate", + "-alias", "-sigalg", "-dname", "-startdate", "-validity", "-keypass", + "-storetype", "-keystore", "-storepass", "-providername", + "-providerclass", "-providerarg", "-providerpath", "-v"), + STOREPASSWD("Changes the store password of a keystore", + "-new", "-keystore", "-storepass", "-storetype", "-providername", + "-providerclass", "-providerarg", "-providerpath", "-v"); + + final String description; + final String[] options; + Command(String d, String... o) { + description = d; + options = o; + } + @Override + public String toString() { + return "-" + name().toLowerCase(Locale.ENGLISH); + } + }; + + private static String[][] options = { + // name, arg, description + {"-alias", "", "alias name of the entry to process"}, + {"-destalias", "", "destination alias"}, + {"-destkeypass", "", "destination key password"}, + {"-destkeystore", "", "destination keystore name"}, + {"-destprotected", null, "destination keystore password protected"}, + {"-destprovidername", "", "destination keystore provider name"}, + {"-deststorepass", "", "destination keystore password"}, + {"-deststoretype", "", "destination keystore type"}, + {"-dname", "", "distinguished name"}, + {"-ext", "", "X.509 extension"}, + {"-file", "", "output file name"}, + {"-file", "", "input file name"}, + {"-infile", "", "input file name"}, + {"-keyalg", "", "key algorithm name"}, + {"-keypass", "", "key password"}, + {"-keysize", "", "key bit size"}, + {"-keystore", "", "keystore name"}, + {"-new", "", "new password"}, + {"-noprompt", null, "do not prompt"}, + {"-outfile", "", "output file name"}, + {"-protected", null, "password through protected mechanism"}, + {"-providerarg", "", "provider argument"}, + {"-providerclass", "", "provider class name"}, + {"-providername", "", "provider name"}, + {"-providerpath", "", "provider classpath"}, + {"-rfc", null, "output in RFC style"}, + {"-sigalg", "", "signature algorithm name"}, + {"-srcalias", "", "source alias"}, + {"-srckeypass", "", "source keystore password"}, + {"-srckeystore", "", "source keystore name"}, + {"-srcprotected", null, "source keystore password protected"}, + {"-srcprovidername", "", "source keystore provider name"}, + {"-srcstorepass", "", "source keystore password"}, + {"-srcstoretype", "", "source keystore type"}, + {"-sslserver", "", "SSL server host and port"}, + {"-startdate", "", "certificate validity start date/time"}, + {"-storepass", "", "keystore password"}, + {"-storetype", "", "keystore type"}, + {"-trustcacerts", null, "trust certificates from cacerts"}, + {"-v", null, "verbose output"}, + {"-validity", "", "validity number of days"}, + }; private static final Class[] PARAM_STRING = { String.class }; @@ -192,7 +301,7 @@ public final class KeyTool { private void run(String[] args, PrintStream out) throws Exception { try { parseArgs(args); - if (command != -1) { + if (command != null) { doCommands(out); } } catch (Exception e) { @@ -224,59 +333,59 @@ public final class KeyTool { */ void parseArgs(String[] args) { - if (args.length == 0) { - usage(); - return; - } - int i=0; + boolean help = args.length == 0; for (i=0; (i < args.length) && args[i].startsWith("-"); i++) { String flags = args[i]; + + // Check if the last option needs an arg + if (i == args.length - 1) { + for (String[] option: options) { + // Only options with an arg need to be checked + if (collator.compare(flags, option[0]) == 0) { + if (option[1] != null) errorNeedArgument(flags); + break; + } + } + } + + /* + * Check modifiers + */ + String modifier = null; + int pos = flags.indexOf(':'); + if (pos > 0) { + modifier = flags.substring(pos+1); + flags = flags.substring(0, pos); + } /* * command modes */ - if (collator.compare(flags, "-certreq") == 0) { - command = CERTREQ; - } else if (collator.compare(flags, "-delete") == 0) { - command = DELETE; - } else if (collator.compare(flags, "-export") == 0 || - collator.compare(flags, "-exportcert") == 0) { + boolean isCommand = false; + for (Command c: Command.values()) { + if (collator.compare(flags, c.toString()) == 0) { + command = c; + isCommand = true; + break; + } + } + + if (isCommand) { + // already recognized as a command + } else if (collator.compare(flags, "-export") == 0) { command = EXPORTCERT; - } else if (collator.compare(flags, "-genkey") == 0 || - collator.compare(flags, "-genkeypair") == 0) { + } else if (collator.compare(flags, "-genkey") == 0) { command = GENKEYPAIR; - } else if (collator.compare(flags, "-help") == 0) { - usage(); - return; - } else if (collator.compare(flags, "-identitydb") == 0) { // obsolete - command = IDENTITYDB; - } else if (collator.compare(flags, "-import") == 0 || - collator.compare(flags, "-importcert") == 0) { + } else if (collator.compare(flags, "-import") == 0) { command = IMPORTCERT; - } else if (collator.compare(flags, "-keyclone") == 0) { // obsolete - command = KEYCLONE; - } else if (collator.compare(flags, "-changealias") == 0) { - command = CHANGEALIAS; - } else if (collator.compare(flags, "-keypasswd") == 0) { - command = KEYPASSWD; - } else if (collator.compare(flags, "-list") == 0) { - command = LIST; - } else if (collator.compare(flags, "-printcert") == 0) { - command = PRINTCERT; - } else if (collator.compare(flags, "-selfcert") == 0) { // obsolete - command = SELFCERT; - } else if (collator.compare(flags, "-storepasswd") == 0) { - command = STOREPASSWD; - } else if (collator.compare(flags, "-importkeystore") == 0) { - command = IMPORTKEYSTORE; - } else if (collator.compare(flags, "-genseckey") == 0) { - command = GENSECKEY; - } else if (collator.compare(flags, "-gencert") == 0) { - command = GENCERT; - } else if (collator.compare(flags, "-printcertreq") == 0) { - command = PRINTCERTREQ; + } + /* + * Help + */ + else if (collator.compare(flags, "-help") == 0) { + help = true; } /* @@ -284,101 +393,74 @@ public final class KeyTool { */ else if (collator.compare(flags, "-keystore") == 0 || collator.compare(flags, "-destkeystore") == 0) { - if (++i == args.length) errorNeedArgument(flags); - ksfname = args[i]; + ksfname = args[++i]; } else if (collator.compare(flags, "-storepass") == 0 || collator.compare(flags, "-deststorepass") == 0) { - if (++i == args.length) errorNeedArgument(flags); - storePass = args[i].toCharArray(); + storePass = getPass(modifier, args[++i]); passwords.add(storePass); } else if (collator.compare(flags, "-storetype") == 0 || collator.compare(flags, "-deststoretype") == 0) { - if (++i == args.length) errorNeedArgument(flags); - storetype = args[i]; + storetype = args[++i]; } else if (collator.compare(flags, "-srcstorepass") == 0) { - if (++i == args.length) errorNeedArgument(flags); - srcstorePass = args[i].toCharArray(); + srcstorePass = getPass(modifier, args[++i]); passwords.add(srcstorePass); } else if (collator.compare(flags, "-srcstoretype") == 0) { - if (++i == args.length) errorNeedArgument(flags); - srcstoretype = args[i]; + srcstoretype = args[++i]; } else if (collator.compare(flags, "-srckeypass") == 0) { - if (++i == args.length) errorNeedArgument(flags); - srckeyPass = args[i].toCharArray(); + srckeyPass = getPass(modifier, args[++i]); passwords.add(srckeyPass); } else if (collator.compare(flags, "-srcprovidername") == 0) { - if (++i == args.length) errorNeedArgument(flags); - srcProviderName = args[i]; + srcProviderName = args[++i]; } else if (collator.compare(flags, "-providername") == 0 || collator.compare(flags, "-destprovidername") == 0) { - if (++i == args.length) errorNeedArgument(flags); - providerName = args[i]; + providerName = args[++i]; } else if (collator.compare(flags, "-providerpath") == 0) { - if (++i == args.length) errorNeedArgument(flags); - pathlist = args[i]; + pathlist = args[++i]; } else if (collator.compare(flags, "-keypass") == 0) { - if (++i == args.length) errorNeedArgument(flags); - keyPass = args[i].toCharArray(); + keyPass = getPass(modifier, args[++i]); passwords.add(keyPass); } else if (collator.compare(flags, "-new") == 0) { - if (++i == args.length) errorNeedArgument(flags); - newPass = args[i].toCharArray(); + newPass = getPass(modifier, args[++i]); passwords.add(newPass); } else if (collator.compare(flags, "-destkeypass") == 0) { - if (++i == args.length) errorNeedArgument(flags); - destKeyPass = args[i].toCharArray(); + destKeyPass = getPass(modifier, args[++i]); passwords.add(destKeyPass); } else if (collator.compare(flags, "-alias") == 0 || collator.compare(flags, "-srcalias") == 0) { - if (++i == args.length) errorNeedArgument(flags); - alias = args[i]; + alias = args[++i]; } else if (collator.compare(flags, "-dest") == 0 || collator.compare(flags, "-destalias") == 0) { - if (++i == args.length) errorNeedArgument(flags); - dest = args[i]; + dest = args[++i]; } else if (collator.compare(flags, "-dname") == 0) { - if (++i == args.length) errorNeedArgument(flags); - dname = args[i]; + dname = args[++i]; } else if (collator.compare(flags, "-keysize") == 0) { - if (++i == args.length) errorNeedArgument(flags); - keysize = Integer.parseInt(args[i]); + keysize = Integer.parseInt(args[++i]); } else if (collator.compare(flags, "-keyalg") == 0) { - if (++i == args.length) errorNeedArgument(flags); - keyAlgName = args[i]; + keyAlgName = args[++i]; } else if (collator.compare(flags, "-sigalg") == 0) { - if (++i == args.length) errorNeedArgument(flags); - sigAlgName = args[i]; + sigAlgName = args[++i]; } else if (collator.compare(flags, "-startdate") == 0) { - if (++i == args.length) errorNeedArgument(flags); - startDate = args[i]; + startDate = args[++i]; } else if (collator.compare(flags, "-validity") == 0) { - if (++i == args.length) errorNeedArgument(flags); - validity = Long.parseLong(args[i]); + validity = Long.parseLong(args[++i]); } else if (collator.compare(flags, "-ext") == 0) { - if (++i == args.length) errorNeedArgument(flags); - v3ext.add(args[i]); + v3ext.add(args[++i]); } else if (collator.compare(flags, "-file") == 0) { - if (++i == args.length) errorNeedArgument(flags); - filename = args[i]; + filename = args[++i]; } else if (collator.compare(flags, "-infile") == 0) { - if (++i == args.length) errorNeedArgument(flags); - infilename = args[i]; + infilename = args[++i]; } else if (collator.compare(flags, "-outfile") == 0) { - if (++i == args.length) errorNeedArgument(flags); - outfilename = args[i]; + outfilename = args[++i]; } else if (collator.compare(flags, "-sslserver") == 0) { - if (++i == args.length) errorNeedArgument(flags); - sslserver = args[i]; + sslserver = args[++i]; } else if (collator.compare(flags, "-srckeystore") == 0) { - if (++i == args.length) errorNeedArgument(flags); - srcksfname = args[i]; + srcksfname = args[++i]; } else if ((collator.compare(flags, "-provider") == 0) || (collator.compare(flags, "-providerclass") == 0)) { - if (++i == args.length) errorNeedArgument(flags); if (providers == null) { providers = new HashSet> (3); } - String providerClass = args[i]; + String providerClass = args[++i]; String providerArg = null; if (args.length > (i+1)) { @@ -418,19 +500,24 @@ public final class KeyTool { } if (i is not a legal command")); - Object[] source = {args[i]}; - throw new RuntimeException(form.format(source)); + System.err.println(rb.getString("Illegal option: ") + args[i]); + tinyHelp(); } - if (command == -1) { - System.err.println(rb.getString("Usage error: no command provided")); - tinyHelp(); + if (command == null) { + if (help) { + usage(); + } else { + System.err.println(rb.getString("Usage error: no command provided")); + tinyHelp(); + } + } else if (help) { + usage(); + command = null; } } - boolean isKeyStoreRelated(int cmd) { + boolean isKeyStoreRelated(Command cmd) { return cmd != PRINTCERT && cmd != PRINTCERTREQ; } @@ -2600,7 +2687,7 @@ public final class KeyTool { do { if (maxRetry-- < 0) { throw new RuntimeException(rb.getString( - "Too may retries, program terminated")); + "Too many retries, program terminated")); } commonName = inputString(in, rb.getString("What is your first and last name?"), @@ -3086,7 +3173,7 @@ public final class KeyTool { do { if (maxRetry-- < 0) { throw new RuntimeException(rb.getString( - "Too may retries, program terminated")); + "Too many retries, program terminated")); } System.err.print(prompt); System.err.flush(); @@ -3258,7 +3345,8 @@ public final class KeyTool { int nmatch = 0; for (int i = 0; i] [-sigalg ]")); - System.err.println(rb.getString - ("\t [-dname ]")); - System.err.println(rb.getString - ("\t [-file ] [-keypass ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-changealias [-v] [-protected] -alias -destalias ")); - System.err.println(rb.getString - ("\t [-keypass ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-delete [-v] [-protected] -alias ")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-exportcert [-v] [-rfc] [-protected]")); - System.err.println(rb.getString - ("\t [-alias ] [-file ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-genkeypair [-v] [-protected]")); - System.err.println(rb.getString - ("\t [-alias ]")); - System.err.println(rb.getString - ("\t [-keyalg ] [-keysize ]")); - System.err.println(rb.getString - ("\t [-sigalg ] [-dname ]")); - System.err.println(rb.getString - ("\t [-startdate ]")); - System.err.println(rb.getString - ("\t [-ext [:critical][=]]...")); - System.err.println(rb.getString - ("\t [-validity ] [-keypass ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-gencert [-v] [-rfc] [-protected]")); - System.err.println(rb.getString - ("\t [-infile ] [-outfile ]")); - System.err.println(rb.getString - ("\t [-alias ]")); - System.err.println(rb.getString - ("\t [-dname ]")); - System.err.println(rb.getString - ("\t [-sigalg ]")); - System.err.println(rb.getString - ("\t [-startdate ]")); - System.err.println(rb.getString - ("\t [-ext [:critical][=]]...")); - System.err.println(rb.getString - ("\t [-validity ] [-keypass ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-genseckey [-v] [-protected]")); - System.err.println(rb.getString - ("\t [-alias ] [-keypass ]")); - System.err.println(rb.getString - ("\t [-keyalg ] [-keysize ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString("-help")); - System.err.println(); - - System.err.println(rb.getString - ("-importcert [-v] [-noprompt] [-trustcacerts] [-protected]")); - System.err.println(rb.getString - ("\t [-alias ]")); - System.err.println(rb.getString - ("\t [-file ] [-keypass ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-importkeystore [-v] ")); - System.err.println(rb.getString - ("\t [-srckeystore ] [-destkeystore ]")); - System.err.println(rb.getString - ("\t [-srcstoretype ] [-deststoretype ]")); - System.err.println(rb.getString - ("\t [-srcstorepass ] [-deststorepass ]")); - System.err.println(rb.getString - ("\t [-srcprotected] [-destprotected]")); - System.err.println(rb.getString - ("\t [-srcprovidername ]\n\t [-destprovidername ]")); - System.err.println(rb.getString - ("\t [-srcalias [-destalias ]")); - System.err.println(rb.getString - ("\t [-srckeypass ] [-destkeypass ]]")); - System.err.println(rb.getString - ("\t [-noprompt]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-keypasswd [-v] [-alias ]")); - System.err.println(rb.getString - ("\t [-keypass ] [-new ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-list [-v | -rfc] [-protected]")); - System.err.println(rb.getString - ("\t [-alias ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); - System.err.println(); - - System.err.println(rb.getString - ("-printcert [-v] [-rfc] [-file | -sslserver ]")); - System.err.println(); - - System.err.println(rb.getString - ("-printcertreq [-v] [-file ]")); - System.err.println(); + if (command != null) { + System.err.println("keytool " + command + + rb.getString(" [OPTION]...")); + System.err.println(); + System.err.println(rb.getString(command.description)); + System.err.println(); + System.err.println(rb.getString("Options:")); + System.err.println(); - System.err.println(rb.getString - ("-storepasswd [-v] [-new ]")); - System.err.println(rb.getString - ("\t [-keystore ] [-storepass ]")); - System.err.println(rb.getString - ("\t [-storetype ] [-providername ]")); - System.err.println(rb.getString - ("\t [-providerclass [-providerarg ]] ...")); - System.err.println(rb.getString - ("\t [-providerpath ]")); + // Left and right sides of the options list + String[] left = new String[command.options.length]; + String[] right = new String[command.options.length]; + + // Check if there's an unknown option + boolean found = false; + + // Length of left side of options list + int lenLeft = 0; + for (int j=0; j lenLeft) { + lenLeft = left[j].length(); + } + right[j] = rb.getString(opt[2]); + found = true; + break; + } + } + if (!found) { + throw new RuntimeException("ERROR: CANNOT FIND " + command.options[j]); + } + } + for (int j=0; j needs an argument.")).format(source)); tinyHelp(); } + + private char[] getPass(String modifier, String arg) { + char[] output = getPassWithModifier(modifier, arg); + if (output != null) return output; + tinyHelp(); + return null; // Useless, tinyHelp() already exits. + } + + // This method also used by JarSigner + public static char[] getPassWithModifier(String modifier, String arg) { + if (modifier == null) { + return arg.toCharArray(); + } else if (collator.compare(modifier, "env") == 0) { + String value = System.getenv(arg); + if (value == null) { + System.err.println(rb.getString( + "Cannot find environment variable: ") + arg); + return null; + } else { + return value.toCharArray(); + } + } else if (collator.compare(modifier, "file") == 0) { + try { + URL url = null; + try { + url = new URL(arg); + } catch (java.net.MalformedURLException mue) { + File f = new File(arg); + if (f.exists()) { + url = f.toURI().toURL(); + } else { + System.err.println(rb.getString( + "Cannot find file: ") + arg); + return null; + } + } + BufferedReader br = new BufferedReader(new InputStreamReader( + url.openStream())); + String value = br.readLine(); + br.close(); + if (value == null) { + return new char[0]; + } else { + return value.toCharArray(); + } + } catch (IOException ioe) { + System.err.println(ioe); + return null; + } + } else { + System.err.println(rb.getString("Unknown password type: ") + + modifier); + return null; + } + } } // This class is exactly the same as com.sun.tools.javac.util.Pair, @@ -3960,3 +3945,4 @@ class Pair { return new Pair(a,b); } } + diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasPath.java b/src/share/classes/sun/security/util/PermissionFactory.java similarity index 79% rename from make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasPath.java rename to src/share/classes/sun/security/util/PermissionFactory.java index f5459e1dcdbd7c72edab94f0535ea8817c08c6e7..10356051fa39fda1c56f7112c8b4171c62ac53ed 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/swingx/designer/utils/HasPath.java +++ b/src/share/classes/sun/security/util/PermissionFactory.java @@ -1,5 +1,5 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,13 +22,15 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.swingx.designer.utils; + +package sun.security.util; + +import java.security.Permission; /** - * HasPath - interface for model nodes that can provide there path in the tree - * - * @author Created by Jasper Potts (Jul 2, 2007) + * A factory object that creates Permission objects. */ -public interface HasPath { - public String getPath(); + +public interface PermissionFactory { + T newPermission(String name); } diff --git a/src/share/classes/sun/security/util/Resources.java b/src/share/classes/sun/security/util/Resources.java index 9b3931b68a1cc65e8db05783672cb47dfbdba27c..686e91469a87812ed9aba456a1d64c9161840b5a 100644 --- a/src/share/classes/sun/security/util/Resources.java +++ b/src/share/classes/sun/security/util/Resources.java @@ -46,18 +46,149 @@ public class Resources extends java.util.ListResourceBundle { {"*******************************************\n\n", "*******************************************\n\n"}, - // keytool + // keytool: Help part + {" [OPTION]...", " [OPTION]..."}, + {"Options:", "Options:"}, + {"Use \"keytool -help\" for all available commands", + "Use \"keytool -help\" for all available commands"}, + {"Key and Certificate Management Tool", + "Key and Certificate Management Tool"}, + {"Commands:", "Commands:"}, + {"Use \"keytool -command_name -help\" for usage of command_name", + "Use \"keytool -command_name -help\" for usage of command_name"}, + // keytool: help: commands + {"Generates a certificate request", + "Generates a certificate request"}, //-certreq + {"Changes an entry's alias", + "Changes an entry's alias"}, //-changealias + {"Deletes an entry", + "Deletes an entry"}, //-delete + {"Exports certificate", + "Exports certificate"}, //-exportcert + {"Generates a key pair", + "Generates a key pair"}, //-genkeypair + {"Generates a secret key", + "Generates a secret key"}, //-genseckey + {"Generates certificate from a certificate request", + "Generates certificate from a certificate request"}, //-gencert + {"Imports entries from a JDK 1.1.x-style identity database", + "Imports entries from a JDK 1.1.x-style identity database"}, //-identitydb + {"Imports a certificate or a certificate chain", + "Imports a certificate or a certificate chain"}, //-importcert + {"Imports one or all entries from another keystore", + "Imports one or all entries from another keystore"}, //-importkeystore + {"Clones a key entry", + "Clones a key entry"}, //-keyclone + {"Changes the key password of an entry", + "Changes the key password of an entry"}, //-keypasswd + {"Lists entries in a keystore", + "Lists entries in a keystore"}, //-list + {"Prints the content of a certificate", + "Prints the content of a certificate"}, //-printcert + {"Prints the content of a certificate request", + "Prints the content of a certificate request"}, //-printcertreq + {"Generates a self-signed certificate", + "Generates a self-signed certificate"}, //-selfcert + {"Changes the store password of a keystore", + "Changes the store password of a keystore"}, //-storepasswd + // keytool: help: options + {"alias name of the entry to process", + "alias name of the entry to process"}, //-alias + {"destination alias", + "destination alias"}, //-destalias + {"destination key password", + "destination key password"}, //-destkeypass + {"destination keystore name", + "destination keystore name"}, //-destkeystore + {"destination keystore password protected", + "destination keystore password protected"}, //-destprotected + {"destination keystore provider name", + "destination keystore provider name"}, //-destprovidername + {"destination keystore password", + "destination keystore password"}, //-deststorepass + {"destination keystore type", + "destination keystore type"}, //-deststoretype + {"distinguished name", + "distinguished name"}, //-dname + {"X.509 extension", + "X.509 extension"}, //-ext + {"output file name", + "output file name"}, //-file + {"input file name", + "input file name"}, //-file + {"input file name", + "input file name"}, //-infile + {"key algorithm name", + "key algorithm name"}, //-keyalg + {"key password", + "key password"}, //-keypass + {"key bit size", + "key bit size"}, //-keysize + {"keystore name", + "keystore name"}, //-keystore + {"new password", + "new password"}, //-new + {"do not prompt", + "do not prompt"}, //-noprompt + {"output file name", + "output file name"}, //-outfile + {"password through protected mechanism", + "password through protected mechanism"}, //-protected + {"provider argument", + "provider argument"}, //-providerarg + {"provider class name", + "provider class name"}, //-providerclass + {"provider name", + "provider name"}, //-providername + {"provider classpath", + "provider classpath"}, //-providerpath + {"output in RFC style", + "output in RFC style"}, //-rfc + {"signature algorithm name", + "signature algorithm name"}, //-sigalg + {"source alias", + "source alias"}, //-srcalias + {"source keystore password", + "source keystore password"}, //-srckeypass + {"source keystore name", + "source keystore name"}, //-srckeystore + {"source keystore password protected", + "source keystore password protected"}, //-srcprotected + {"source keystore provider name", + "source keystore provider name"}, //-srcprovidername + {"source keystore password", + "source keystore password"}, //-srcstorepass + {"source keystore type", + "source keystore type"}, //-srcstoretype + {"SSL server host and port", + "SSL server host and port"}, //-sslserver + {"certificate validity start date/time", + "certificate validity start date/time"}, //-startdate + {"keystore password", + "keystore password"}, //-storepass + {"keystore type", + "keystore type"}, //-storetype + {"trust certificates from cacerts", + "trust certificates from cacerts"}, //-trustcacerts + {"verbose output", + "verbose output"}, //-v + {"validity number of days", + "validity number of days"}, //-validity + // keytool: Running part {"keytool error: ", "keytool error: "}, {"Illegal option: ", "Illegal option: "}, {"Illegal value: ", "Illegal value: "}, - {"Try keytool -help","Try keytool -help"}, + {"Unknown password type: ", "Unknown password type: "}, + {"Cannot find environment variable: ", + "Cannot find environment variable: "}, + {"Cannot find file: ", "Cannot find file: "}, {"Command option needs an argument.", "Command option {0} needs an argument."}, {"Warning: Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified value.", "Warning: Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified {0} value."}, {"-keystore must be NONE if -storetype is {0}", "-keystore must be NONE if -storetype is {0}"}, - {"Too may retries, program terminated", - "Too may retries, program terminated"}, + {"Too many retries, program terminated", + "Too many retries, program terminated"}, {"-storepasswd and -keypasswd commands not supported if -storetype is {0}", "-storepasswd and -keypasswd commands not supported if -storetype is {0}"}, {"-keypasswd commands not supported if -storetype is PKCS12", @@ -77,7 +208,6 @@ public class Resources extends java.util.ListResourceBundle { "Validity must be greater than zero"}, {"provName not a provider", "{0} not a provider"}, {"Usage error: no command provided", "Usage error: no command provided"}, - {"Usage error, is not a legal command", "Usage error, {0} is not a legal command"}, {"Source keystore file exists, but is empty: ", "Source keystore file exists, but is empty: "}, {"Please specify -srckeystore", "Please specify -srckeystore"}, {"Must not specify both -v and -rfc with 'list' command", @@ -279,7 +409,6 @@ public class Resources extends java.util.ListResourceBundle { "Secret Key not generated, alias <{0}> already exists"}, {"Please provide -keysize for secret key generation", "Please provide -keysize for secret key generation"}, - {"keytool usage:\n", "keytool usage:\n"}, {"Extensions: ", "Extensions: "}, {"(Empty value)", "(Empty value)"}, @@ -297,139 +426,6 @@ public class Resources extends java.util.ListResourceBundle { {"Odd number of hex digits found: ", "Odd number of hex digits found: "}, {"command {0} is ambiguous:", "command {0} is ambiguous:"}, - {"-certreq [-v] [-protected]", - "-certreq [-v] [-protected]"}, - {"\t [-alias ] [-sigalg ]", - "\t [-alias ] [-sigalg ]"}, - {"\t [-dname ]", "\t [-dname ]"}, - {"\t [-file ] [-keypass ]", - "\t [-file ] [-keypass ]"}, - {"\t [-keystore ] [-storepass ]", - "\t [-keystore ] [-storepass ]"}, - {"\t [-storetype ] [-providername ]", - "\t [-storetype ] [-providername ]"}, - {"\t [-providerclass [-providerarg ]] ...", - "\t [-providerclass [-providerarg ]] ..."}, - {"\t [-providerpath ]", - "\t [-providerpath ]"}, - {"-delete [-v] [-protected] -alias ", - "-delete [-v] [-protected] -alias "}, - /** rest is same as -certreq starting from -keystore **/ - - //{"-export [-v] [-rfc] [-protected]", - // "-export [-v] [-rfc] [-protected]"}, - {"-exportcert [-v] [-rfc] [-protected]", - "-exportcert [-v] [-rfc] [-protected]"}, - {"\t [-alias ] [-file ]", - "\t [-alias ] [-file ]"}, - /** rest is same as -certreq starting from -keystore **/ - - //{"-genkey [-v] [-protected]", - // "-genkey [-v] [-protected]"}, - {"-genkeypair [-v] [-protected]", - "-genkeypair [-v] [-protected]"}, - {"\t [-alias ]", "\t [-alias ]"}, - {"\t [-keyalg ] [-keysize ]", - "\t [-keyalg ] [-keysize ]"}, - {"\t [-sigalg ] [-dname ]", - "\t [-sigalg ] [-dname ]"}, - {"\t [-startdate ]", - "\t [-startdate ]"}, - {"\t [-validity ] [-keypass ]", - "\t [-validity ] [-keypass ]"}, - /** rest is same as -certreq starting from -keystore **/ - {"-gencert [-v] [-rfc] [-protected]", - "-gencert [-v] [-rfc] [-protected]"}, - {"\t [-infile ] [-outfile ]", - "\t [-infile ] [-outfile ]"}, - {"\t [-sigalg ]", - "\t [-sigalg ]"}, - {"\t [-ext [:critical][=]]...", - "\t [-ext [:critical][=]]..."}, - - {"-genseckey [-v] [-protected]", - "-genseckey [-v] [-protected]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-help", "-help"}, - //{"-identitydb [-v] [-protected]", - // "-identitydb [-v] [-protected]"}, - //{"\t [-file ]", "\t [-file ]"}, - /** rest is same as -certreq starting from -keystore **/ - - //{"-import [-v] [-noprompt] [-trustcacerts] [-protected]", - // "-import [-v] [-noprompt] [-trustcacerts] [-protected]"}, - {"-importcert [-v] [-noprompt] [-trustcacerts] [-protected]", - "-importcert [-v] [-noprompt] [-trustcacerts] [-protected]"}, - {"\t [-alias ]", "\t [-alias ]"}, - {"\t [-alias ] [-keypass ]", - "\t [-alias ] [-keypass ]"}, - {"\t [-file ] [-keypass ]", - "\t [-file ] [-keypass ]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-importkeystore [-v] ", - "-importkeystore [-v] "}, - {"\t [-srckeystore ] [-destkeystore ]", - "\t [-srckeystore ] [-destkeystore ]"}, - {"\t [-srcstoretype ] [-deststoretype ]", - "\t [-srcstoretype ] [-deststoretype ]"}, - {"\t [-srcprotected] [-destprotected]", - "\t [-srcprotected] [-destprotected]"}, - {"\t [-srcstorepass ] [-deststorepass ]", - "\t [-srcstorepass ] [-deststorepass ]"}, - {"\t [-srcprovidername ]\n\t [-destprovidername ]", // line too long, split to 2 - "\t [-srcprovidername ]\n\t [-destprovidername ]"}, - {"\t [-srcalias [-destalias ]", - "\t [-srcalias [-destalias ]"}, - {"\t [-srckeypass ] [-destkeypass ]]", - "\t [-srckeypass ] [-destkeypass ]]"}, - {"\t [-noprompt]", "\t [-noprompt]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-changealias [-v] [-protected] -alias -destalias ", - "-changealias [-v] [-protected] -alias -destalias "}, - {"\t [-keypass ]", "\t [-keypass ]"}, - - //{"-keyclone [-v] [-protected]", - // "-keyclone [-v] [-protected]"}, - //{"\t [-alias ] -dest ", - // "\t [-alias ] -dest "}, - //{"\t [-keypass ] [-new ]", - // "\t [-keypass ] [-new ]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-keypasswd [-v] [-alias ]", - "-keypasswd [-v] [-alias ]"}, - {"\t [-keypass ] [-new ]", - "\t [-keypass ] [-new ]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-list [-v | -rfc] [-protected]", - "-list [-v | -rfc] [-protected]"}, - {"\t [-alias ]", "\t [-alias ]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-printcert [-v] [-rfc] [-file | -sslserver ]", - "-printcert [-v] [-rfc] [-file | -sslserver ]"}, - {"-printcertreq [-v] [-file ]", - "-printcertreq [-v] [-file ]"}, - {"No certificate from the SSL server", - "No certificate from the SSL server"}, - - //{"-selfcert [-v] [-protected]", - // "-selfcert [-v] [-protected]"}, - {"\t [-alias ]", "\t [-alias ]"}, - //{"\t [-dname ] [-validity ]", - // "\t [-dname ] [-validity ]"}, - //{"\t [-keypass ] [-sigalg ]", - // "\t [-keypass ] [-sigalg ]"}, - /** rest is same as -certreq starting from -keystore **/ - - {"-storepasswd [-v] [-new ]", - "-storepasswd [-v] [-new ]"}, - /** rest is same as -certreq starting from -keystore **/ - // policytool {"Warning: A public key for alias 'signers[i]' does not exist. Make sure a KeyStore is properly configured.", "Warning: A public key for alias {0} does not exist. Make sure a KeyStore is properly configured."}, @@ -679,3 +675,4 @@ public class Resources extends java.util.ListResourceBundle { return contents; } } + diff --git a/src/share/classes/sun/security/util/SecurityConstants.java b/src/share/classes/sun/security/util/SecurityConstants.java index 43e2cd3d792de6ed9be1fdb7c21f3addda83fc12..89c6fd7fdea445fa4dea06c28114e18cf539c3fd 100644 --- a/src/share/classes/sun/security/util/SecurityConstants.java +++ b/src/share/classes/sun/security/util/SecurityConstants.java @@ -25,12 +25,12 @@ package sun.security.util; -import java.io.FilePermission; -import java.awt.AWTPermission; -import java.util.PropertyPermission; -import java.lang.RuntimePermission; import java.net.SocketPermission; import java.net.NetPermission; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.security.Permission; +import java.security.BasicPermission; import java.security.SecurityPermission; import java.security.AllPermission; import javax.security.auth.AuthPermission; @@ -71,45 +71,118 @@ public final class SecurityConstants { // sun.security.provider.PolicyFile public static final AllPermission ALL_PERMISSION = new AllPermission(); - // java.lang.SecurityManager - public static final AWTPermission TOPLEVEL_WINDOW_PERMISSION = - new AWTPermission("showWindowWithoutWarningBanner"); - - // java.lang.SecurityManager - public static final AWTPermission ACCESS_CLIPBOARD_PERMISSION = - new AWTPermission("accessClipboard"); - - // java.lang.SecurityManager - public static final AWTPermission CHECK_AWT_EVENTQUEUE_PERMISSION = - new AWTPermission("accessEventQueue"); - - // java.awt.Dialog - public static final AWTPermission TOOLKIT_MODALITY_PERMISSION = - new AWTPermission("toolkitModality"); - - // java.awt.Robot - public static final AWTPermission READ_DISPLAY_PIXELS_PERMISSION = - new AWTPermission("readDisplayPixels"); - - // java.awt.Robot - public static final AWTPermission CREATE_ROBOT_PERMISSION = - new AWTPermission("createRobot"); - - // java.awt.MouseInfo - public static final AWTPermission WATCH_MOUSE_PERMISSION = - new AWTPermission("watchMousePointer"); - - // java.awt.Window - public static final AWTPermission SET_WINDOW_ALWAYS_ON_TOP_PERMISSION = - new AWTPermission("setWindowAlwaysOnTop"); + /** + * Permission type used when AWT is not present. + */ + private static class FakeAWTPermission extends BasicPermission { + private static final long serialVersionUID = -1L; + public FakeAWTPermission(String name) { + super(name); + } + public String toString() { + return "(\"java.awt.AWTPermission\" \"" + getName() + "\")"; + } + } - // java.awt.Toolkit - public static final AWTPermission ALL_AWT_EVENTS_PERMISSION = - new AWTPermission("listenToAllAWTEvents"); + /** + * Permission factory used when AWT is not present. + */ + private static class FakeAWTPermissionFactory + implements PermissionFactory + { + @Override + public FakeAWTPermission newPermission(String name) { + return new FakeAWTPermission(name); + } + } - // java.awt.SystemTray - public static final AWTPermission ACCESS_SYSTEM_TRAY_PERMISSION = - new AWTPermission("accessSystemTray"); + /** + * AWT Permissions used in the JDK. + */ + public static class AWT { + private AWT() { } + + /** + * The class name of the factory to create java.awt.AWTPermission objects. + */ + private static final String AWTFactory = "sun.awt.AWTPermissionFactory"; + + /** + * The PermissionFactory to create AWT permissions (or fake permissions + * if AWT is not present). + */ + private static final PermissionFactory factory = permissionFactory(); + + private static PermissionFactory permissionFactory() { + Class c = AccessController + .doPrivileged(new PrivilegedAction>() { + public Class run() { + try { + return Class.forName(AWTFactory, true, null); + } catch (ClassNotFoundException e) { + // not available + return null; + } + }}); + if (c != null) { + // AWT present + try { + return (PermissionFactory)c.newInstance(); + } catch (InstantiationException x) { + throw new InternalError(x.getMessage()); + } catch (IllegalAccessException x) { + throw new InternalError(x.getMessage()); + } + } else { + // AWT not present + return new FakeAWTPermissionFactory(); + } + } + + private static Permission newAWTPermission(String name) { + return factory.newPermission(name); + } + + // java.lang.SecurityManager + public static final Permission TOPLEVEL_WINDOW_PERMISSION = + newAWTPermission("showWindowWithoutWarningBanner"); + + // java.lang.SecurityManager + public static final Permission ACCESS_CLIPBOARD_PERMISSION = + newAWTPermission("accessClipboard"); + + // java.lang.SecurityManager + public static final Permission CHECK_AWT_EVENTQUEUE_PERMISSION = + newAWTPermission("accessEventQueue"); + + // java.awt.Dialog + public static final Permission TOOLKIT_MODALITY_PERMISSION = + newAWTPermission("toolkitModality"); + + // java.awt.Robot + public static final Permission READ_DISPLAY_PIXELS_PERMISSION = + newAWTPermission("readDisplayPixels"); + + // java.awt.Robot + public static final Permission CREATE_ROBOT_PERMISSION = + newAWTPermission("createRobot"); + + // java.awt.MouseInfo + public static final Permission WATCH_MOUSE_PERMISSION = + newAWTPermission("watchMousePointer"); + + // java.awt.Window + public static final Permission SET_WINDOW_ALWAYS_ON_TOP_PERMISSION = + newAWTPermission("setWindowAlwaysOnTop"); + + // java.awt.Toolkit + public static final Permission ALL_AWT_EVENTS_PERMISSION = + newAWTPermission("listenToAllAWTEvents"); + + // java.awt.SystemTray + public static final Permission ACCESS_SYSTEM_TRAY_PERMISSION = + newAWTPermission("accessSystemTray"); + } // java.net.URL public static final NetPermission SPECIFY_HANDLER_PERMISSION = diff --git a/src/share/classes/sun/security/x509/AccessDescription.java b/src/share/classes/sun/security/x509/AccessDescription.java index 1544ea953bec5864f786be79daf0459cd7614995..0911018110fe23a243a6e4b067c9bc4899c1848e 100644 --- a/src/share/classes/sun/security/x509/AccessDescription.java +++ b/src/share/classes/sun/security/x509/AccessDescription.java @@ -113,7 +113,7 @@ public final class AccessDescription { } else { method = accessMethod.toString(); } - return ("accessMethod: " + method + + return ("\n accessMethod: " + method + "\n accessLocation: " + accessLocation.toString() + "\n"); } } diff --git a/src/share/classes/sun/swing/MenuItemLayoutHelper.java b/src/share/classes/sun/swing/MenuItemLayoutHelper.java index 1f0281e9be3a1ba34f8b27c18ebec3fca9fba2e1..02ce9abe9b10d8ba2f4fecad234907be9ff68206 100644 --- a/src/share/classes/sun/swing/MenuItemLayoutHelper.java +++ b/src/share/classes/sun/swing/MenuItemLayoutHelper.java @@ -84,7 +84,6 @@ public class MenuItemLayoutHelper { private int minTextOffset; private int leftTextExtraWidth; - private int rightTextExtraWidth; private Rectangle viewRect; @@ -157,7 +156,6 @@ public class MenuItemLayoutHelper { private void calcExtraWidths() { leftTextExtraWidth = getLeftExtraWidth(text); - rightTextExtraWidth = getRightExtraWidth(text); } private int getLeftExtraWidth(String str) { @@ -169,15 +167,6 @@ public class MenuItemLayoutHelper { } } - private int getRightExtraWidth(String str) { - int rsb = SwingUtilities2.getRightSideBearing(mi, fm, str); - if (rsb > 0) { - return rsb; - } else { - return 0; - } - } - private void setOriginalWidths() { iconSize.origWidth = iconSize.width; textSize.origWidth = textSize.width; @@ -313,7 +302,7 @@ public class MenuItemLayoutHelper { verticalAlignment, horizontalAlignment, verticalTextPosition, horizontalTextPosition, viewRect, iconRect, textRect, gap); - textRect.width += leftTextExtraWidth + rightTextExtraWidth; + textRect.width += leftTextExtraWidth; Rectangle labelRect = iconRect.union(textRect); labelSize.height = labelRect.height; labelSize.width = labelRect.width; @@ -1121,10 +1110,6 @@ public class MenuItemLayoutHelper { return leftTextExtraWidth; } - public int getRightTextExtraWidth() { - return rightTextExtraWidth; - } - /** * Returns false if the component is a JMenu and it is a top * level menu (on the menubar). diff --git a/src/share/classes/sun/swing/SwingUtilities2.java b/src/share/classes/sun/swing/SwingUtilities2.java index 3a4bc2141c3aec82f7aa78dd07103327964d229d..d4492e694818e350d19e1e8f20d16ed0357b6061 100644 --- a/src/share/classes/sun/swing/SwingUtilities2.java +++ b/src/share/classes/sun/swing/SwingUtilities2.java @@ -27,7 +27,6 @@ package sun.swing; import java.security.*; import java.lang.reflect.*; -import java.lang.ref.SoftReference; import java.awt.*; import static java.awt.RenderingHints.*; import java.awt.event.*; @@ -78,17 +77,23 @@ public class SwingUtilities2 { public static final Object LAF_STATE_KEY = new StringBuffer("LookAndFeel State"); - // Most of applications use 10 or less fonts simultaneously - private static final int STRONG_BEARING_CACHE_SIZE = 10; - // Strong cache for the left and right side bearings - // for STRONG_BEARING_CACHE_SIZE most recently used fonts. - private static BearingCacheEntry[] strongBearingCache = - new BearingCacheEntry[STRONG_BEARING_CACHE_SIZE]; - // Next index to insert an entry into the strong bearing cache - private static int strongBearingCacheNextIndex = 0; - // Soft cache for the left and right side bearings - private static Set> softBearingCache = - new HashSet>(); + // Maintain a cache of CACHE_SIZE fonts and the left side bearing + // of the characters falling into the range MIN_CHAR_INDEX to + // MAX_CHAR_INDEX. The values in fontCache are created as needed. + private static LSBCacheEntry[] fontCache; + // Windows defines 6 font desktop properties, we will therefore only + // cache the metrics for 6 fonts. + private static final int CACHE_SIZE = 6; + // nextIndex in fontCache to insert a font into. + private static int nextIndex; + // LSBCacheEntry used to search in fontCache to see if we already + // have an entry for a particular font + private static LSBCacheEntry searchKey; + + // getLeftSideBearing will consult all characters that fall in the + // range MIN_CHAR_INDEX to MAX_CHAR_INDEX. + private static final int MIN_CHAR_INDEX = (int)'W'; + private static final int MAX_CHAR_INDEX = (int)'W' + 1; public static final FontRenderContext DEFAULT_FRC = new FontRenderContext(null, false, false); @@ -183,6 +188,10 @@ public class SwingUtilities2 { private static final Object charsBufferLock = new Object(); private static char[] charsBuffer = new char[CHAR_BUFFER_SIZE]; + static { + fontCache = new LSBCacheEntry[CACHE_SIZE]; + } + /** * checks whether TextLayout is required to handle characters. * @@ -226,7 +235,9 @@ public class SwingUtilities2 { /** * Returns the left side bearing of the first character of string. The - * left side bearing is calculated from the passed in FontMetrics. + * left side bearing is calculated from the passed in + * FontMetrics. If the passed in String is less than one + * character, this will throw a StringIndexOutOfBoundsException exception. * * @param c JComponent that will display the string * @param fm FontMetrics used to measure the String width @@ -234,14 +245,11 @@ public class SwingUtilities2 { */ public static int getLeftSideBearing(JComponent c, FontMetrics fm, String string) { - if ((string == null) || (string.length() == 0)) { - return 0; - } return getLeftSideBearing(c, fm, string.charAt(0)); } /** - * Returns the left side bearing of the specified character. The + * Returns the left side bearing of the first character of string. The * left side bearing is calculated from the passed in FontMetrics. * * @param c JComponent that will display the string @@ -250,105 +258,37 @@ public class SwingUtilities2 { */ public static int getLeftSideBearing(JComponent c, FontMetrics fm, char firstChar) { - return getBearing(c, fm, firstChar, true); - } + int charIndex = (int) firstChar; + if (charIndex < MAX_CHAR_INDEX && charIndex >= MIN_CHAR_INDEX) { + byte[] lsbs = null; - /** - * Returns the right side bearing of the last character of string. The - * right side bearing is calculated from the passed in FontMetrics. - * - * @param c JComponent that will display the string - * @param fm FontMetrics used to measure the String width - * @param string String to get the right side bearing for. - */ - public static int getRightSideBearing(JComponent c, FontMetrics fm, - String string) { - if ((string == null) || (string.length() == 0)) { - return 0; - } - return getRightSideBearing(c, fm, string.charAt(string.length() - 1)); - } - - /** - * Returns the right side bearing of the specified character. The - * right side bearing is calculated from the passed in FontMetrics. - * - * @param c JComponent that will display the string - * @param fm FontMetrics used to measure the String width - * @param lastChar Character to get the right side bearing for. - */ - public static int getRightSideBearing(JComponent c, FontMetrics fm, - char lastChar) { - return getBearing(c, fm, lastChar, false); - } - - /* Calculates the left and right side bearing for a character. - * Strongly caches bearings for STRONG_BEARING_CACHE_SIZE - * most recently used Fonts and softly caches as many as GC allows. - */ - private static int getBearing(JComponent comp, FontMetrics fm, char c, - boolean isLeftBearing) { - if (fm == null) { - if (comp == null) { - return 0; - } else { - fm = comp.getFontMetrics(comp.getFont()); - } - } - synchronized (SwingUtilities2.class) { - BearingCacheEntry entry = null; - BearingCacheEntry searchKey = new BearingCacheEntry(fm); - // See if we already have an entry in the strong cache - for (BearingCacheEntry cacheEntry : strongBearingCache) { - if (searchKey.equals(cacheEntry)) { - entry = cacheEntry; - break; + FontRenderContext frc = getFontRenderContext(c, fm); + Font font = fm.getFont(); + synchronized (SwingUtilities2.class) { + LSBCacheEntry entry = null; + if (searchKey == null) { + searchKey = new LSBCacheEntry(frc, font); + } else { + searchKey.reset(frc, font); } - } - // See if we already have an entry in the soft cache - if (entry == null) { - Iterator> iter = - softBearingCache.iterator(); - while (iter.hasNext()) { - BearingCacheEntry cacheEntry = iter.next().get(); - if (cacheEntry == null) { - // Remove discarded soft reference from the cache - iter.remove(); - continue; - } + // See if we already have an entry for this pair + for (LSBCacheEntry cacheEntry : fontCache) { if (searchKey.equals(cacheEntry)) { entry = cacheEntry; - putEntryInStrongCache(entry); break; } } + if (entry == null) { + // No entry for this pair, add it. + entry = searchKey; + fontCache[nextIndex] = searchKey; + searchKey = null; + nextIndex = (nextIndex + 1) % CACHE_SIZE; + } + return entry.getLeftSideBearing(firstChar); } - if (entry == null) { - // No entry, add it - entry = searchKey; - cacheEntry(entry); - } - return (isLeftBearing) - ? entry.getLeftSideBearing(c) - : entry.getRightSideBearing(c); } - } - - private synchronized static void cacheEntry(BearingCacheEntry entry) { - // Move the oldest entry from the strong cache into the soft cache - BearingCacheEntry oldestEntry = - strongBearingCache[strongBearingCacheNextIndex]; - if (oldestEntry != null) { - softBearingCache.add(new SoftReference(oldestEntry)); - } - // Put entry in the strong cache - putEntryInStrongCache(entry); - } - - private synchronized static void putEntryInStrongCache(BearingCacheEntry entry) { - strongBearingCache[strongBearingCacheNextIndex] = entry; - strongBearingCacheNextIndex = (strongBearingCacheNextIndex + 1) - % STRONG_BEARING_CACHE_SIZE; + return 0; } /** @@ -1063,99 +1003,72 @@ public class SwingUtilities2 { } /** - * BearingCacheEntry is used to cache left and right character bearings - * for a particular Font and FontRenderContext. + * LSBCacheEntry is used to cache the left side bearing (lsb) for + * a particular Font and FontRenderContext. + * This only caches characters that fall in the range + * MIN_CHAR_INDEX to MAX_CHAR_INDEX. */ - private static class BearingCacheEntry { - private FontMetrics fontMetrics; + private static class LSBCacheEntry { + // Used to indicate a particular entry in lsb has not been set. + private static final byte UNSET = Byte.MAX_VALUE; + // Used in creating a GlyphVector to get the lsb + private static final char[] oneChar = new char[1]; + + private byte[] lsbCache; private Font font; private FontRenderContext frc; - private Map cache; - // Used for the creation of a GlyphVector - private static final char[] oneChar = new char[1]; - public BearingCacheEntry(FontMetrics fontMetrics) { - this.fontMetrics = fontMetrics; - this.font = fontMetrics.getFont(); - this.frc = fontMetrics.getFontRenderContext(); - this.cache = new HashMap(); - assert (font != null && frc != null); - } - public int getLeftSideBearing(char aChar) { - Short bearing = cache.get(aChar); - if (bearing == null) { - bearing = calcBearing(aChar); - cache.put(aChar, bearing); - } - return ((0xFF00 & bearing) >>> 8) - 127; + public LSBCacheEntry(FontRenderContext frc, Font font) { + lsbCache = new byte[MAX_CHAR_INDEX - MIN_CHAR_INDEX]; + reset(frc, font); + } - public int getRightSideBearing(char aChar) { - Short bearing = cache.get(aChar); - if (bearing == null) { - bearing = calcBearing(aChar); - cache.put(aChar, bearing); + public void reset(FontRenderContext frc, Font font) { + this.font = font; + this.frc = frc; + for (int counter = lsbCache.length - 1; counter >= 0; counter--) { + lsbCache[counter] = UNSET; } - return (0xFF & bearing) - 127; } - /* Calculates left and right side bearings for a character. - * Makes an assumption that bearing is a value between -127 and +127. - * Stores LSB and RSB as single two-byte number (short): - * LSB is the high byte, RSB is the low byte. - */ - private short calcBearing(char aChar) { - oneChar[0] = aChar; - GlyphVector gv = font.createGlyphVector(frc, oneChar); - Rectangle pixelBounds = gv.getGlyphPixelBounds(0, frc, 0f, 0f); - - // Get bearings - int lsb = pixelBounds.x; - int rsb = pixelBounds.width - fontMetrics.charWidth(aChar); - - /* HRGB/HBGR LCD glyph images will always have a pixel - * on the left and a pixel on the right - * used in colour fringe reduction. - * Text rendering positions this correctly but here - * we are using the glyph image to adjust that position - * so must account for it. - */ - if (lsb < 0) { - Object aaHint = frc.getAntiAliasingHint(); - if (aaHint == VALUE_TEXT_ANTIALIAS_LCD_HRGB || - aaHint == VALUE_TEXT_ANTIALIAS_LCD_HBGR) { - lsb++; - } - } - if (rsb > 0) { - Object aaHint = frc.getAntiAliasingHint(); - if (aaHint == VALUE_TEXT_ANTIALIAS_LCD_HRGB || - aaHint == VALUE_TEXT_ANTIALIAS_LCD_HBGR) { - rsb--; - } + public int getLeftSideBearing(char aChar) { + int index = aChar - MIN_CHAR_INDEX; + assert (index >= 0 && index < (MAX_CHAR_INDEX - MIN_CHAR_INDEX)); + byte lsb = lsbCache[index]; + if (lsb == UNSET) { + oneChar[0] = aChar; + GlyphVector gv = font.createGlyphVector(frc, oneChar); + lsb = (byte) gv.getGlyphPixelBounds(0, frc, 0f, 0f).x; + if (lsb < 0) { + /* HRGB/HBGR LCD glyph images will always have a pixel + * on the left used in colour fringe reduction. + * Text rendering positions this correctly but here + * we are using the glyph image to adjust that position + * so must account for it. + */ + Object aaHint = frc.getAntiAliasingHint(); + if (aaHint == VALUE_TEXT_ANTIALIAS_LCD_HRGB || + aaHint == VALUE_TEXT_ANTIALIAS_LCD_HBGR) { + lsb++; + } + } + lsbCache[index] = lsb; } + return lsb; - // Make sure that LSB and RSB are valid (see 6472972) - if (lsb < -127 || lsb > 127) { - lsb = 0; - } - if (rsb < -127 || rsb > 127) { - rsb = 0; - } - int bearing = ((lsb + 127) << 8) + (rsb + 127); - return (short)bearing; } public boolean equals(Object entry) { if (entry == this) { return true; } - if (!(entry instanceof BearingCacheEntry)) { + if (!(entry instanceof LSBCacheEntry)) { return false; } - BearingCacheEntry oEntry = (BearingCacheEntry)entry; + LSBCacheEntry oEntry = (LSBCacheEntry) entry; return (font.equals(oEntry.font) && frc.equals(oEntry.frc)); } @@ -1172,7 +1085,6 @@ public class SwingUtilities2 { } } - /* * here goes the fix for 4856343 [Problem with applet interaction * with system selection clipboard] @@ -1181,36 +1093,34 @@ public class SwingUtilities2 { * are to be performed */ - /** - * checks the security permissions for accessing system clipboard - * - * for untrusted context (see isTrustedContext) checks the - * permissions for the current event being handled - * - */ - public static boolean canAccessSystemClipboard() { - boolean canAccess = false; - if (!GraphicsEnvironment.isHeadless()) { - SecurityManager sm = System.getSecurityManager(); - if (sm == null) { - canAccess = true; - } else { - try { - sm.checkSystemClipboardAccess(); - canAccess = true; - } catch (SecurityException e) { - } - if (canAccess && ! isTrustedContext()) { - canAccess = canCurrentEventAccessSystemClipboard(true); - } - } - } - return canAccess; - } - + * checks the security permissions for accessing system clipboard + * + * for untrusted context (see isTrustedContext) checks the + * permissions for the current event being handled + * + */ + public static boolean canAccessSystemClipboard() { + boolean canAccess = false; + if (!GraphicsEnvironment.isHeadless()) { + SecurityManager sm = System.getSecurityManager(); + if (sm == null) { + canAccess = true; + } else { + try { + sm.checkSystemClipboardAccess(); + canAccess = true; + } catch (SecurityException e) { + } + if (canAccess && ! isTrustedContext()) { + canAccess = canCurrentEventAccessSystemClipboard(true); + } + } + } + return canAccess; + } /** - * Returns true if EventQueue.getCurrentEvent() has the permissions to + * Returns true if EventQueue.getCurrentEvent() has the permissions to * access the system clipboard */ public static boolean canCurrentEventAccessSystemClipboard() { @@ -1844,4 +1754,22 @@ public class SwingUtilities2 { boolean three) { return liesIn(rect, p, false, false, three); } + + /** + * Returns the {@code JViewport} instance for the {@code component} + * or {@code null}. + * + * @return the {@code JViewport} instance for the {@code component} + * or {@code null} + * @throws NullPointerException if {@code component} is {@code null} + */ + public static JViewport getViewport(Component component) { + do { + component = component.getParent(); + if (component instanceof JViewport) { + return (JViewport) component; + } + } while(component instanceof JLayer); + return null; + } } diff --git a/src/share/classes/sun/util/LocaleServiceProviderPool.java b/src/share/classes/sun/util/LocaleServiceProviderPool.java index 8fd21c9ce0a003ee4654a7edae946397a0575e51..9fcfe5b7abc0fc983b07a373ae1f9186fdcac551 100644 --- a/src/share/classes/sun/util/LocaleServiceProviderPool.java +++ b/src/share/classes/sun/util/LocaleServiceProviderPool.java @@ -39,8 +39,8 @@ import java.util.ServiceLoader; import java.util.ServiceConfigurationError; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.logging.Logger; import java.util.spi.LocaleServiceProvider; +import sun.util.logging.PlatformLogger; import sun.util.resources.LocaleData; import sun.util.resources.OpenListResourceBundle; @@ -122,10 +122,15 @@ public final class LocaleServiceProviderPool { } }); } catch (PrivilegedActionException e) { - Logger.getLogger("sun.util.LocaleServiceProviderPool").config(e.toString()); + config(e.toString()); } } + private static void config(String message) { + PlatformLogger logger = PlatformLogger.getLogger("sun.util.LocaleServiceProviderPool"); + logger.config(message); + } + /** * Lazy loaded set of available locales. * Loading all locales is a very long operation. @@ -337,7 +342,7 @@ public final class LocaleServiceProviderPool { if (providersObj != null) { return providersObj; } else if (isObjectProvider) { - Logger.getLogger("sun.util.LocaleServiceProviderPool").config( + config( "A locale sensitive service provider returned null for a localized objects, which should not happen. provider: " + lsp + " locale: " + requested); } } diff --git a/src/share/classes/sun/util/logging/PlatformLogger.java b/src/share/classes/sun/util/logging/PlatformLogger.java new file mode 100644 index 0000000000000000000000000000000000000000..e8523b81f8d6283907b2b8aaff5d133ad175b24f --- /dev/null +++ b/src/share/classes/sun/util/logging/PlatformLogger.java @@ -0,0 +1,635 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Sun designates this + * particular file as subject to the "Classpath" exception as provided + * by Sun in the LICENSE file that accompanied this code. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + + +package sun.util.logging; + +import java.lang.ref.WeakReference; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.security.AccessController; +import java.security.PrivilegedAction; +import java.text.MessageFormat; +import java.util.Date; +import java.util.HashMap; +import java.util.Map; +import sun.misc.JavaLangAccess; +import sun.misc.SharedSecrets; + +/** + * Platform logger provides an API for the JRE components to log + * messages. This enables the runtime components to eliminate the + * static dependency of the logging facility and also defers the + * java.util.logging initialization until it is enabled. + * In addition, the PlatformLogger API can be used if the logging + * module does not exist. + * + * If the logging facility is not enabled, the platform loggers + * will output log messages per the default logging configuration + * (see below). In this implementation, it does not log the + * the stack frame information issuing the log message. + * + * When the logging facility is enabled (at startup or runtime), + * the java.util.logging.Logger will be created for each platform + * logger and all log messages will be forwarded to the Logger + * to handle. + * + * Logging facility is "enabled" when one of the following + * conditions is met: + * 1) a system property "java.util.logging.config.class" or + * "java.util.logging.config.file" is set + * 2) java.util.logging.LogManager or java.util.logging.Logger + * is referenced that will trigger the logging initialization. + * + * Default logging configuration: + * global logging level = INFO + * handlers = java.util.logging.ConsoleHandler + * java.util.logging.ConsoleHandler.level = INFO + * java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + * + * Limitation: + * /lib/logging.properties is the system-wide logging + * configuration defined in the specification and read in the + * default case to configure any java.util.logging.Logger instances. + * Platform loggers will not detect if /lib/logging.properties + * is modified. In other words, unless the java.util.logging API + * is used at runtime or the logging system properties is set, + * the platform loggers will use the default setting described above. + * The platform loggers are designed for JDK developers use and + * this limitation can be workaround with setting + * -Djava.util.logging.config.file system property. + * + * @since 1.7 + */ +public class PlatformLogger { + // Same values as java.util.logging.Level for easy mapping + public static final int OFF = Integer.MAX_VALUE; + public static final int SEVERE = 1000; + public static final int WARNING = 900; + public static final int INFO = 800; + public static final int CONFIG = 700; + public static final int FINE = 500; + public static final int FINER = 400; + public static final int FINEST = 300; + public static final int ALL = Integer.MIN_VALUE; + + private static final int defaultLevel = INFO; + private static boolean loggingEnabled; + static { + loggingEnabled = AccessController.doPrivileged( + new PrivilegedAction() { + public Boolean run() { + String cname = System.getProperty("java.util.logging.config.class"); + String fname = System.getProperty("java.util.logging.config.file"); + return (cname != null || fname != null); + } + }); + } + + // Table of known loggers. Maps names to PlatformLoggers. + private static Map> loggers = + new HashMap>(); + + /** + * Returns a PlatformLogger of a given name. + */ + public static synchronized PlatformLogger getLogger(String name) { + PlatformLogger log = null; + WeakReference ref = loggers.get(name); + if (ref != null) { + log = ref.get(); + } + if (log == null) { + log = new PlatformLogger(name); + loggers.put(name, new WeakReference(log)); + } + return log; + } + + /** + * Initialize java.util.logging.Logger objects for all platform loggers. + * This method is called from LogManager.readPrimordialConfiguration(). + */ + public static synchronized void redirectPlatformLoggers() { + if (loggingEnabled || !JavaLogger.supported) return; + + loggingEnabled = true; + for (Map.Entry> entry : loggers.entrySet()) { + WeakReference ref = entry.getValue(); + PlatformLogger plog = ref.get(); + if (plog != null) { + plog.newJavaLogger(); + } + } + } + + /** + * Creates a new JavaLogger that the platform logger uses + */ + private void newJavaLogger() { + logger = new JavaLogger(logger.name, logger.effectiveLevel); + } + + // logger may be replaced with a JavaLogger object + // when the logging facility is enabled + private volatile LoggerProxy logger; + + private PlatformLogger(String name) { + if (loggingEnabled) { + this.logger = new JavaLogger(name); + } else { + this.logger = new LoggerProxy(name); + } + } + + /** + * A convenience method to test if the logger is turned off. + * (i.e. its level is OFF). + */ + public boolean isEnabled() { + return logger.isEnabled(); + } + + /** + * Gets the name for this platform logger. + */ + public String getName() { + return logger.name; + } + + /** + * Returns true if a message of the given level would actually + * be logged by this logger. + */ + public boolean isLoggable(int level) { + return logger.isLoggable(level); + } + + /** + * Gets the current log level. Returns 0 if the current effective level + * is not set (equivalent to Logger.getLevel() returns null). + */ + public int getLevel() { + return logger.getLevel(); + } + + /** + * Sets the log level. + */ + public void setLevel(int newLevel) { + logger.setLevel(newLevel); + } + + /** + * Logs a SEVERE message. + */ + public void severe(String msg) { + logger.doLog(SEVERE, msg); + } + + public void severe(String msg, Throwable t) { + logger.doLog(SEVERE, msg, t); + } + + public void severe(String msg, Object... params) { + logger.doLog(SEVERE, msg, params); + } + + /** + * Logs a WARNING message. + */ + public void warning(String msg) { + logger.doLog(WARNING, msg); + } + + public void warning(String msg, Throwable t) { + logger.doLog(WARNING, msg, t); + } + + public void warning(String msg, Object... params) { + logger.doLog(WARNING, msg, params); + } + + /** + * Logs an INFO message. + */ + public void info(String msg) { + logger.doLog(INFO, msg); + } + + public void info(String msg, Throwable t) { + logger.doLog(INFO, msg, t); + } + + public void info(String msg, Object... params) { + logger.doLog(INFO, msg, params); + } + + /** + * Logs a CONFIG message. + */ + public void config(String msg) { + logger.doLog(CONFIG, msg); + } + + public void config(String msg, Throwable t) { + logger.doLog(CONFIG, msg, t); + } + + public void config(String msg, Object... params) { + logger.doLog(CONFIG, msg, params); + } + + /** + * Logs a FINE message. + */ + public void fine(String msg) { + logger.doLog(FINE, msg); + } + + public void fine(String msg, Throwable t) { + logger.doLog(FINE, msg, t); + } + + public void fine(String msg, Object... params) { + logger.doLog(FINE, msg, params); + } + + /** + * Logs a FINER message. + */ + public void finer(String msg) { + logger.doLog(FINER, msg); + } + + public void finer(String msg, Throwable t) { + logger.doLog(FINER, msg, t); + } + + public void finer(String msg, Object... params) { + logger.doLog(FINER, msg, params); + } + + /** + * Logs a FINEST message. + */ + public void finest(String msg) { + logger.doLog(FINEST, msg); + } + + public void finest(String msg, Throwable t) { + logger.doLog(FINEST, msg, t); + } + + public void finest(String msg, Object... params) { + logger.doLog(FINEST, msg, params); + } + + /** + * Default platform logging support - output messages to + * System.err - equivalent to ConsoleHandler with SimpleFormatter. + */ + static class LoggerProxy { + private static final PrintStream defaultStream = System.err; + private static final String lineSeparator = AccessController.doPrivileged( + new PrivilegedAction() { + public String run() { + return System.getProperty("line.separator"); + } + }); + + final String name; + volatile int levelValue; + volatile int effectiveLevel = 0; // current effective level value + + LoggerProxy(String name) { + this(name, defaultLevel); + } + + LoggerProxy(String name, int level) { + this.name = name; + this.levelValue = level == 0 ? defaultLevel : level; + } + + boolean isEnabled() { + return levelValue != OFF; + } + + int getLevel() { + return effectiveLevel; + } + + void setLevel(int newLevel) { + levelValue = newLevel; + effectiveLevel = newLevel; + } + + void doLog(int level, String msg) { + if (level < levelValue || levelValue == OFF) { + return; + } + defaultStream.println(format(level, msg, null)); + } + + void doLog(int level, String msg, Throwable thrown) { + if (level < levelValue || levelValue == OFF) { + return; + } + defaultStream.println(format(level, msg, thrown)); + } + + void doLog(int level, String msg, Object... params) { + if (level < levelValue || levelValue == OFF) { + return; + } + String newMsg = formatMessage(msg, params); + defaultStream.println(format(level, newMsg, null)); + } + + public boolean isLoggable(int level) { + if (level < levelValue || levelValue == OFF) { + return false; + } + return true; + } + + private static final String format = "{0,date} {0,time}"; + + private Object args[] = new Object[1]; + private MessageFormat formatter; + private Date dat; + + // Copied from java.util.logging.Formatter.formatMessage + private String formatMessage(String format, Object... parameters) { + // Do the formatting. + try { + if (parameters == null || parameters.length == 0) { + // No parameters. Just return format string. + return format; + } + // Is it a java.text style format? + // Ideally we could match with + // Pattern.compile("\\{\\d").matcher(format).find()) + // However the cost is 14% higher, so we cheaply check for + // 1 of the first 4 parameters + if (format.indexOf("{0") >= 0 || format.indexOf("{1") >=0 || + format.indexOf("{2") >=0|| format.indexOf("{3") >=0) { + return java.text.MessageFormat.format(format, parameters); + } + return format; + } catch (Exception ex) { + // Formatting failed: use format string. + return format; + } + } + + private synchronized String format(int level, String msg, Throwable thrown) { + StringBuffer sb = new StringBuffer(); + // Minimize memory allocations here. + if (dat == null) { + dat = new Date(); + formatter = new MessageFormat(format); + } + dat.setTime(System.currentTimeMillis()); + args[0] = dat; + StringBuffer text = new StringBuffer(); + formatter.format(args, text, null); + sb.append(text); + sb.append(" "); + sb.append(getCallerInfo()); + sb.append(lineSeparator); + sb.append(PlatformLogger.getLevelName(level)); + sb.append(": "); + sb.append(msg); + if (thrown != null) { + try { + StringWriter sw = new StringWriter(); + PrintWriter pw = new PrintWriter(sw); + thrown.printStackTrace(pw); + pw.close(); + sb.append(sw.toString()); + } catch (Exception ex) { + throw new AssertionError(ex); + } + } + + return sb.toString(); + } + + // Returns the caller's class and method's name; best effort + // if cannot infer, return the logger's name. + private String getCallerInfo() { + String sourceClassName = null; + String sourceMethodName = null; + + JavaLangAccess access = SharedSecrets.getJavaLangAccess(); + Throwable throwable = new Throwable(); + int depth = access.getStackTraceDepth(throwable); + + String logClassName = "sun.util.logging.PlatformLogger"; + boolean lookingForLogger = true; + for (int ix = 0; ix < depth; ix++) { + // Calling getStackTraceElement directly prevents the VM + // from paying the cost of building the entire stack frame. + StackTraceElement frame = + access.getStackTraceElement(throwable, ix); + String cname = frame.getClassName(); + if (lookingForLogger) { + // Skip all frames until we have found the first logger frame. + if (cname.equals(logClassName)) { + lookingForLogger = false; + } + } else { + if (!cname.equals(logClassName)) { + // We've found the relevant frame. + sourceClassName = cname; + sourceMethodName = frame.getMethodName(); + break; + } + } + } + + if (sourceClassName != null) { + return sourceClassName + " " + sourceMethodName; + } else { + return name; + } + } + } + + /** + * JavaLogger forwards all the calls to its corresponding + * java.util.logging.Logger object. + */ + static class JavaLogger extends LoggerProxy { + private static final boolean supported; + private static final Class loggerClass; + private static final Class levelClass; + private static final Method getLoggerMethod; + private static final Method setLevelMethod; + private static final Method getLevelMethod; + private static final Method isLoggableMethod; + private static final Method logMethod; + private static final Method logThrowMethod; + private static final Method logParamsMethod; + private static final Map levelObjects = + new HashMap(); + + static { + loggerClass = getClass("java.util.logging.Logger"); + levelClass = getClass("java.util.logging.Level"); + getLoggerMethod = getMethod(loggerClass, "getLogger", String.class); + setLevelMethod = getMethod(loggerClass, "setLevel", levelClass); + getLevelMethod = getMethod(loggerClass, "getLevel"); + isLoggableMethod = getMethod(loggerClass, "isLoggable", levelClass); + logMethod = getMethod(loggerClass, "log", levelClass, String.class); + logThrowMethod = getMethod(loggerClass, "log", levelClass, String.class, Throwable.class); + logParamsMethod = getMethod(loggerClass, "log", levelClass, String.class, Object[].class); + supported = (loggerClass != null && levelClass != null && getLoggerMethod != null && + getLevelMethod != null && setLevelMethod != null && + logMethod != null && logThrowMethod != null && logParamsMethod != null); + if (supported) { + // initialize the map to Level objects + getLevelObjects(); + } + } + + private static Class getClass(String name) { + try { + return Class.forName(name, true, null); + } catch (ClassNotFoundException e) { + return null; + } + } + + private static Method getMethod(Class cls, String name, Class... parameterTypes) { + if (cls == null) return null; + + try { + return cls.getMethod(name, parameterTypes); + } catch (NoSuchMethodException e) { + throw new AssertionError(e); + } + } + + private static Object invoke(Method m, Object obj, Object... params) { + try { + return m.invoke(obj, params); + } catch (IllegalAccessException e) { + throw new AssertionError(e); + } catch (InvocationTargetException e) { + throw new AssertionError(e); + } + } + + private static void getLevelObjects() { + // get all java.util.logging.Level objects + Method parseLevelMethod = getMethod(levelClass, "parse", String.class); + int[] levelArray = new int[] {OFF, SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST, ALL}; + for (int l : levelArray) { + Object o = invoke(parseLevelMethod, null, getLevelName(l)); + levelObjects.put(l, o); + } + } + + private final Object javaLogger; + JavaLogger(String name) { + this(name, 0); + } + + JavaLogger(String name, int level) { + super(name, level); + this.javaLogger = invoke(getLoggerMethod, null, name); + if (level != 0) { + // level has been updated and so set the Logger's level + invoke(setLevelMethod, javaLogger, levelObjects.get(level)); + } + } + + /** + * Let Logger.log() do the filtering since if the level of a + * platform logger is altered directly from + * java.util.logging.Logger.setLevel(), the levelValue will + * not be updated. + */ + void doLog(int level, String msg) { + invoke(logMethod, javaLogger, levelObjects.get(level), msg); + } + + void doLog(int level, String msg, Throwable t) { + invoke(logThrowMethod, javaLogger, levelObjects.get(level), msg, t); + } + + void doLog(int level, String msg, Object... params) { + invoke(logParamsMethod, javaLogger, levelObjects.get(level), msg, params); + } + + boolean isEnabled() { + Object level = invoke(getLevelMethod, javaLogger); + return level == null || level.equals(levelObjects.get(OFF)) == false; + } + + int getLevel() { + Object level = invoke(getLevelMethod, javaLogger); + if (level != null) { + for (Map.Entry l : levelObjects.entrySet()) { + if (level == l.getValue()) { + return l.getKey(); + } + } + } + return 0; + } + + void setLevel(int newLevel) { + levelValue = newLevel; + invoke(setLevelMethod, javaLogger, levelObjects.get(newLevel)); + } + + public boolean isLoggable(int level) { + return (Boolean) invoke(isLoggableMethod, javaLogger, levelObjects.get(level)); + } + } + + + private static String getLevelName(int level) { + switch (level) { + case OFF : return "OFF"; + case SEVERE : return "SEVERE"; + case WARNING : return "WARNING"; + case INFO : return "INFO"; + case CONFIG : return "CONFIG"; + case FINE : return "FINE"; + case FINER : return "FINER"; + case FINEST : return "FINEST"; + case ALL : return "ALL"; + default : return "UNKNOWN"; + } + } + +} diff --git a/src/share/demo/jvmti/waiters/Agent.cpp b/src/share/demo/jvmti/waiters/Agent.cpp index 30786133d50236e7de6c4171b453d6891786a23d..f4da70281fd75e817ad38fd939b8dcbf379fc0e3 100644 --- a/src/share/demo/jvmti/waiters/Agent.cpp +++ b/src/share/demo/jvmti/waiters/Agent.cpp @@ -72,36 +72,30 @@ Agent::get_monitor(jvmtiEnv *jvmti, JNIEnv *env, jobject object) { jvmtiError err; Monitor *m; + jlong tag; - /* We use tags to track these, the tag is the Monitor pointer */ - err = jvmti->RawMonitorEnter(lock); { - check_jvmti_error(jvmti, err, "raw monitor enter"); - - /* The raw monitor enter/exit protects us from creating two - * instances for the same object. - */ - jlong tag; - - m = NULL; - tag = (jlong)0; - err = jvmti->GetTag(object, &tag); - check_jvmti_error(jvmti, err, "get tag"); - /*LINTED*/ - m = (Monitor *)(void *)(ptrdiff_t)tag; - if ( m == NULL ) { - m = new Monitor(jvmti, env, object); - /*LINTED*/ - tag = (jlong)(ptrdiff_t)(void *)m; - err = jvmti->SetTag(object, tag); - check_jvmti_error(jvmti, err, "set tag"); - /* Save monitor on list */ + m = NULL; + tag = (jlong)0; + err = jvmti->GetTag(object, &tag); + check_jvmti_error(jvmti, err, "get tag"); + /*LINTED*/ + m = (Monitor *)(void *)(ptrdiff_t)tag; + if ( m == NULL ) { + m = new Monitor(jvmti, env, object); + /* Save monitor on list */ + if (monitor_count == monitor_list_size) { + monitor_list_size += monitor_list_grow_size; monitor_list = (Monitor**)realloc((void*)monitor_list, - (monitor_count+1)*(int)sizeof(Monitor*)); - monitor_list[monitor_count++] = m; + (monitor_list_size)*(int)sizeof(Monitor*)); } - } err = jvmti->RawMonitorExit(lock); - check_jvmti_error(jvmti, err, "raw monitor exit"); - + monitor_list[monitor_count] = m; + m->set_slot(monitor_count); + monitor_count++; + /*LINTED*/ + tag = (jlong)(ptrdiff_t)(void *)m; + err = jvmti->SetTag(object, tag); + check_jvmti_error(jvmti, err, "set tag"); + } return m; } @@ -112,12 +106,11 @@ Agent::Agent(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) stdout_message("Agent created..\n"); stdout_message("VMInit...\n"); - /* Create a Monitor lock to use */ - err = jvmti->CreateRawMonitor("waiters Agent lock", &lock); - check_jvmti_error(jvmti, err, "create raw monitor"); /* Start monitor list */ monitor_count = 0; - monitor_list = (Monitor**)malloc((int)sizeof(Monitor*)); + monitor_list_size = initial_monitor_list_size; + monitor_list = (Monitor**) + malloc(monitor_list_size*(int)sizeof(Monitor*)); } Agent::~Agent() @@ -134,9 +127,6 @@ void Agent::vm_death(jvmtiEnv *jvmti, JNIEnv *env) delete monitor_list[i]; } free(monitor_list); - /* Destroy the Monitor lock to use */ - err = jvmti->DestroyRawMonitor(lock); - check_jvmti_error(jvmti, err, "destroy raw monitor"); /* Print death message */ stdout_message("VMDeath...\n"); } @@ -215,8 +205,16 @@ void Agent::object_free(jvmtiEnv* jvmti, jlong tag) /* We just cast the tag to a C++ pointer and delete it. * we know it can only be a Monitor *. */ - Monitor *m; + Monitor *m; /*LINTED*/ m = (Monitor *)(ptrdiff_t)tag; + if (monitor_count > 1) { + /* Move the last element to this Monitor's slot */ + int slot = m->get_slot(); + Monitor *last = monitor_list[monitor_count-1]; + monitor_list[slot] = last; + last->set_slot(slot); + } + monitor_count--; delete m; } diff --git a/src/share/demo/jvmti/waiters/Agent.hpp b/src/share/demo/jvmti/waiters/Agent.hpp index 9885baf8ba35a6d4749139bd7c8236abd3d2a811..65fe1227362500f7b82d0703b3062ff24584510c 100644 --- a/src/share/demo/jvmti/waiters/Agent.hpp +++ b/src/share/demo/jvmti/waiters/Agent.hpp @@ -34,8 +34,12 @@ class Agent { private: - jrawMonitorID lock; + enum { + initial_monitor_list_size = 64, + monitor_list_grow_size = 16 + }; Monitor **monitor_list; + unsigned monitor_list_size; unsigned monitor_count; Thread *get_thread(jvmtiEnv *jvmti, JNIEnv *env, jthread thread); Monitor *get_monitor(jvmtiEnv *jvmti, JNIEnv *env, jobject object); diff --git a/src/share/demo/jvmti/waiters/Monitor.cpp b/src/share/demo/jvmti/waiters/Monitor.cpp index a5efc5b23b30b660b7b7b3d4d58bbec9ad14e902..acd092a142af03341c283d965ba1416e94ad2978 100644 --- a/src/share/demo/jvmti/waiters/Monitor.cpp +++ b/src/share/demo/jvmti/waiters/Monitor.cpp @@ -73,6 +73,16 @@ Monitor::~Monitor() name, contends, waits, timeouts); } +int Monitor::get_slot() +{ + return slot; +} + +void Monitor::set_slot(int aslot) +{ + slot = aslot; +} + void Monitor::contended() { contends++; diff --git a/src/share/demo/jvmti/waiters/Monitor.hpp b/src/share/demo/jvmti/waiters/Monitor.hpp index 95b49560abdc23d12365512adc681aef0e40fca3..af6dedda5b9f65ee4f519fd1685e6296ff879dd8 100644 --- a/src/share/demo/jvmti/waiters/Monitor.hpp +++ b/src/share/demo/jvmti/waiters/Monitor.hpp @@ -35,6 +35,7 @@ class Monitor { private: char name[64]; + int slot; unsigned contends; unsigned waits; unsigned timeouts; @@ -42,6 +43,8 @@ class Monitor { public: Monitor(jvmtiEnv *jvmti, JNIEnv *env, jobject object); ~Monitor(); + int get_slot(); + void set_slot(int i); void contended(); void waited(); void timeout(); diff --git a/src/share/javavm/export/jvm.h b/src/share/javavm/export/jvm.h index df8f27e6602eaf6d68f43018fcb3b15ce653fe6e..4f141d21fb8dc0202e4aed41c94cc677d293fd19 100644 --- a/src/share/javavm/export/jvm.h +++ b/src/share/javavm/export/jvm.h @@ -374,6 +374,12 @@ JVM_FindPrimitiveClass(JNIEnv *env, const char *utf); JNIEXPORT void JNICALL JVM_ResolveClass(JNIEnv *env, jclass cls); +/* + * Find a class from a boot class loader. Returns NULL if class not found. + */ +JNIEXPORT jclass JNICALL +JVM_FindClassFromBootLoader(JNIEnv *env, const char *name); + /* * Find a class from a given class loader. Throw ClassNotFoundException * or NoClassDefFoundError depending on the value of the last diff --git a/src/share/lib/net.properties b/src/share/lib/net.properties index e941d50e3f49fdaf5e26359c07695c0d3cc11a42..da78a84d511d3a137736d6f0438c3c1892515b38 100644 --- a/src/share/lib/net.properties +++ b/src/share/lib/net.properties @@ -32,7 +32,7 @@ java.net.useSystemProxies=false # # http.proxyHost= # http.proxyPort=80 -# http.nonProxyHosts=localhost|127.0.0.1 +http.nonProxyHosts=localhost|127.*|[::1] # # HTTPS Proxy Settings. proxyHost is the name of the proxy server # (e.g. proxy.mydomain.com), proxyPort is the port number to use (default @@ -49,7 +49,7 @@ java.net.useSystemProxies=false # # ftp.proxyHost= # ftp.proxyPort=80 -# ftp.nonProxyHosts=localhost|127.0.0.1 +ftp.nonProxyHosts=localhost|127.*|[::1] # # Gopher Proxy settings. proxyHost is the name of the proxy server # (e.g. proxy.mydomain.com), proxyPort is the port number to use (default diff --git a/src/share/native/java/lang/ClassLoader.c b/src/share/native/java/lang/ClassLoader.c index bedf87ce7e6571ad4fa3cce43edf456ff4581d6b..b080fef2e53be7b744e7b01a9801301e24a31c4e 100644 --- a/src/share/native/java/lang/ClassLoader.c +++ b/src/share/native/java/lang/ClassLoader.c @@ -237,6 +237,9 @@ Java_java_lang_ClassLoader_resolveClass0(JNIEnv *env, jobject this, JVM_ResolveClass(env, cls); } +/* + * Returns NULL if class not found. + */ JNIEXPORT jclass JNICALL Java_java_lang_ClassLoader_findBootstrapClass(JNIEnv *env, jobject loader, jstring classname) @@ -246,7 +249,6 @@ Java_java_lang_ClassLoader_findBootstrapClass(JNIEnv *env, jobject loader, char buf[128]; if (classname == NULL) { - JNU_ThrowClassNotFoundException(env, 0); return 0; } @@ -258,11 +260,10 @@ Java_java_lang_ClassLoader_findBootstrapClass(JNIEnv *env, jobject loader, VerifyFixClassname(clname); if (!VerifyClassname(clname, JNI_TRUE)) { /* expects slashed name */ - JNU_ThrowClassNotFoundException(env, clname); goto done; } - cls = JVM_FindClassFromClassLoader(env, clname, JNI_FALSE, 0, JNI_FALSE); + cls = JVM_FindClassFromBootLoader(env, clname); done: if (clname != buf) { diff --git a/src/share/native/sun/misc/VM.c b/src/share/native/sun/misc/VM.c index 6dcc8d68ff9e2e4430dfa3479c549129837014ec..73618dd96566eba3e9146ec3e3dfa790d171a868 100644 --- a/src/share/native/sun/misc/VM.c +++ b/src/share/native/sun/misc/VM.c @@ -131,17 +131,6 @@ Java_sun_misc_VM_initialize(JNIEnv *env, jclass cls) { /* obtain the JVM version info */ (*func_p)(env, &info, sizeof(info)); - - if (info.is_kernel_jvm == 1) { - /* set the static field VM.kernelVM to true for kernel VM */ - fid = (*env)->GetStaticFieldID(env, cls, "kernelVM", "Z"); - if (fid != 0) { - (*env)->SetStaticBooleanField(env, cls, fid, info.is_kernel_jvm); - } else { - sprintf(errmsg, "Static kernelVM boolean field not found"); - JNU_ThrowInternalError(env, errmsg); - } - } } } diff --git a/src/share/native/sun/security/ec/ECC_JNI.cpp b/src/share/native/sun/security/ec/ECC_JNI.cpp index fb227e82cac8668080991a85d68da4e0ec8cfc94..e847391a09b289bda6fa0eb5f5a365ae0d4b5b3f 100644 --- a/src/share/native/sun/security/ec/ECC_JNI.cpp +++ b/src/share/native/sun/security/ec/ECC_JNI.cpp @@ -24,7 +24,7 @@ */ #include -#include "ecc_impl.h" +#include "impl/ecc_impl.h" #define ILLEGAL_STATE_EXCEPTION "java/lang/IllegalStateException" #define INVALID_ALGORITHM_PARAMETER_EXCEPTION \ diff --git a/src/share/native/sun/security/ec/ec.c b/src/share/native/sun/security/ec/impl/ec.c similarity index 100% rename from src/share/native/sun/security/ec/ec.c rename to src/share/native/sun/security/ec/impl/ec.c diff --git a/src/share/native/sun/security/ec/impl/ec.h b/src/share/native/sun/security/ec/impl/ec.h new file mode 100644 index 0000000000000000000000000000000000000000..d472670913bddd81d1c993f708411879c1ad91d0 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec.h @@ -0,0 +1,72 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Elliptic Curve Cryptography library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Dr Vipul Gupta , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef __ec_h_ +#define __ec_h_ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#define EC_DEBUG 0 +#define EC_POINT_FORM_COMPRESSED_Y0 0x02 +#define EC_POINT_FORM_COMPRESSED_Y1 0x03 +#define EC_POINT_FORM_UNCOMPRESSED 0x04 +#define EC_POINT_FORM_HYBRID_Y0 0x06 +#define EC_POINT_FORM_HYBRID_Y1 0x07 + +#define ANSI_X962_CURVE_OID_TOTAL_LEN 10 +#define SECG_CURVE_OID_TOTAL_LEN 7 + +#endif /* __ec_h_ */ diff --git a/src/share/native/sun/security/ec/impl/ec2.h b/src/share/native/sun/security/ec/impl/ec2.h new file mode 100644 index 0000000000000000000000000000000000000000..c1b2d7965e5d300c4d65aa96c09f62fb38907c9b --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec2.h @@ -0,0 +1,146 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for binary polynomial field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _EC2_H +#define _EC2_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecl-priv.h" + +/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */ +mp_err ec_GF2m_pt_is_inf_aff(const mp_int *px, const mp_int *py); + +/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */ +mp_err ec_GF2m_pt_set_inf_aff(mp_int *px, mp_int *py); + +/* Computes R = P + Q where R is (rx, ry), P is (px, py) and Q is (qx, + * qy). Uses affine coordinates. */ +mp_err ec_GF2m_pt_add_aff(const mp_int *px, const mp_int *py, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Computes R = P - Q. Uses affine coordinates. */ +mp_err ec_GF2m_pt_sub_aff(const mp_int *px, const mp_int *py, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Computes R = 2P. Uses affine coordinates. */ +mp_err ec_GF2m_pt_dbl_aff(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Validates a point on a GF2m curve. */ +mp_err ec_GF2m_validate_point(const mp_int *px, const mp_int *py, const ECGroup *group); + +/* by default, this routine is unused and thus doesn't need to be compiled */ +#ifdef ECL_ENABLE_GF2M_PT_MUL_AFF +/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters + * a, b and p are the elliptic curve coefficients and the irreducible that + * determines the field GF2m. Uses affine coordinates. */ +mp_err ec_GF2m_pt_mul_aff(const mp_int *n, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); +#endif + +/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters + * a, b and p are the elliptic curve coefficients and the irreducible that + * determines the field GF2m. Uses Montgomery projective coordinates. */ +mp_err ec_GF2m_pt_mul_mont(const mp_int *n, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); + +#ifdef ECL_ENABLE_GF2M_PROJ +/* Converts a point P(px, py) from affine coordinates to projective + * coordinates R(rx, ry, rz). */ +mp_err ec_GF2m_pt_aff2proj(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, mp_int *rz, const ECGroup *group); + +/* Converts a point P(px, py, pz) from projective coordinates to affine + * coordinates R(rx, ry). */ +mp_err ec_GF2m_pt_proj2aff(const mp_int *px, const mp_int *py, + const mp_int *pz, mp_int *rx, mp_int *ry, + const ECGroup *group); + +/* Checks if point P(px, py, pz) is at infinity. Uses projective + * coordinates. */ +mp_err ec_GF2m_pt_is_inf_proj(const mp_int *px, const mp_int *py, + const mp_int *pz); + +/* Sets P(px, py, pz) to be the point at infinity. Uses projective + * coordinates. */ +mp_err ec_GF2m_pt_set_inf_proj(mp_int *px, mp_int *py, mp_int *pz); + +/* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and Q is + * (qx, qy, qz). Uses projective coordinates. */ +mp_err ec_GF2m_pt_add_proj(const mp_int *px, const mp_int *py, + const mp_int *pz, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, + mp_int *rz, const ECGroup *group); + +/* Computes R = 2P. Uses projective coordinates. */ +mp_err ec_GF2m_pt_dbl_proj(const mp_int *px, const mp_int *py, + const mp_int *pz, mp_int *rx, mp_int *ry, + mp_int *rz, const ECGroup *group); + +/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters + * a, b and p are the elliptic curve coefficients and the prime that + * determines the field GF2m. Uses projective coordinates. */ +mp_err ec_GF2m_pt_mul_proj(const mp_int *n, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); +#endif + +#endif /* _EC2_H */ diff --git a/src/share/native/sun/security/ec/impl/ec2_163.c b/src/share/native/sun/security/ec/impl/ec2_163.c new file mode 100644 index 0000000000000000000000000000000000000000..ecdb51210639e3963bad368bbb7915d1143fded9 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec2_163.c @@ -0,0 +1,281 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for binary polynomial field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang-Shantz , + * Stephen Fung , and + * Douglas Stebila , Sun Microsystems Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ec2.h" +#include "mp_gf2m.h" +#include "mp_gf2m-priv.h" +#include "mpi.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Fast reduction for polynomials over a 163-bit curve. Assumes reduction + * polynomial with terms {163, 7, 6, 3, 0}. */ +mp_err +ec_GF2m_163_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit *u, z; + + if (a != r) { + MP_CHECKOK(mp_copy(a, r)); + } +#ifdef ECL_SIXTY_FOUR_BIT + if (MP_USED(r) < 6) { + MP_CHECKOK(s_mp_pad(r, 6)); + } + u = MP_DIGITS(r); + MP_USED(r) = 6; + + /* u[5] only has 6 significant bits */ + z = u[5]; + u[2] ^= (z << 36) ^ (z << 35) ^ (z << 32) ^ (z << 29); + z = u[4]; + u[2] ^= (z >> 28) ^ (z >> 29) ^ (z >> 32) ^ (z >> 35); + u[1] ^= (z << 36) ^ (z << 35) ^ (z << 32) ^ (z << 29); + z = u[3]; + u[1] ^= (z >> 28) ^ (z >> 29) ^ (z >> 32) ^ (z >> 35); + u[0] ^= (z << 36) ^ (z << 35) ^ (z << 32) ^ (z << 29); + z = u[2] >> 35; /* z only has 29 significant bits */ + u[0] ^= (z << 7) ^ (z << 6) ^ (z << 3) ^ z; + /* clear bits above 163 */ + u[5] = u[4] = u[3] = 0; + u[2] ^= z << 35; +#else + if (MP_USED(r) < 11) { + MP_CHECKOK(s_mp_pad(r, 11)); + } + u = MP_DIGITS(r); + MP_USED(r) = 11; + + /* u[11] only has 6 significant bits */ + z = u[10]; + u[5] ^= (z << 4) ^ (z << 3) ^ z ^ (z >> 3); + u[4] ^= (z << 29); + z = u[9]; + u[5] ^= (z >> 28) ^ (z >> 29); + u[4] ^= (z << 4) ^ (z << 3) ^ z ^ (z >> 3); + u[3] ^= (z << 29); + z = u[8]; + u[4] ^= (z >> 28) ^ (z >> 29); + u[3] ^= (z << 4) ^ (z << 3) ^ z ^ (z >> 3); + u[2] ^= (z << 29); + z = u[7]; + u[3] ^= (z >> 28) ^ (z >> 29); + u[2] ^= (z << 4) ^ (z << 3) ^ z ^ (z >> 3); + u[1] ^= (z << 29); + z = u[6]; + u[2] ^= (z >> 28) ^ (z >> 29); + u[1] ^= (z << 4) ^ (z << 3) ^ z ^ (z >> 3); + u[0] ^= (z << 29); + z = u[5] >> 3; /* z only has 29 significant bits */ + u[1] ^= (z >> 25) ^ (z >> 26); + u[0] ^= (z << 7) ^ (z << 6) ^ (z << 3) ^ z; + /* clear bits above 163 */ + u[11] = u[10] = u[9] = u[8] = u[7] = u[6] = 0; + u[5] ^= z << 3; +#endif + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* Fast squaring for polynomials over a 163-bit curve. Assumes reduction + * polynomial with terms {163, 7, 6, 3, 0}. */ +mp_err +ec_GF2m_163_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit *u, *v; + + v = MP_DIGITS(a); + +#ifdef ECL_SIXTY_FOUR_BIT + if (MP_USED(a) < 3) { + return mp_bsqrmod(a, meth->irr_arr, r); + } + if (MP_USED(r) < 6) { + MP_CHECKOK(s_mp_pad(r, 6)); + } + MP_USED(r) = 6; +#else + if (MP_USED(a) < 6) { + return mp_bsqrmod(a, meth->irr_arr, r); + } + if (MP_USED(r) < 12) { + MP_CHECKOK(s_mp_pad(r, 12)); + } + MP_USED(r) = 12; +#endif + u = MP_DIGITS(r); + +#ifdef ECL_THIRTY_TWO_BIT + u[11] = gf2m_SQR1(v[5]); + u[10] = gf2m_SQR0(v[5]); + u[9] = gf2m_SQR1(v[4]); + u[8] = gf2m_SQR0(v[4]); + u[7] = gf2m_SQR1(v[3]); + u[6] = gf2m_SQR0(v[3]); +#endif + u[5] = gf2m_SQR1(v[2]); + u[4] = gf2m_SQR0(v[2]); + u[3] = gf2m_SQR1(v[1]); + u[2] = gf2m_SQR0(v[1]); + u[1] = gf2m_SQR1(v[0]); + u[0] = gf2m_SQR0(v[0]); + return ec_GF2m_163_mod(r, r, meth); + + CLEANUP: + return res; +} + +/* Fast multiplication for polynomials over a 163-bit curve. Assumes + * reduction polynomial with terms {163, 7, 6, 3, 0}. */ +mp_err +ec_GF2m_163_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a2 = 0, a1 = 0, a0, b2 = 0, b1 = 0, b0; + +#ifdef ECL_THIRTY_TWO_BIT + mp_digit a5 = 0, a4 = 0, a3 = 0, b5 = 0, b4 = 0, b3 = 0; + mp_digit rm[6]; +#endif + + if (a == b) { + return ec_GF2m_163_sqr(a, r, meth); + } else { + switch (MP_USED(a)) { +#ifdef ECL_THIRTY_TWO_BIT + case 6: + a5 = MP_DIGIT(a, 5); + case 5: + a4 = MP_DIGIT(a, 4); + case 4: + a3 = MP_DIGIT(a, 3); +#endif + case 3: + a2 = MP_DIGIT(a, 2); + case 2: + a1 = MP_DIGIT(a, 1); + default: + a0 = MP_DIGIT(a, 0); + } + switch (MP_USED(b)) { +#ifdef ECL_THIRTY_TWO_BIT + case 6: + b5 = MP_DIGIT(b, 5); + case 5: + b4 = MP_DIGIT(b, 4); + case 4: + b3 = MP_DIGIT(b, 3); +#endif + case 3: + b2 = MP_DIGIT(b, 2); + case 2: + b1 = MP_DIGIT(b, 1); + default: + b0 = MP_DIGIT(b, 0); + } +#ifdef ECL_SIXTY_FOUR_BIT + MP_CHECKOK(s_mp_pad(r, 6)); + s_bmul_3x3(MP_DIGITS(r), a2, a1, a0, b2, b1, b0); + MP_USED(r) = 6; + s_mp_clamp(r); +#else + MP_CHECKOK(s_mp_pad(r, 12)); + s_bmul_3x3(MP_DIGITS(r) + 6, a5, a4, a3, b5, b4, b3); + s_bmul_3x3(MP_DIGITS(r), a2, a1, a0, b2, b1, b0); + s_bmul_3x3(rm, a5 ^ a2, a4 ^ a1, a3 ^ a0, b5 ^ b2, b4 ^ b1, + b3 ^ b0); + rm[5] ^= MP_DIGIT(r, 5) ^ MP_DIGIT(r, 11); + rm[4] ^= MP_DIGIT(r, 4) ^ MP_DIGIT(r, 10); + rm[3] ^= MP_DIGIT(r, 3) ^ MP_DIGIT(r, 9); + rm[2] ^= MP_DIGIT(r, 2) ^ MP_DIGIT(r, 8); + rm[1] ^= MP_DIGIT(r, 1) ^ MP_DIGIT(r, 7); + rm[0] ^= MP_DIGIT(r, 0) ^ MP_DIGIT(r, 6); + MP_DIGIT(r, 8) ^= rm[5]; + MP_DIGIT(r, 7) ^= rm[4]; + MP_DIGIT(r, 6) ^= rm[3]; + MP_DIGIT(r, 5) ^= rm[2]; + MP_DIGIT(r, 4) ^= rm[1]; + MP_DIGIT(r, 3) ^= rm[0]; + MP_USED(r) = 12; + s_mp_clamp(r); +#endif + return ec_GF2m_163_mod(r, r, meth); + } + + CLEANUP: + return res; +} + +/* Wire in fast field arithmetic for 163-bit curves. */ +mp_err +ec_group_set_gf2m163(ECGroup *group, ECCurveName name) +{ + group->meth->field_mod = &ec_GF2m_163_mod; + group->meth->field_mul = &ec_GF2m_163_mul; + group->meth->field_sqr = &ec_GF2m_163_sqr; + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ec2_193.c b/src/share/native/sun/security/ec/impl/ec2_193.c new file mode 100644 index 0000000000000000000000000000000000000000..f6187d356125cda91c70cfb16e6fb3c5830905d3 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec2_193.c @@ -0,0 +1,298 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for binary polynomial field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang-Shantz , + * Stephen Fung , and + * Douglas Stebila , Sun Microsystems Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ec2.h" +#include "mp_gf2m.h" +#include "mp_gf2m-priv.h" +#include "mpi.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Fast reduction for polynomials over a 193-bit curve. Assumes reduction + * polynomial with terms {193, 15, 0}. */ +mp_err +ec_GF2m_193_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit *u, z; + + if (a != r) { + MP_CHECKOK(mp_copy(a, r)); + } +#ifdef ECL_SIXTY_FOUR_BIT + if (MP_USED(r) < 7) { + MP_CHECKOK(s_mp_pad(r, 7)); + } + u = MP_DIGITS(r); + MP_USED(r) = 7; + + /* u[6] only has 2 significant bits */ + z = u[6]; + u[3] ^= (z << 14) ^ (z >> 1); + u[2] ^= (z << 63); + z = u[5]; + u[3] ^= (z >> 50); + u[2] ^= (z << 14) ^ (z >> 1); + u[1] ^= (z << 63); + z = u[4]; + u[2] ^= (z >> 50); + u[1] ^= (z << 14) ^ (z >> 1); + u[0] ^= (z << 63); + z = u[3] >> 1; /* z only has 63 significant bits */ + u[1] ^= (z >> 49); + u[0] ^= (z << 15) ^ z; + /* clear bits above 193 */ + u[6] = u[5] = u[4] = 0; + u[3] ^= z << 1; +#else + if (MP_USED(r) < 13) { + MP_CHECKOK(s_mp_pad(r, 13)); + } + u = MP_DIGITS(r); + MP_USED(r) = 13; + + /* u[12] only has 2 significant bits */ + z = u[12]; + u[6] ^= (z << 14) ^ (z >> 1); + u[5] ^= (z << 31); + z = u[11]; + u[6] ^= (z >> 18); + u[5] ^= (z << 14) ^ (z >> 1); + u[4] ^= (z << 31); + z = u[10]; + u[5] ^= (z >> 18); + u[4] ^= (z << 14) ^ (z >> 1); + u[3] ^= (z << 31); + z = u[9]; + u[4] ^= (z >> 18); + u[3] ^= (z << 14) ^ (z >> 1); + u[2] ^= (z << 31); + z = u[8]; + u[3] ^= (z >> 18); + u[2] ^= (z << 14) ^ (z >> 1); + u[1] ^= (z << 31); + z = u[7]; + u[2] ^= (z >> 18); + u[1] ^= (z << 14) ^ (z >> 1); + u[0] ^= (z << 31); + z = u[6] >> 1; /* z only has 31 significant bits */ + u[1] ^= (z >> 17); + u[0] ^= (z << 15) ^ z; + /* clear bits above 193 */ + u[12] = u[11] = u[10] = u[9] = u[8] = u[7] = 0; + u[6] ^= z << 1; +#endif + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* Fast squaring for polynomials over a 193-bit curve. Assumes reduction + * polynomial with terms {193, 15, 0}. */ +mp_err +ec_GF2m_193_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit *u, *v; + + v = MP_DIGITS(a); + +#ifdef ECL_SIXTY_FOUR_BIT + if (MP_USED(a) < 4) { + return mp_bsqrmod(a, meth->irr_arr, r); + } + if (MP_USED(r) < 7) { + MP_CHECKOK(s_mp_pad(r, 7)); + } + MP_USED(r) = 7; +#else + if (MP_USED(a) < 7) { + return mp_bsqrmod(a, meth->irr_arr, r); + } + if (MP_USED(r) < 13) { + MP_CHECKOK(s_mp_pad(r, 13)); + } + MP_USED(r) = 13; +#endif + u = MP_DIGITS(r); + +#ifdef ECL_THIRTY_TWO_BIT + u[12] = gf2m_SQR0(v[6]); + u[11] = gf2m_SQR1(v[5]); + u[10] = gf2m_SQR0(v[5]); + u[9] = gf2m_SQR1(v[4]); + u[8] = gf2m_SQR0(v[4]); + u[7] = gf2m_SQR1(v[3]); +#endif + u[6] = gf2m_SQR0(v[3]); + u[5] = gf2m_SQR1(v[2]); + u[4] = gf2m_SQR0(v[2]); + u[3] = gf2m_SQR1(v[1]); + u[2] = gf2m_SQR0(v[1]); + u[1] = gf2m_SQR1(v[0]); + u[0] = gf2m_SQR0(v[0]); + return ec_GF2m_193_mod(r, r, meth); + + CLEANUP: + return res; +} + +/* Fast multiplication for polynomials over a 193-bit curve. Assumes + * reduction polynomial with terms {193, 15, 0}. */ +mp_err +ec_GF2m_193_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a3 = 0, a2 = 0, a1 = 0, a0, b3 = 0, b2 = 0, b1 = 0, b0; + +#ifdef ECL_THIRTY_TWO_BIT + mp_digit a6 = 0, a5 = 0, a4 = 0, b6 = 0, b5 = 0, b4 = 0; + mp_digit rm[8]; +#endif + + if (a == b) { + return ec_GF2m_193_sqr(a, r, meth); + } else { + switch (MP_USED(a)) { +#ifdef ECL_THIRTY_TWO_BIT + case 7: + a6 = MP_DIGIT(a, 6); + case 6: + a5 = MP_DIGIT(a, 5); + case 5: + a4 = MP_DIGIT(a, 4); +#endif + case 4: + a3 = MP_DIGIT(a, 3); + case 3: + a2 = MP_DIGIT(a, 2); + case 2: + a1 = MP_DIGIT(a, 1); + default: + a0 = MP_DIGIT(a, 0); + } + switch (MP_USED(b)) { +#ifdef ECL_THIRTY_TWO_BIT + case 7: + b6 = MP_DIGIT(b, 6); + case 6: + b5 = MP_DIGIT(b, 5); + case 5: + b4 = MP_DIGIT(b, 4); +#endif + case 4: + b3 = MP_DIGIT(b, 3); + case 3: + b2 = MP_DIGIT(b, 2); + case 2: + b1 = MP_DIGIT(b, 1); + default: + b0 = MP_DIGIT(b, 0); + } +#ifdef ECL_SIXTY_FOUR_BIT + MP_CHECKOK(s_mp_pad(r, 8)); + s_bmul_4x4(MP_DIGITS(r), a3, a2, a1, a0, b3, b2, b1, b0); + MP_USED(r) = 8; + s_mp_clamp(r); +#else + MP_CHECKOK(s_mp_pad(r, 14)); + s_bmul_3x3(MP_DIGITS(r) + 8, a6, a5, a4, b6, b5, b4); + s_bmul_4x4(MP_DIGITS(r), a3, a2, a1, a0, b3, b2, b1, b0); + s_bmul_4x4(rm, a3, a6 ^ a2, a5 ^ a1, a4 ^ a0, b3, b6 ^ b2, b5 ^ b1, + b4 ^ b0); + rm[7] ^= MP_DIGIT(r, 7); + rm[6] ^= MP_DIGIT(r, 6); + rm[5] ^= MP_DIGIT(r, 5) ^ MP_DIGIT(r, 13); + rm[4] ^= MP_DIGIT(r, 4) ^ MP_DIGIT(r, 12); + rm[3] ^= MP_DIGIT(r, 3) ^ MP_DIGIT(r, 11); + rm[2] ^= MP_DIGIT(r, 2) ^ MP_DIGIT(r, 10); + rm[1] ^= MP_DIGIT(r, 1) ^ MP_DIGIT(r, 9); + rm[0] ^= MP_DIGIT(r, 0) ^ MP_DIGIT(r, 8); + MP_DIGIT(r, 11) ^= rm[7]; + MP_DIGIT(r, 10) ^= rm[6]; + MP_DIGIT(r, 9) ^= rm[5]; + MP_DIGIT(r, 8) ^= rm[4]; + MP_DIGIT(r, 7) ^= rm[3]; + MP_DIGIT(r, 6) ^= rm[2]; + MP_DIGIT(r, 5) ^= rm[1]; + MP_DIGIT(r, 4) ^= rm[0]; + MP_USED(r) = 14; + s_mp_clamp(r); +#endif + return ec_GF2m_193_mod(r, r, meth); + } + + CLEANUP: + return res; +} + +/* Wire in fast field arithmetic for 193-bit curves. */ +mp_err +ec_group_set_gf2m193(ECGroup *group, ECCurveName name) +{ + group->meth->field_mod = &ec_GF2m_193_mod; + group->meth->field_mul = &ec_GF2m_193_mul; + group->meth->field_sqr = &ec_GF2m_193_sqr; + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ec2_233.c b/src/share/native/sun/security/ec/impl/ec2_233.c new file mode 100644 index 0000000000000000000000000000000000000000..2b29c46ea762e7bcc48389f83cfd41947886db5c --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec2_233.c @@ -0,0 +1,321 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for binary polynomial field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang-Shantz , + * Stephen Fung , and + * Douglas Stebila , Sun Microsystems Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ec2.h" +#include "mp_gf2m.h" +#include "mp_gf2m-priv.h" +#include "mpi.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Fast reduction for polynomials over a 233-bit curve. Assumes reduction + * polynomial with terms {233, 74, 0}. */ +mp_err +ec_GF2m_233_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit *u, z; + + if (a != r) { + MP_CHECKOK(mp_copy(a, r)); + } +#ifdef ECL_SIXTY_FOUR_BIT + if (MP_USED(r) < 8) { + MP_CHECKOK(s_mp_pad(r, 8)); + } + u = MP_DIGITS(r); + MP_USED(r) = 8; + + /* u[7] only has 18 significant bits */ + z = u[7]; + u[4] ^= (z << 33) ^ (z >> 41); + u[3] ^= (z << 23); + z = u[6]; + u[4] ^= (z >> 31); + u[3] ^= (z << 33) ^ (z >> 41); + u[2] ^= (z << 23); + z = u[5]; + u[3] ^= (z >> 31); + u[2] ^= (z << 33) ^ (z >> 41); + u[1] ^= (z << 23); + z = u[4]; + u[2] ^= (z >> 31); + u[1] ^= (z << 33) ^ (z >> 41); + u[0] ^= (z << 23); + z = u[3] >> 41; /* z only has 23 significant bits */ + u[1] ^= (z << 10); + u[0] ^= z; + /* clear bits above 233 */ + u[7] = u[6] = u[5] = u[4] = 0; + u[3] ^= z << 41; +#else + if (MP_USED(r) < 15) { + MP_CHECKOK(s_mp_pad(r, 15)); + } + u = MP_DIGITS(r); + MP_USED(r) = 15; + + /* u[14] only has 18 significant bits */ + z = u[14]; + u[9] ^= (z << 1); + u[7] ^= (z >> 9); + u[6] ^= (z << 23); + z = u[13]; + u[9] ^= (z >> 31); + u[8] ^= (z << 1); + u[6] ^= (z >> 9); + u[5] ^= (z << 23); + z = u[12]; + u[8] ^= (z >> 31); + u[7] ^= (z << 1); + u[5] ^= (z >> 9); + u[4] ^= (z << 23); + z = u[11]; + u[7] ^= (z >> 31); + u[6] ^= (z << 1); + u[4] ^= (z >> 9); + u[3] ^= (z << 23); + z = u[10]; + u[6] ^= (z >> 31); + u[5] ^= (z << 1); + u[3] ^= (z >> 9); + u[2] ^= (z << 23); + z = u[9]; + u[5] ^= (z >> 31); + u[4] ^= (z << 1); + u[2] ^= (z >> 9); + u[1] ^= (z << 23); + z = u[8]; + u[4] ^= (z >> 31); + u[3] ^= (z << 1); + u[1] ^= (z >> 9); + u[0] ^= (z << 23); + z = u[7] >> 9; /* z only has 23 significant bits */ + u[3] ^= (z >> 22); + u[2] ^= (z << 10); + u[0] ^= z; + /* clear bits above 233 */ + u[14] = u[13] = u[12] = u[11] = u[10] = u[9] = u[8] = 0; + u[7] ^= z << 9; +#endif + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* Fast squaring for polynomials over a 233-bit curve. Assumes reduction + * polynomial with terms {233, 74, 0}. */ +mp_err +ec_GF2m_233_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit *u, *v; + + v = MP_DIGITS(a); + +#ifdef ECL_SIXTY_FOUR_BIT + if (MP_USED(a) < 4) { + return mp_bsqrmod(a, meth->irr_arr, r); + } + if (MP_USED(r) < 8) { + MP_CHECKOK(s_mp_pad(r, 8)); + } + MP_USED(r) = 8; +#else + if (MP_USED(a) < 8) { + return mp_bsqrmod(a, meth->irr_arr, r); + } + if (MP_USED(r) < 15) { + MP_CHECKOK(s_mp_pad(r, 15)); + } + MP_USED(r) = 15; +#endif + u = MP_DIGITS(r); + +#ifdef ECL_THIRTY_TWO_BIT + u[14] = gf2m_SQR0(v[7]); + u[13] = gf2m_SQR1(v[6]); + u[12] = gf2m_SQR0(v[6]); + u[11] = gf2m_SQR1(v[5]); + u[10] = gf2m_SQR0(v[5]); + u[9] = gf2m_SQR1(v[4]); + u[8] = gf2m_SQR0(v[4]); +#endif + u[7] = gf2m_SQR1(v[3]); + u[6] = gf2m_SQR0(v[3]); + u[5] = gf2m_SQR1(v[2]); + u[4] = gf2m_SQR0(v[2]); + u[3] = gf2m_SQR1(v[1]); + u[2] = gf2m_SQR0(v[1]); + u[1] = gf2m_SQR1(v[0]); + u[0] = gf2m_SQR0(v[0]); + return ec_GF2m_233_mod(r, r, meth); + + CLEANUP: + return res; +} + +/* Fast multiplication for polynomials over a 233-bit curve. Assumes + * reduction polynomial with terms {233, 74, 0}. */ +mp_err +ec_GF2m_233_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a3 = 0, a2 = 0, a1 = 0, a0, b3 = 0, b2 = 0, b1 = 0, b0; + +#ifdef ECL_THIRTY_TWO_BIT + mp_digit a7 = 0, a6 = 0, a5 = 0, a4 = 0, b7 = 0, b6 = 0, b5 = 0, b4 = + 0; + mp_digit rm[8]; +#endif + + if (a == b) { + return ec_GF2m_233_sqr(a, r, meth); + } else { + switch (MP_USED(a)) { +#ifdef ECL_THIRTY_TWO_BIT + case 8: + a7 = MP_DIGIT(a, 7); + case 7: + a6 = MP_DIGIT(a, 6); + case 6: + a5 = MP_DIGIT(a, 5); + case 5: + a4 = MP_DIGIT(a, 4); +#endif + case 4: + a3 = MP_DIGIT(a, 3); + case 3: + a2 = MP_DIGIT(a, 2); + case 2: + a1 = MP_DIGIT(a, 1); + default: + a0 = MP_DIGIT(a, 0); + } + switch (MP_USED(b)) { +#ifdef ECL_THIRTY_TWO_BIT + case 8: + b7 = MP_DIGIT(b, 7); + case 7: + b6 = MP_DIGIT(b, 6); + case 6: + b5 = MP_DIGIT(b, 5); + case 5: + b4 = MP_DIGIT(b, 4); +#endif + case 4: + b3 = MP_DIGIT(b, 3); + case 3: + b2 = MP_DIGIT(b, 2); + case 2: + b1 = MP_DIGIT(b, 1); + default: + b0 = MP_DIGIT(b, 0); + } +#ifdef ECL_SIXTY_FOUR_BIT + MP_CHECKOK(s_mp_pad(r, 8)); + s_bmul_4x4(MP_DIGITS(r), a3, a2, a1, a0, b3, b2, b1, b0); + MP_USED(r) = 8; + s_mp_clamp(r); +#else + MP_CHECKOK(s_mp_pad(r, 16)); + s_bmul_4x4(MP_DIGITS(r) + 8, a7, a6, a5, a4, b7, b6, b5, b4); + s_bmul_4x4(MP_DIGITS(r), a3, a2, a1, a0, b3, b2, b1, b0); + s_bmul_4x4(rm, a7 ^ a3, a6 ^ a2, a5 ^ a1, a4 ^ a0, b7 ^ b3, + b6 ^ b2, b5 ^ b1, b4 ^ b0); + rm[7] ^= MP_DIGIT(r, 7) ^ MP_DIGIT(r, 15); + rm[6] ^= MP_DIGIT(r, 6) ^ MP_DIGIT(r, 14); + rm[5] ^= MP_DIGIT(r, 5) ^ MP_DIGIT(r, 13); + rm[4] ^= MP_DIGIT(r, 4) ^ MP_DIGIT(r, 12); + rm[3] ^= MP_DIGIT(r, 3) ^ MP_DIGIT(r, 11); + rm[2] ^= MP_DIGIT(r, 2) ^ MP_DIGIT(r, 10); + rm[1] ^= MP_DIGIT(r, 1) ^ MP_DIGIT(r, 9); + rm[0] ^= MP_DIGIT(r, 0) ^ MP_DIGIT(r, 8); + MP_DIGIT(r, 11) ^= rm[7]; + MP_DIGIT(r, 10) ^= rm[6]; + MP_DIGIT(r, 9) ^= rm[5]; + MP_DIGIT(r, 8) ^= rm[4]; + MP_DIGIT(r, 7) ^= rm[3]; + MP_DIGIT(r, 6) ^= rm[2]; + MP_DIGIT(r, 5) ^= rm[1]; + MP_DIGIT(r, 4) ^= rm[0]; + MP_USED(r) = 16; + s_mp_clamp(r); +#endif + return ec_GF2m_233_mod(r, r, meth); + } + + CLEANUP: + return res; +} + +/* Wire in fast field arithmetic for 233-bit curves. */ +mp_err +ec_group_set_gf2m233(ECGroup *group, ECCurveName name) +{ + group->meth->field_mod = &ec_GF2m_233_mod; + group->meth->field_mul = &ec_GF2m_233_mul; + group->meth->field_sqr = &ec_GF2m_233_sqr; + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ec2_aff.c b/src/share/native/sun/security/ec/impl/ec2_aff.c new file mode 100644 index 0000000000000000000000000000000000000000..bb52cbc97f987a0912163a3ce22a832bbf51556d --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec2_aff.c @@ -0,0 +1,368 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for binary polynomial field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ec2.h" +#include "mplogic.h" +#include "mp_gf2m.h" +#ifndef _KERNEL +#include +#endif + +/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */ +mp_err +ec_GF2m_pt_is_inf_aff(const mp_int *px, const mp_int *py) +{ + + if ((mp_cmp_z(px) == 0) && (mp_cmp_z(py) == 0)) { + return MP_YES; + } else { + return MP_NO; + } + +} + +/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */ +mp_err +ec_GF2m_pt_set_inf_aff(mp_int *px, mp_int *py) +{ + mp_zero(px); + mp_zero(py); + return MP_OKAY; +} + +/* Computes R = P + Q based on IEEE P1363 A.10.2. Elliptic curve points P, + * Q, and R can all be identical. Uses affine coordinates. */ +mp_err +ec_GF2m_pt_add_aff(const mp_int *px, const mp_int *py, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int lambda, tempx, tempy; + + MP_DIGITS(&lambda) = 0; + MP_DIGITS(&tempx) = 0; + MP_DIGITS(&tempy) = 0; + MP_CHECKOK(mp_init(&lambda, FLAG(px))); + MP_CHECKOK(mp_init(&tempx, FLAG(px))); + MP_CHECKOK(mp_init(&tempy, FLAG(px))); + /* if P = inf, then R = Q */ + if (ec_GF2m_pt_is_inf_aff(px, py) == 0) { + MP_CHECKOK(mp_copy(qx, rx)); + MP_CHECKOK(mp_copy(qy, ry)); + res = MP_OKAY; + goto CLEANUP; + } + /* if Q = inf, then R = P */ + if (ec_GF2m_pt_is_inf_aff(qx, qy) == 0) { + MP_CHECKOK(mp_copy(px, rx)); + MP_CHECKOK(mp_copy(py, ry)); + res = MP_OKAY; + goto CLEANUP; + } + /* if px != qx, then lambda = (py+qy) / (px+qx), tempx = a + lambda^2 + * + lambda + px + qx */ + if (mp_cmp(px, qx) != 0) { + MP_CHECKOK(group->meth->field_add(py, qy, &tempy, group->meth)); + MP_CHECKOK(group->meth->field_add(px, qx, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_div(&tempy, &tempx, &lambda, group->meth)); + MP_CHECKOK(group->meth->field_sqr(&lambda, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, &lambda, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, &group->curvea, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, px, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, qx, &tempx, group->meth)); + } else { + /* if py != qy or qx = 0, then R = inf */ + if (((mp_cmp(py, qy) != 0)) || (mp_cmp_z(qx) == 0)) { + mp_zero(rx); + mp_zero(ry); + res = MP_OKAY; + goto CLEANUP; + } + /* lambda = qx + qy / qx */ + MP_CHECKOK(group->meth->field_div(qy, qx, &lambda, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&lambda, qx, &lambda, group->meth)); + /* tempx = a + lambda^2 + lambda */ + MP_CHECKOK(group->meth->field_sqr(&lambda, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, &lambda, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, &group->curvea, &tempx, group->meth)); + } + /* ry = (qx + tempx) * lambda + tempx + qy */ + MP_CHECKOK(group->meth->field_add(qx, &tempx, &tempy, group->meth)); + MP_CHECKOK(group->meth-> + field_mul(&tempy, &lambda, &tempy, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempy, &tempx, &tempy, group->meth)); + MP_CHECKOK(group->meth->field_add(&tempy, qy, ry, group->meth)); + /* rx = tempx */ + MP_CHECKOK(mp_copy(&tempx, rx)); + + CLEANUP: + mp_clear(&lambda); + mp_clear(&tempx); + mp_clear(&tempy); + return res; +} + +/* Computes R = P - Q. Elliptic curve points P, Q, and R can all be + * identical. Uses affine coordinates. */ +mp_err +ec_GF2m_pt_sub_aff(const mp_int *px, const mp_int *py, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int nqy; + + MP_DIGITS(&nqy) = 0; + MP_CHECKOK(mp_init(&nqy, FLAG(px))); + /* nqy = qx+qy */ + MP_CHECKOK(group->meth->field_add(qx, qy, &nqy, group->meth)); + MP_CHECKOK(group->point_add(px, py, qx, &nqy, rx, ry, group)); + CLEANUP: + mp_clear(&nqy); + return res; +} + +/* Computes R = 2P. Elliptic curve points P and R can be identical. Uses + * affine coordinates. */ +mp_err +ec_GF2m_pt_dbl_aff(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group) +{ + return group->point_add(px, py, px, py, rx, ry, group); +} + +/* by default, this routine is unused and thus doesn't need to be compiled */ +#ifdef ECL_ENABLE_GF2M_PT_MUL_AFF +/* Computes R = nP based on IEEE P1363 A.10.3. Elliptic curve points P and + * R can be identical. Uses affine coordinates. */ +mp_err +ec_GF2m_pt_mul_aff(const mp_int *n, const mp_int *px, const mp_int *py, + mp_int *rx, mp_int *ry, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int k, k3, qx, qy, sx, sy; + int b1, b3, i, l; + + MP_DIGITS(&k) = 0; + MP_DIGITS(&k3) = 0; + MP_DIGITS(&qx) = 0; + MP_DIGITS(&qy) = 0; + MP_DIGITS(&sx) = 0; + MP_DIGITS(&sy) = 0; + MP_CHECKOK(mp_init(&k)); + MP_CHECKOK(mp_init(&k3)); + MP_CHECKOK(mp_init(&qx)); + MP_CHECKOK(mp_init(&qy)); + MP_CHECKOK(mp_init(&sx)); + MP_CHECKOK(mp_init(&sy)); + + /* if n = 0 then r = inf */ + if (mp_cmp_z(n) == 0) { + mp_zero(rx); + mp_zero(ry); + res = MP_OKAY; + goto CLEANUP; + } + /* Q = P, k = n */ + MP_CHECKOK(mp_copy(px, &qx)); + MP_CHECKOK(mp_copy(py, &qy)); + MP_CHECKOK(mp_copy(n, &k)); + /* if n < 0 then Q = -Q, k = -k */ + if (mp_cmp_z(n) < 0) { + MP_CHECKOK(group->meth->field_add(&qx, &qy, &qy, group->meth)); + MP_CHECKOK(mp_neg(&k, &k)); + } +#ifdef ECL_DEBUG /* basic double and add method */ + l = mpl_significant_bits(&k) - 1; + MP_CHECKOK(mp_copy(&qx, &sx)); + MP_CHECKOK(mp_copy(&qy, &sy)); + for (i = l - 1; i >= 0; i--) { + /* S = 2S */ + MP_CHECKOK(group->point_dbl(&sx, &sy, &sx, &sy, group)); + /* if k_i = 1, then S = S + Q */ + if (mpl_get_bit(&k, i) != 0) { + MP_CHECKOK(group-> + point_add(&sx, &sy, &qx, &qy, &sx, &sy, group)); + } + } +#else /* double and add/subtract method from + * standard */ + /* k3 = 3 * k */ + MP_CHECKOK(mp_set_int(&k3, 3)); + MP_CHECKOK(mp_mul(&k, &k3, &k3)); + /* S = Q */ + MP_CHECKOK(mp_copy(&qx, &sx)); + MP_CHECKOK(mp_copy(&qy, &sy)); + /* l = index of high order bit in binary representation of 3*k */ + l = mpl_significant_bits(&k3) - 1; + /* for i = l-1 downto 1 */ + for (i = l - 1; i >= 1; i--) { + /* S = 2S */ + MP_CHECKOK(group->point_dbl(&sx, &sy, &sx, &sy, group)); + b3 = MP_GET_BIT(&k3, i); + b1 = MP_GET_BIT(&k, i); + /* if k3_i = 1 and k_i = 0, then S = S + Q */ + if ((b3 == 1) && (b1 == 0)) { + MP_CHECKOK(group-> + point_add(&sx, &sy, &qx, &qy, &sx, &sy, group)); + /* if k3_i = 0 and k_i = 1, then S = S - Q */ + } else if ((b3 == 0) && (b1 == 1)) { + MP_CHECKOK(group-> + point_sub(&sx, &sy, &qx, &qy, &sx, &sy, group)); + } + } +#endif + /* output S */ + MP_CHECKOK(mp_copy(&sx, rx)); + MP_CHECKOK(mp_copy(&sy, ry)); + + CLEANUP: + mp_clear(&k); + mp_clear(&k3); + mp_clear(&qx); + mp_clear(&qy); + mp_clear(&sx); + mp_clear(&sy); + return res; +} +#endif + +/* Validates a point on a GF2m curve. */ +mp_err +ec_GF2m_validate_point(const mp_int *px, const mp_int *py, const ECGroup *group) +{ + mp_err res = MP_NO; + mp_int accl, accr, tmp, pxt, pyt; + + MP_DIGITS(&accl) = 0; + MP_DIGITS(&accr) = 0; + MP_DIGITS(&tmp) = 0; + MP_DIGITS(&pxt) = 0; + MP_DIGITS(&pyt) = 0; + MP_CHECKOK(mp_init(&accl, FLAG(px))); + MP_CHECKOK(mp_init(&accr, FLAG(px))); + MP_CHECKOK(mp_init(&tmp, FLAG(px))); + MP_CHECKOK(mp_init(&pxt, FLAG(px))); + MP_CHECKOK(mp_init(&pyt, FLAG(px))); + + /* 1: Verify that publicValue is not the point at infinity */ + if (ec_GF2m_pt_is_inf_aff(px, py) == MP_YES) { + res = MP_NO; + goto CLEANUP; + } + /* 2: Verify that the coordinates of publicValue are elements + * of the field. + */ + if ((MP_SIGN(px) == MP_NEG) || (mp_cmp(px, &group->meth->irr) >= 0) || + (MP_SIGN(py) == MP_NEG) || (mp_cmp(py, &group->meth->irr) >= 0)) { + res = MP_NO; + goto CLEANUP; + } + /* 3: Verify that publicValue is on the curve. */ + if (group->meth->field_enc) { + group->meth->field_enc(px, &pxt, group->meth); + group->meth->field_enc(py, &pyt, group->meth); + } else { + mp_copy(px, &pxt); + mp_copy(py, &pyt); + } + /* left-hand side: y^2 + x*y */ + MP_CHECKOK( group->meth->field_sqr(&pyt, &accl, group->meth) ); + MP_CHECKOK( group->meth->field_mul(&pxt, &pyt, &tmp, group->meth) ); + MP_CHECKOK( group->meth->field_add(&accl, &tmp, &accl, group->meth) ); + /* right-hand side: x^3 + a*x^2 + b */ + MP_CHECKOK( group->meth->field_sqr(&pxt, &tmp, group->meth) ); + MP_CHECKOK( group->meth->field_mul(&pxt, &tmp, &accr, group->meth) ); + MP_CHECKOK( group->meth->field_mul(&group->curvea, &tmp, &tmp, group->meth) ); + MP_CHECKOK( group->meth->field_add(&tmp, &accr, &accr, group->meth) ); + MP_CHECKOK( group->meth->field_add(&accr, &group->curveb, &accr, group->meth) ); + /* check LHS - RHS == 0 */ + MP_CHECKOK( group->meth->field_add(&accl, &accr, &accr, group->meth) ); + if (mp_cmp_z(&accr) != 0) { + res = MP_NO; + goto CLEANUP; + } + /* 4: Verify that the order of the curve times the publicValue + * is the point at infinity. + */ + MP_CHECKOK( ECPoint_mul(group, &group->order, px, py, &pxt, &pyt) ); + if (ec_GF2m_pt_is_inf_aff(&pxt, &pyt) != MP_YES) { + res = MP_NO; + goto CLEANUP; + } + + res = MP_YES; + +CLEANUP: + mp_clear(&accl); + mp_clear(&accr); + mp_clear(&tmp); + mp_clear(&pxt); + mp_clear(&pyt); + return res; +} diff --git a/src/share/native/sun/security/ec/impl/ec2_mont.c b/src/share/native/sun/security/ec/impl/ec2_mont.c new file mode 100644 index 0000000000000000000000000000000000000000..5cef20f5303c3c2da0fb126bfa7f8863c48453d7 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec2_mont.c @@ -0,0 +1,296 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for binary polynomial field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang-Shantz , + * Stephen Fung , and + * Douglas Stebila , Sun Microsystems Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ec2.h" +#include "mplogic.h" +#include "mp_gf2m.h" +#ifndef _KERNEL +#include +#endif + +/* Compute the x-coordinate x/z for the point 2*(x/z) in Montgomery + * projective coordinates. Uses algorithm Mdouble in appendix of Lopez, J. + * and Dahab, R. "Fast multiplication on elliptic curves over GF(2^m) + * without precomputation". modified to not require precomputation of + * c=b^{2^{m-1}}. */ +static mp_err +gf2m_Mdouble(mp_int *x, mp_int *z, const ECGroup *group, int kmflag) +{ + mp_err res = MP_OKAY; + mp_int t1; + + MP_DIGITS(&t1) = 0; + MP_CHECKOK(mp_init(&t1, kmflag)); + + MP_CHECKOK(group->meth->field_sqr(x, x, group->meth)); + MP_CHECKOK(group->meth->field_sqr(z, &t1, group->meth)); + MP_CHECKOK(group->meth->field_mul(x, &t1, z, group->meth)); + MP_CHECKOK(group->meth->field_sqr(x, x, group->meth)); + MP_CHECKOK(group->meth->field_sqr(&t1, &t1, group->meth)); + MP_CHECKOK(group->meth-> + field_mul(&group->curveb, &t1, &t1, group->meth)); + MP_CHECKOK(group->meth->field_add(x, &t1, x, group->meth)); + + CLEANUP: + mp_clear(&t1); + return res; +} + +/* Compute the x-coordinate x1/z1 for the point (x1/z1)+(x2/x2) in + * Montgomery projective coordinates. Uses algorithm Madd in appendix of + * Lopex, J. and Dahab, R. "Fast multiplication on elliptic curves over + * GF(2^m) without precomputation". */ +static mp_err +gf2m_Madd(const mp_int *x, mp_int *x1, mp_int *z1, mp_int *x2, mp_int *z2, + const ECGroup *group, int kmflag) +{ + mp_err res = MP_OKAY; + mp_int t1, t2; + + MP_DIGITS(&t1) = 0; + MP_DIGITS(&t2) = 0; + MP_CHECKOK(mp_init(&t1, kmflag)); + MP_CHECKOK(mp_init(&t2, kmflag)); + + MP_CHECKOK(mp_copy(x, &t1)); + MP_CHECKOK(group->meth->field_mul(x1, z2, x1, group->meth)); + MP_CHECKOK(group->meth->field_mul(z1, x2, z1, group->meth)); + MP_CHECKOK(group->meth->field_mul(x1, z1, &t2, group->meth)); + MP_CHECKOK(group->meth->field_add(z1, x1, z1, group->meth)); + MP_CHECKOK(group->meth->field_sqr(z1, z1, group->meth)); + MP_CHECKOK(group->meth->field_mul(z1, &t1, x1, group->meth)); + MP_CHECKOK(group->meth->field_add(x1, &t2, x1, group->meth)); + + CLEANUP: + mp_clear(&t1); + mp_clear(&t2); + return res; +} + +/* Compute the x, y affine coordinates from the point (x1, z1) (x2, z2) + * using Montgomery point multiplication algorithm Mxy() in appendix of + * Lopex, J. and Dahab, R. "Fast multiplication on elliptic curves over + * GF(2^m) without precomputation". Returns: 0 on error 1 if return value + * should be the point at infinity 2 otherwise */ +static int +gf2m_Mxy(const mp_int *x, const mp_int *y, mp_int *x1, mp_int *z1, + mp_int *x2, mp_int *z2, const ECGroup *group) +{ + mp_err res = MP_OKAY; + int ret = 0; + mp_int t3, t4, t5; + + MP_DIGITS(&t3) = 0; + MP_DIGITS(&t4) = 0; + MP_DIGITS(&t5) = 0; + MP_CHECKOK(mp_init(&t3, FLAG(x2))); + MP_CHECKOK(mp_init(&t4, FLAG(x2))); + MP_CHECKOK(mp_init(&t5, FLAG(x2))); + + if (mp_cmp_z(z1) == 0) { + mp_zero(x2); + mp_zero(z2); + ret = 1; + goto CLEANUP; + } + + if (mp_cmp_z(z2) == 0) { + MP_CHECKOK(mp_copy(x, x2)); + MP_CHECKOK(group->meth->field_add(x, y, z2, group->meth)); + ret = 2; + goto CLEANUP; + } + + MP_CHECKOK(mp_set_int(&t5, 1)); + if (group->meth->field_enc) { + MP_CHECKOK(group->meth->field_enc(&t5, &t5, group->meth)); + } + + MP_CHECKOK(group->meth->field_mul(z1, z2, &t3, group->meth)); + + MP_CHECKOK(group->meth->field_mul(z1, x, z1, group->meth)); + MP_CHECKOK(group->meth->field_add(z1, x1, z1, group->meth)); + MP_CHECKOK(group->meth->field_mul(z2, x, z2, group->meth)); + MP_CHECKOK(group->meth->field_mul(z2, x1, x1, group->meth)); + MP_CHECKOK(group->meth->field_add(z2, x2, z2, group->meth)); + + MP_CHECKOK(group->meth->field_mul(z2, z1, z2, group->meth)); + MP_CHECKOK(group->meth->field_sqr(x, &t4, group->meth)); + MP_CHECKOK(group->meth->field_add(&t4, y, &t4, group->meth)); + MP_CHECKOK(group->meth->field_mul(&t4, &t3, &t4, group->meth)); + MP_CHECKOK(group->meth->field_add(&t4, z2, &t4, group->meth)); + + MP_CHECKOK(group->meth->field_mul(&t3, x, &t3, group->meth)); + MP_CHECKOK(group->meth->field_div(&t5, &t3, &t3, group->meth)); + MP_CHECKOK(group->meth->field_mul(&t3, &t4, &t4, group->meth)); + MP_CHECKOK(group->meth->field_mul(x1, &t3, x2, group->meth)); + MP_CHECKOK(group->meth->field_add(x2, x, z2, group->meth)); + + MP_CHECKOK(group->meth->field_mul(z2, &t4, z2, group->meth)); + MP_CHECKOK(group->meth->field_add(z2, y, z2, group->meth)); + + ret = 2; + + CLEANUP: + mp_clear(&t3); + mp_clear(&t4); + mp_clear(&t5); + if (res == MP_OKAY) { + return ret; + } else { + return 0; + } +} + +/* Computes R = nP based on algorithm 2P of Lopex, J. and Dahab, R. "Fast + * multiplication on elliptic curves over GF(2^m) without + * precomputation". Elliptic curve points P and R can be identical. Uses + * Montgomery projective coordinates. */ +mp_err +ec_GF2m_pt_mul_mont(const mp_int *n, const mp_int *px, const mp_int *py, + mp_int *rx, mp_int *ry, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int x1, x2, z1, z2; + int i, j; + mp_digit top_bit, mask; + + MP_DIGITS(&x1) = 0; + MP_DIGITS(&x2) = 0; + MP_DIGITS(&z1) = 0; + MP_DIGITS(&z2) = 0; + MP_CHECKOK(mp_init(&x1, FLAG(n))); + MP_CHECKOK(mp_init(&x2, FLAG(n))); + MP_CHECKOK(mp_init(&z1, FLAG(n))); + MP_CHECKOK(mp_init(&z2, FLAG(n))); + + /* if result should be point at infinity */ + if ((mp_cmp_z(n) == 0) || (ec_GF2m_pt_is_inf_aff(px, py) == MP_YES)) { + MP_CHECKOK(ec_GF2m_pt_set_inf_aff(rx, ry)); + goto CLEANUP; + } + + MP_CHECKOK(mp_copy(px, &x1)); /* x1 = px */ + MP_CHECKOK(mp_set_int(&z1, 1)); /* z1 = 1 */ + MP_CHECKOK(group->meth->field_sqr(&x1, &z2, group->meth)); /* z2 = + * x1^2 = + * px^2 */ + MP_CHECKOK(group->meth->field_sqr(&z2, &x2, group->meth)); + MP_CHECKOK(group->meth->field_add(&x2, &group->curveb, &x2, group->meth)); /* x2 + * = + * px^4 + * + + * b + */ + + /* find top-most bit and go one past it */ + i = MP_USED(n) - 1; + j = MP_DIGIT_BIT - 1; + top_bit = 1; + top_bit <<= MP_DIGIT_BIT - 1; + mask = top_bit; + while (!(MP_DIGITS(n)[i] & mask)) { + mask >>= 1; + j--; + } + mask >>= 1; + j--; + + /* if top most bit was at word break, go to next word */ + if (!mask) { + i--; + j = MP_DIGIT_BIT - 1; + mask = top_bit; + } + + for (; i >= 0; i--) { + for (; j >= 0; j--) { + if (MP_DIGITS(n)[i] & mask) { + MP_CHECKOK(gf2m_Madd(px, &x1, &z1, &x2, &z2, group, FLAG(n))); + MP_CHECKOK(gf2m_Mdouble(&x2, &z2, group, FLAG(n))); + } else { + MP_CHECKOK(gf2m_Madd(px, &x2, &z2, &x1, &z1, group, FLAG(n))); + MP_CHECKOK(gf2m_Mdouble(&x1, &z1, group, FLAG(n))); + } + mask >>= 1; + } + j = MP_DIGIT_BIT - 1; + mask = top_bit; + } + + /* convert out of "projective" coordinates */ + i = gf2m_Mxy(px, py, &x1, &z1, &x2, &z2, group); + if (i == 0) { + res = MP_BADARG; + goto CLEANUP; + } else if (i == 1) { + MP_CHECKOK(ec_GF2m_pt_set_inf_aff(rx, ry)); + } else { + MP_CHECKOK(mp_copy(&x2, rx)); + MP_CHECKOK(mp_copy(&z2, ry)); + } + + CLEANUP: + mp_clear(&x1); + mp_clear(&x2); + mp_clear(&z1); + mp_clear(&z2); + return res; +} diff --git a/src/share/native/sun/security/ec/impl/ec_naf.c b/src/share/native/sun/security/ec/impl/ec_naf.c new file mode 100644 index 0000000000000000000000000000000000000000..1d110904d295af34ad282021b1f1fb5662ff613e --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ec_naf.c @@ -0,0 +1,123 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Stephen Fung , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecl-priv.h" + +/* Returns 2^e as an integer. This is meant to be used for small powers of + * two. */ +int +ec_twoTo(int e) +{ + int a = 1; + int i; + + for (i = 0; i < e; i++) { + a *= 2; + } + return a; +} + +/* Computes the windowed non-adjacent-form (NAF) of a scalar. Out should + * be an array of signed char's to output to, bitsize should be the number + * of bits of out, in is the original scalar, and w is the window size. + * NAF is discussed in the paper: D. Hankerson, J. Hernandez and A. + * Menezes, "Software implementation of elliptic curve cryptography over + * binary fields", Proc. CHES 2000. */ +mp_err +ec_compute_wNAF(signed char *out, int bitsize, const mp_int *in, int w) +{ + mp_int k; + mp_err res = MP_OKAY; + int i, twowm1, mask; + + twowm1 = ec_twoTo(w - 1); + mask = 2 * twowm1 - 1; + + MP_DIGITS(&k) = 0; + MP_CHECKOK(mp_init_copy(&k, in)); + + i = 0; + /* Compute wNAF form */ + while (mp_cmp_z(&k) > 0) { + if (mp_isodd(&k)) { + out[i] = MP_DIGIT(&k, 0) & mask; + if (out[i] >= twowm1) + out[i] -= 2 * twowm1; + + /* Subtract off out[i]. Note mp_sub_d only works with + * unsigned digits */ + if (out[i] >= 0) { + mp_sub_d(&k, out[i], &k); + } else { + mp_add_d(&k, -(out[i]), &k); + } + } else { + out[i] = 0; + } + mp_div_2(&k, &k); + i++; + } + /* Zero out the remaining elements of the out array. */ + for (; i < bitsize + 1; i++) { + out[i] = 0; + } + CLEANUP: + mp_clear(&k); + return res; + +} diff --git a/src/share/native/sun/security/ec/impl/ecc_impl.h b/src/share/native/sun/security/ec/impl/ecc_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..95fc93b3e7168ff8e15369449caa285373b2ef35 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecc_impl.h @@ -0,0 +1,275 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1994-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Dr Vipul Gupta and + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _ECC_IMPL_H +#define _ECC_IMPL_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +#ifdef __cplusplus +extern "C" { +#endif + +#include +#include "ecl-exp.h" + +/* + * Multi-platform definitions + */ +#ifdef __linux__ +#define B_FALSE FALSE +#define B_TRUE TRUE +typedef unsigned char uint8_t; +typedef unsigned long ulong_t; +typedef enum { B_FALSE, B_TRUE } boolean_t; +#endif /* __linux__ */ + +#ifdef _WIN32 +typedef unsigned char uint8_t; +typedef unsigned long ulong_t; +typedef enum boolean { B_FALSE, B_TRUE } boolean_t; +#endif /* _WIN32 */ + +#ifndef _KERNEL +#include +#endif /* _KERNEL */ + +#define EC_MAX_DIGEST_LEN 1024 /* max digest that can be signed */ +#define EC_MAX_POINT_LEN 145 /* max len of DER encoded Q */ +#define EC_MAX_VALUE_LEN 72 /* max len of ANSI X9.62 private value d */ +#define EC_MAX_SIG_LEN 144 /* max signature len for supported curves */ +#define EC_MIN_KEY_LEN 112 /* min key length in bits */ +#define EC_MAX_KEY_LEN 571 /* max key length in bits */ +#define EC_MAX_OID_LEN 10 /* max length of OID buffer */ + +/* + * Various structures and definitions from NSS are here. + */ + +#ifdef _KERNEL +#define PORT_ArenaAlloc(a, n, f) kmem_alloc((n), (f)) +#define PORT_ArenaZAlloc(a, n, f) kmem_zalloc((n), (f)) +#define PORT_ArenaGrow(a, b, c, d) NULL +#define PORT_ZAlloc(n, f) kmem_zalloc((n), (f)) +#define PORT_Alloc(n, f) kmem_alloc((n), (f)) +#else +#define PORT_ArenaAlloc(a, n, f) malloc((n)) +#define PORT_ArenaZAlloc(a, n, f) calloc(1, (n)) +#define PORT_ArenaGrow(a, b, c, d) NULL +#define PORT_ZAlloc(n, f) calloc(1, (n)) +#define PORT_Alloc(n, f) malloc((n)) +#endif + +#define PORT_NewArena(b) (char *)12345 +#define PORT_ArenaMark(a) NULL +#define PORT_ArenaUnmark(a, b) +#define PORT_ArenaRelease(a, m) +#define PORT_FreeArena(a, b) +#define PORT_Strlen(s) strlen((s)) +#define PORT_SetError(e) + +#define PRBool boolean_t +#define PR_TRUE B_TRUE +#define PR_FALSE B_FALSE + +#ifdef _KERNEL +#define PORT_Assert ASSERT +#define PORT_Memcpy(t, f, l) bcopy((f), (t), (l)) +#else +#define PORT_Assert assert +#define PORT_Memcpy(t, f, l) memcpy((t), (f), (l)) +#endif + +#define CHECK_OK(func) if (func == NULL) goto cleanup +#define CHECK_SEC_OK(func) if (SECSuccess != (rv = func)) goto cleanup + +typedef enum { + siBuffer = 0, + siClearDataBuffer = 1, + siCipherDataBuffer = 2, + siDERCertBuffer = 3, + siEncodedCertBuffer = 4, + siDERNameBuffer = 5, + siEncodedNameBuffer = 6, + siAsciiNameString = 7, + siAsciiString = 8, + siDEROID = 9, + siUnsignedInteger = 10, + siUTCTime = 11, + siGeneralizedTime = 12 +} SECItemType; + +typedef struct SECItemStr SECItem; + +struct SECItemStr { + SECItemType type; + unsigned char *data; + unsigned int len; +}; + +typedef SECItem SECKEYECParams; + +typedef enum { ec_params_explicit, + ec_params_named +} ECParamsType; + +typedef enum { ec_field_GFp = 1, + ec_field_GF2m +} ECFieldType; + +struct ECFieldIDStr { + int size; /* field size in bits */ + ECFieldType type; + union { + SECItem prime; /* prime p for (GFp) */ + SECItem poly; /* irreducible binary polynomial for (GF2m) */ + } u; + int k1; /* first coefficient of pentanomial or + * the only coefficient of trinomial + */ + int k2; /* two remaining coefficients of pentanomial */ + int k3; +}; +typedef struct ECFieldIDStr ECFieldID; + +struct ECCurveStr { + SECItem a; /* contains octet stream encoding of + * field element (X9.62 section 4.3.3) + */ + SECItem b; + SECItem seed; +}; +typedef struct ECCurveStr ECCurve; + +typedef void PRArenaPool; + +struct ECParamsStr { + PRArenaPool * arena; + ECParamsType type; + ECFieldID fieldID; + ECCurve curve; + SECItem base; + SECItem order; + int cofactor; + SECItem DEREncoding; + ECCurveName name; + SECItem curveOID; +}; +typedef struct ECParamsStr ECParams; + +struct ECPublicKeyStr { + ECParams ecParams; + SECItem publicValue; /* elliptic curve point encoded as + * octet stream. + */ +}; +typedef struct ECPublicKeyStr ECPublicKey; + +struct ECPrivateKeyStr { + ECParams ecParams; + SECItem publicValue; /* encoded ec point */ + SECItem privateValue; /* private big integer */ + SECItem version; /* As per SEC 1, Appendix C, Section C.4 */ +}; +typedef struct ECPrivateKeyStr ECPrivateKey; + +typedef enum _SECStatus { + SECBufferTooSmall = -3, + SECWouldBlock = -2, + SECFailure = -1, + SECSuccess = 0 +} SECStatus; + +#ifdef _KERNEL +#define RNG_GenerateGlobalRandomBytes(p,l) ecc_knzero_random_generator((p), (l)) +#else +/* + This function is no longer required because the random bytes are now + supplied by the caller. Force a failure. +*/ +#define RNG_GenerateGlobalRandomBytes(p,l) SECFailure +#endif +#define CHECK_MPI_OK(func) if (MP_OKAY > (err = func)) goto cleanup +#define MP_TO_SEC_ERROR(err) + +#define SECITEM_TO_MPINT(it, mp) \ + CHECK_MPI_OK(mp_read_unsigned_octets((mp), (it).data, (it).len)) + +extern int ecc_knzero_random_generator(uint8_t *, size_t); +extern ulong_t soft_nzero_random_generator(uint8_t *, ulong_t); + +extern SECStatus EC_DecodeParams(const SECItem *, ECParams **, int); +extern SECItem * SECITEM_AllocItem(PRArenaPool *, SECItem *, unsigned int, int); +extern SECStatus SECITEM_CopyItem(PRArenaPool *, SECItem *, const SECItem *, + int); +extern void SECITEM_FreeItem(SECItem *, boolean_t); +/* This function has been modified to accept an array of random bytes */ +extern SECStatus EC_NewKey(ECParams *ecParams, ECPrivateKey **privKey, + const unsigned char* random, int randomlen, int); +/* This function has been modified to accept an array of random bytes */ +extern SECStatus ECDSA_SignDigest(ECPrivateKey *, SECItem *, const SECItem *, + const unsigned char* random, int randomlen, int); +extern SECStatus ECDSA_VerifyDigest(ECPublicKey *, const SECItem *, + const SECItem *, int); +extern SECStatus ECDH_Derive(SECItem *, ECParams *, SECItem *, boolean_t, + SECItem *, int); + +#ifdef __cplusplus +} +#endif + +#endif /* _ECC_IMPL_H */ diff --git a/src/share/native/sun/security/ec/impl/ecdecode.c b/src/share/native/sun/security/ec/impl/ecdecode.c new file mode 100644 index 0000000000000000000000000000000000000000..d610f3b1b5af279c40cf81ff9e75d0046a4807bf --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecdecode.c @@ -0,0 +1,632 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Elliptic Curve Cryptography library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Dr Vipul Gupta and + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include + +#ifndef _WIN32 +#ifndef __linux__ +#include +#endif /* __linux__ */ +#include +#endif /* _WIN32 */ + +#ifdef _KERNEL +#include +#else +#include +#endif +#include "ec.h" +#include "ecl-curve.h" +#include "ecc_impl.h" + +#define MAX_ECKEY_LEN 72 +#define SEC_ASN1_OBJECT_ID 0x06 + +/* + * Initializes a SECItem from a hexadecimal string + * + * Warning: This function ignores leading 00's, so any leading 00's + * in the hexadecimal string must be optional. + */ +static SECItem * +hexString2SECItem(PRArenaPool *arena, SECItem *item, const char *str, + int kmflag) +{ + int i = 0; + int byteval = 0; + int tmp = strlen(str); + + if ((tmp % 2) != 0) return NULL; + + /* skip leading 00's unless the hex string is "00" */ + while ((tmp > 2) && (str[0] == '0') && (str[1] == '0')) { + str += 2; + tmp -= 2; + } + + item->data = (unsigned char *) PORT_ArenaAlloc(arena, tmp/2, kmflag); + if (item->data == NULL) return NULL; + item->len = tmp/2; + + while (str[i]) { + if ((str[i] >= '0') && (str[i] <= '9')) + tmp = str[i] - '0'; + else if ((str[i] >= 'a') && (str[i] <= 'f')) + tmp = str[i] - 'a' + 10; + else if ((str[i] >= 'A') && (str[i] <= 'F')) + tmp = str[i] - 'A' + 10; + else + return NULL; + + byteval = byteval * 16 + tmp; + if ((i % 2) != 0) { + item->data[i/2] = byteval; + byteval = 0; + } + i++; + } + + return item; +} + +static SECStatus +gf_populate_params(ECCurveName name, ECFieldType field_type, ECParams *params, + int kmflag) +{ + SECStatus rv = SECFailure; + const ECCurveParams *curveParams; + /* 2 ['0'+'4'] + MAX_ECKEY_LEN * 2 [x,y] * 2 [hex string] + 1 ['\0'] */ + char genenc[3 + 2 * 2 * MAX_ECKEY_LEN]; + + if ((name < ECCurve_noName) || (name > ECCurve_pastLastCurve)) goto cleanup; + params->name = name; + curveParams = ecCurve_map[params->name]; + CHECK_OK(curveParams); + params->fieldID.size = curveParams->size; + params->fieldID.type = field_type; + if (field_type == ec_field_GFp) { + CHECK_OK(hexString2SECItem(NULL, ¶ms->fieldID.u.prime, + curveParams->irr, kmflag)); + } else { + CHECK_OK(hexString2SECItem(NULL, ¶ms->fieldID.u.poly, + curveParams->irr, kmflag)); + } + CHECK_OK(hexString2SECItem(NULL, ¶ms->curve.a, + curveParams->curvea, kmflag)); + CHECK_OK(hexString2SECItem(NULL, ¶ms->curve.b, + curveParams->curveb, kmflag)); + genenc[0] = '0'; + genenc[1] = '4'; + genenc[2] = '\0'; + strcat(genenc, curveParams->genx); + strcat(genenc, curveParams->geny); + CHECK_OK(hexString2SECItem(NULL, ¶ms->base, genenc, kmflag)); + CHECK_OK(hexString2SECItem(NULL, ¶ms->order, + curveParams->order, kmflag)); + params->cofactor = curveParams->cofactor; + + rv = SECSuccess; + +cleanup: + return rv; +} + +ECCurveName SECOID_FindOIDTag(const SECItem *); + +SECStatus +EC_FillParams(PRArenaPool *arena, const SECItem *encodedParams, + ECParams *params, int kmflag) +{ + SECStatus rv = SECFailure; + ECCurveName tag; + SECItem oid = { siBuffer, NULL, 0}; + +#if EC_DEBUG + int i; + + printf("Encoded params in EC_DecodeParams: "); + for (i = 0; i < encodedParams->len; i++) { + printf("%02x:", encodedParams->data[i]); + } + printf("\n"); +#endif + + if ((encodedParams->len != ANSI_X962_CURVE_OID_TOTAL_LEN) && + (encodedParams->len != SECG_CURVE_OID_TOTAL_LEN)) { + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return SECFailure; + }; + + oid.len = encodedParams->len - 2; + oid.data = encodedParams->data + 2; + if ((encodedParams->data[0] != SEC_ASN1_OBJECT_ID) || + ((tag = SECOID_FindOIDTag(&oid)) == ECCurve_noName)) { + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); + return SECFailure; + } + + params->arena = arena; + params->cofactor = 0; + params->type = ec_params_named; + params->name = ECCurve_noName; + + /* For named curves, fill out curveOID */ + params->curveOID.len = oid.len; + params->curveOID.data = (unsigned char *) PORT_ArenaAlloc(NULL, oid.len, + kmflag); + if (params->curveOID.data == NULL) goto cleanup; + memcpy(params->curveOID.data, oid.data, oid.len); + +#if EC_DEBUG +#ifndef SECOID_FindOIDTagDescription + printf("Curve: %s\n", ecCurve_map[tag]->text); +#else + printf("Curve: %s\n", SECOID_FindOIDTagDescription(tag)); +#endif +#endif + + switch (tag) { + + /* Binary curves */ + + case ECCurve_X9_62_CHAR2_PNB163V1: + /* Populate params for c2pnb163v1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB163V1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB163V2: + /* Populate params for c2pnb163v2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB163V2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB163V3: + /* Populate params for c2pnb163v3 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB163V3, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB176V1: + /* Populate params for c2pnb176v1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB176V1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB191V1: + /* Populate params for c2tnb191v1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB191V1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB191V2: + /* Populate params for c2tnb191v2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB191V2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB191V3: + /* Populate params for c2tnb191v3 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB191V3, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB208W1: + /* Populate params for c2pnb208w1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB208W1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB239V1: + /* Populate params for c2tnb239v1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB239V1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB239V2: + /* Populate params for c2tnb239v2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB239V2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB239V3: + /* Populate params for c2tnb239v3 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB239V3, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB272W1: + /* Populate params for c2pnb272w1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB272W1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB304W1: + /* Populate params for c2pnb304w1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB304W1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB359V1: + /* Populate params for c2tnb359v1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB359V1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_PNB368W1: + /* Populate params for c2pnb368w1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_PNB368W1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_X9_62_CHAR2_TNB431R1: + /* Populate params for c2tnb431r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_CHAR2_TNB431R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_113R1: + /* Populate params for sect113r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_113R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_113R2: + /* Populate params for sect113r2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_113R2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_131R1: + /* Populate params for sect131r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_131R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_131R2: + /* Populate params for sect131r2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_131R2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_163K1: + /* Populate params for sect163k1 + * (the NIST K-163 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_163K1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_163R1: + /* Populate params for sect163r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_163R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_163R2: + /* Populate params for sect163r2 + * (the NIST B-163 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_163R2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_193R1: + /* Populate params for sect193r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_193R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_193R2: + /* Populate params for sect193r2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_193R2, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_233K1: + /* Populate params for sect233k1 + * (the NIST K-233 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_233K1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_233R1: + /* Populate params for sect233r1 + * (the NIST B-233 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_233R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_239K1: + /* Populate params for sect239k1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_239K1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_283K1: + /* Populate params for sect283k1 + * (the NIST K-283 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_283K1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_283R1: + /* Populate params for sect283r1 + * (the NIST B-283 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_283R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_409K1: + /* Populate params for sect409k1 + * (the NIST K-409 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_409K1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_409R1: + /* Populate params for sect409r1 + * (the NIST B-409 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_409R1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_571K1: + /* Populate params for sect571k1 + * (the NIST K-571 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_571K1, ec_field_GF2m, + params, kmflag) ); + break; + + case ECCurve_SECG_CHAR2_571R1: + /* Populate params for sect571r1 + * (the NIST B-571 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_CHAR2_571R1, ec_field_GF2m, + params, kmflag) ); + break; + + /* Prime curves */ + + case ECCurve_X9_62_PRIME_192V1: + /* Populate params for prime192v1 aka secp192r1 + * (the NIST P-192 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_192V1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_X9_62_PRIME_192V2: + /* Populate params for prime192v2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_192V2, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_X9_62_PRIME_192V3: + /* Populate params for prime192v3 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_192V3, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_X9_62_PRIME_239V1: + /* Populate params for prime239v1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_239V1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_X9_62_PRIME_239V2: + /* Populate params for prime239v2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_239V2, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_X9_62_PRIME_239V3: + /* Populate params for prime239v3 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_239V3, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_X9_62_PRIME_256V1: + /* Populate params for prime256v1 aka secp256r1 + * (the NIST P-256 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_X9_62_PRIME_256V1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_112R1: + /* Populate params for secp112r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_112R1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_112R2: + /* Populate params for secp112r2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_112R2, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_128R1: + /* Populate params for secp128r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_128R1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_128R2: + /* Populate params for secp128r2 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_128R2, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_160K1: + /* Populate params for secp160k1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_160K1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_160R1: + /* Populate params for secp160r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_160R1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_160R2: + /* Populate params for secp160r1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_160R2, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_192K1: + /* Populate params for secp192k1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_192K1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_224K1: + /* Populate params for secp224k1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_224K1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_224R1: + /* Populate params for secp224r1 + * (the NIST P-224 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_224R1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_256K1: + /* Populate params for secp256k1 */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_256K1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_384R1: + /* Populate params for secp384r1 + * (the NIST P-384 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_384R1, ec_field_GFp, + params, kmflag) ); + break; + + case ECCurve_SECG_PRIME_521R1: + /* Populate params for secp521r1 + * (the NIST P-521 curve) + */ + CHECK_SEC_OK( gf_populate_params(ECCurve_SECG_PRIME_521R1, ec_field_GFp, + params, kmflag) ); + break; + + default: + break; + }; + +cleanup: + if (!params->cofactor) { + PORT_SetError(SEC_ERROR_UNSUPPORTED_ELLIPTIC_CURVE); +#if EC_DEBUG + printf("Unrecognized curve, returning NULL params\n"); +#endif + } + + return rv; +} + +SECStatus +EC_DecodeParams(const SECItem *encodedParams, ECParams **ecparams, int kmflag) +{ + PRArenaPool *arena; + ECParams *params; + SECStatus rv = SECFailure; + + /* Initialize an arena for the ECParams structure */ + if (!(arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE))) + return SECFailure; + + params = (ECParams *)PORT_ArenaZAlloc(NULL, sizeof(ECParams), kmflag); + if (!params) { + PORT_FreeArena(NULL, B_TRUE); + return SECFailure; + } + + /* Copy the encoded params */ + SECITEM_AllocItem(arena, &(params->DEREncoding), encodedParams->len, + kmflag); + memcpy(params->DEREncoding.data, encodedParams->data, encodedParams->len); + + /* Fill out the rest of the ECParams structure based on + * the encoded params + */ + rv = EC_FillParams(NULL, encodedParams, params, kmflag); + if (rv == SECFailure) { + PORT_FreeArena(NULL, B_TRUE); + return SECFailure; + } else { + *ecparams = params;; + return SECSuccess; + } +} diff --git a/src/share/native/sun/security/ec/impl/ecl-curve.h b/src/share/native/sun/security/ec/impl/ecl-curve.h new file mode 100644 index 0000000000000000000000000000000000000000..bb7f9a7d46600fa39f29e88cb51ccdd0ffa46df4 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl-curve.h @@ -0,0 +1,710 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _ECL_CURVE_H +#define _ECL_CURVE_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecl-exp.h" +#ifndef _KERNEL +#include +#endif + +/* NIST prime curves */ +static const ECCurveParams ecCurve_NIST_P192 = { + "NIST-P192", ECField_GFp, 192, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", + "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", + "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", + "07192B95FFC8DA78631011ED6B24CDD573F977A11E794811", + "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", 1 +}; + +static const ECCurveParams ecCurve_NIST_P224 = { + "NIST-P224", ECField_GFp, 224, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", + "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", + "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", + "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", 1 +}; + +static const ECCurveParams ecCurve_NIST_P256 = { + "NIST-P256", ECField_GFp, 256, + "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", + "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", + "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", + "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", 1 +}; + +static const ECCurveParams ecCurve_NIST_P384 = { + "NIST-P384", ECField_GFp, 384, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", + "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", + 1 +}; + +static const ECCurveParams ecCurve_NIST_P521 = { + "NIST-P521", ECField_GFp, 521, + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", + "0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", + 1 +}; + +/* NIST binary curves */ +static const ECCurveParams ecCurve_NIST_K163 = { + "NIST-K163", ECField_GF2m, 163, + "0800000000000000000000000000000000000000C9", + "000000000000000000000000000000000000000001", + "000000000000000000000000000000000000000001", + "02FE13C0537BBC11ACAA07D793DE4E6D5E5C94EEE8", + "0289070FB05D38FF58321F2E800536D538CCDAA3D9", + "04000000000000000000020108A2E0CC0D99F8A5EF", 2 +}; + +static const ECCurveParams ecCurve_NIST_B163 = { + "NIST-B163", ECField_GF2m, 163, + "0800000000000000000000000000000000000000C9", + "000000000000000000000000000000000000000001", + "020A601907B8C953CA1481EB10512F78744A3205FD", + "03F0EBA16286A2D57EA0991168D4994637E8343E36", + "00D51FBC6C71A0094FA2CDD545B11C5C0C797324F1", + "040000000000000000000292FE77E70C12A4234C33", 2 +}; + +static const ECCurveParams ecCurve_NIST_K233 = { + "NIST-K233", ECField_GF2m, 233, + "020000000000000000000000000000000000000004000000000000000001", + "000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000001", + "017232BA853A7E731AF129F22FF4149563A419C26BF50A4C9D6EEFAD6126", + "01DB537DECE819B7F70F555A67C427A8CD9BF18AEB9B56E0C11056FAE6A3", + "008000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF", 4 +}; + +static const ECCurveParams ecCurve_NIST_B233 = { + "NIST-B233", ECField_GF2m, 233, + "020000000000000000000000000000000000000004000000000000000001", + "000000000000000000000000000000000000000000000000000000000001", + "0066647EDE6C332C7F8C0923BB58213B333B20E9CE4281FE115F7D8F90AD", + "00FAC9DFCBAC8313BB2139F1BB755FEF65BC391F8B36F8F8EB7371FD558B", + "01006A08A41903350678E58528BEBF8A0BEFF867A7CA36716F7E01F81052", + "01000000000000000000000000000013E974E72F8A6922031D2603CFE0D7", 2 +}; + +static const ECCurveParams ecCurve_NIST_K283 = { + "NIST-K283", ECField_GF2m, 283, + "0800000000000000000000000000000000000000000000000000000000000000000010A1", + "000000000000000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000000000000000001", + "0503213F78CA44883F1A3B8162F188E553CD265F23C1567A16876913B0C2AC2458492836", + "01CCDA380F1C9E318D90F95D07E5426FE87E45C0E8184698E45962364E34116177DD2259", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61", 4 +}; + +static const ECCurveParams ecCurve_NIST_B283 = { + "NIST-B283", ECField_GF2m, 283, + "0800000000000000000000000000000000000000000000000000000000000000000010A1", + "000000000000000000000000000000000000000000000000000000000000000000000001", + "027B680AC8B8596DA5A4AF8A19A0303FCA97FD7645309FA2A581485AF6263E313B79A2F5", + "05F939258DB7DD90E1934F8C70B0DFEC2EED25B8557EAC9C80E2E198F8CDBECD86B12053", + "03676854FE24141CB98FE6D4B20D02B4516FF702350EDDB0826779C813F0DF45BE8112F4", + "03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307", 2 +}; + +static const ECCurveParams ecCurve_NIST_K409 = { + "NIST-K409", ECField_GF2m, 409, + "02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001", + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "0060F05F658F49C1AD3AB1890F7184210EFD0987E307C84C27ACCFB8F9F67CC2C460189EB5AAAA62EE222EB1B35540CFE9023746", + "01E369050B7C4E42ACBA1DACBF04299C3460782F918EA427E6325165E9EA10E3DA5F6C42E9C55215AA9CA27A5863EC48D8E0286B", + "007FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF", 4 +}; + +static const ECCurveParams ecCurve_NIST_B409 = { + "NIST-B409", ECField_GF2m, 409, + "02000000000000000000000000000000000000000000000000000000000000000000000000000000008000000000000000000001", + "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "0021A5C2C8EE9FEB5C4B9A753B7B476B7FD6422EF1F3DD674761FA99D6AC27C8A9A197B272822F6CD57A55AA4F50AE317B13545F", + "015D4860D088DDB3496B0C6064756260441CDE4AF1771D4DB01FFE5B34E59703DC255A868A1180515603AEAB60794E54BB7996A7", + "0061B1CFAB6BE5F32BBFA78324ED106A7636B9C5A7BD198D0158AA4F5488D08F38514F1FDF4B4F40D2181B3681C364BA0273C706", + "010000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173", 2 +}; + +static const ECCurveParams ecCurve_NIST_K571 = { + "NIST-K571", ECField_GF2m, 571, + "080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "026EB7A859923FBC82189631F8103FE4AC9CA2970012D5D46024804801841CA44370958493B205E647DA304DB4CEB08CBBD1BA39494776FB988B47174DCA88C7E2945283A01C8972", + "0349DC807F4FBF374F4AEADE3BCA95314DD58CEC9F307A54FFC61EFC006D8A2C9D4979C0AC44AEA74FBEBBB9F772AEDCB620B01A7BA7AF1B320430C8591984F601CD4C143EF1C7A3", + "020000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001", 4 +}; + +static const ECCurveParams ecCurve_NIST_B571 = { + "NIST-B571", ECField_GF2m, 571, + "080000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000425", + "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001", + "02F40E7E2221F295DE297117B7F3D62F5C6A97FFCB8CEFF1CD6BA8CE4A9A18AD84FFABBD8EFA59332BE7AD6756A66E294AFD185A78FF12AA520E4DE739BACA0C7FFEFF7F2955727A", + "0303001D34B856296C16C0D40D3CD7750A93D1D2955FA80AA5F40FC8DB7B2ABDBDE53950F4C0D293CDD711A35B67FB1499AE60038614F1394ABFA3B4C850D927E1E7769C8EEC2D19", + "037BF27342DA639B6DCCFFFEB73D69D78C6C27A6009CBBCA1980F8533921E8A684423E43BAB08A576291AF8F461BB2A8B3531D2F0485C19B16E2F1516E23DD3C1A4827AF1B8AC15B", + "03FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47", 2 +}; + +/* ANSI X9.62 prime curves */ +static const ECCurveParams ecCurve_X9_62_PRIME_192V2 = { + "X9.62 P-192V2", ECField_GFp, 192, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", + "CC22D6DFB95C6B25E49C0D6364A4E5980C393AA21668D953", + "EEA2BAE7E1497842F2DE7769CFE9C989C072AD696F48034A", + "6574D11D69B6EC7A672BB82A083DF2F2B0847DE970B2DE15", + "FFFFFFFFFFFFFFFFFFFFFFFE5FB1A724DC80418648D8DD31", 1 +}; + +static const ECCurveParams ecCurve_X9_62_PRIME_192V3 = { + "X9.62 P-192V3", ECField_GFp, 192, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", + "22123DC2395A05CAA7423DAECCC94760A7D462256BD56916", + "7D29778100C65A1DA1783716588DCE2B8B4AEE8E228F1896", + "38A90F22637337334B49DCB66A6DC8F9978ACA7648A943B0", + "FFFFFFFFFFFFFFFFFFFFFFFF7A62D031C83F4294F640EC13", 1 +}; + +static const ECCurveParams ecCurve_X9_62_PRIME_239V1 = { + "X9.62 P-239V1", ECField_GFp, 239, + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", + "6B016C3BDCF18941D0D654921475CA71A9DB2FB27D1D37796185C2942C0A", + "0FFA963CDCA8816CCC33B8642BEDF905C3D358573D3F27FBBD3B3CB9AAAF", + "7DEBE8E4E90A5DAE6E4054CA530BA04654B36818CE226B39FCCB7B02F1AE", + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF9E5E9A9F5D9071FBD1522688909D0B", 1 +}; + +static const ECCurveParams ecCurve_X9_62_PRIME_239V2 = { + "X9.62 P-239V2", ECField_GFp, 239, + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", + "617FAB6832576CBBFED50D99F0249C3FEE58B94BA0038C7AE84C8C832F2C", + "38AF09D98727705120C921BB5E9E26296A3CDCF2F35757A0EAFD87B830E7", + "5B0125E4DBEA0EC7206DA0FC01D9B081329FB555DE6EF460237DFF8BE4BA", + "7FFFFFFFFFFFFFFFFFFFFFFF800000CFA7E8594377D414C03821BC582063", 1 +}; + +static const ECCurveParams ecCurve_X9_62_PRIME_239V3 = { + "X9.62 P-239V3", ECField_GFp, 239, + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", + "255705FA2A306654B1F4CB03D6A750A30C250102D4988717D9BA15AB6D3E", + "6768AE8E18BB92CFCF005C949AA2C6D94853D0E660BBF854B1C9505FE95A", + "1607E6898F390C06BC1D552BAD226F3B6FCFE48B6E818499AF18E3ED6CF3", + "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF975DEB41B3A6057C3C432146526551", 1 +}; + +/* ANSI X9.62 binary curves */ +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB163V1 = { + "X9.62 C2-PNB163V1", ECField_GF2m, 163, + "080000000000000000000000000000000000000107", + "072546B5435234A422E0789675F432C89435DE5242", + "00C9517D06D5240D3CFF38C74B20B6CD4D6F9DD4D9", + "07AF69989546103D79329FCC3D74880F33BBE803CB", + "01EC23211B5966ADEA1D3F87F7EA5848AEF0B7CA9F", + "0400000000000000000001E60FC8821CC74DAEAFC1", 2 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB163V2 = { + "X9.62 C2-PNB163V2", ECField_GF2m, 163, + "080000000000000000000000000000000000000107", + "0108B39E77C4B108BED981ED0E890E117C511CF072", + "0667ACEB38AF4E488C407433FFAE4F1C811638DF20", + "0024266E4EB5106D0A964D92C4860E2671DB9B6CC5", + "079F684DDF6684C5CD258B3890021B2386DFD19FC5", + "03FFFFFFFFFFFFFFFFFFFDF64DE1151ADBB78F10A7", 2 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB163V3 = { + "X9.62 C2-PNB163V3", ECField_GF2m, 163, + "080000000000000000000000000000000000000107", + "07A526C63D3E25A256A007699F5447E32AE456B50E", + "03F7061798EB99E238FD6F1BF95B48FEEB4854252B", + "02F9F87B7C574D0BDECF8A22E6524775F98CDEBDCB", + "05B935590C155E17EA48EB3FF3718B893DF59A05D0", + "03FFFFFFFFFFFFFFFFFFFE1AEE140F110AFF961309", 2 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB176V1 = { + "X9.62 C2-PNB176V1", ECField_GF2m, 176, + "0100000000000000000000000000000000080000000007", + "E4E6DB2995065C407D9D39B8D0967B96704BA8E9C90B", + "5DDA470ABE6414DE8EC133AE28E9BBD7FCEC0AE0FFF2", + "8D16C2866798B600F9F08BB4A8E860F3298CE04A5798", + "6FA4539C2DADDDD6BAB5167D61B436E1D92BB16A562C", + "00010092537397ECA4F6145799D62B0A19CE06FE26AD", 0xFF6E +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB191V1 = { + "X9.62 C2-TNB191V1", ECField_GF2m, 191, + "800000000000000000000000000000000000000000000201", + "2866537B676752636A68F56554E12640276B649EF7526267", + "2E45EF571F00786F67B0081B9495A3D95462F5DE0AA185EC", + "36B3DAF8A23206F9C4F299D7B21A9C369137F2C84AE1AA0D", + "765BE73433B3F95E332932E70EA245CA2418EA0EF98018FB", + "40000000000000000000000004A20E90C39067C893BBB9A5", 2 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB191V2 = { + "X9.62 C2-TNB191V2", ECField_GF2m, 191, + "800000000000000000000000000000000000000000000201", + "401028774D7777C7B7666D1366EA432071274F89FF01E718", + "0620048D28BCBD03B6249C99182B7C8CD19700C362C46A01", + "3809B2B7CC1B28CC5A87926AAD83FD28789E81E2C9E3BF10", + "17434386626D14F3DBF01760D9213A3E1CF37AEC437D668A", + "20000000000000000000000050508CB89F652824E06B8173", 4 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB191V3 = { + "X9.62 C2-TNB191V3", ECField_GF2m, 191, + "800000000000000000000000000000000000000000000201", + "6C01074756099122221056911C77D77E77A777E7E7E77FCB", + "71FE1AF926CF847989EFEF8DB459F66394D90F32AD3F15E8", + "375D4CE24FDE434489DE8746E71786015009E66E38A926DD", + "545A39176196575D985999366E6AD34CE0A77CD7127B06BE", + "155555555555555555555555610C0B196812BFB6288A3EA3", 6 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB208W1 = { + "X9.62 C2-PNB208W1", ECField_GF2m, 208, + "010000000000000000000000000000000800000000000000000007", + "0000000000000000000000000000000000000000000000000000", + "C8619ED45A62E6212E1160349E2BFA844439FAFC2A3FD1638F9E", + "89FDFBE4ABE193DF9559ECF07AC0CE78554E2784EB8C1ED1A57A", + "0F55B51A06E78E9AC38A035FF520D8B01781BEB1A6BB08617DE3", + "000101BAF95C9723C57B6C21DA2EFF2D5ED588BDD5717E212F9D", 0xFE48 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB239V1 = { + "X9.62 C2-TNB239V1", ECField_GF2m, 239, + "800000000000000000000000000000000000000000000000001000000001", + "32010857077C5431123A46B808906756F543423E8D27877578125778AC76", + "790408F2EEDAF392B012EDEFB3392F30F4327C0CA3F31FC383C422AA8C16", + "57927098FA932E7C0A96D3FD5B706EF7E5F5C156E16B7E7C86038552E91D", + "61D8EE5077C33FECF6F1A16B268DE469C3C7744EA9A971649FC7A9616305", + "2000000000000000000000000000000F4D42FFE1492A4993F1CAD666E447", 4 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB239V2 = { + "X9.62 C2-TNB239V2", ECField_GF2m, 239, + "800000000000000000000000000000000000000000000000001000000001", + "4230017757A767FAE42398569B746325D45313AF0766266479B75654E65F", + "5037EA654196CFF0CD82B2C14A2FCF2E3FF8775285B545722F03EACDB74B", + "28F9D04E900069C8DC47A08534FE76D2B900B7D7EF31F5709F200C4CA205", + "5667334C45AFF3B5A03BAD9DD75E2C71A99362567D5453F7FA6E227EC833", + "1555555555555555555555555555553C6F2885259C31E3FCDF154624522D", 6 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB239V3 = { + "X9.62 C2-TNB239V3", ECField_GF2m, 239, + "800000000000000000000000000000000000000000000000001000000001", + "01238774666A67766D6676F778E676B66999176666E687666D8766C66A9F", + "6A941977BA9F6A435199ACFC51067ED587F519C5ECB541B8E44111DE1D40", + "70F6E9D04D289C4E89913CE3530BFDE903977D42B146D539BF1BDE4E9C92", + "2E5A0EAF6E5E1305B9004DCE5C0ED7FE59A35608F33837C816D80B79F461", + "0CCCCCCCCCCCCCCCCCCCCCCCCCCCCCAC4912D2D9DF903EF9888B8A0E4CFF", 0xA +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB272W1 = { + "X9.62 C2-PNB272W1", ECField_GF2m, 272, + "010000000000000000000000000000000000000000000000000000010000000000000B", + "91A091F03B5FBA4AB2CCF49C4EDD220FB028712D42BE752B2C40094DBACDB586FB20", + "7167EFC92BB2E3CE7C8AAAFF34E12A9C557003D7C73A6FAF003F99F6CC8482E540F7", + "6108BABB2CEEBCF787058A056CBE0CFE622D7723A289E08A07AE13EF0D10D171DD8D", + "10C7695716851EEF6BA7F6872E6142FBD241B830FF5EFCACECCAB05E02005DDE9D23", + "000100FAF51354E0E39E4892DF6E319C72C8161603FA45AA7B998A167B8F1E629521", + 0xFF06 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB304W1 = { + "X9.62 C2-PNB304W1", ECField_GF2m, 304, + "010000000000000000000000000000000000000000000000000000000000000000000000000807", + "FD0D693149A118F651E6DCE6802085377E5F882D1B510B44160074C1288078365A0396C8E681", + "BDDB97E555A50A908E43B01C798EA5DAA6788F1EA2794EFCF57166B8C14039601E55827340BE", + "197B07845E9BE2D96ADB0F5F3C7F2CFFBD7A3EB8B6FEC35C7FD67F26DDF6285A644F740A2614", + "E19FBEB76E0DA171517ECF401B50289BF014103288527A9B416A105E80260B549FDC1B92C03B", + "000101D556572AABAC800101D556572AABAC8001022D5C91DD173F8FB561DA6899164443051D", 0xFE2E +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB359V1 = { + "X9.62 C2-TNB359V1", ECField_GF2m, 359, + "800000000000000000000000000000000000000000000000000000000000000000000000100000000000000001", + "5667676A654B20754F356EA92017D946567C46675556F19556A04616B567D223A5E05656FB549016A96656A557", + "2472E2D0197C49363F1FE7F5B6DB075D52B6947D135D8CA445805D39BC345626089687742B6329E70680231988", + "3C258EF3047767E7EDE0F1FDAA79DAEE3841366A132E163ACED4ED2401DF9C6BDCDE98E8E707C07A2239B1B097", + "53D7E08529547048121E9C95F3791DD804963948F34FAE7BF44EA82365DC7868FE57E4AE2DE211305A407104BD", + "01AF286BCA1AF286BCA1AF286BCA1AF286BCA1AF286BC9FB8F6B85C556892C20A7EB964FE7719E74F490758D3B", 0x4C +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_PNB368W1 = { + "X9.62 C2-PNB368W1", ECField_GF2m, 368, + "0100000000000000000000000000000000000000000000000000000000000000000000002000000000000000000007", + "E0D2EE25095206F5E2A4F9ED229F1F256E79A0E2B455970D8D0D865BD94778C576D62F0AB7519CCD2A1A906AE30D", + "FC1217D4320A90452C760A58EDCD30C8DD069B3C34453837A34ED50CB54917E1C2112D84D164F444F8F74786046A", + "1085E2755381DCCCE3C1557AFA10C2F0C0C2825646C5B34A394CBCFA8BC16B22E7E789E927BE216F02E1FB136A5F", + "7B3EB1BDDCBA62D5D8B2059B525797FC73822C59059C623A45FF3843CEE8F87CD1855ADAA81E2A0750B80FDA2310", + "00010090512DA9AF72B08349D98A5DD4C7B0532ECA51CE03E2D10F3B7AC579BD87E909AE40A6F131E9CFCE5BD967", 0xFF70 +}; + +static const ECCurveParams ecCurve_X9_62_CHAR2_TNB431R1 = { + "X9.62 C2-TNB431R1", ECField_GF2m, 431, + "800000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000001", + "1A827EF00DD6FC0E234CAF046C6A5D8A85395B236CC4AD2CF32A0CADBDC9DDF620B0EB9906D0957F6C6FEACD615468DF104DE296CD8F", + "10D9B4A3D9047D8B154359ABFB1B7F5485B04CEB868237DDC9DEDA982A679A5A919B626D4E50A8DD731B107A9962381FB5D807BF2618", + "120FC05D3C67A99DE161D2F4092622FECA701BE4F50F4758714E8A87BBF2A658EF8C21E7C5EFE965361F6C2999C0C247B0DBD70CE6B7", + "20D0AF8903A96F8D5FA2C255745D3C451B302C9346D9B7E485E7BCE41F6B591F3E8F6ADDCBB0BC4C2F947A7DE1A89B625D6A598B3760", + "0340340340340340340340340340340340340340340340340340340323C313FAB50589703B5EC68D3587FEC60D161CC149C1AD4A91", 0x2760 +}; + +/* SEC2 prime curves */ +static const ECCurveParams ecCurve_SECG_PRIME_112R1 = { + "SECP-112R1", ECField_GFp, 112, + "DB7C2ABF62E35E668076BEAD208B", + "DB7C2ABF62E35E668076BEAD2088", + "659EF8BA043916EEDE8911702B22", + "09487239995A5EE76B55F9C2F098", + "A89CE5AF8724C0A23E0E0FF77500", + "DB7C2ABF62E35E7628DFAC6561C5", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_112R2 = { + "SECP-112R2", ECField_GFp, 112, + "DB7C2ABF62E35E668076BEAD208B", + "6127C24C05F38A0AAAF65C0EF02C", + "51DEF1815DB5ED74FCC34C85D709", + "4BA30AB5E892B4E1649DD0928643", + "adcd46f5882e3747def36e956e97", + "36DF0AAFD8B8D7597CA10520D04B", 4 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_128R1 = { + "SECP-128R1", ECField_GFp, 128, + "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", + "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", + "E87579C11079F43DD824993C2CEE5ED3", + "161FF7528B899B2D0C28607CA52C5B86", + "CF5AC8395BAFEB13C02DA292DDED7A83", + "FFFFFFFE0000000075A30D1B9038A115", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_128R2 = { + "SECP-128R2", ECField_GFp, 128, + "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", + "D6031998D1B3BBFEBF59CC9BBFF9AEE1", + "5EEEFCA380D02919DC2C6558BB6D8A5D", + "7B6AA5D85E572983E6FB32A7CDEBC140", + "27B6916A894D3AEE7106FE805FC34B44", + "3FFFFFFF7FFFFFFFBE0024720613B5A3", 4 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_160K1 = { + "SECP-160K1", ECField_GFp, 160, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", + "0000000000000000000000000000000000000000", + "0000000000000000000000000000000000000007", + "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", + "938CF935318FDCED6BC28286531733C3F03C4FEE", + "0100000000000000000001B8FA16DFAB9ACA16B6B3", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_160R1 = { + "SECP-160R1", ECField_GFp, 160, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", + "1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", + "4A96B5688EF573284664698968C38BB913CBFC82", + "23A628553168947D59DCC912042351377AC5FB32", + "0100000000000000000001F4C8F927AED3CA752257", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_160R2 = { + "SECP-160R2", ECField_GFp, 160, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70", + "B4E134D3FB59EB8BAB57274904664D5AF50388BA", + "52DCB034293A117E1F4FF11B30F7199D3144CE6D", + "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E", + "0100000000000000000000351EE786A818F3A1A16B", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_192K1 = { + "SECP-192K1", ECField_GFp, 192, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", + "000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000003", + "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", + "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", + "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_224K1 = { + "SECP-224K1", ECField_GFp, 224, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", + "00000000000000000000000000000000000000000000000000000000", + "00000000000000000000000000000000000000000000000000000005", + "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", + "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", + "010000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7", 1 +}; + +static const ECCurveParams ecCurve_SECG_PRIME_256K1 = { + "SECP-256K1", ECField_GFp, 256, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", + "0000000000000000000000000000000000000000000000000000000000000000", + "0000000000000000000000000000000000000000000000000000000000000007", + "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", + "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", 1 +}; + +/* SEC2 binary curves */ +static const ECCurveParams ecCurve_SECG_CHAR2_113R1 = { + "SECT-113R1", ECField_GF2m, 113, + "020000000000000000000000000201", + "003088250CA6E7C7FE649CE85820F7", + "00E8BEE4D3E2260744188BE0E9C723", + "009D73616F35F4AB1407D73562C10F", + "00A52830277958EE84D1315ED31886", + "0100000000000000D9CCEC8A39E56F", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_113R2 = { + "SECT-113R2", ECField_GF2m, 113, + "020000000000000000000000000201", + "00689918DBEC7E5A0DD6DFC0AA55C7", + "0095E9A9EC9B297BD4BF36E059184F", + "01A57A6A7B26CA5EF52FCDB8164797", + "00B3ADC94ED1FE674C06E695BABA1D", + "010000000000000108789B2496AF93", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_131R1 = { + "SECT-131R1", ECField_GF2m, 131, + "080000000000000000000000000000010D", + "07A11B09A76B562144418FF3FF8C2570B8", + "0217C05610884B63B9C6C7291678F9D341", + "0081BAF91FDF9833C40F9C181343638399", + "078C6E7EA38C001F73C8134B1B4EF9E150", + "0400000000000000023123953A9464B54D", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_131R2 = { + "SECT-131R2", ECField_GF2m, 131, + "080000000000000000000000000000010D", + "03E5A88919D7CAFCBF415F07C2176573B2", + "04B8266A46C55657AC734CE38F018F2192", + "0356DCD8F2F95031AD652D23951BB366A8", + "0648F06D867940A5366D9E265DE9EB240F", + "0400000000000000016954A233049BA98F", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_163R1 = { + "SECT-163R1", ECField_GF2m, 163, + "0800000000000000000000000000000000000000C9", + "07B6882CAAEFA84F9554FF8428BD88E246D2782AE2", + "0713612DCDDCB40AAB946BDA29CA91F73AF958AFD9", + "0369979697AB43897789566789567F787A7876A654", + "00435EDB42EFAFB2989D51FEFCE3C80988F41FF883", + "03FFFFFFFFFFFFFFFFFFFF48AAB689C29CA710279B", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_193R1 = { + "SECT-193R1", ECField_GF2m, 193, + "02000000000000000000000000000000000000000000008001", + "0017858FEB7A98975169E171F77B4087DE098AC8A911DF7B01", + "00FDFB49BFE6C3A89FACADAA7A1E5BBC7CC1C2E5D831478814", + "01F481BC5F0FF84A74AD6CDF6FDEF4BF6179625372D8C0C5E1", + "0025E399F2903712CCF3EA9E3A1AD17FB0B3201B6AF7CE1B05", + "01000000000000000000000000C7F34A778F443ACC920EBA49", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_193R2 = { + "SECT-193R2", ECField_GF2m, 193, + "02000000000000000000000000000000000000000000008001", + "0163F35A5137C2CE3EA6ED8667190B0BC43ECD69977702709B", + "00C9BB9E8927D4D64C377E2AB2856A5B16E3EFB7F61D4316AE", + "00D9B67D192E0367C803F39E1A7E82CA14A651350AAE617E8F", + "01CE94335607C304AC29E7DEFBD9CA01F596F927224CDECF6C", + "010000000000000000000000015AAB561B005413CCD4EE99D5", 2 +}; + +static const ECCurveParams ecCurve_SECG_CHAR2_239K1 = { + "SECT-239K1", ECField_GF2m, 239, + "800000000000000000004000000000000000000000000000000000000001", + "000000000000000000000000000000000000000000000000000000000000", + "000000000000000000000000000000000000000000000000000000000001", + "29A0B6A887A983E9730988A68727A8B2D126C44CC2CC7B2A6555193035DC", + "76310804F12E549BDB011C103089E73510ACB275FC312A5DC6B76553F0CA", + "2000000000000000000000000000005A79FEC67CB6E91F1C1DA800E478A5", 4 +}; + +/* WTLS curves */ +static const ECCurveParams ecCurve_WTLS_1 = { + "WTLS-1", ECField_GF2m, 113, + "020000000000000000000000000201", + "000000000000000000000000000001", + "000000000000000000000000000001", + "01667979A40BA497E5D5C270780617", + "00F44B4AF1ECC2630E08785CEBCC15", + "00FFFFFFFFFFFFFFFDBF91AF6DEA73", 2 +}; + +static const ECCurveParams ecCurve_WTLS_8 = { + "WTLS-8", ECField_GFp, 112, + "FFFFFFFFFFFFFFFFFFFFFFFFFDE7", + "0000000000000000000000000000", + "0000000000000000000000000003", + "0000000000000000000000000001", + "0000000000000000000000000002", + "0100000000000001ECEA551AD837E9", 1 +}; + +static const ECCurveParams ecCurve_WTLS_9 = { + "WTLS-9", ECField_GFp, 160, + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC808F", + "0000000000000000000000000000000000000000", + "0000000000000000000000000000000000000003", + "0000000000000000000000000000000000000001", + "0000000000000000000000000000000000000002", + "0100000000000000000001CDC98AE0E2DE574ABF33", 1 +}; + +/* mapping between ECCurveName enum and pointers to ECCurveParams */ +static const ECCurveParams *ecCurve_map[] = { + NULL, /* ECCurve_noName */ + &ecCurve_NIST_P192, /* ECCurve_NIST_P192 */ + &ecCurve_NIST_P224, /* ECCurve_NIST_P224 */ + &ecCurve_NIST_P256, /* ECCurve_NIST_P256 */ + &ecCurve_NIST_P384, /* ECCurve_NIST_P384 */ + &ecCurve_NIST_P521, /* ECCurve_NIST_P521 */ + &ecCurve_NIST_K163, /* ECCurve_NIST_K163 */ + &ecCurve_NIST_B163, /* ECCurve_NIST_B163 */ + &ecCurve_NIST_K233, /* ECCurve_NIST_K233 */ + &ecCurve_NIST_B233, /* ECCurve_NIST_B233 */ + &ecCurve_NIST_K283, /* ECCurve_NIST_K283 */ + &ecCurve_NIST_B283, /* ECCurve_NIST_B283 */ + &ecCurve_NIST_K409, /* ECCurve_NIST_K409 */ + &ecCurve_NIST_B409, /* ECCurve_NIST_B409 */ + &ecCurve_NIST_K571, /* ECCurve_NIST_K571 */ + &ecCurve_NIST_B571, /* ECCurve_NIST_B571 */ + &ecCurve_X9_62_PRIME_192V2, /* ECCurve_X9_62_PRIME_192V2 */ + &ecCurve_X9_62_PRIME_192V3, /* ECCurve_X9_62_PRIME_192V3 */ + &ecCurve_X9_62_PRIME_239V1, /* ECCurve_X9_62_PRIME_239V1 */ + &ecCurve_X9_62_PRIME_239V2, /* ECCurve_X9_62_PRIME_239V2 */ + &ecCurve_X9_62_PRIME_239V3, /* ECCurve_X9_62_PRIME_239V3 */ + &ecCurve_X9_62_CHAR2_PNB163V1, /* ECCurve_X9_62_CHAR2_PNB163V1 */ + &ecCurve_X9_62_CHAR2_PNB163V2, /* ECCurve_X9_62_CHAR2_PNB163V2 */ + &ecCurve_X9_62_CHAR2_PNB163V3, /* ECCurve_X9_62_CHAR2_PNB163V3 */ + &ecCurve_X9_62_CHAR2_PNB176V1, /* ECCurve_X9_62_CHAR2_PNB176V1 */ + &ecCurve_X9_62_CHAR2_TNB191V1, /* ECCurve_X9_62_CHAR2_TNB191V1 */ + &ecCurve_X9_62_CHAR2_TNB191V2, /* ECCurve_X9_62_CHAR2_TNB191V2 */ + &ecCurve_X9_62_CHAR2_TNB191V3, /* ECCurve_X9_62_CHAR2_TNB191V3 */ + &ecCurve_X9_62_CHAR2_PNB208W1, /* ECCurve_X9_62_CHAR2_PNB208W1 */ + &ecCurve_X9_62_CHAR2_TNB239V1, /* ECCurve_X9_62_CHAR2_TNB239V1 */ + &ecCurve_X9_62_CHAR2_TNB239V2, /* ECCurve_X9_62_CHAR2_TNB239V2 */ + &ecCurve_X9_62_CHAR2_TNB239V3, /* ECCurve_X9_62_CHAR2_TNB239V3 */ + &ecCurve_X9_62_CHAR2_PNB272W1, /* ECCurve_X9_62_CHAR2_PNB272W1 */ + &ecCurve_X9_62_CHAR2_PNB304W1, /* ECCurve_X9_62_CHAR2_PNB304W1 */ + &ecCurve_X9_62_CHAR2_TNB359V1, /* ECCurve_X9_62_CHAR2_TNB359V1 */ + &ecCurve_X9_62_CHAR2_PNB368W1, /* ECCurve_X9_62_CHAR2_PNB368W1 */ + &ecCurve_X9_62_CHAR2_TNB431R1, /* ECCurve_X9_62_CHAR2_TNB431R1 */ + &ecCurve_SECG_PRIME_112R1, /* ECCurve_SECG_PRIME_112R1 */ + &ecCurve_SECG_PRIME_112R2, /* ECCurve_SECG_PRIME_112R2 */ + &ecCurve_SECG_PRIME_128R1, /* ECCurve_SECG_PRIME_128R1 */ + &ecCurve_SECG_PRIME_128R2, /* ECCurve_SECG_PRIME_128R2 */ + &ecCurve_SECG_PRIME_160K1, /* ECCurve_SECG_PRIME_160K1 */ + &ecCurve_SECG_PRIME_160R1, /* ECCurve_SECG_PRIME_160R1 */ + &ecCurve_SECG_PRIME_160R2, /* ECCurve_SECG_PRIME_160R2 */ + &ecCurve_SECG_PRIME_192K1, /* ECCurve_SECG_PRIME_192K1 */ + &ecCurve_SECG_PRIME_224K1, /* ECCurve_SECG_PRIME_224K1 */ + &ecCurve_SECG_PRIME_256K1, /* ECCurve_SECG_PRIME_256K1 */ + &ecCurve_SECG_CHAR2_113R1, /* ECCurve_SECG_CHAR2_113R1 */ + &ecCurve_SECG_CHAR2_113R2, /* ECCurve_SECG_CHAR2_113R2 */ + &ecCurve_SECG_CHAR2_131R1, /* ECCurve_SECG_CHAR2_131R1 */ + &ecCurve_SECG_CHAR2_131R2, /* ECCurve_SECG_CHAR2_131R2 */ + &ecCurve_SECG_CHAR2_163R1, /* ECCurve_SECG_CHAR2_163R1 */ + &ecCurve_SECG_CHAR2_193R1, /* ECCurve_SECG_CHAR2_193R1 */ + &ecCurve_SECG_CHAR2_193R2, /* ECCurve_SECG_CHAR2_193R2 */ + &ecCurve_SECG_CHAR2_239K1, /* ECCurve_SECG_CHAR2_239K1 */ + &ecCurve_WTLS_1, /* ECCurve_WTLS_1 */ + &ecCurve_WTLS_8, /* ECCurve_WTLS_8 */ + &ecCurve_WTLS_9, /* ECCurve_WTLS_9 */ + NULL /* ECCurve_pastLastCurve */ +}; + +#endif /* _ECL_CURVE_H */ diff --git a/src/share/native/sun/security/ec/impl/ecl-exp.h b/src/share/native/sun/security/ec/impl/ecl-exp.h new file mode 100644 index 0000000000000000000000000000000000000000..ce9a2cf803ce64cfb6e39a3e44a42997926bc56f --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl-exp.h @@ -0,0 +1,216 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _ECL_EXP_H +#define _ECL_EXP_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* Curve field type */ +typedef enum { + ECField_GFp, + ECField_GF2m +} ECField; + +/* Hexadecimal encoding of curve parameters */ +struct ECCurveParamsStr { + char *text; + ECField field; + unsigned int size; + char *irr; + char *curvea; + char *curveb; + char *genx; + char *geny; + char *order; + int cofactor; +}; +typedef struct ECCurveParamsStr ECCurveParams; + +/* Named curve parameters */ +typedef enum { + + ECCurve_noName = 0, + + /* NIST prime curves */ + ECCurve_NIST_P192, + ECCurve_NIST_P224, + ECCurve_NIST_P256, + ECCurve_NIST_P384, + ECCurve_NIST_P521, + + /* NIST binary curves */ + ECCurve_NIST_K163, + ECCurve_NIST_B163, + ECCurve_NIST_K233, + ECCurve_NIST_B233, + ECCurve_NIST_K283, + ECCurve_NIST_B283, + ECCurve_NIST_K409, + ECCurve_NIST_B409, + ECCurve_NIST_K571, + ECCurve_NIST_B571, + + /* ANSI X9.62 prime curves */ + /* ECCurve_X9_62_PRIME_192V1 == ECCurve_NIST_P192 */ + ECCurve_X9_62_PRIME_192V2, + ECCurve_X9_62_PRIME_192V3, + ECCurve_X9_62_PRIME_239V1, + ECCurve_X9_62_PRIME_239V2, + ECCurve_X9_62_PRIME_239V3, + /* ECCurve_X9_62_PRIME_256V1 == ECCurve_NIST_P256 */ + + /* ANSI X9.62 binary curves */ + ECCurve_X9_62_CHAR2_PNB163V1, + ECCurve_X9_62_CHAR2_PNB163V2, + ECCurve_X9_62_CHAR2_PNB163V3, + ECCurve_X9_62_CHAR2_PNB176V1, + ECCurve_X9_62_CHAR2_TNB191V1, + ECCurve_X9_62_CHAR2_TNB191V2, + ECCurve_X9_62_CHAR2_TNB191V3, + ECCurve_X9_62_CHAR2_PNB208W1, + ECCurve_X9_62_CHAR2_TNB239V1, + ECCurve_X9_62_CHAR2_TNB239V2, + ECCurve_X9_62_CHAR2_TNB239V3, + ECCurve_X9_62_CHAR2_PNB272W1, + ECCurve_X9_62_CHAR2_PNB304W1, + ECCurve_X9_62_CHAR2_TNB359V1, + ECCurve_X9_62_CHAR2_PNB368W1, + ECCurve_X9_62_CHAR2_TNB431R1, + + /* SEC2 prime curves */ + ECCurve_SECG_PRIME_112R1, + ECCurve_SECG_PRIME_112R2, + ECCurve_SECG_PRIME_128R1, + ECCurve_SECG_PRIME_128R2, + ECCurve_SECG_PRIME_160K1, + ECCurve_SECG_PRIME_160R1, + ECCurve_SECG_PRIME_160R2, + ECCurve_SECG_PRIME_192K1, + /* ECCurve_SECG_PRIME_192R1 == ECCurve_NIST_P192 */ + ECCurve_SECG_PRIME_224K1, + /* ECCurve_SECG_PRIME_224R1 == ECCurve_NIST_P224 */ + ECCurve_SECG_PRIME_256K1, + /* ECCurve_SECG_PRIME_256R1 == ECCurve_NIST_P256 */ + /* ECCurve_SECG_PRIME_384R1 == ECCurve_NIST_P384 */ + /* ECCurve_SECG_PRIME_521R1 == ECCurve_NIST_P521 */ + + /* SEC2 binary curves */ + ECCurve_SECG_CHAR2_113R1, + ECCurve_SECG_CHAR2_113R2, + ECCurve_SECG_CHAR2_131R1, + ECCurve_SECG_CHAR2_131R2, + /* ECCurve_SECG_CHAR2_163K1 == ECCurve_NIST_K163 */ + ECCurve_SECG_CHAR2_163R1, + /* ECCurve_SECG_CHAR2_163R2 == ECCurve_NIST_B163 */ + ECCurve_SECG_CHAR2_193R1, + ECCurve_SECG_CHAR2_193R2, + /* ECCurve_SECG_CHAR2_233K1 == ECCurve_NIST_K233 */ + /* ECCurve_SECG_CHAR2_233R1 == ECCurve_NIST_B233 */ + ECCurve_SECG_CHAR2_239K1, + /* ECCurve_SECG_CHAR2_283K1 == ECCurve_NIST_K283 */ + /* ECCurve_SECG_CHAR2_283R1 == ECCurve_NIST_B283 */ + /* ECCurve_SECG_CHAR2_409K1 == ECCurve_NIST_K409 */ + /* ECCurve_SECG_CHAR2_409R1 == ECCurve_NIST_B409 */ + /* ECCurve_SECG_CHAR2_571K1 == ECCurve_NIST_K571 */ + /* ECCurve_SECG_CHAR2_571R1 == ECCurve_NIST_B571 */ + + /* WTLS curves */ + ECCurve_WTLS_1, + /* there is no WTLS 2 curve */ + /* ECCurve_WTLS_3 == ECCurve_NIST_K163 */ + /* ECCurve_WTLS_4 == ECCurve_SECG_CHAR2_113R1 */ + /* ECCurve_WTLS_5 == ECCurve_X9_62_CHAR2_PNB163V1 */ + /* ECCurve_WTLS_6 == ECCurve_SECG_PRIME_112R1 */ + /* ECCurve_WTLS_7 == ECCurve_SECG_PRIME_160R1 */ + ECCurve_WTLS_8, + ECCurve_WTLS_9, + /* ECCurve_WTLS_10 == ECCurve_NIST_K233 */ + /* ECCurve_WTLS_11 == ECCurve_NIST_B233 */ + /* ECCurve_WTLS_12 == ECCurve_NIST_P224 */ + + ECCurve_pastLastCurve +} ECCurveName; + +/* Aliased named curves */ + +#define ECCurve_X9_62_PRIME_192V1 ECCurve_NIST_P192 +#define ECCurve_X9_62_PRIME_256V1 ECCurve_NIST_P256 +#define ECCurve_SECG_PRIME_192R1 ECCurve_NIST_P192 +#define ECCurve_SECG_PRIME_224R1 ECCurve_NIST_P224 +#define ECCurve_SECG_PRIME_256R1 ECCurve_NIST_P256 +#define ECCurve_SECG_PRIME_384R1 ECCurve_NIST_P384 +#define ECCurve_SECG_PRIME_521R1 ECCurve_NIST_P521 +#define ECCurve_SECG_CHAR2_163K1 ECCurve_NIST_K163 +#define ECCurve_SECG_CHAR2_163R2 ECCurve_NIST_B163 +#define ECCurve_SECG_CHAR2_233K1 ECCurve_NIST_K233 +#define ECCurve_SECG_CHAR2_233R1 ECCurve_NIST_B233 +#define ECCurve_SECG_CHAR2_283K1 ECCurve_NIST_K283 +#define ECCurve_SECG_CHAR2_283R1 ECCurve_NIST_B283 +#define ECCurve_SECG_CHAR2_409K1 ECCurve_NIST_K409 +#define ECCurve_SECG_CHAR2_409R1 ECCurve_NIST_B409 +#define ECCurve_SECG_CHAR2_571K1 ECCurve_NIST_K571 +#define ECCurve_SECG_CHAR2_571R1 ECCurve_NIST_B571 +#define ECCurve_WTLS_3 ECCurve_NIST_K163 +#define ECCurve_WTLS_4 ECCurve_SECG_CHAR2_113R1 +#define ECCurve_WTLS_5 ECCurve_X9_62_CHAR2_PNB163V1 +#define ECCurve_WTLS_6 ECCurve_SECG_PRIME_112R1 +#define ECCurve_WTLS_7 ECCurve_SECG_PRIME_160R1 +#define ECCurve_WTLS_10 ECCurve_NIST_K233 +#define ECCurve_WTLS_11 ECCurve_NIST_B233 +#define ECCurve_WTLS_12 ECCurve_NIST_P224 + +#endif /* _ECL_EXP_H */ diff --git a/src/share/native/sun/security/ec/impl/ecl-priv.h b/src/share/native/sun/security/ec/impl/ecl-priv.h new file mode 100644 index 0000000000000000000000000000000000000000..12caaf70577959e4e6d14430a1e3226bc19828e6 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl-priv.h @@ -0,0 +1,304 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Stephen Fung and + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _ECL_PRIV_H +#define _ECL_PRIV_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecl.h" +#include "mpi.h" +#include "mplogic.h" + +/* MAX_FIELD_SIZE_DIGITS is the maximum size of field element supported */ +/* the following needs to go away... */ +#if defined(MP_USE_LONG_LONG_DIGIT) || defined(MP_USE_LONG_DIGIT) +#define ECL_SIXTY_FOUR_BIT +#else +#define ECL_THIRTY_TWO_BIT +#endif + +#define ECL_CURVE_DIGITS(curve_size_in_bits) \ + (((curve_size_in_bits)+(sizeof(mp_digit)*8-1))/(sizeof(mp_digit)*8)) +#define ECL_BITS (sizeof(mp_digit)*8) +#define ECL_MAX_FIELD_SIZE_DIGITS (80/sizeof(mp_digit)) + +/* Gets the i'th bit in the binary representation of a. If i >= length(a), + * then return 0. (The above behaviour differs from mpl_get_bit, which + * causes an error if i >= length(a).) */ +#define MP_GET_BIT(a, i) \ + ((i) >= mpl_significant_bits((a))) ? 0 : mpl_get_bit((a), (i)) + +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) +#define MP_ADD_CARRY(a1, a2, s, cin, cout) \ + { mp_word w; \ + w = ((mp_word)(cin)) + (a1) + (a2); \ + s = ACCUM(w); \ + cout = CARRYOUT(w); } + +#define MP_SUB_BORROW(a1, a2, s, bin, bout) \ + { mp_word w; \ + w = ((mp_word)(a1)) - (a2) - (bin); \ + s = ACCUM(w); \ + bout = (w >> MP_DIGIT_BIT) & 1; } + +#else +/* NOTE, + * cin and cout could be the same variable. + * bin and bout could be the same variable. + * a1 or a2 and s could be the same variable. + * don't trash those outputs until their respective inputs have + * been read. */ +#define MP_ADD_CARRY(a1, a2, s, cin, cout) \ + { mp_digit tmp,sum; \ + tmp = (a1); \ + sum = tmp + (a2); \ + tmp = (sum < tmp); /* detect overflow */ \ + s = sum += (cin); \ + cout = tmp + (sum < (cin)); } + +#define MP_SUB_BORROW(a1, a2, s, bin, bout) \ + { mp_digit tmp; \ + tmp = (a1); \ + s = tmp - (a2); \ + tmp = (s > tmp); /* detect borrow */ \ + if ((bin) && !s--) tmp++; \ + bout = tmp; } +#endif + + +struct GFMethodStr; +typedef struct GFMethodStr GFMethod; +struct GFMethodStr { + /* Indicates whether the structure was constructed from dynamic memory + * or statically created. */ + int constructed; + /* Irreducible that defines the field. For prime fields, this is the + * prime p. For binary polynomial fields, this is the bitstring + * representation of the irreducible polynomial. */ + mp_int irr; + /* For prime fields, the value irr_arr[0] is the number of bits in the + * field. For binary polynomial fields, the irreducible polynomial + * f(t) is represented as an array of unsigned int[], where f(t) is + * of the form: f(t) = t^p[0] + t^p[1] + ... + t^p[4] where m = p[0] + * > p[1] > ... > p[4] = 0. */ + unsigned int irr_arr[5]; + /* Field arithmetic methods. All methods (except field_enc and + * field_dec) are assumed to take field-encoded parameters and return + * field-encoded values. All methods (except field_enc and field_dec) + * are required to be implemented. */ + mp_err (*field_add) (const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + mp_err (*field_neg) (const mp_int *a, mp_int *r, const GFMethod *meth); + mp_err (*field_sub) (const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + mp_err (*field_mod) (const mp_int *a, mp_int *r, const GFMethod *meth); + mp_err (*field_mul) (const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + mp_err (*field_sqr) (const mp_int *a, mp_int *r, const GFMethod *meth); + mp_err (*field_div) (const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + mp_err (*field_enc) (const mp_int *a, mp_int *r, const GFMethod *meth); + mp_err (*field_dec) (const mp_int *a, mp_int *r, const GFMethod *meth); + /* Extra storage for implementation-specific data. Any memory + * allocated to these extra fields will be cleared by extra_free. */ + void *extra1; + void *extra2; + void (*extra_free) (GFMethod *meth); +}; + +/* Construct generic GFMethods. */ +GFMethod *GFMethod_consGFp(const mp_int *irr); +GFMethod *GFMethod_consGFp_mont(const mp_int *irr); +GFMethod *GFMethod_consGF2m(const mp_int *irr, + const unsigned int irr_arr[5]); +/* Free the memory allocated (if any) to a GFMethod object. */ +void GFMethod_free(GFMethod *meth); + +struct ECGroupStr { + /* Indicates whether the structure was constructed from dynamic memory + * or statically created. */ + int constructed; + /* Field definition and arithmetic. */ + GFMethod *meth; + /* Textual representation of curve name, if any. */ + char *text; +#ifdef _KERNEL + int text_len; +#endif + /* Curve parameters, field-encoded. */ + mp_int curvea, curveb; + /* x and y coordinates of the base point, field-encoded. */ + mp_int genx, geny; + /* Order and cofactor of the base point. */ + mp_int order; + int cofactor; + /* Point arithmetic methods. All methods are assumed to take + * field-encoded parameters and return field-encoded values. All + * methods (except base_point_mul and points_mul) are required to be + * implemented. */ + mp_err (*point_add) (const mp_int *px, const mp_int *py, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, const ECGroup *group); + mp_err (*point_sub) (const mp_int *px, const mp_int *py, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, const ECGroup *group); + mp_err (*point_dbl) (const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group); + mp_err (*point_mul) (const mp_int *n, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); + mp_err (*base_point_mul) (const mp_int *n, mp_int *rx, mp_int *ry, + const ECGroup *group); + mp_err (*points_mul) (const mp_int *k1, const mp_int *k2, + const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group); + mp_err (*validate_point) (const mp_int *px, const mp_int *py, const ECGroup *group); + /* Extra storage for implementation-specific data. Any memory + * allocated to these extra fields will be cleared by extra_free. */ + void *extra1; + void *extra2; + void (*extra_free) (ECGroup *group); +}; + +/* Wrapper functions for generic prime field arithmetic. */ +mp_err ec_GFp_add(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_neg(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GFp_sub(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + +/* fixed length in-line adds. Count is in words */ +mp_err ec_GFp_add_3(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_add_4(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_add_5(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_add_6(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_sub_3(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_sub_4(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_sub_5(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_sub_6(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + +mp_err ec_GFp_mod(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GFp_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_sqr(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GFp_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +/* Wrapper functions for generic binary polynomial field arithmetic. */ +mp_err ec_GF2m_add(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GF2m_neg(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GF2m_mod(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GF2m_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GF2m_sqr(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GF2m_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); + +/* Montgomery prime field arithmetic. */ +mp_err ec_GFp_mul_mont(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_sqr_mont(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GFp_div_mont(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth); +mp_err ec_GFp_enc_mont(const mp_int *a, mp_int *r, const GFMethod *meth); +mp_err ec_GFp_dec_mont(const mp_int *a, mp_int *r, const GFMethod *meth); +void ec_GFp_extra_free_mont(GFMethod *meth); + +/* point multiplication */ +mp_err ec_pts_mul_basic(const mp_int *k1, const mp_int *k2, + const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group); +mp_err ec_pts_mul_simul_w2(const mp_int *k1, const mp_int *k2, + const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Computes the windowed non-adjacent-form (NAF) of a scalar. Out should + * be an array of signed char's to output to, bitsize should be the number + * of bits of out, in is the original scalar, and w is the window size. + * NAF is discussed in the paper: D. Hankerson, J. Hernandez and A. + * Menezes, "Software implementation of elliptic curve cryptography over + * binary fields", Proc. CHES 2000. */ +mp_err ec_compute_wNAF(signed char *out, int bitsize, const mp_int *in, + int w); + +/* Optimized field arithmetic */ +mp_err ec_group_set_gfp192(ECGroup *group, ECCurveName); +mp_err ec_group_set_gfp224(ECGroup *group, ECCurveName); +mp_err ec_group_set_gfp256(ECGroup *group, ECCurveName); +mp_err ec_group_set_gfp384(ECGroup *group, ECCurveName); +mp_err ec_group_set_gfp521(ECGroup *group, ECCurveName); +mp_err ec_group_set_gf2m163(ECGroup *group, ECCurveName name); +mp_err ec_group_set_gf2m193(ECGroup *group, ECCurveName name); +mp_err ec_group_set_gf2m233(ECGroup *group, ECCurveName name); + +/* Optimized floating-point arithmetic */ +#ifdef ECL_USE_FP +mp_err ec_group_set_secp160r1_fp(ECGroup *group); +mp_err ec_group_set_nistp192_fp(ECGroup *group); +mp_err ec_group_set_nistp224_fp(ECGroup *group); +#endif + +#endif /* _ECL_PRIV_H */ diff --git a/src/share/native/sun/security/ec/impl/ecl.c b/src/share/native/sun/security/ec/impl/ecl.c new file mode 100644 index 0000000000000000000000000000000000000000..7089a6d0e9d2c043e0a9a0a654ed2aff41a3e8b3 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl.c @@ -0,0 +1,475 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mpi.h" +#include "mplogic.h" +#include "ecl.h" +#include "ecl-priv.h" +#include "ec2.h" +#include "ecp.h" +#ifndef _KERNEL +#include +#include +#endif + +/* Allocate memory for a new ECGroup object. */ +ECGroup * +ECGroup_new(int kmflag) +{ + mp_err res = MP_OKAY; + ECGroup *group; +#ifdef _KERNEL + group = (ECGroup *) kmem_alloc(sizeof(ECGroup), kmflag); +#else + group = (ECGroup *) malloc(sizeof(ECGroup)); +#endif + if (group == NULL) + return NULL; + group->constructed = MP_YES; + group->meth = NULL; + group->text = NULL; + MP_DIGITS(&group->curvea) = 0; + MP_DIGITS(&group->curveb) = 0; + MP_DIGITS(&group->genx) = 0; + MP_DIGITS(&group->geny) = 0; + MP_DIGITS(&group->order) = 0; + group->base_point_mul = NULL; + group->points_mul = NULL; + group->validate_point = NULL; + group->extra1 = NULL; + group->extra2 = NULL; + group->extra_free = NULL; + MP_CHECKOK(mp_init(&group->curvea, kmflag)); + MP_CHECKOK(mp_init(&group->curveb, kmflag)); + MP_CHECKOK(mp_init(&group->genx, kmflag)); + MP_CHECKOK(mp_init(&group->geny, kmflag)); + MP_CHECKOK(mp_init(&group->order, kmflag)); + + CLEANUP: + if (res != MP_OKAY) { + ECGroup_free(group); + return NULL; + } + return group; +} + +/* Construct a generic ECGroup for elliptic curves over prime fields. */ +ECGroup * +ECGroup_consGFp(const mp_int *irr, const mp_int *curvea, + const mp_int *curveb, const mp_int *genx, + const mp_int *geny, const mp_int *order, int cofactor) +{ + mp_err res = MP_OKAY; + ECGroup *group = NULL; + + group = ECGroup_new(FLAG(irr)); + if (group == NULL) + return NULL; + + group->meth = GFMethod_consGFp(irr); + if (group->meth == NULL) { + res = MP_MEM; + goto CLEANUP; + } + MP_CHECKOK(mp_copy(curvea, &group->curvea)); + MP_CHECKOK(mp_copy(curveb, &group->curveb)); + MP_CHECKOK(mp_copy(genx, &group->genx)); + MP_CHECKOK(mp_copy(geny, &group->geny)); + MP_CHECKOK(mp_copy(order, &group->order)); + group->cofactor = cofactor; + group->point_add = &ec_GFp_pt_add_aff; + group->point_sub = &ec_GFp_pt_sub_aff; + group->point_dbl = &ec_GFp_pt_dbl_aff; + group->point_mul = &ec_GFp_pt_mul_jm_wNAF; + group->base_point_mul = NULL; + group->points_mul = &ec_GFp_pts_mul_jac; + group->validate_point = &ec_GFp_validate_point; + + CLEANUP: + if (res != MP_OKAY) { + ECGroup_free(group); + return NULL; + } + return group; +} + +/* Construct a generic ECGroup for elliptic curves over prime fields with + * field arithmetic implemented in Montgomery coordinates. */ +ECGroup * +ECGroup_consGFp_mont(const mp_int *irr, const mp_int *curvea, + const mp_int *curveb, const mp_int *genx, + const mp_int *geny, const mp_int *order, int cofactor) +{ + mp_err res = MP_OKAY; + ECGroup *group = NULL; + + group = ECGroup_new(FLAG(irr)); + if (group == NULL) + return NULL; + + group->meth = GFMethod_consGFp_mont(irr); + if (group->meth == NULL) { + res = MP_MEM; + goto CLEANUP; + } + MP_CHECKOK(group->meth-> + field_enc(curvea, &group->curvea, group->meth)); + MP_CHECKOK(group->meth-> + field_enc(curveb, &group->curveb, group->meth)); + MP_CHECKOK(group->meth->field_enc(genx, &group->genx, group->meth)); + MP_CHECKOK(group->meth->field_enc(geny, &group->geny, group->meth)); + MP_CHECKOK(mp_copy(order, &group->order)); + group->cofactor = cofactor; + group->point_add = &ec_GFp_pt_add_aff; + group->point_sub = &ec_GFp_pt_sub_aff; + group->point_dbl = &ec_GFp_pt_dbl_aff; + group->point_mul = &ec_GFp_pt_mul_jm_wNAF; + group->base_point_mul = NULL; + group->points_mul = &ec_GFp_pts_mul_jac; + group->validate_point = &ec_GFp_validate_point; + + CLEANUP: + if (res != MP_OKAY) { + ECGroup_free(group); + return NULL; + } + return group; +} + +#ifdef NSS_ECC_MORE_THAN_SUITE_B +/* Construct a generic ECGroup for elliptic curves over binary polynomial + * fields. */ +ECGroup * +ECGroup_consGF2m(const mp_int *irr, const unsigned int irr_arr[5], + const mp_int *curvea, const mp_int *curveb, + const mp_int *genx, const mp_int *geny, + const mp_int *order, int cofactor) +{ + mp_err res = MP_OKAY; + ECGroup *group = NULL; + + group = ECGroup_new(FLAG(irr)); + if (group == NULL) + return NULL; + + group->meth = GFMethod_consGF2m(irr, irr_arr); + if (group->meth == NULL) { + res = MP_MEM; + goto CLEANUP; + } + MP_CHECKOK(mp_copy(curvea, &group->curvea)); + MP_CHECKOK(mp_copy(curveb, &group->curveb)); + MP_CHECKOK(mp_copy(genx, &group->genx)); + MP_CHECKOK(mp_copy(geny, &group->geny)); + MP_CHECKOK(mp_copy(order, &group->order)); + group->cofactor = cofactor; + group->point_add = &ec_GF2m_pt_add_aff; + group->point_sub = &ec_GF2m_pt_sub_aff; + group->point_dbl = &ec_GF2m_pt_dbl_aff; + group->point_mul = &ec_GF2m_pt_mul_mont; + group->base_point_mul = NULL; + group->points_mul = &ec_pts_mul_basic; + group->validate_point = &ec_GF2m_validate_point; + + CLEANUP: + if (res != MP_OKAY) { + ECGroup_free(group); + return NULL; + } + return group; +} +#endif + +/* Construct ECGroup from hex parameters and name, if any. Called by + * ECGroup_fromHex and ECGroup_fromName. */ +ECGroup * +ecgroup_fromNameAndHex(const ECCurveName name, + const ECCurveParams * params, int kmflag) +{ + mp_int irr, curvea, curveb, genx, geny, order; + int bits; + ECGroup *group = NULL; + mp_err res = MP_OKAY; + + /* initialize values */ + MP_DIGITS(&irr) = 0; + MP_DIGITS(&curvea) = 0; + MP_DIGITS(&curveb) = 0; + MP_DIGITS(&genx) = 0; + MP_DIGITS(&geny) = 0; + MP_DIGITS(&order) = 0; + MP_CHECKOK(mp_init(&irr, kmflag)); + MP_CHECKOK(mp_init(&curvea, kmflag)); + MP_CHECKOK(mp_init(&curveb, kmflag)); + MP_CHECKOK(mp_init(&genx, kmflag)); + MP_CHECKOK(mp_init(&geny, kmflag)); + MP_CHECKOK(mp_init(&order, kmflag)); + MP_CHECKOK(mp_read_radix(&irr, params->irr, 16)); + MP_CHECKOK(mp_read_radix(&curvea, params->curvea, 16)); + MP_CHECKOK(mp_read_radix(&curveb, params->curveb, 16)); + MP_CHECKOK(mp_read_radix(&genx, params->genx, 16)); + MP_CHECKOK(mp_read_radix(&geny, params->geny, 16)); + MP_CHECKOK(mp_read_radix(&order, params->order, 16)); + + /* determine number of bits */ + bits = mpl_significant_bits(&irr) - 1; + if (bits < MP_OKAY) { + res = bits; + goto CLEANUP; + } + + /* determine which optimizations (if any) to use */ + if (params->field == ECField_GFp) { +#ifdef NSS_ECC_MORE_THAN_SUITE_B + switch (name) { +#ifdef ECL_USE_FP + case ECCurve_SECG_PRIME_160R1: + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_secp160r1_fp(group)); + break; +#endif + case ECCurve_SECG_PRIME_192R1: +#ifdef ECL_USE_FP + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_nistp192_fp(group)); +#else + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_gfp192(group, name)); +#endif + break; + case ECCurve_SECG_PRIME_224R1: +#ifdef ECL_USE_FP + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_nistp224_fp(group)); +#else + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_gfp224(group, name)); +#endif + break; + case ECCurve_SECG_PRIME_256R1: + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_gfp256(group, name)); + break; + case ECCurve_SECG_PRIME_521R1: + group = + ECGroup_consGFp(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + MP_CHECKOK(ec_group_set_gfp521(group, name)); + break; + default: + /* use generic arithmetic */ +#endif + group = + ECGroup_consGFp_mont(&irr, &curvea, &curveb, &genx, &geny, + &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } +#ifdef NSS_ECC_MORE_THAN_SUITE_B + } + } else if (params->field == ECField_GF2m) { + group = ECGroup_consGF2m(&irr, NULL, &curvea, &curveb, &genx, &geny, &order, params->cofactor); + if (group == NULL) { res = MP_UNDEF; goto CLEANUP; } + if ((name == ECCurve_NIST_K163) || + (name == ECCurve_NIST_B163) || + (name == ECCurve_SECG_CHAR2_163R1)) { + MP_CHECKOK(ec_group_set_gf2m163(group, name)); + } else if ((name == ECCurve_SECG_CHAR2_193R1) || + (name == ECCurve_SECG_CHAR2_193R2)) { + MP_CHECKOK(ec_group_set_gf2m193(group, name)); + } else if ((name == ECCurve_NIST_K233) || + (name == ECCurve_NIST_B233)) { + MP_CHECKOK(ec_group_set_gf2m233(group, name)); + } +#endif + } else { + res = MP_UNDEF; + goto CLEANUP; + } + + /* set name, if any */ + if ((group != NULL) && (params->text != NULL)) { +#ifdef _KERNEL + int n = strlen(params->text) + 1; + + group->text = kmem_alloc(n, kmflag); + if (group->text == NULL) { + res = MP_MEM; + goto CLEANUP; + } + bcopy(params->text, group->text, n); + group->text_len = n; +#else + group->text = strdup(params->text); + if (group->text == NULL) { + res = MP_MEM; + } +#endif + } + + CLEANUP: + mp_clear(&irr); + mp_clear(&curvea); + mp_clear(&curveb); + mp_clear(&genx); + mp_clear(&geny); + mp_clear(&order); + if (res != MP_OKAY) { + ECGroup_free(group); + return NULL; + } + return group; +} + +/* Construct ECGroup from hexadecimal representations of parameters. */ +ECGroup * +ECGroup_fromHex(const ECCurveParams * params, int kmflag) +{ + return ecgroup_fromNameAndHex(ECCurve_noName, params, kmflag); +} + +/* Construct ECGroup from named parameters. */ +ECGroup * +ECGroup_fromName(const ECCurveName name, int kmflag) +{ + ECGroup *group = NULL; + ECCurveParams *params = NULL; + mp_err res = MP_OKAY; + + params = EC_GetNamedCurveParams(name, kmflag); + if (params == NULL) { + res = MP_UNDEF; + goto CLEANUP; + } + + /* construct actual group */ + group = ecgroup_fromNameAndHex(name, params, kmflag); + if (group == NULL) { + res = MP_UNDEF; + goto CLEANUP; + } + + CLEANUP: + EC_FreeCurveParams(params); + if (res != MP_OKAY) { + ECGroup_free(group); + return NULL; + } + return group; +} + +/* Validates an EC public key as described in Section 5.2.2 of X9.62. */ +mp_err ECPoint_validate(const ECGroup *group, const mp_int *px, const + mp_int *py) +{ + /* 1: Verify that publicValue is not the point at infinity */ + /* 2: Verify that the coordinates of publicValue are elements + * of the field. + */ + /* 3: Verify that publicValue is on the curve. */ + /* 4: Verify that the order of the curve times the publicValue + * is the point at infinity. + */ + return group->validate_point(px, py, group); +} + +/* Free the memory allocated (if any) to an ECGroup object. */ +void +ECGroup_free(ECGroup *group) +{ + if (group == NULL) + return; + GFMethod_free(group->meth); + if (group->constructed == MP_NO) + return; + mp_clear(&group->curvea); + mp_clear(&group->curveb); + mp_clear(&group->genx); + mp_clear(&group->geny); + mp_clear(&group->order); + if (group->text != NULL) +#ifdef _KERNEL + kmem_free(group->text, group->text_len); +#else + free(group->text); +#endif + if (group->extra_free != NULL) + group->extra_free(group); +#ifdef _KERNEL + kmem_free(group, sizeof (ECGroup)); +#else + free(group); +#endif +} diff --git a/src/share/native/sun/security/ec/impl/ecl.h b/src/share/native/sun/security/ec/impl/ecl.h new file mode 100644 index 0000000000000000000000000000000000000000..9dcdbc677ced32605047b4fc1abe809807713e09 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl.h @@ -0,0 +1,111 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _ECL_H +#define _ECL_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* Although this is not an exported header file, code which uses elliptic + * curve point operations will need to include it. */ + +#include "ecl-exp.h" +#include "mpi.h" + +struct ECGroupStr; +typedef struct ECGroupStr ECGroup; + +/* Construct ECGroup from hexadecimal representations of parameters. */ +ECGroup *ECGroup_fromHex(const ECCurveParams * params, int kmflag); + +/* Construct ECGroup from named parameters. */ +ECGroup *ECGroup_fromName(const ECCurveName name, int kmflag); + +/* Free an allocated ECGroup. */ +void ECGroup_free(ECGroup *group); + +/* Construct ECCurveParams from an ECCurveName */ +ECCurveParams *EC_GetNamedCurveParams(const ECCurveName name, int kmflag); + +/* Duplicates an ECCurveParams */ +ECCurveParams *ECCurveParams_dup(const ECCurveParams * params, int kmflag); + +/* Free an allocated ECCurveParams */ +void EC_FreeCurveParams(ECCurveParams * params); + +/* Elliptic curve scalar-point multiplication. Computes Q(x, y) = k * P(x, + * y). If x, y = NULL, then P is assumed to be the generator (base point) + * of the group of points on the elliptic curve. Input and output values + * are assumed to be NOT field-encoded. */ +mp_err ECPoint_mul(const ECGroup *group, const mp_int *k, const mp_int *px, + const mp_int *py, mp_int *qx, mp_int *qy); + +/* Elliptic curve scalar-point multiplication. Computes Q(x, y) = k1 * G + + * k2 * P(x, y), where G is the generator (base point) of the group of + * points on the elliptic curve. Input and output values are assumed to + * be NOT field-encoded. */ +mp_err ECPoints_mul(const ECGroup *group, const mp_int *k1, + const mp_int *k2, const mp_int *px, const mp_int *py, + mp_int *qx, mp_int *qy); + +/* Validates an EC public key as described in Section 5.2.2 of X9.62. + * Returns MP_YES if the public key is valid, MP_NO if the public key + * is invalid, or an error code if the validation could not be + * performed. */ +mp_err ECPoint_validate(const ECGroup *group, const mp_int *px, const + mp_int *py); + +#endif /* _ECL_H */ diff --git a/src/share/native/sun/security/ec/impl/ecl_curve.c b/src/share/native/sun/security/ec/impl/ecl_curve.c new file mode 100644 index 0000000000000000000000000000000000000000..d2d2d82291c25ab1238545a47b56d4e4d2b40b5b --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl_curve.c @@ -0,0 +1,216 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecl.h" +#include "ecl-curve.h" +#include "ecl-priv.h" +#ifndef _KERNEL +#include +#include +#endif + +#define CHECK(func) if ((func) == NULL) { res = 0; goto CLEANUP; } + +/* Duplicates an ECCurveParams */ +ECCurveParams * +ECCurveParams_dup(const ECCurveParams * params, int kmflag) +{ + int res = 1; + ECCurveParams *ret = NULL; + +#ifdef _KERNEL + ret = (ECCurveParams *) kmem_zalloc(sizeof(ECCurveParams), kmflag); +#else + CHECK(ret = (ECCurveParams *) calloc(1, sizeof(ECCurveParams))); +#endif + if (params->text != NULL) { +#ifdef _KERNEL + ret->text = kmem_alloc(strlen(params->text) + 1, kmflag); + bcopy(params->text, ret->text, strlen(params->text) + 1); +#else + CHECK(ret->text = strdup(params->text)); +#endif + } + ret->field = params->field; + ret->size = params->size; + if (params->irr != NULL) { +#ifdef _KERNEL + ret->irr = kmem_alloc(strlen(params->irr) + 1, kmflag); + bcopy(params->irr, ret->irr, strlen(params->irr) + 1); +#else + CHECK(ret->irr = strdup(params->irr)); +#endif + } + if (params->curvea != NULL) { +#ifdef _KERNEL + ret->curvea = kmem_alloc(strlen(params->curvea) + 1, kmflag); + bcopy(params->curvea, ret->curvea, strlen(params->curvea) + 1); +#else + CHECK(ret->curvea = strdup(params->curvea)); +#endif + } + if (params->curveb != NULL) { +#ifdef _KERNEL + ret->curveb = kmem_alloc(strlen(params->curveb) + 1, kmflag); + bcopy(params->curveb, ret->curveb, strlen(params->curveb) + 1); +#else + CHECK(ret->curveb = strdup(params->curveb)); +#endif + } + if (params->genx != NULL) { +#ifdef _KERNEL + ret->genx = kmem_alloc(strlen(params->genx) + 1, kmflag); + bcopy(params->genx, ret->genx, strlen(params->genx) + 1); +#else + CHECK(ret->genx = strdup(params->genx)); +#endif + } + if (params->geny != NULL) { +#ifdef _KERNEL + ret->geny = kmem_alloc(strlen(params->geny) + 1, kmflag); + bcopy(params->geny, ret->geny, strlen(params->geny) + 1); +#else + CHECK(ret->geny = strdup(params->geny)); +#endif + } + if (params->order != NULL) { +#ifdef _KERNEL + ret->order = kmem_alloc(strlen(params->order) + 1, kmflag); + bcopy(params->order, ret->order, strlen(params->order) + 1); +#else + CHECK(ret->order = strdup(params->order)); +#endif + } + ret->cofactor = params->cofactor; + + CLEANUP: + if (res != 1) { + EC_FreeCurveParams(ret); + return NULL; + } + return ret; +} + +#undef CHECK + +/* Construct ECCurveParams from an ECCurveName */ +ECCurveParams * +EC_GetNamedCurveParams(const ECCurveName name, int kmflag) +{ + if ((name <= ECCurve_noName) || (ECCurve_pastLastCurve <= name) || + (ecCurve_map[name] == NULL)) { + return NULL; + } else { + return ECCurveParams_dup(ecCurve_map[name], kmflag); + } +} + +/* Free the memory allocated (if any) to an ECCurveParams object. */ +void +EC_FreeCurveParams(ECCurveParams * params) +{ + if (params == NULL) + return; + if (params->text != NULL) +#ifdef _KERNEL + kmem_free(params->text, strlen(params->text) + 1); +#else + free(params->text); +#endif + if (params->irr != NULL) +#ifdef _KERNEL + kmem_free(params->irr, strlen(params->irr) + 1); +#else + free(params->irr); +#endif + if (params->curvea != NULL) +#ifdef _KERNEL + kmem_free(params->curvea, strlen(params->curvea) + 1); +#else + free(params->curvea); +#endif + if (params->curveb != NULL) +#ifdef _KERNEL + kmem_free(params->curveb, strlen(params->curveb) + 1); +#else + free(params->curveb); +#endif + if (params->genx != NULL) +#ifdef _KERNEL + kmem_free(params->genx, strlen(params->genx) + 1); +#else + free(params->genx); +#endif + if (params->geny != NULL) +#ifdef _KERNEL + kmem_free(params->geny, strlen(params->geny) + 1); +#else + free(params->geny); +#endif + if (params->order != NULL) +#ifdef _KERNEL + kmem_free(params->order, strlen(params->order) + 1); +#else + free(params->order); +#endif +#ifdef _KERNEL + kmem_free(params, sizeof(ECCurveParams)); +#else + free(params); +#endif +} diff --git a/src/share/native/sun/security/ec/impl/ecl_gf.c b/src/share/native/sun/security/ec/impl/ecl_gf.c new file mode 100644 index 0000000000000000000000000000000000000000..a651fa84e7c220a07e5049355a00634e9f171bc7 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl_gf.c @@ -0,0 +1,1062 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Stephen Fung and + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mpi.h" +#include "mp_gf2m.h" +#include "ecl-priv.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Allocate memory for a new GFMethod object. */ +GFMethod * +GFMethod_new(int kmflag) +{ + mp_err res = MP_OKAY; + GFMethod *meth; +#ifdef _KERNEL + meth = (GFMethod *) kmem_alloc(sizeof(GFMethod), kmflag); +#else + meth = (GFMethod *) malloc(sizeof(GFMethod)); + if (meth == NULL) + return NULL; +#endif + meth->constructed = MP_YES; + MP_DIGITS(&meth->irr) = 0; + meth->extra_free = NULL; + MP_CHECKOK(mp_init(&meth->irr, kmflag)); + + CLEANUP: + if (res != MP_OKAY) { + GFMethod_free(meth); + return NULL; + } + return meth; +} + +/* Construct a generic GFMethod for arithmetic over prime fields with + * irreducible irr. */ +GFMethod * +GFMethod_consGFp(const mp_int *irr) +{ + mp_err res = MP_OKAY; + GFMethod *meth = NULL; + + meth = GFMethod_new(FLAG(irr)); + if (meth == NULL) + return NULL; + + MP_CHECKOK(mp_copy(irr, &meth->irr)); + meth->irr_arr[0] = mpl_significant_bits(irr); + meth->irr_arr[1] = meth->irr_arr[2] = meth->irr_arr[3] = + meth->irr_arr[4] = 0; + switch(MP_USED(&meth->irr)) { + /* maybe we need 1 and 2 words here as well?*/ + case 3: + meth->field_add = &ec_GFp_add_3; + meth->field_sub = &ec_GFp_sub_3; + break; + case 4: + meth->field_add = &ec_GFp_add_4; + meth->field_sub = &ec_GFp_sub_4; + break; + case 5: + meth->field_add = &ec_GFp_add_5; + meth->field_sub = &ec_GFp_sub_5; + break; + case 6: + meth->field_add = &ec_GFp_add_6; + meth->field_sub = &ec_GFp_sub_6; + break; + default: + meth->field_add = &ec_GFp_add; + meth->field_sub = &ec_GFp_sub; + } + meth->field_neg = &ec_GFp_neg; + meth->field_mod = &ec_GFp_mod; + meth->field_mul = &ec_GFp_mul; + meth->field_sqr = &ec_GFp_sqr; + meth->field_div = &ec_GFp_div; + meth->field_enc = NULL; + meth->field_dec = NULL; + meth->extra1 = NULL; + meth->extra2 = NULL; + meth->extra_free = NULL; + + CLEANUP: + if (res != MP_OKAY) { + GFMethod_free(meth); + return NULL; + } + return meth; +} + +/* Construct a generic GFMethod for arithmetic over binary polynomial + * fields with irreducible irr that has array representation irr_arr (see + * ecl-priv.h for description of the representation). If irr_arr is NULL, + * then it is constructed from the bitstring representation. */ +GFMethod * +GFMethod_consGF2m(const mp_int *irr, const unsigned int irr_arr[5]) +{ + mp_err res = MP_OKAY; + int ret; + GFMethod *meth = NULL; + + meth = GFMethod_new(FLAG(irr)); + if (meth == NULL) + return NULL; + + MP_CHECKOK(mp_copy(irr, &meth->irr)); + if (irr_arr != NULL) { + /* Irreducible polynomials are either trinomials or pentanomials. */ + meth->irr_arr[0] = irr_arr[0]; + meth->irr_arr[1] = irr_arr[1]; + meth->irr_arr[2] = irr_arr[2]; + if (irr_arr[2] > 0) { + meth->irr_arr[3] = irr_arr[3]; + meth->irr_arr[4] = irr_arr[4]; + } else { + meth->irr_arr[3] = meth->irr_arr[4] = 0; + } + } else { + ret = mp_bpoly2arr(irr, meth->irr_arr, 5); + /* Irreducible polynomials are either trinomials or pentanomials. */ + if ((ret != 5) && (ret != 3)) { + res = MP_UNDEF; + goto CLEANUP; + } + } + meth->field_add = &ec_GF2m_add; + meth->field_neg = &ec_GF2m_neg; + meth->field_sub = &ec_GF2m_add; + meth->field_mod = &ec_GF2m_mod; + meth->field_mul = &ec_GF2m_mul; + meth->field_sqr = &ec_GF2m_sqr; + meth->field_div = &ec_GF2m_div; + meth->field_enc = NULL; + meth->field_dec = NULL; + meth->extra1 = NULL; + meth->extra2 = NULL; + meth->extra_free = NULL; + + CLEANUP: + if (res != MP_OKAY) { + GFMethod_free(meth); + return NULL; + } + return meth; +} + +/* Free the memory allocated (if any) to a GFMethod object. */ +void +GFMethod_free(GFMethod *meth) +{ + if (meth == NULL) + return; + if (meth->constructed == MP_NO) + return; + mp_clear(&meth->irr); + if (meth->extra_free != NULL) + meth->extra_free(meth); +#ifdef _KERNEL + kmem_free(meth, sizeof(GFMethod)); +#else + free(meth); +#endif +} + +/* Wrapper functions for generic prime field arithmetic. */ + +/* Add two field elements. Assumes that 0 <= a, b < meth->irr */ +mp_err +ec_GFp_add(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + /* PRE: 0 <= a, b < p = meth->irr POST: 0 <= r < p, r = a + b (mod p) */ + mp_err res; + + if ((res = mp_add(a, b, r)) != MP_OKAY) { + return res; + } + if (mp_cmp(r, &meth->irr) >= 0) { + return mp_sub(r, &meth->irr, r); + } + return res; +} + +/* Negates a field element. Assumes that 0 <= a < meth->irr */ +mp_err +ec_GFp_neg(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + /* PRE: 0 <= a < p = meth->irr POST: 0 <= r < p, r = -a (mod p) */ + + if (mp_cmp_z(a) == 0) { + mp_zero(r); + return MP_OKAY; + } + return mp_sub(&meth->irr, a, r); +} + +/* Subtracts two field elements. Assumes that 0 <= a, b < meth->irr */ +mp_err +ec_GFp_sub(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + /* PRE: 0 <= a, b < p = meth->irr POST: 0 <= r < p, r = a - b (mod p) */ + res = mp_sub(a, b, r); + if (res == MP_RANGE) { + MP_CHECKOK(mp_sub(b, a, r)); + if (mp_cmp_z(r) < 0) { + MP_CHECKOK(mp_add(r, &meth->irr, r)); + } + MP_CHECKOK(ec_GFp_neg(r, r, meth)); + } + if (mp_cmp_z(r) < 0) { + MP_CHECKOK(mp_add(r, &meth->irr, r)); + } + CLEANUP: + return res; +} +/* + * Inline adds for small curve lengths. + */ +/* 3 words */ +mp_err +ec_GFp_add_3(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a0 = 0, a1 = 0, a2 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0; + mp_digit carry; + + switch(MP_USED(a)) { + case 3: + a2 = MP_DIGIT(a,2); + case 2: + a1 = MP_DIGIT(a,1); + case 1: + a0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 3: + r2 = MP_DIGIT(b,2); + case 2: + r1 = MP_DIGIT(b,1); + case 1: + r0 = MP_DIGIT(b,0); + } + +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(a0, r0, r0, 0, carry); + MP_ADD_CARRY(a1, r1, r1, carry, carry); + MP_ADD_CARRY(a2, r2, r2, carry, carry); +#else + __asm__ ( + "xorq %3,%3 \n\t" + "addq %4,%0 \n\t" + "adcq %5,%1 \n\t" + "adcq %6,%2 \n\t" + "adcq $0,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(carry) + : "r" (a0), "r" (a1), "r" (a2), + "0" (r0), "1" (r1), "2" (r2) + : "%cc" ); +#endif + + MP_CHECKOK(s_mp_pad(r, 3)); + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 3; + + /* Do quick 'subract' if we've gone over + * (add the 2's complement of the curve field) */ + a2 = MP_DIGIT(&meth->irr,2); + if (carry || r2 > a2 || + ((r2 == a2) && mp_cmp(r,&meth->irr) != MP_LT)) { + a1 = MP_DIGIT(&meth->irr,1); + a0 = MP_DIGIT(&meth->irr,0); +#ifndef MPI_AMD64_ADD + MP_SUB_BORROW(r0, a0, r0, 0, carry); + MP_SUB_BORROW(r1, a1, r1, carry, carry); + MP_SUB_BORROW(r2, a2, r2, carry, carry); +#else + __asm__ ( + "subq %3,%0 \n\t" + "sbbq %4,%1 \n\t" + "sbbq %5,%2 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2) + : "r" (a0), "r" (a1), "r" (a2), + "0" (r0), "1" (r1), "2" (r2) + : "%cc" ); +#endif + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + } + + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* 4 words */ +mp_err +ec_GFp_add_4(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a0 = 0, a1 = 0, a2 = 0, a3 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0, r3 = 0; + mp_digit carry; + + switch(MP_USED(a)) { + case 4: + a3 = MP_DIGIT(a,3); + case 3: + a2 = MP_DIGIT(a,2); + case 2: + a1 = MP_DIGIT(a,1); + case 1: + a0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 4: + r3 = MP_DIGIT(b,3); + case 3: + r2 = MP_DIGIT(b,2); + case 2: + r1 = MP_DIGIT(b,1); + case 1: + r0 = MP_DIGIT(b,0); + } + +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(a0, r0, r0, 0, carry); + MP_ADD_CARRY(a1, r1, r1, carry, carry); + MP_ADD_CARRY(a2, r2, r2, carry, carry); + MP_ADD_CARRY(a3, r3, r3, carry, carry); +#else + __asm__ ( + "xorq %4,%4 \n\t" + "addq %5,%0 \n\t" + "adcq %6,%1 \n\t" + "adcq %7,%2 \n\t" + "adcq %8,%3 \n\t" + "adcq $0,%4 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3), "=r"(carry) + : "r" (a0), "r" (a1), "r" (a2), "r" (a3), + "0" (r0), "1" (r1), "2" (r2), "3" (r3) + : "%cc" ); +#endif + + MP_CHECKOK(s_mp_pad(r, 4)); + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 4; + + /* Do quick 'subract' if we've gone over + * (add the 2's complement of the curve field) */ + a3 = MP_DIGIT(&meth->irr,3); + if (carry || r3 > a3 || + ((r3 == a3) && mp_cmp(r,&meth->irr) != MP_LT)) { + a2 = MP_DIGIT(&meth->irr,2); + a1 = MP_DIGIT(&meth->irr,1); + a0 = MP_DIGIT(&meth->irr,0); +#ifndef MPI_AMD64_ADD + MP_SUB_BORROW(r0, a0, r0, 0, carry); + MP_SUB_BORROW(r1, a1, r1, carry, carry); + MP_SUB_BORROW(r2, a2, r2, carry, carry); + MP_SUB_BORROW(r3, a3, r3, carry, carry); +#else + __asm__ ( + "subq %4,%0 \n\t" + "sbbq %5,%1 \n\t" + "sbbq %6,%2 \n\t" + "sbbq %7,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) + : "r" (a0), "r" (a1), "r" (a2), "r" (a3), + "0" (r0), "1" (r1), "2" (r2), "3" (r3) + : "%cc" ); +#endif + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + } + + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* 5 words */ +mp_err +ec_GFp_add_5(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a0 = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0; + mp_digit carry; + + switch(MP_USED(a)) { + case 5: + a4 = MP_DIGIT(a,4); + case 4: + a3 = MP_DIGIT(a,3); + case 3: + a2 = MP_DIGIT(a,2); + case 2: + a1 = MP_DIGIT(a,1); + case 1: + a0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 5: + r4 = MP_DIGIT(b,4); + case 4: + r3 = MP_DIGIT(b,3); + case 3: + r2 = MP_DIGIT(b,2); + case 2: + r1 = MP_DIGIT(b,1); + case 1: + r0 = MP_DIGIT(b,0); + } + + MP_ADD_CARRY(a0, r0, r0, 0, carry); + MP_ADD_CARRY(a1, r1, r1, carry, carry); + MP_ADD_CARRY(a2, r2, r2, carry, carry); + MP_ADD_CARRY(a3, r3, r3, carry, carry); + MP_ADD_CARRY(a4, r4, r4, carry, carry); + + MP_CHECKOK(s_mp_pad(r, 5)); + MP_DIGIT(r, 4) = r4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 5; + + /* Do quick 'subract' if we've gone over + * (add the 2's complement of the curve field) */ + a4 = MP_DIGIT(&meth->irr,4); + if (carry || r4 > a4 || + ((r4 == a4) && mp_cmp(r,&meth->irr) != MP_LT)) { + a3 = MP_DIGIT(&meth->irr,3); + a2 = MP_DIGIT(&meth->irr,2); + a1 = MP_DIGIT(&meth->irr,1); + a0 = MP_DIGIT(&meth->irr,0); + MP_SUB_BORROW(r0, a0, r0, 0, carry); + MP_SUB_BORROW(r1, a1, r1, carry, carry); + MP_SUB_BORROW(r2, a2, r2, carry, carry); + MP_SUB_BORROW(r3, a3, r3, carry, carry); + MP_SUB_BORROW(r4, a4, r4, carry, carry); + MP_DIGIT(r, 4) = r4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + } + + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* 6 words */ +mp_err +ec_GFp_add_6(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a0 = 0, a1 = 0, a2 = 0, a3 = 0, a4 = 0, a5 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, r5 = 0; + mp_digit carry; + + switch(MP_USED(a)) { + case 6: + a5 = MP_DIGIT(a,5); + case 5: + a4 = MP_DIGIT(a,4); + case 4: + a3 = MP_DIGIT(a,3); + case 3: + a2 = MP_DIGIT(a,2); + case 2: + a1 = MP_DIGIT(a,1); + case 1: + a0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 6: + r5 = MP_DIGIT(b,5); + case 5: + r4 = MP_DIGIT(b,4); + case 4: + r3 = MP_DIGIT(b,3); + case 3: + r2 = MP_DIGIT(b,2); + case 2: + r1 = MP_DIGIT(b,1); + case 1: + r0 = MP_DIGIT(b,0); + } + + MP_ADD_CARRY(a0, r0, r0, 0, carry); + MP_ADD_CARRY(a1, r1, r1, carry, carry); + MP_ADD_CARRY(a2, r2, r2, carry, carry); + MP_ADD_CARRY(a3, r3, r3, carry, carry); + MP_ADD_CARRY(a4, r4, r4, carry, carry); + MP_ADD_CARRY(a5, r5, r5, carry, carry); + + MP_CHECKOK(s_mp_pad(r, 6)); + MP_DIGIT(r, 5) = r5; + MP_DIGIT(r, 4) = r4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 6; + + /* Do quick 'subract' if we've gone over + * (add the 2's complement of the curve field) */ + a5 = MP_DIGIT(&meth->irr,5); + if (carry || r5 > a5 || + ((r5 == a5) && mp_cmp(r,&meth->irr) != MP_LT)) { + a4 = MP_DIGIT(&meth->irr,4); + a3 = MP_DIGIT(&meth->irr,3); + a2 = MP_DIGIT(&meth->irr,2); + a1 = MP_DIGIT(&meth->irr,1); + a0 = MP_DIGIT(&meth->irr,0); + MP_SUB_BORROW(r0, a0, r0, 0, carry); + MP_SUB_BORROW(r1, a1, r1, carry, carry); + MP_SUB_BORROW(r2, a2, r2, carry, carry); + MP_SUB_BORROW(r3, a3, r3, carry, carry); + MP_SUB_BORROW(r4, a4, r4, carry, carry); + MP_SUB_BORROW(r5, a5, r5, carry, carry); + MP_DIGIT(r, 5) = r5; + MP_DIGIT(r, 4) = r4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + } + + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* + * The following subraction functions do in-line subractions based + * on our curve size. + * + * ... 3 words + */ +mp_err +ec_GFp_sub_3(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit b0 = 0, b1 = 0, b2 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0; + mp_digit borrow; + + switch(MP_USED(a)) { + case 3: + r2 = MP_DIGIT(a,2); + case 2: + r1 = MP_DIGIT(a,1); + case 1: + r0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 3: + b2 = MP_DIGIT(b,2); + case 2: + b1 = MP_DIGIT(b,1); + case 1: + b0 = MP_DIGIT(b,0); + } + +#ifndef MPI_AMD64_ADD + MP_SUB_BORROW(r0, b0, r0, 0, borrow); + MP_SUB_BORROW(r1, b1, r1, borrow, borrow); + MP_SUB_BORROW(r2, b2, r2, borrow, borrow); +#else + __asm__ ( + "xorq %3,%3 \n\t" + "subq %4,%0 \n\t" + "sbbq %5,%1 \n\t" + "sbbq %6,%2 \n\t" + "adcq $0,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r" (borrow) + : "r" (b0), "r" (b1), "r" (b2), + "0" (r0), "1" (r1), "2" (r2) + : "%cc" ); +#endif + + /* Do quick 'add' if we've gone under 0 + * (subtract the 2's complement of the curve field) */ + if (borrow) { + b2 = MP_DIGIT(&meth->irr,2); + b1 = MP_DIGIT(&meth->irr,1); + b0 = MP_DIGIT(&meth->irr,0); +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(b0, r0, r0, 0, borrow); + MP_ADD_CARRY(b1, r1, r1, borrow, borrow); + MP_ADD_CARRY(b2, r2, r2, borrow, borrow); +#else + __asm__ ( + "addq %3,%0 \n\t" + "adcq %4,%1 \n\t" + "adcq %5,%2 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2) + : "r" (b0), "r" (b1), "r" (b2), + "0" (r0), "1" (r1), "2" (r2) + : "%cc" ); +#endif + } + +#ifdef MPI_AMD64_ADD + /* compiler fakeout? */ + if ((r2 == b0) && (r1 == b0) && (r0 == b0)) { + MP_CHECKOK(s_mp_pad(r, 4)); + } +#endif + MP_CHECKOK(s_mp_pad(r, 3)); + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 3; + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* 4 words */ +mp_err +ec_GFp_sub_4(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit b0 = 0, b1 = 0, b2 = 0, b3 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0, r3 = 0; + mp_digit borrow; + + switch(MP_USED(a)) { + case 4: + r3 = MP_DIGIT(a,3); + case 3: + r2 = MP_DIGIT(a,2); + case 2: + r1 = MP_DIGIT(a,1); + case 1: + r0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 4: + b3 = MP_DIGIT(b,3); + case 3: + b2 = MP_DIGIT(b,2); + case 2: + b1 = MP_DIGIT(b,1); + case 1: + b0 = MP_DIGIT(b,0); + } + +#ifndef MPI_AMD64_ADD + MP_SUB_BORROW(r0, b0, r0, 0, borrow); + MP_SUB_BORROW(r1, b1, r1, borrow, borrow); + MP_SUB_BORROW(r2, b2, r2, borrow, borrow); + MP_SUB_BORROW(r3, b3, r3, borrow, borrow); +#else + __asm__ ( + "xorq %4,%4 \n\t" + "subq %5,%0 \n\t" + "sbbq %6,%1 \n\t" + "sbbq %7,%2 \n\t" + "sbbq %8,%3 \n\t" + "adcq $0,%4 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3), "=r" (borrow) + : "r" (b0), "r" (b1), "r" (b2), "r" (b3), + "0" (r0), "1" (r1), "2" (r2), "3" (r3) + : "%cc" ); +#endif + + /* Do quick 'add' if we've gone under 0 + * (subtract the 2's complement of the curve field) */ + if (borrow) { + b3 = MP_DIGIT(&meth->irr,3); + b2 = MP_DIGIT(&meth->irr,2); + b1 = MP_DIGIT(&meth->irr,1); + b0 = MP_DIGIT(&meth->irr,0); +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(b0, r0, r0, 0, borrow); + MP_ADD_CARRY(b1, r1, r1, borrow, borrow); + MP_ADD_CARRY(b2, r2, r2, borrow, borrow); + MP_ADD_CARRY(b3, r3, r3, borrow, borrow); +#else + __asm__ ( + "addq %4,%0 \n\t" + "adcq %5,%1 \n\t" + "adcq %6,%2 \n\t" + "adcq %7,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3) + : "r" (b0), "r" (b1), "r" (b2), "r" (b3), + "0" (r0), "1" (r1), "2" (r2), "3" (r3) + : "%cc" ); +#endif + } +#ifdef MPI_AMD64_ADD + /* compiler fakeout? */ + if ((r3 == b0) && (r1 == b0) && (r0 == b0)) { + MP_CHECKOK(s_mp_pad(r, 4)); + } +#endif + MP_CHECKOK(s_mp_pad(r, 4)); + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 4; + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* 5 words */ +mp_err +ec_GFp_sub_5(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0; + mp_digit borrow; + + switch(MP_USED(a)) { + case 5: + r4 = MP_DIGIT(a,4); + case 4: + r3 = MP_DIGIT(a,3); + case 3: + r2 = MP_DIGIT(a,2); + case 2: + r1 = MP_DIGIT(a,1); + case 1: + r0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 5: + b4 = MP_DIGIT(b,4); + case 4: + b3 = MP_DIGIT(b,3); + case 3: + b2 = MP_DIGIT(b,2); + case 2: + b1 = MP_DIGIT(b,1); + case 1: + b0 = MP_DIGIT(b,0); + } + + MP_SUB_BORROW(r0, b0, r0, 0, borrow); + MP_SUB_BORROW(r1, b1, r1, borrow, borrow); + MP_SUB_BORROW(r2, b2, r2, borrow, borrow); + MP_SUB_BORROW(r3, b3, r3, borrow, borrow); + MP_SUB_BORROW(r4, b4, r4, borrow, borrow); + + /* Do quick 'add' if we've gone under 0 + * (subtract the 2's complement of the curve field) */ + if (borrow) { + b4 = MP_DIGIT(&meth->irr,4); + b3 = MP_DIGIT(&meth->irr,3); + b2 = MP_DIGIT(&meth->irr,2); + b1 = MP_DIGIT(&meth->irr,1); + b0 = MP_DIGIT(&meth->irr,0); + MP_ADD_CARRY(b0, r0, r0, 0, borrow); + MP_ADD_CARRY(b1, r1, r1, borrow, borrow); + MP_ADD_CARRY(b2, r2, r2, borrow, borrow); + MP_ADD_CARRY(b3, r3, r3, borrow, borrow); + } + MP_CHECKOK(s_mp_pad(r, 5)); + MP_DIGIT(r, 4) = r4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 5; + s_mp_clamp(r); + + CLEANUP: + return res; +} + +/* 6 words */ +mp_err +ec_GFp_sub_6(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0, r3 = 0, r4 = 0, r5 = 0; + mp_digit borrow; + + switch(MP_USED(a)) { + case 6: + r5 = MP_DIGIT(a,5); + case 5: + r4 = MP_DIGIT(a,4); + case 4: + r3 = MP_DIGIT(a,3); + case 3: + r2 = MP_DIGIT(a,2); + case 2: + r1 = MP_DIGIT(a,1); + case 1: + r0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 6: + b5 = MP_DIGIT(b,5); + case 5: + b4 = MP_DIGIT(b,4); + case 4: + b3 = MP_DIGIT(b,3); + case 3: + b2 = MP_DIGIT(b,2); + case 2: + b1 = MP_DIGIT(b,1); + case 1: + b0 = MP_DIGIT(b,0); + } + + MP_SUB_BORROW(r0, b0, r0, 0, borrow); + MP_SUB_BORROW(r1, b1, r1, borrow, borrow); + MP_SUB_BORROW(r2, b2, r2, borrow, borrow); + MP_SUB_BORROW(r3, b3, r3, borrow, borrow); + MP_SUB_BORROW(r4, b4, r4, borrow, borrow); + MP_SUB_BORROW(r5, b5, r5, borrow, borrow); + + /* Do quick 'add' if we've gone under 0 + * (subtract the 2's complement of the curve field) */ + if (borrow) { + b5 = MP_DIGIT(&meth->irr,5); + b4 = MP_DIGIT(&meth->irr,4); + b3 = MP_DIGIT(&meth->irr,3); + b2 = MP_DIGIT(&meth->irr,2); + b1 = MP_DIGIT(&meth->irr,1); + b0 = MP_DIGIT(&meth->irr,0); + MP_ADD_CARRY(b0, r0, r0, 0, borrow); + MP_ADD_CARRY(b1, r1, r1, borrow, borrow); + MP_ADD_CARRY(b2, r2, r2, borrow, borrow); + MP_ADD_CARRY(b3, r3, r3, borrow, borrow); + MP_ADD_CARRY(b4, r4, r4, borrow, borrow); + } + + MP_CHECKOK(s_mp_pad(r, 6)); + MP_DIGIT(r, 5) = r5; + MP_DIGIT(r, 4) = r4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 6; + s_mp_clamp(r); + + CLEANUP: + return res; +} + + +/* Reduces an integer to a field element. */ +mp_err +ec_GFp_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + return mp_mod(a, &meth->irr, r); +} + +/* Multiplies two field elements. */ +mp_err +ec_GFp_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + return mp_mulmod(a, b, &meth->irr, r); +} + +/* Squares a field element. */ +mp_err +ec_GFp_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + return mp_sqrmod(a, &meth->irr, r); +} + +/* Divides two field elements. If a is NULL, then returns the inverse of + * b. */ +mp_err +ec_GFp_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_int t; + + /* If a is NULL, then return the inverse of b, otherwise return a/b. */ + if (a == NULL) { + return mp_invmod(b, &meth->irr, r); + } else { + /* MPI doesn't support divmod, so we implement it using invmod and + * mulmod. */ + MP_CHECKOK(mp_init(&t, FLAG(b))); + MP_CHECKOK(mp_invmod(b, &meth->irr, &t)); + MP_CHECKOK(mp_mulmod(a, &t, &meth->irr, r)); + CLEANUP: + mp_clear(&t); + return res; + } +} + +/* Wrapper functions for generic binary polynomial field arithmetic. */ + +/* Adds two field elements. */ +mp_err +ec_GF2m_add(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + return mp_badd(a, b, r); +} + +/* Negates a field element. Note that for binary polynomial fields, the + * negation of a field element is the field element itself. */ +mp_err +ec_GF2m_neg(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + if (a == r) { + return MP_OKAY; + } else { + return mp_copy(a, r); + } +} + +/* Reduces a binary polynomial to a field element. */ +mp_err +ec_GF2m_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + return mp_bmod(a, meth->irr_arr, r); +} + +/* Multiplies two field elements. */ +mp_err +ec_GF2m_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + return mp_bmulmod(a, b, meth->irr_arr, r); +} + +/* Squares a field element. */ +mp_err +ec_GF2m_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + return mp_bsqrmod(a, meth->irr_arr, r); +} + +/* Divides two field elements. If a is NULL, then returns the inverse of + * b. */ +mp_err +ec_GF2m_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_int t; + + /* If a is NULL, then return the inverse of b, otherwise return a/b. */ + if (a == NULL) { + /* The GF(2^m) portion of MPI doesn't support invmod, so we + * compute 1/b. */ + MP_CHECKOK(mp_init(&t, FLAG(b))); + MP_CHECKOK(mp_set_int(&t, 1)); + MP_CHECKOK(mp_bdivmod(&t, b, &meth->irr, meth->irr_arr, r)); + CLEANUP: + mp_clear(&t); + return res; + } else { + return mp_bdivmod(a, b, &meth->irr, meth->irr_arr, r); + } +} diff --git a/src/share/native/sun/security/ec/impl/ecl_mult.c b/src/share/native/sun/security/ec/impl/ecl_mult.c new file mode 100644 index 0000000000000000000000000000000000000000..c5a01fabad328f3812cbcd81fa9097c11337b776 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecl_mult.c @@ -0,0 +1,378 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mpi.h" +#include "mplogic.h" +#include "ecl.h" +#include "ecl-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Elliptic curve scalar-point multiplication. Computes R(x, y) = k * P(x, + * y). If x, y = NULL, then P is assumed to be the generator (base point) + * of the group of points on the elliptic curve. Input and output values + * are assumed to be NOT field-encoded. */ +mp_err +ECPoint_mul(const ECGroup *group, const mp_int *k, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry) +{ + mp_err res = MP_OKAY; + mp_int kt; + + ARGCHK((k != NULL) && (group != NULL), MP_BADARG); + MP_DIGITS(&kt) = 0; + + /* want scalar to be less than or equal to group order */ + if (mp_cmp(k, &group->order) > 0) { + MP_CHECKOK(mp_init(&kt, FLAG(k))); + MP_CHECKOK(mp_mod(k, &group->order, &kt)); + } else { + MP_SIGN(&kt) = MP_ZPOS; + MP_USED(&kt) = MP_USED(k); + MP_ALLOC(&kt) = MP_ALLOC(k); + MP_DIGITS(&kt) = MP_DIGITS(k); + } + + if ((px == NULL) || (py == NULL)) { + if (group->base_point_mul) { + MP_CHECKOK(group->base_point_mul(&kt, rx, ry, group)); + } else { + MP_CHECKOK(group-> + point_mul(&kt, &group->genx, &group->geny, rx, ry, + group)); + } + } else { + if (group->meth->field_enc) { + MP_CHECKOK(group->meth->field_enc(px, rx, group->meth)); + MP_CHECKOK(group->meth->field_enc(py, ry, group->meth)); + MP_CHECKOK(group->point_mul(&kt, rx, ry, rx, ry, group)); + } else { + MP_CHECKOK(group->point_mul(&kt, px, py, rx, ry, group)); + } + } + if (group->meth->field_dec) { + MP_CHECKOK(group->meth->field_dec(rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_dec(ry, ry, group->meth)); + } + + CLEANUP: + if (MP_DIGITS(&kt) != MP_DIGITS(k)) { + mp_clear(&kt); + } + return res; +} + +/* Elliptic curve scalar-point multiplication. Computes R(x, y) = k1 * G + + * k2 * P(x, y), where G is the generator (base point) of the group of + * points on the elliptic curve. Allows k1 = NULL or { k2, P } = NULL. + * Input and output values are assumed to be NOT field-encoded. */ +mp_err +ec_pts_mul_basic(const mp_int *k1, const mp_int *k2, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int sx, sy; + + ARGCHK(group != NULL, MP_BADARG); + ARGCHK(!((k1 == NULL) + && ((k2 == NULL) || (px == NULL) + || (py == NULL))), MP_BADARG); + + /* if some arguments are not defined used ECPoint_mul */ + if (k1 == NULL) { + return ECPoint_mul(group, k2, px, py, rx, ry); + } else if ((k2 == NULL) || (px == NULL) || (py == NULL)) { + return ECPoint_mul(group, k1, NULL, NULL, rx, ry); + } + + MP_DIGITS(&sx) = 0; + MP_DIGITS(&sy) = 0; + MP_CHECKOK(mp_init(&sx, FLAG(k1))); + MP_CHECKOK(mp_init(&sy, FLAG(k1))); + + MP_CHECKOK(ECPoint_mul(group, k1, NULL, NULL, &sx, &sy)); + MP_CHECKOK(ECPoint_mul(group, k2, px, py, rx, ry)); + + if (group->meth->field_enc) { + MP_CHECKOK(group->meth->field_enc(&sx, &sx, group->meth)); + MP_CHECKOK(group->meth->field_enc(&sy, &sy, group->meth)); + MP_CHECKOK(group->meth->field_enc(rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_enc(ry, ry, group->meth)); + } + + MP_CHECKOK(group->point_add(&sx, &sy, rx, ry, rx, ry, group)); + + if (group->meth->field_dec) { + MP_CHECKOK(group->meth->field_dec(rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_dec(ry, ry, group->meth)); + } + + CLEANUP: + mp_clear(&sx); + mp_clear(&sy); + return res; +} + +/* Elliptic curve scalar-point multiplication. Computes R(x, y) = k1 * G + + * k2 * P(x, y), where G is the generator (base point) of the group of + * points on the elliptic curve. Allows k1 = NULL or { k2, P } = NULL. + * Input and output values are assumed to be NOT field-encoded. Uses + * algorithm 15 (simultaneous multiple point multiplication) from Brown, + * Hankerson, Lopez, Menezes. Software Implementation of the NIST + * Elliptic Curves over Prime Fields. */ +mp_err +ec_pts_mul_simul_w2(const mp_int *k1, const mp_int *k2, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int precomp[4][4][2]; + const mp_int *a, *b; + int i, j; + int ai, bi, d; + + ARGCHK(group != NULL, MP_BADARG); + ARGCHK(!((k1 == NULL) + && ((k2 == NULL) || (px == NULL) + || (py == NULL))), MP_BADARG); + + /* if some arguments are not defined used ECPoint_mul */ + if (k1 == NULL) { + return ECPoint_mul(group, k2, px, py, rx, ry); + } else if ((k2 == NULL) || (px == NULL) || (py == NULL)) { + return ECPoint_mul(group, k1, NULL, NULL, rx, ry); + } + + /* initialize precomputation table */ + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + MP_DIGITS(&precomp[i][j][0]) = 0; + MP_DIGITS(&precomp[i][j][1]) = 0; + } + } + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + MP_CHECKOK( mp_init_size(&precomp[i][j][0], + ECL_MAX_FIELD_SIZE_DIGITS, FLAG(k1)) ); + MP_CHECKOK( mp_init_size(&precomp[i][j][1], + ECL_MAX_FIELD_SIZE_DIGITS, FLAG(k1)) ); + } + } + + /* fill precomputation table */ + /* assign {k1, k2} = {a, b} such that len(a) >= len(b) */ + if (mpl_significant_bits(k1) < mpl_significant_bits(k2)) { + a = k2; + b = k1; + if (group->meth->field_enc) { + MP_CHECKOK(group->meth-> + field_enc(px, &precomp[1][0][0], group->meth)); + MP_CHECKOK(group->meth-> + field_enc(py, &precomp[1][0][1], group->meth)); + } else { + MP_CHECKOK(mp_copy(px, &precomp[1][0][0])); + MP_CHECKOK(mp_copy(py, &precomp[1][0][1])); + } + MP_CHECKOK(mp_copy(&group->genx, &precomp[0][1][0])); + MP_CHECKOK(mp_copy(&group->geny, &precomp[0][1][1])); + } else { + a = k1; + b = k2; + MP_CHECKOK(mp_copy(&group->genx, &precomp[1][0][0])); + MP_CHECKOK(mp_copy(&group->geny, &precomp[1][0][1])); + if (group->meth->field_enc) { + MP_CHECKOK(group->meth-> + field_enc(px, &precomp[0][1][0], group->meth)); + MP_CHECKOK(group->meth-> + field_enc(py, &precomp[0][1][1], group->meth)); + } else { + MP_CHECKOK(mp_copy(px, &precomp[0][1][0])); + MP_CHECKOK(mp_copy(py, &precomp[0][1][1])); + } + } + /* precompute [*][0][*] */ + mp_zero(&precomp[0][0][0]); + mp_zero(&precomp[0][0][1]); + MP_CHECKOK(group-> + point_dbl(&precomp[1][0][0], &precomp[1][0][1], + &precomp[2][0][0], &precomp[2][0][1], group)); + MP_CHECKOK(group-> + point_add(&precomp[1][0][0], &precomp[1][0][1], + &precomp[2][0][0], &precomp[2][0][1], + &precomp[3][0][0], &precomp[3][0][1], group)); + /* precompute [*][1][*] */ + for (i = 1; i < 4; i++) { + MP_CHECKOK(group-> + point_add(&precomp[0][1][0], &precomp[0][1][1], + &precomp[i][0][0], &precomp[i][0][1], + &precomp[i][1][0], &precomp[i][1][1], group)); + } + /* precompute [*][2][*] */ + MP_CHECKOK(group-> + point_dbl(&precomp[0][1][0], &precomp[0][1][1], + &precomp[0][2][0], &precomp[0][2][1], group)); + for (i = 1; i < 4; i++) { + MP_CHECKOK(group-> + point_add(&precomp[0][2][0], &precomp[0][2][1], + &precomp[i][0][0], &precomp[i][0][1], + &precomp[i][2][0], &precomp[i][2][1], group)); + } + /* precompute [*][3][*] */ + MP_CHECKOK(group-> + point_add(&precomp[0][1][0], &precomp[0][1][1], + &precomp[0][2][0], &precomp[0][2][1], + &precomp[0][3][0], &precomp[0][3][1], group)); + for (i = 1; i < 4; i++) { + MP_CHECKOK(group-> + point_add(&precomp[0][3][0], &precomp[0][3][1], + &precomp[i][0][0], &precomp[i][0][1], + &precomp[i][3][0], &precomp[i][3][1], group)); + } + + d = (mpl_significant_bits(a) + 1) / 2; + + /* R = inf */ + mp_zero(rx); + mp_zero(ry); + + for (i = d - 1; i >= 0; i--) { + ai = MP_GET_BIT(a, 2 * i + 1); + ai <<= 1; + ai |= MP_GET_BIT(a, 2 * i); + bi = MP_GET_BIT(b, 2 * i + 1); + bi <<= 1; + bi |= MP_GET_BIT(b, 2 * i); + /* R = 2^2 * R */ + MP_CHECKOK(group->point_dbl(rx, ry, rx, ry, group)); + MP_CHECKOK(group->point_dbl(rx, ry, rx, ry, group)); + /* R = R + (ai * A + bi * B) */ + MP_CHECKOK(group-> + point_add(rx, ry, &precomp[ai][bi][0], + &precomp[ai][bi][1], rx, ry, group)); + } + + if (group->meth->field_dec) { + MP_CHECKOK(group->meth->field_dec(rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_dec(ry, ry, group->meth)); + } + + CLEANUP: + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + mp_clear(&precomp[i][j][0]); + mp_clear(&precomp[i][j][1]); + } + } + return res; +} + +/* Elliptic curve scalar-point multiplication. Computes R(x, y) = k1 * G + + * k2 * P(x, y), where G is the generator (base point) of the group of + * points on the elliptic curve. Allows k1 = NULL or { k2, P } = NULL. + * Input and output values are assumed to be NOT field-encoded. */ +mp_err +ECPoints_mul(const ECGroup *group, const mp_int *k1, const mp_int *k2, + const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry) +{ + mp_err res = MP_OKAY; + mp_int k1t, k2t; + const mp_int *k1p, *k2p; + + MP_DIGITS(&k1t) = 0; + MP_DIGITS(&k2t) = 0; + + ARGCHK(group != NULL, MP_BADARG); + + /* want scalar to be less than or equal to group order */ + if (k1 != NULL) { + if (mp_cmp(k1, &group->order) >= 0) { + MP_CHECKOK(mp_init(&k1t, FLAG(k1))); + MP_CHECKOK(mp_mod(k1, &group->order, &k1t)); + k1p = &k1t; + } else { + k1p = k1; + } + } else { + k1p = k1; + } + if (k2 != NULL) { + if (mp_cmp(k2, &group->order) >= 0) { + MP_CHECKOK(mp_init(&k2t, FLAG(k2))); + MP_CHECKOK(mp_mod(k2, &group->order, &k2t)); + k2p = &k2t; + } else { + k2p = k2; + } + } else { + k2p = k2; + } + + /* if points_mul is defined, then use it */ + if (group->points_mul) { + res = group->points_mul(k1p, k2p, px, py, rx, ry, group); + } else { + res = ec_pts_mul_simul_w2(k1p, k2p, px, py, rx, ry, group); + } + + CLEANUP: + mp_clear(&k1t); + mp_clear(&k2t); + return res; +} diff --git a/src/share/native/sun/security/ec/impl/ecp.h b/src/share/native/sun/security/ec/impl/ecp.h new file mode 100644 index 0000000000000000000000000000000000000000..5e045ba63201babbdfd271ea3095846e3c20aec3 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp.h @@ -0,0 +1,160 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _ECP_H +#define _ECP_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecl-priv.h" + +/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */ +mp_err ec_GFp_pt_is_inf_aff(const mp_int *px, const mp_int *py); + +/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */ +mp_err ec_GFp_pt_set_inf_aff(mp_int *px, mp_int *py); + +/* Computes R = P + Q where R is (rx, ry), P is (px, py) and Q is (qx, + * qy). Uses affine coordinates. */ +mp_err ec_GFp_pt_add_aff(const mp_int *px, const mp_int *py, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Computes R = P - Q. Uses affine coordinates. */ +mp_err ec_GFp_pt_sub_aff(const mp_int *px, const mp_int *py, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Computes R = 2P. Uses affine coordinates. */ +mp_err ec_GFp_pt_dbl_aff(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group); + +/* Validates a point on a GFp curve. */ +mp_err ec_GFp_validate_point(const mp_int *px, const mp_int *py, const ECGroup *group); + +#ifdef ECL_ENABLE_GFP_PT_MUL_AFF +/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters + * a, b and p are the elliptic curve coefficients and the prime that + * determines the field GFp. Uses affine coordinates. */ +mp_err ec_GFp_pt_mul_aff(const mp_int *n, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); +#endif + +/* Converts a point P(px, py) from affine coordinates to Jacobian + * projective coordinates R(rx, ry, rz). */ +mp_err ec_GFp_pt_aff2jac(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, mp_int *rz, const ECGroup *group); + +/* Converts a point P(px, py, pz) from Jacobian projective coordinates to + * affine coordinates R(rx, ry). */ +mp_err ec_GFp_pt_jac2aff(const mp_int *px, const mp_int *py, + const mp_int *pz, mp_int *rx, mp_int *ry, + const ECGroup *group); + +/* Checks if point P(px, py, pz) is at infinity. Uses Jacobian + * coordinates. */ +mp_err ec_GFp_pt_is_inf_jac(const mp_int *px, const mp_int *py, + const mp_int *pz); + +/* Sets P(px, py, pz) to be the point at infinity. Uses Jacobian + * coordinates. */ +mp_err ec_GFp_pt_set_inf_jac(mp_int *px, mp_int *py, mp_int *pz); + +/* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and Q is + * (qx, qy, qz). Uses Jacobian coordinates. */ +mp_err ec_GFp_pt_add_jac_aff(const mp_int *px, const mp_int *py, + const mp_int *pz, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, + mp_int *rz, const ECGroup *group); + +/* Computes R = 2P. Uses Jacobian coordinates. */ +mp_err ec_GFp_pt_dbl_jac(const mp_int *px, const mp_int *py, + const mp_int *pz, mp_int *rx, mp_int *ry, + mp_int *rz, const ECGroup *group); + +#ifdef ECL_ENABLE_GFP_PT_MUL_JAC +/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters + * a, b and p are the elliptic curve coefficients and the prime that + * determines the field GFp. Uses Jacobian coordinates. */ +mp_err ec_GFp_pt_mul_jac(const mp_int *n, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); +#endif + +/* Computes R(x, y) = k1 * G + k2 * P(x, y), where G is the generator + * (base point) of the group of points on the elliptic curve. Allows k1 = + * NULL or { k2, P } = NULL. Implemented using mixed Jacobian-affine + * coordinates. Input and output values are assumed to be NOT + * field-encoded and are in affine form. */ +mp_err + ec_GFp_pts_mul_jac(const mp_int *k1, const mp_int *k2, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group); + +/* Computes R = nP where R is (rx, ry) and P is the base point. Elliptic + * curve points P and R can be identical. Uses mixed Modified-Jacobian + * co-ordinates for doubling and Chudnovsky Jacobian coordinates for + * additions. Assumes input is already field-encoded using field_enc, and + * returns output that is still field-encoded. Uses 5-bit window NAF + * method (algorithm 11) for scalar-point multiplication from Brown, + * Hankerson, Lopez, Menezes. Software Implementation of the NIST Elliptic + * Curves Over Prime Fields. */ +mp_err + ec_GFp_pt_mul_jm_wNAF(const mp_int *n, const mp_int *px, const mp_int *py, + mp_int *rx, mp_int *ry, const ECGroup *group); + +#endif /* _ECP_H */ diff --git a/src/share/native/sun/security/ec/impl/ecp_192.c b/src/share/native/sun/security/ec/impl/ecp_192.c new file mode 100644 index 0000000000000000000000000000000000000000..f2c62a40e909014b2cb25641ebbf675535ce0dbd --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_192.c @@ -0,0 +1,538 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mpi.h" +#include "mplogic.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +#define ECP192_DIGITS ECL_CURVE_DIGITS(192) + +/* Fast modular reduction for p192 = 2^192 - 2^64 - 1. a can be r. Uses + * algorithm 7 from Brown, Hankerson, Lopez, Menezes. Software + * Implementation of the NIST Elliptic Curves over Prime Fields. */ +mp_err +ec_GFp_nistp192_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_size a_used = MP_USED(a); + mp_digit r3; +#ifndef MPI_AMD64_ADD + mp_digit carry; +#endif +#ifdef ECL_THIRTY_TWO_BIT + mp_digit a5a = 0, a5b = 0, a4a = 0, a4b = 0, a3a = 0, a3b = 0; + mp_digit r0a, r0b, r1a, r1b, r2a, r2b; +#else + mp_digit a5 = 0, a4 = 0, a3 = 0; + mp_digit r0, r1, r2; +#endif + + /* reduction not needed if a is not larger than field size */ + if (a_used < ECP192_DIGITS) { + if (a == r) { + return MP_OKAY; + } + return mp_copy(a, r); + } + + /* for polynomials larger than twice the field size, use regular + * reduction */ + if (a_used > ECP192_DIGITS*2) { + MP_CHECKOK(mp_mod(a, &meth->irr, r)); + } else { + /* copy out upper words of a */ + +#ifdef ECL_THIRTY_TWO_BIT + + /* in all the math below, + * nXb is most signifiant, nXa is least significant */ + switch (a_used) { + case 12: + a5b = MP_DIGIT(a, 11); + case 11: + a5a = MP_DIGIT(a, 10); + case 10: + a4b = MP_DIGIT(a, 9); + case 9: + a4a = MP_DIGIT(a, 8); + case 8: + a3b = MP_DIGIT(a, 7); + case 7: + a3a = MP_DIGIT(a, 6); + } + + + r2b= MP_DIGIT(a, 5); + r2a= MP_DIGIT(a, 4); + r1b = MP_DIGIT(a, 3); + r1a = MP_DIGIT(a, 2); + r0b = MP_DIGIT(a, 1); + r0a = MP_DIGIT(a, 0); + + /* implement r = (a2,a1,a0)+(a5,a5,a5)+(a4,a4,0)+(0,a3,a3) */ + MP_ADD_CARRY(r0a, a3a, r0a, 0, carry); + MP_ADD_CARRY(r0b, a3b, r0b, carry, carry); + MP_ADD_CARRY(r1a, a3a, r1a, carry, carry); + MP_ADD_CARRY(r1b, a3b, r1b, carry, carry); + MP_ADD_CARRY(r2a, a4a, r2a, carry, carry); + MP_ADD_CARRY(r2b, a4b, r2b, carry, carry); + r3 = carry; carry = 0; + MP_ADD_CARRY(r0a, a5a, r0a, 0, carry); + MP_ADD_CARRY(r0b, a5b, r0b, carry, carry); + MP_ADD_CARRY(r1a, a5a, r1a, carry, carry); + MP_ADD_CARRY(r1b, a5b, r1b, carry, carry); + MP_ADD_CARRY(r2a, a5a, r2a, carry, carry); + MP_ADD_CARRY(r2b, a5b, r2b, carry, carry); + r3 += carry; + MP_ADD_CARRY(r1a, a4a, r1a, 0, carry); + MP_ADD_CARRY(r1b, a4b, r1b, carry, carry); + MP_ADD_CARRY(r2a, 0, r2a, carry, carry); + MP_ADD_CARRY(r2b, 0, r2b, carry, carry); + r3 += carry; + + /* reduce out the carry */ + while (r3) { + MP_ADD_CARRY(r0a, r3, r0a, 0, carry); + MP_ADD_CARRY(r0b, 0, r0b, carry, carry); + MP_ADD_CARRY(r1a, r3, r1a, carry, carry); + MP_ADD_CARRY(r1b, 0, r1b, carry, carry); + MP_ADD_CARRY(r2a, 0, r2a, carry, carry); + MP_ADD_CARRY(r2b, 0, r2b, carry, carry); + r3 = carry; + } + + /* check for final reduction */ + /* + * our field is 0xffffffffffffffff, 0xfffffffffffffffe, + * 0xffffffffffffffff. That means we can only be over and need + * one more reduction + * if r2 == 0xffffffffffffffffff (same as r2+1 == 0) + * and + * r1 == 0xffffffffffffffffff or + * r1 == 0xfffffffffffffffffe and r0 = 0xfffffffffffffffff + * In all cases, we subtract the field (or add the 2's + * complement value (1,1,0)). (r0, r1, r2) + */ + if (((r2b == 0xffffffff) && (r2a == 0xffffffff) + && (r1b == 0xffffffff) ) && + ((r1a == 0xffffffff) || + (r1a == 0xfffffffe) && (r0a == 0xffffffff) && + (r0b == 0xffffffff)) ) { + /* do a quick subtract */ + MP_ADD_CARRY(r0a, 1, r0a, 0, carry); + r0b += carry; + r1a = r1b = r2a = r2b = 0; + } + + /* set the lower words of r */ + if (a != r) { + MP_CHECKOK(s_mp_pad(r, 6)); + } + MP_DIGIT(r, 5) = r2b; + MP_DIGIT(r, 4) = r2a; + MP_DIGIT(r, 3) = r1b; + MP_DIGIT(r, 2) = r1a; + MP_DIGIT(r, 1) = r0b; + MP_DIGIT(r, 0) = r0a; + MP_USED(r) = 6; +#else + switch (a_used) { + case 6: + a5 = MP_DIGIT(a, 5); + case 5: + a4 = MP_DIGIT(a, 4); + case 4: + a3 = MP_DIGIT(a, 3); + } + + r2 = MP_DIGIT(a, 2); + r1 = MP_DIGIT(a, 1); + r0 = MP_DIGIT(a, 0); + + /* implement r = (a2,a1,a0)+(a5,a5,a5)+(a4,a4,0)+(0,a3,a3) */ +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(r0, a3, r0, 0, carry); + MP_ADD_CARRY(r1, a3, r1, carry, carry); + MP_ADD_CARRY(r2, a4, r2, carry, carry); + r3 = carry; + MP_ADD_CARRY(r0, a5, r0, 0, carry); + MP_ADD_CARRY(r1, a5, r1, carry, carry); + MP_ADD_CARRY(r2, a5, r2, carry, carry); + r3 += carry; + MP_ADD_CARRY(r1, a4, r1, 0, carry); + MP_ADD_CARRY(r2, 0, r2, carry, carry); + r3 += carry; + +#else + r2 = MP_DIGIT(a, 2); + r1 = MP_DIGIT(a, 1); + r0 = MP_DIGIT(a, 0); + + /* set the lower words of r */ + __asm__ ( + "xorq %3,%3 \n\t" + "addq %4,%0 \n\t" + "adcq %4,%1 \n\t" + "adcq %5,%2 \n\t" + "adcq $0,%3 \n\t" + "addq %6,%0 \n\t" + "adcq %6,%1 \n\t" + "adcq %6,%2 \n\t" + "adcq $0,%3 \n\t" + "addq %5,%1 \n\t" + "adcq $0,%2 \n\t" + "adcq $0,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3), "=r"(a3), + "=r"(a4), "=r"(a5) + : "0" (r0), "1" (r1), "2" (r2), "3" (r3), + "4" (a3), "5" (a4), "6"(a5) + : "%cc" ); +#endif + + /* reduce out the carry */ + while (r3) { +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(r0, r3, r0, 0, carry); + MP_ADD_CARRY(r1, r3, r1, carry, carry); + MP_ADD_CARRY(r2, 0, r2, carry, carry); + r3 = carry; +#else + a3=r3; + __asm__ ( + "xorq %3,%3 \n\t" + "addq %4,%0 \n\t" + "adcq %4,%1 \n\t" + "adcq $0,%2 \n\t" + "adcq $0,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(r3), "=r"(a3) + : "0" (r0), "1" (r1), "2" (r2), "3" (r3), "4"(a3) + : "%cc" ); +#endif + } + + /* check for final reduction */ + /* + * our field is 0xffffffffffffffff, 0xfffffffffffffffe, + * 0xffffffffffffffff. That means we can only be over and need + * one more reduction + * if r2 == 0xffffffffffffffffff (same as r2+1 == 0) + * and + * r1 == 0xffffffffffffffffff or + * r1 == 0xfffffffffffffffffe and r0 = 0xfffffffffffffffff + * In all cases, we subtract the field (or add the 2's + * complement value (1,1,0)). (r0, r1, r2) + */ + if (r3 || ((r2 == MP_DIGIT_MAX) && + ((r1 == MP_DIGIT_MAX) || + ((r1 == (MP_DIGIT_MAX-1)) && (r0 == MP_DIGIT_MAX))))) { + /* do a quick subtract */ + r0++; + r1 = r2 = 0; + } + /* set the lower words of r */ + if (a != r) { + MP_CHECKOK(s_mp_pad(r, 3)); + } + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_USED(r) = 3; +#endif + } + + CLEANUP: + return res; +} + +#ifndef ECL_THIRTY_TWO_BIT +/* Compute the sum of 192 bit curves. Do the work in-line since the + * number of words are so small, we don't want to overhead of mp function + * calls. Uses optimized modular reduction for p192. + */ +mp_err +ec_GFp_nistp192_add(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit a0 = 0, a1 = 0, a2 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0; + mp_digit carry; + + switch(MP_USED(a)) { + case 3: + a2 = MP_DIGIT(a,2); + case 2: + a1 = MP_DIGIT(a,1); + case 1: + a0 = MP_DIGIT(a,0); + } + switch(MP_USED(b)) { + case 3: + r2 = MP_DIGIT(b,2); + case 2: + r1 = MP_DIGIT(b,1); + case 1: + r0 = MP_DIGIT(b,0); + } + +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(a0, r0, r0, 0, carry); + MP_ADD_CARRY(a1, r1, r1, carry, carry); + MP_ADD_CARRY(a2, r2, r2, carry, carry); +#else + __asm__ ( + "xorq %3,%3 \n\t" + "addq %4,%0 \n\t" + "adcq %5,%1 \n\t" + "adcq %6,%2 \n\t" + "adcq $0,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(carry) + : "r" (a0), "r" (a1), "r" (a2), "0" (r0), + "1" (r1), "2" (r2) + : "%cc" ); +#endif + + /* Do quick 'subract' if we've gone over + * (add the 2's complement of the curve field) */ + if (carry || ((r2 == MP_DIGIT_MAX) && + ((r1 == MP_DIGIT_MAX) || + ((r1 == (MP_DIGIT_MAX-1)) && (r0 == MP_DIGIT_MAX))))) { +#ifndef MPI_AMD64_ADD + MP_ADD_CARRY(r0, 1, r0, 0, carry); + MP_ADD_CARRY(r1, 1, r1, carry, carry); + MP_ADD_CARRY(r2, 0, r2, carry, carry); +#else + __asm__ ( + "addq $1,%0 \n\t" + "adcq $1,%1 \n\t" + "adcq $0,%2 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2) + : "0" (r0), "1" (r1), "2" (r2) + : "%cc" ); +#endif + } + + + MP_CHECKOK(s_mp_pad(r, 3)); + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 3; + s_mp_clamp(r); + + + CLEANUP: + return res; +} + +/* Compute the diff of 192 bit curves. Do the work in-line since the + * number of words are so small, we don't want to overhead of mp function + * calls. Uses optimized modular reduction for p192. + */ +mp_err +ec_GFp_nistp192_sub(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_digit b0 = 0, b1 = 0, b2 = 0; + mp_digit r0 = 0, r1 = 0, r2 = 0; + mp_digit borrow; + + switch(MP_USED(a)) { + case 3: + r2 = MP_DIGIT(a,2); + case 2: + r1 = MP_DIGIT(a,1); + case 1: + r0 = MP_DIGIT(a,0); + } + + switch(MP_USED(b)) { + case 3: + b2 = MP_DIGIT(b,2); + case 2: + b1 = MP_DIGIT(b,1); + case 1: + b0 = MP_DIGIT(b,0); + } + +#ifndef MPI_AMD64_ADD + MP_SUB_BORROW(r0, b0, r0, 0, borrow); + MP_SUB_BORROW(r1, b1, r1, borrow, borrow); + MP_SUB_BORROW(r2, b2, r2, borrow, borrow); +#else + __asm__ ( + "xorq %3,%3 \n\t" + "subq %4,%0 \n\t" + "sbbq %5,%1 \n\t" + "sbbq %6,%2 \n\t" + "adcq $0,%3 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2), "=r"(borrow) + : "r" (b0), "r" (b1), "r" (b2), "0" (r0), + "1" (r1), "2" (r2) + : "%cc" ); +#endif + + /* Do quick 'add' if we've gone under 0 + * (subtract the 2's complement of the curve field) */ + if (borrow) { +#ifndef MPI_AMD64_ADD + MP_SUB_BORROW(r0, 1, r0, 0, borrow); + MP_SUB_BORROW(r1, 1, r1, borrow, borrow); + MP_SUB_BORROW(r2, 0, r2, borrow, borrow); +#else + __asm__ ( + "subq $1,%0 \n\t" + "sbbq $1,%1 \n\t" + "sbbq $0,%2 \n\t" + : "=r"(r0), "=r"(r1), "=r"(r2) + : "0" (r0), "1" (r1), "2" (r2) + : "%cc" ); +#endif + } + + MP_CHECKOK(s_mp_pad(r, 3)); + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 3; + s_mp_clamp(r); + + CLEANUP: + return res; +} + +#endif + +/* Compute the square of polynomial a, reduce modulo p192. Store the + * result in r. r could be a. Uses optimized modular reduction for p192. + */ +mp_err +ec_GFp_nistp192_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_sqr(a, r)); + MP_CHECKOK(ec_GFp_nistp192_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Compute the product of two polynomials a and b, reduce modulo p192. + * Store the result in r. r could be a or b; a could be b. Uses + * optimized modular reduction for p192. */ +mp_err +ec_GFp_nistp192_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_mul(a, b, r)); + MP_CHECKOK(ec_GFp_nistp192_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Divides two field elements. If a is NULL, then returns the inverse of + * b. */ +mp_err +ec_GFp_nistp192_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_int t; + + /* If a is NULL, then return the inverse of b, otherwise return a/b. */ + if (a == NULL) { + return mp_invmod(b, &meth->irr, r); + } else { + /* MPI doesn't support divmod, so we implement it using invmod and + * mulmod. */ + MP_CHECKOK(mp_init(&t, FLAG(b))); + MP_CHECKOK(mp_invmod(b, &meth->irr, &t)); + MP_CHECKOK(mp_mul(a, &t, r)); + MP_CHECKOK(ec_GFp_nistp192_mod(r, r, meth)); + CLEANUP: + mp_clear(&t); + return res; + } +} + +/* Wire in fast field arithmetic and precomputation of base point for + * named curves. */ +mp_err +ec_group_set_gfp192(ECGroup *group, ECCurveName name) +{ + if (name == ECCurve_NIST_P192) { + group->meth->field_mod = &ec_GFp_nistp192_mod; + group->meth->field_mul = &ec_GFp_nistp192_mul; + group->meth->field_sqr = &ec_GFp_nistp192_sqr; + group->meth->field_div = &ec_GFp_nistp192_div; +#ifndef ECL_THIRTY_TWO_BIT + group->meth->field_add = &ec_GFp_nistp192_add; + group->meth->field_sub = &ec_GFp_nistp192_sub; +#endif + } + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_224.c b/src/share/native/sun/security/ec/impl/ecp_224.c new file mode 100644 index 0000000000000000000000000000000000000000..1ea82fd78d749a8ba1e6ec2211eaf1f27de75f93 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_224.c @@ -0,0 +1,394 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mpi.h" +#include "mplogic.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +#define ECP224_DIGITS ECL_CURVE_DIGITS(224) + +/* Fast modular reduction for p224 = 2^224 - 2^96 + 1. a can be r. Uses + * algorithm 7 from Brown, Hankerson, Lopez, Menezes. Software + * Implementation of the NIST Elliptic Curves over Prime Fields. */ +mp_err +ec_GFp_nistp224_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_size a_used = MP_USED(a); + + int r3b; + mp_digit carry; +#ifdef ECL_THIRTY_TWO_BIT + mp_digit a6a = 0, a6b = 0, + a5a = 0, a5b = 0, a4a = 0, a4b = 0, a3a = 0, a3b = 0; + mp_digit r0a, r0b, r1a, r1b, r2a, r2b, r3a; +#else + mp_digit a6 = 0, a5 = 0, a4 = 0, a3b = 0, a5a = 0; + mp_digit a6b = 0, a6a_a5b = 0, a5b = 0, a5a_a4b = 0, a4a_a3b = 0; + mp_digit r0, r1, r2, r3; +#endif + + /* reduction not needed if a is not larger than field size */ + if (a_used < ECP224_DIGITS) { + if (a == r) return MP_OKAY; + return mp_copy(a, r); + } + /* for polynomials larger than twice the field size, use regular + * reduction */ + if (a_used > ECL_CURVE_DIGITS(224*2)) { + MP_CHECKOK(mp_mod(a, &meth->irr, r)); + } else { +#ifdef ECL_THIRTY_TWO_BIT + /* copy out upper words of a */ + switch (a_used) { + case 14: + a6b = MP_DIGIT(a, 13); + case 13: + a6a = MP_DIGIT(a, 12); + case 12: + a5b = MP_DIGIT(a, 11); + case 11: + a5a = MP_DIGIT(a, 10); + case 10: + a4b = MP_DIGIT(a, 9); + case 9: + a4a = MP_DIGIT(a, 8); + case 8: + a3b = MP_DIGIT(a, 7); + } + r3a = MP_DIGIT(a, 6); + r2b= MP_DIGIT(a, 5); + r2a= MP_DIGIT(a, 4); + r1b = MP_DIGIT(a, 3); + r1a = MP_DIGIT(a, 2); + r0b = MP_DIGIT(a, 1); + r0a = MP_DIGIT(a, 0); + + + /* implement r = (a3a,a2,a1,a0) + +(a5a, a4,a3b, 0) + +( 0, a6,a5b, 0) + -( 0 0, 0|a6b, a6a|a5b ) + -( a6b, a6a|a5b, a5a|a4b, a4a|a3b ) */ + MP_ADD_CARRY (r1b, a3b, r1b, 0, carry); + MP_ADD_CARRY (r2a, a4a, r2a, carry, carry); + MP_ADD_CARRY (r2b, a4b, r2b, carry, carry); + MP_ADD_CARRY (r3a, a5a, r3a, carry, carry); + r3b = carry; + MP_ADD_CARRY (r1b, a5b, r1b, 0, carry); + MP_ADD_CARRY (r2a, a6a, r2a, carry, carry); + MP_ADD_CARRY (r2b, a6b, r2b, carry, carry); + MP_ADD_CARRY (r3a, 0, r3a, carry, carry); + r3b += carry; + MP_SUB_BORROW(r0a, a3b, r0a, 0, carry); + MP_SUB_BORROW(r0b, a4a, r0b, carry, carry); + MP_SUB_BORROW(r1a, a4b, r1a, carry, carry); + MP_SUB_BORROW(r1b, a5a, r1b, carry, carry); + MP_SUB_BORROW(r2a, a5b, r2a, carry, carry); + MP_SUB_BORROW(r2b, a6a, r2b, carry, carry); + MP_SUB_BORROW(r3a, a6b, r3a, carry, carry); + r3b -= carry; + MP_SUB_BORROW(r0a, a5b, r0a, 0, carry); + MP_SUB_BORROW(r0b, a6a, r0b, carry, carry); + MP_SUB_BORROW(r1a, a6b, r1a, carry, carry); + if (carry) { + MP_SUB_BORROW(r1b, 0, r1b, carry, carry); + MP_SUB_BORROW(r2a, 0, r2a, carry, carry); + MP_SUB_BORROW(r2b, 0, r2b, carry, carry); + MP_SUB_BORROW(r3a, 0, r3a, carry, carry); + r3b -= carry; + } + + while (r3b > 0) { + int tmp; + MP_ADD_CARRY(r1b, r3b, r1b, 0, carry); + if (carry) { + MP_ADD_CARRY(r2a, 0, r2a, carry, carry); + MP_ADD_CARRY(r2b, 0, r2b, carry, carry); + MP_ADD_CARRY(r3a, 0, r3a, carry, carry); + } + tmp = carry; + MP_SUB_BORROW(r0a, r3b, r0a, 0, carry); + if (carry) { + MP_SUB_BORROW(r0b, 0, r0b, carry, carry); + MP_SUB_BORROW(r1a, 0, r1a, carry, carry); + MP_SUB_BORROW(r1b, 0, r1b, carry, carry); + MP_SUB_BORROW(r2a, 0, r2a, carry, carry); + MP_SUB_BORROW(r2b, 0, r2b, carry, carry); + MP_SUB_BORROW(r3a, 0, r3a, carry, carry); + tmp -= carry; + } + r3b = tmp; + } + + while (r3b < 0) { + mp_digit maxInt = MP_DIGIT_MAX; + MP_ADD_CARRY (r0a, 1, r0a, 0, carry); + MP_ADD_CARRY (r0b, 0, r0b, carry, carry); + MP_ADD_CARRY (r1a, 0, r1a, carry, carry); + MP_ADD_CARRY (r1b, maxInt, r1b, carry, carry); + MP_ADD_CARRY (r2a, maxInt, r2a, carry, carry); + MP_ADD_CARRY (r2b, maxInt, r2b, carry, carry); + MP_ADD_CARRY (r3a, maxInt, r3a, carry, carry); + r3b += carry; + } + /* check for final reduction */ + /* now the only way we are over is if the top 4 words are all ones */ + if ((r3a == MP_DIGIT_MAX) && (r2b == MP_DIGIT_MAX) + && (r2a == MP_DIGIT_MAX) && (r1b == MP_DIGIT_MAX) && + ((r1a != 0) || (r0b != 0) || (r0a != 0)) ) { + /* one last subraction */ + MP_SUB_BORROW(r0a, 1, r0a, 0, carry); + MP_SUB_BORROW(r0b, 0, r0b, carry, carry); + MP_SUB_BORROW(r1a, 0, r1a, carry, carry); + r1b = r2a = r2b = r3a = 0; + } + + + if (a != r) { + MP_CHECKOK(s_mp_pad(r, 7)); + } + /* set the lower words of r */ + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 7; + MP_DIGIT(r, 6) = r3a; + MP_DIGIT(r, 5) = r2b; + MP_DIGIT(r, 4) = r2a; + MP_DIGIT(r, 3) = r1b; + MP_DIGIT(r, 2) = r1a; + MP_DIGIT(r, 1) = r0b; + MP_DIGIT(r, 0) = r0a; +#else + /* copy out upper words of a */ + switch (a_used) { + case 7: + a6 = MP_DIGIT(a, 6); + a6b = a6 >> 32; + a6a_a5b = a6 << 32; + case 6: + a5 = MP_DIGIT(a, 5); + a5b = a5 >> 32; + a6a_a5b |= a5b; + a5b = a5b << 32; + a5a_a4b = a5 << 32; + a5a = a5 & 0xffffffff; + case 5: + a4 = MP_DIGIT(a, 4); + a5a_a4b |= a4 >> 32; + a4a_a3b = a4 << 32; + case 4: + a3b = MP_DIGIT(a, 3) >> 32; + a4a_a3b |= a3b; + a3b = a3b << 32; + } + + r3 = MP_DIGIT(a, 3) & 0xffffffff; + r2 = MP_DIGIT(a, 2); + r1 = MP_DIGIT(a, 1); + r0 = MP_DIGIT(a, 0); + + /* implement r = (a3a,a2,a1,a0) + +(a5a, a4,a3b, 0) + +( 0, a6,a5b, 0) + -( 0 0, 0|a6b, a6a|a5b ) + -( a6b, a6a|a5b, a5a|a4b, a4a|a3b ) */ + MP_ADD_CARRY (r1, a3b, r1, 0, carry); + MP_ADD_CARRY (r2, a4 , r2, carry, carry); + MP_ADD_CARRY (r3, a5a, r3, carry, carry); + MP_ADD_CARRY (r1, a5b, r1, 0, carry); + MP_ADD_CARRY (r2, a6 , r2, carry, carry); + MP_ADD_CARRY (r3, 0, r3, carry, carry); + + MP_SUB_BORROW(r0, a4a_a3b, r0, 0, carry); + MP_SUB_BORROW(r1, a5a_a4b, r1, carry, carry); + MP_SUB_BORROW(r2, a6a_a5b, r2, carry, carry); + MP_SUB_BORROW(r3, a6b , r3, carry, carry); + MP_SUB_BORROW(r0, a6a_a5b, r0, 0, carry); + MP_SUB_BORROW(r1, a6b , r1, carry, carry); + if (carry) { + MP_SUB_BORROW(r2, 0, r2, carry, carry); + MP_SUB_BORROW(r3, 0, r3, carry, carry); + } + + + /* if the value is negative, r3 has a 2's complement + * high value */ + r3b = (int)(r3 >>32); + while (r3b > 0) { + r3 &= 0xffffffff; + MP_ADD_CARRY(r1,((mp_digit)r3b) << 32, r1, 0, carry); + if (carry) { + MP_ADD_CARRY(r2, 0, r2, carry, carry); + MP_ADD_CARRY(r3, 0, r3, carry, carry); + } + MP_SUB_BORROW(r0, r3b, r0, 0, carry); + if (carry) { + MP_SUB_BORROW(r1, 0, r1, carry, carry); + MP_SUB_BORROW(r2, 0, r2, carry, carry); + MP_SUB_BORROW(r3, 0, r3, carry, carry); + } + r3b = (int)(r3 >>32); + } + + while (r3b < 0) { + MP_ADD_CARRY (r0, 1, r0, 0, carry); + MP_ADD_CARRY (r1, MP_DIGIT_MAX <<32, r1, carry, carry); + MP_ADD_CARRY (r2, MP_DIGIT_MAX, r2, carry, carry); + MP_ADD_CARRY (r3, MP_DIGIT_MAX >> 32, r3, carry, carry); + r3b = (int)(r3 >>32); + } + /* check for final reduction */ + /* now the only way we are over is if the top 4 words are all ones */ + if ((r3 == (MP_DIGIT_MAX >> 32)) && (r2 == MP_DIGIT_MAX) + && ((r1 & MP_DIGIT_MAX << 32)== MP_DIGIT_MAX << 32) && + ((r1 != MP_DIGIT_MAX << 32 ) || (r0 != 0)) ) { + /* one last subraction */ + MP_SUB_BORROW(r0, 1, r0, 0, carry); + MP_SUB_BORROW(r1, 0, r1, carry, carry); + r2 = r3 = 0; + } + + + if (a != r) { + MP_CHECKOK(s_mp_pad(r, 4)); + } + /* set the lower words of r */ + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 4; + MP_DIGIT(r, 3) = r3; + MP_DIGIT(r, 2) = r2; + MP_DIGIT(r, 1) = r1; + MP_DIGIT(r, 0) = r0; +#endif + } + + CLEANUP: + return res; +} + +/* Compute the square of polynomial a, reduce modulo p224. Store the + * result in r. r could be a. Uses optimized modular reduction for p224. + */ +mp_err +ec_GFp_nistp224_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_sqr(a, r)); + MP_CHECKOK(ec_GFp_nistp224_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Compute the product of two polynomials a and b, reduce modulo p224. + * Store the result in r. r could be a or b; a could be b. Uses + * optimized modular reduction for p224. */ +mp_err +ec_GFp_nistp224_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_mul(a, b, r)); + MP_CHECKOK(ec_GFp_nistp224_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Divides two field elements. If a is NULL, then returns the inverse of + * b. */ +mp_err +ec_GFp_nistp224_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_int t; + + /* If a is NULL, then return the inverse of b, otherwise return a/b. */ + if (a == NULL) { + return mp_invmod(b, &meth->irr, r); + } else { + /* MPI doesn't support divmod, so we implement it using invmod and + * mulmod. */ + MP_CHECKOK(mp_init(&t, FLAG(b))); + MP_CHECKOK(mp_invmod(b, &meth->irr, &t)); + MP_CHECKOK(mp_mul(a, &t, r)); + MP_CHECKOK(ec_GFp_nistp224_mod(r, r, meth)); + CLEANUP: + mp_clear(&t); + return res; + } +} + +/* Wire in fast field arithmetic and precomputation of base point for + * named curves. */ +mp_err +ec_group_set_gfp224(ECGroup *group, ECCurveName name) +{ + if (name == ECCurve_NIST_P224) { + group->meth->field_mod = &ec_GFp_nistp224_mod; + group->meth->field_mul = &ec_GFp_nistp224_mul; + group->meth->field_sqr = &ec_GFp_nistp224_sqr; + group->meth->field_div = &ec_GFp_nistp224_div; + } + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_256.c b/src/share/native/sun/security/ec/impl/ecp_256.c new file mode 100644 index 0000000000000000000000000000000000000000..6f4de5be0ee46e6c17b308fdf579fe7b5fb82662 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_256.c @@ -0,0 +1,451 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mpi.h" +#include "mplogic.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Fast modular reduction for p256 = 2^256 - 2^224 + 2^192+ 2^96 - 1. a can be r. + * Uses algorithm 2.29 from Hankerson, Menezes, Vanstone. Guide to + * Elliptic Curve Cryptography. */ +mp_err +ec_GFp_nistp256_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_size a_used = MP_USED(a); + int a_bits = mpl_significant_bits(a); + mp_digit carry; + +#ifdef ECL_THIRTY_TWO_BIT + mp_digit a8=0, a9=0, a10=0, a11=0, a12=0, a13=0, a14=0, a15=0; + mp_digit r0, r1, r2, r3, r4, r5, r6, r7; + int r8; /* must be a signed value ! */ +#else + mp_digit a4=0, a5=0, a6=0, a7=0; + mp_digit a4h, a4l, a5h, a5l, a6h, a6l, a7h, a7l; + mp_digit r0, r1, r2, r3; + int r4; /* must be a signed value ! */ +#endif + /* for polynomials larger than twice the field size + * use regular reduction */ + if (a_bits < 256) { + if (a == r) return MP_OKAY; + return mp_copy(a,r); + } + if (a_bits > 512) { + MP_CHECKOK(mp_mod(a, &meth->irr, r)); + } else { + +#ifdef ECL_THIRTY_TWO_BIT + switch (a_used) { + case 16: + a15 = MP_DIGIT(a,15); + case 15: + a14 = MP_DIGIT(a,14); + case 14: + a13 = MP_DIGIT(a,13); + case 13: + a12 = MP_DIGIT(a,12); + case 12: + a11 = MP_DIGIT(a,11); + case 11: + a10 = MP_DIGIT(a,10); + case 10: + a9 = MP_DIGIT(a,9); + case 9: + a8 = MP_DIGIT(a,8); + } + + r0 = MP_DIGIT(a,0); + r1 = MP_DIGIT(a,1); + r2 = MP_DIGIT(a,2); + r3 = MP_DIGIT(a,3); + r4 = MP_DIGIT(a,4); + r5 = MP_DIGIT(a,5); + r6 = MP_DIGIT(a,6); + r7 = MP_DIGIT(a,7); + + /* sum 1 */ + MP_ADD_CARRY(r3, a11, r3, 0, carry); + MP_ADD_CARRY(r4, a12, r4, carry, carry); + MP_ADD_CARRY(r5, a13, r5, carry, carry); + MP_ADD_CARRY(r6, a14, r6, carry, carry); + MP_ADD_CARRY(r7, a15, r7, carry, carry); + r8 = carry; + MP_ADD_CARRY(r3, a11, r3, 0, carry); + MP_ADD_CARRY(r4, a12, r4, carry, carry); + MP_ADD_CARRY(r5, a13, r5, carry, carry); + MP_ADD_CARRY(r6, a14, r6, carry, carry); + MP_ADD_CARRY(r7, a15, r7, carry, carry); + r8 += carry; + /* sum 2 */ + MP_ADD_CARRY(r3, a12, r3, 0, carry); + MP_ADD_CARRY(r4, a13, r4, carry, carry); + MP_ADD_CARRY(r5, a14, r5, carry, carry); + MP_ADD_CARRY(r6, a15, r6, carry, carry); + MP_ADD_CARRY(r7, 0, r7, carry, carry); + r8 += carry; + /* combine last bottom of sum 3 with second sum 2 */ + MP_ADD_CARRY(r0, a8, r0, 0, carry); + MP_ADD_CARRY(r1, a9, r1, carry, carry); + MP_ADD_CARRY(r2, a10, r2, carry, carry); + MP_ADD_CARRY(r3, a12, r3, carry, carry); + MP_ADD_CARRY(r4, a13, r4, carry, carry); + MP_ADD_CARRY(r5, a14, r5, carry, carry); + MP_ADD_CARRY(r6, a15, r6, carry, carry); + MP_ADD_CARRY(r7, a15, r7, carry, carry); /* from sum 3 */ + r8 += carry; + /* sum 3 (rest of it)*/ + MP_ADD_CARRY(r6, a14, r6, 0, carry); + MP_ADD_CARRY(r7, 0, r7, carry, carry); + r8 += carry; + /* sum 4 (rest of it)*/ + MP_ADD_CARRY(r0, a9, r0, 0, carry); + MP_ADD_CARRY(r1, a10, r1, carry, carry); + MP_ADD_CARRY(r2, a11, r2, carry, carry); + MP_ADD_CARRY(r3, a13, r3, carry, carry); + MP_ADD_CARRY(r4, a14, r4, carry, carry); + MP_ADD_CARRY(r5, a15, r5, carry, carry); + MP_ADD_CARRY(r6, a13, r6, carry, carry); + MP_ADD_CARRY(r7, a8, r7, carry, carry); + r8 += carry; + /* diff 5 */ + MP_SUB_BORROW(r0, a11, r0, 0, carry); + MP_SUB_BORROW(r1, a12, r1, carry, carry); + MP_SUB_BORROW(r2, a13, r2, carry, carry); + MP_SUB_BORROW(r3, 0, r3, carry, carry); + MP_SUB_BORROW(r4, 0, r4, carry, carry); + MP_SUB_BORROW(r5, 0, r5, carry, carry); + MP_SUB_BORROW(r6, a8, r6, carry, carry); + MP_SUB_BORROW(r7, a10, r7, carry, carry); + r8 -= carry; + /* diff 6 */ + MP_SUB_BORROW(r0, a12, r0, 0, carry); + MP_SUB_BORROW(r1, a13, r1, carry, carry); + MP_SUB_BORROW(r2, a14, r2, carry, carry); + MP_SUB_BORROW(r3, a15, r3, carry, carry); + MP_SUB_BORROW(r4, 0, r4, carry, carry); + MP_SUB_BORROW(r5, 0, r5, carry, carry); + MP_SUB_BORROW(r6, a9, r6, carry, carry); + MP_SUB_BORROW(r7, a11, r7, carry, carry); + r8 -= carry; + /* diff 7 */ + MP_SUB_BORROW(r0, a13, r0, 0, carry); + MP_SUB_BORROW(r1, a14, r1, carry, carry); + MP_SUB_BORROW(r2, a15, r2, carry, carry); + MP_SUB_BORROW(r3, a8, r3, carry, carry); + MP_SUB_BORROW(r4, a9, r4, carry, carry); + MP_SUB_BORROW(r5, a10, r5, carry, carry); + MP_SUB_BORROW(r6, 0, r6, carry, carry); + MP_SUB_BORROW(r7, a12, r7, carry, carry); + r8 -= carry; + /* diff 8 */ + MP_SUB_BORROW(r0, a14, r0, 0, carry); + MP_SUB_BORROW(r1, a15, r1, carry, carry); + MP_SUB_BORROW(r2, 0, r2, carry, carry); + MP_SUB_BORROW(r3, a9, r3, carry, carry); + MP_SUB_BORROW(r4, a10, r4, carry, carry); + MP_SUB_BORROW(r5, a11, r5, carry, carry); + MP_SUB_BORROW(r6, 0, r6, carry, carry); + MP_SUB_BORROW(r7, a13, r7, carry, carry); + r8 -= carry; + + /* reduce the overflows */ + while (r8 > 0) { + mp_digit r8_d = r8; + MP_ADD_CARRY(r0, r8_d, r0, 0, carry); + MP_ADD_CARRY(r1, 0, r1, carry, carry); + MP_ADD_CARRY(r2, 0, r2, carry, carry); + MP_ADD_CARRY(r3, -r8_d, r3, carry, carry); + MP_ADD_CARRY(r4, MP_DIGIT_MAX, r4, carry, carry); + MP_ADD_CARRY(r5, MP_DIGIT_MAX, r5, carry, carry); + MP_ADD_CARRY(r6, -(r8_d+1), r6, carry, carry); + MP_ADD_CARRY(r7, (r8_d-1), r7, carry, carry); + r8 = carry; + } + + /* reduce the underflows */ + while (r8 < 0) { + mp_digit r8_d = -r8; + MP_SUB_BORROW(r0, r8_d, r0, 0, carry); + MP_SUB_BORROW(r1, 0, r1, carry, carry); + MP_SUB_BORROW(r2, 0, r2, carry, carry); + MP_SUB_BORROW(r3, -r8_d, r3, carry, carry); + MP_SUB_BORROW(r4, MP_DIGIT_MAX, r4, carry, carry); + MP_SUB_BORROW(r5, MP_DIGIT_MAX, r5, carry, carry); + MP_SUB_BORROW(r6, -(r8_d+1), r6, carry, carry); + MP_SUB_BORROW(r7, (r8_d-1), r7, carry, carry); + r8 = -carry; + } + if (a != r) { + MP_CHECKOK(s_mp_pad(r,8)); + } + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 8; + + MP_DIGIT(r,7) = r7; + MP_DIGIT(r,6) = r6; + MP_DIGIT(r,5) = r5; + MP_DIGIT(r,4) = r4; + MP_DIGIT(r,3) = r3; + MP_DIGIT(r,2) = r2; + MP_DIGIT(r,1) = r1; + MP_DIGIT(r,0) = r0; + + /* final reduction if necessary */ + if ((r7 == MP_DIGIT_MAX) && + ((r6 > 1) || ((r6 == 1) && + (r5 || r4 || r3 || + ((r2 == MP_DIGIT_MAX) && (r1 == MP_DIGIT_MAX) + && (r0 == MP_DIGIT_MAX)))))) { + MP_CHECKOK(mp_sub(r, &meth->irr, r)); + } +#ifdef notdef + + + /* smooth the negatives */ + while (MP_SIGN(r) != MP_ZPOS) { + MP_CHECKOK(mp_add(r, &meth->irr, r)); + } + while (MP_USED(r) > 8) { + MP_CHECKOK(mp_sub(r, &meth->irr, r)); + } + + /* final reduction if necessary */ + if (MP_DIGIT(r,7) >= MP_DIGIT(&meth->irr,7)) { + if (mp_cmp(r,&meth->irr) != MP_LT) { + MP_CHECKOK(mp_sub(r, &meth->irr, r)); + } + } +#endif + s_mp_clamp(r); +#else + switch (a_used) { + case 8: + a7 = MP_DIGIT(a,7); + case 7: + a6 = MP_DIGIT(a,6); + case 6: + a5 = MP_DIGIT(a,5); + case 5: + a4 = MP_DIGIT(a,4); + } + a7l = a7 << 32; + a7h = a7 >> 32; + a6l = a6 << 32; + a6h = a6 >> 32; + a5l = a5 << 32; + a5h = a5 >> 32; + a4l = a4 << 32; + a4h = a4 >> 32; + r3 = MP_DIGIT(a,3); + r2 = MP_DIGIT(a,2); + r1 = MP_DIGIT(a,1); + r0 = MP_DIGIT(a,0); + + /* sum 1 */ + MP_ADD_CARRY(r1, a5h << 32, r1, 0, carry); + MP_ADD_CARRY(r2, a6, r2, carry, carry); + MP_ADD_CARRY(r3, a7, r3, carry, carry); + r4 = carry; + MP_ADD_CARRY(r1, a5h << 32, r1, 0, carry); + MP_ADD_CARRY(r2, a6, r2, carry, carry); + MP_ADD_CARRY(r3, a7, r3, carry, carry); + r4 += carry; + /* sum 2 */ + MP_ADD_CARRY(r1, a6l, r1, 0, carry); + MP_ADD_CARRY(r2, a6h | a7l, r2, carry, carry); + MP_ADD_CARRY(r3, a7h, r3, carry, carry); + r4 += carry; + MP_ADD_CARRY(r1, a6l, r1, 0, carry); + MP_ADD_CARRY(r2, a6h | a7l, r2, carry, carry); + MP_ADD_CARRY(r3, a7h, r3, carry, carry); + r4 += carry; + + /* sum 3 */ + MP_ADD_CARRY(r0, a4, r0, 0, carry); + MP_ADD_CARRY(r1, a5l >> 32, r1, carry, carry); + MP_ADD_CARRY(r2, 0, r2, carry, carry); + MP_ADD_CARRY(r3, a7, r3, carry, carry); + r4 += carry; + /* sum 4 */ + MP_ADD_CARRY(r0, a4h | a5l, r0, 0, carry); + MP_ADD_CARRY(r1, a5h|(a6h<<32), r1, carry, carry); + MP_ADD_CARRY(r2, a7, r2, carry, carry); + MP_ADD_CARRY(r3, a6h | a4l, r3, carry, carry); + r4 += carry; + /* diff 5 */ + MP_SUB_BORROW(r0, a5h | a6l, r0, 0, carry); + MP_SUB_BORROW(r1, a6h, r1, carry, carry); + MP_SUB_BORROW(r2, 0, r2, carry, carry); + MP_SUB_BORROW(r3, (a4l>>32)|a5l,r3, carry, carry); + r4 -= carry; + /* diff 6 */ + MP_SUB_BORROW(r0, a6, r0, 0, carry); + MP_SUB_BORROW(r1, a7, r1, carry, carry); + MP_SUB_BORROW(r2, 0, r2, carry, carry); + MP_SUB_BORROW(r3, a4h|(a5h<<32),r3, carry, carry); + r4 -= carry; + /* diff 7 */ + MP_SUB_BORROW(r0, a6h|a7l, r0, 0, carry); + MP_SUB_BORROW(r1, a7h|a4l, r1, carry, carry); + MP_SUB_BORROW(r2, a4h|a5l, r2, carry, carry); + MP_SUB_BORROW(r3, a6l, r3, carry, carry); + r4 -= carry; + /* diff 8 */ + MP_SUB_BORROW(r0, a7, r0, 0, carry); + MP_SUB_BORROW(r1, a4h<<32, r1, carry, carry); + MP_SUB_BORROW(r2, a5, r2, carry, carry); + MP_SUB_BORROW(r3, a6h<<32, r3, carry, carry); + r4 -= carry; + + /* reduce the overflows */ + while (r4 > 0) { + mp_digit r4_long = r4; + mp_digit r4l = (r4_long << 32); + MP_ADD_CARRY(r0, r4_long, r0, 0, carry); + MP_ADD_CARRY(r1, -r4l, r1, carry, carry); + MP_ADD_CARRY(r2, MP_DIGIT_MAX, r2, carry, carry); + MP_ADD_CARRY(r3, r4l-r4_long-1,r3, carry, carry); + r4 = carry; + } + + /* reduce the underflows */ + while (r4 < 0) { + mp_digit r4_long = -r4; + mp_digit r4l = (r4_long << 32); + MP_SUB_BORROW(r0, r4_long, r0, 0, carry); + MP_SUB_BORROW(r1, -r4l, r1, carry, carry); + MP_SUB_BORROW(r2, MP_DIGIT_MAX, r2, carry, carry); + MP_SUB_BORROW(r3, r4l-r4_long-1,r3, carry, carry); + r4 = -carry; + } + + if (a != r) { + MP_CHECKOK(s_mp_pad(r,4)); + } + MP_SIGN(r) = MP_ZPOS; + MP_USED(r) = 4; + + MP_DIGIT(r,3) = r3; + MP_DIGIT(r,2) = r2; + MP_DIGIT(r,1) = r1; + MP_DIGIT(r,0) = r0; + + /* final reduction if necessary */ + if ((r3 > 0xFFFFFFFF00000001ULL) || + ((r3 == 0xFFFFFFFF00000001ULL) && + (r2 || (r1 >> 32)|| + (r1 == 0xFFFFFFFFULL && r0 == MP_DIGIT_MAX)))) { + /* very rare, just use mp_sub */ + MP_CHECKOK(mp_sub(r, &meth->irr, r)); + } + + s_mp_clamp(r); +#endif + } + + CLEANUP: + return res; +} + +/* Compute the square of polynomial a, reduce modulo p256. Store the + * result in r. r could be a. Uses optimized modular reduction for p256. + */ +mp_err +ec_GFp_nistp256_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_sqr(a, r)); + MP_CHECKOK(ec_GFp_nistp256_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Compute the product of two polynomials a and b, reduce modulo p256. + * Store the result in r. r could be a or b; a could be b. Uses + * optimized modular reduction for p256. */ +mp_err +ec_GFp_nistp256_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_mul(a, b, r)); + MP_CHECKOK(ec_GFp_nistp256_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Wire in fast field arithmetic and precomputation of base point for + * named curves. */ +mp_err +ec_group_set_gfp256(ECGroup *group, ECCurveName name) +{ + if (name == ECCurve_NIST_P256) { + group->meth->field_mod = &ec_GFp_nistp256_mod; + group->meth->field_mul = &ec_GFp_nistp256_mul; + group->meth->field_sqr = &ec_GFp_nistp256_sqr; + } + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_384.c b/src/share/native/sun/security/ec/impl/ecp_384.c new file mode 100644 index 0000000000000000000000000000000000000000..93b9259da6ba77105ba168c84eeaa858f235cb72 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_384.c @@ -0,0 +1,315 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mpi.h" +#include "mplogic.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +/* Fast modular reduction for p384 = 2^384 - 2^128 - 2^96 + 2^32 - 1. a can be r. + * Uses algorithm 2.30 from Hankerson, Menezes, Vanstone. Guide to + * Elliptic Curve Cryptography. */ +mp_err +ec_GFp_nistp384_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + int a_bits = mpl_significant_bits(a); + int i; + + /* m1, m2 are statically-allocated mp_int of exactly the size we need */ + mp_int m[10]; + +#ifdef ECL_THIRTY_TWO_BIT + mp_digit s[10][12]; + for (i = 0; i < 10; i++) { + MP_SIGN(&m[i]) = MP_ZPOS; + MP_ALLOC(&m[i]) = 12; + MP_USED(&m[i]) = 12; + MP_DIGITS(&m[i]) = s[i]; + } +#else + mp_digit s[10][6]; + for (i = 0; i < 10; i++) { + MP_SIGN(&m[i]) = MP_ZPOS; + MP_ALLOC(&m[i]) = 6; + MP_USED(&m[i]) = 6; + MP_DIGITS(&m[i]) = s[i]; + } +#endif + +#ifdef ECL_THIRTY_TWO_BIT + /* for polynomials larger than twice the field size or polynomials + * not using all words, use regular reduction */ + if ((a_bits > 768) || (a_bits <= 736)) { + MP_CHECKOK(mp_mod(a, &meth->irr, r)); + } else { + for (i = 0; i < 12; i++) { + s[0][i] = MP_DIGIT(a, i); + } + s[1][0] = 0; + s[1][1] = 0; + s[1][2] = 0; + s[1][3] = 0; + s[1][4] = MP_DIGIT(a, 21); + s[1][5] = MP_DIGIT(a, 22); + s[1][6] = MP_DIGIT(a, 23); + s[1][7] = 0; + s[1][8] = 0; + s[1][9] = 0; + s[1][10] = 0; + s[1][11] = 0; + for (i = 0; i < 12; i++) { + s[2][i] = MP_DIGIT(a, i+12); + } + s[3][0] = MP_DIGIT(a, 21); + s[3][1] = MP_DIGIT(a, 22); + s[3][2] = MP_DIGIT(a, 23); + for (i = 3; i < 12; i++) { + s[3][i] = MP_DIGIT(a, i+9); + } + s[4][0] = 0; + s[4][1] = MP_DIGIT(a, 23); + s[4][2] = 0; + s[4][3] = MP_DIGIT(a, 20); + for (i = 4; i < 12; i++) { + s[4][i] = MP_DIGIT(a, i+8); + } + s[5][0] = 0; + s[5][1] = 0; + s[5][2] = 0; + s[5][3] = 0; + s[5][4] = MP_DIGIT(a, 20); + s[5][5] = MP_DIGIT(a, 21); + s[5][6] = MP_DIGIT(a, 22); + s[5][7] = MP_DIGIT(a, 23); + s[5][8] = 0; + s[5][9] = 0; + s[5][10] = 0; + s[5][11] = 0; + s[6][0] = MP_DIGIT(a, 20); + s[6][1] = 0; + s[6][2] = 0; + s[6][3] = MP_DIGIT(a, 21); + s[6][4] = MP_DIGIT(a, 22); + s[6][5] = MP_DIGIT(a, 23); + s[6][6] = 0; + s[6][7] = 0; + s[6][8] = 0; + s[6][9] = 0; + s[6][10] = 0; + s[6][11] = 0; + s[7][0] = MP_DIGIT(a, 23); + for (i = 1; i < 12; i++) { + s[7][i] = MP_DIGIT(a, i+11); + } + s[8][0] = 0; + s[8][1] = MP_DIGIT(a, 20); + s[8][2] = MP_DIGIT(a, 21); + s[8][3] = MP_DIGIT(a, 22); + s[8][4] = MP_DIGIT(a, 23); + s[8][5] = 0; + s[8][6] = 0; + s[8][7] = 0; + s[8][8] = 0; + s[8][9] = 0; + s[8][10] = 0; + s[8][11] = 0; + s[9][0] = 0; + s[9][1] = 0; + s[9][2] = 0; + s[9][3] = MP_DIGIT(a, 23); + s[9][4] = MP_DIGIT(a, 23); + s[9][5] = 0; + s[9][6] = 0; + s[9][7] = 0; + s[9][8] = 0; + s[9][9] = 0; + s[9][10] = 0; + s[9][11] = 0; + + MP_CHECKOK(mp_add(&m[0], &m[1], r)); + MP_CHECKOK(mp_add(r, &m[1], r)); + MP_CHECKOK(mp_add(r, &m[2], r)); + MP_CHECKOK(mp_add(r, &m[3], r)); + MP_CHECKOK(mp_add(r, &m[4], r)); + MP_CHECKOK(mp_add(r, &m[5], r)); + MP_CHECKOK(mp_add(r, &m[6], r)); + MP_CHECKOK(mp_sub(r, &m[7], r)); + MP_CHECKOK(mp_sub(r, &m[8], r)); + MP_CHECKOK(mp_submod(r, &m[9], &meth->irr, r)); + s_mp_clamp(r); + } +#else + /* for polynomials larger than twice the field size or polynomials + * not using all words, use regular reduction */ + if ((a_bits > 768) || (a_bits <= 736)) { + MP_CHECKOK(mp_mod(a, &meth->irr, r)); + } else { + for (i = 0; i < 6; i++) { + s[0][i] = MP_DIGIT(a, i); + } + s[1][0] = 0; + s[1][1] = 0; + s[1][2] = (MP_DIGIT(a, 10) >> 32) | (MP_DIGIT(a, 11) << 32); + s[1][3] = MP_DIGIT(a, 11) >> 32; + s[1][4] = 0; + s[1][5] = 0; + for (i = 0; i < 6; i++) { + s[2][i] = MP_DIGIT(a, i+6); + } + s[3][0] = (MP_DIGIT(a, 10) >> 32) | (MP_DIGIT(a, 11) << 32); + s[3][1] = (MP_DIGIT(a, 11) >> 32) | (MP_DIGIT(a, 6) << 32); + for (i = 2; i < 6; i++) { + s[3][i] = (MP_DIGIT(a, i+4) >> 32) | (MP_DIGIT(a, i+5) << 32); + } + s[4][0] = (MP_DIGIT(a, 11) >> 32) << 32; + s[4][1] = MP_DIGIT(a, 10) << 32; + for (i = 2; i < 6; i++) { + s[4][i] = MP_DIGIT(a, i+4); + } + s[5][0] = 0; + s[5][1] = 0; + s[5][2] = MP_DIGIT(a, 10); + s[5][3] = MP_DIGIT(a, 11); + s[5][4] = 0; + s[5][5] = 0; + s[6][0] = (MP_DIGIT(a, 10) << 32) >> 32; + s[6][1] = (MP_DIGIT(a, 10) >> 32) << 32; + s[6][2] = MP_DIGIT(a, 11); + s[6][3] = 0; + s[6][4] = 0; + s[6][5] = 0; + s[7][0] = (MP_DIGIT(a, 11) >> 32) | (MP_DIGIT(a, 6) << 32); + for (i = 1; i < 6; i++) { + s[7][i] = (MP_DIGIT(a, i+5) >> 32) | (MP_DIGIT(a, i+6) << 32); + } + s[8][0] = MP_DIGIT(a, 10) << 32; + s[8][1] = (MP_DIGIT(a, 10) >> 32) | (MP_DIGIT(a, 11) << 32); + s[8][2] = MP_DIGIT(a, 11) >> 32; + s[8][3] = 0; + s[8][4] = 0; + s[8][5] = 0; + s[9][0] = 0; + s[9][1] = (MP_DIGIT(a, 11) >> 32) << 32; + s[9][2] = MP_DIGIT(a, 11) >> 32; + s[9][3] = 0; + s[9][4] = 0; + s[9][5] = 0; + + MP_CHECKOK(mp_add(&m[0], &m[1], r)); + MP_CHECKOK(mp_add(r, &m[1], r)); + MP_CHECKOK(mp_add(r, &m[2], r)); + MP_CHECKOK(mp_add(r, &m[3], r)); + MP_CHECKOK(mp_add(r, &m[4], r)); + MP_CHECKOK(mp_add(r, &m[5], r)); + MP_CHECKOK(mp_add(r, &m[6], r)); + MP_CHECKOK(mp_sub(r, &m[7], r)); + MP_CHECKOK(mp_sub(r, &m[8], r)); + MP_CHECKOK(mp_submod(r, &m[9], &meth->irr, r)); + s_mp_clamp(r); + } +#endif + + CLEANUP: + return res; +} + +/* Compute the square of polynomial a, reduce modulo p384. Store the + * result in r. r could be a. Uses optimized modular reduction for p384. + */ +mp_err +ec_GFp_nistp384_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_sqr(a, r)); + MP_CHECKOK(ec_GFp_nistp384_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Compute the product of two polynomials a and b, reduce modulo p384. + * Store the result in r. r could be a or b; a could be b. Uses + * optimized modular reduction for p384. */ +mp_err +ec_GFp_nistp384_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_mul(a, b, r)); + MP_CHECKOK(ec_GFp_nistp384_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Wire in fast field arithmetic and precomputation of base point for + * named curves. */ +mp_err +ec_group_set_gfp384(ECGroup *group, ECCurveName name) +{ + if (name == ECCurve_NIST_P384) { + group->meth->field_mod = &ec_GFp_nistp384_mod; + group->meth->field_mul = &ec_GFp_nistp384_mul; + group->meth->field_sqr = &ec_GFp_nistp384_sqr; + } + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_521.c b/src/share/native/sun/security/ec/impl/ecp_521.c new file mode 100644 index 0000000000000000000000000000000000000000..68dca16a77429091ec12219a00faa4624af27a42 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_521.c @@ -0,0 +1,192 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mpi.h" +#include "mplogic.h" +#include "mpi-priv.h" +#ifndef _KERNEL +#include +#endif + +#define ECP521_DIGITS ECL_CURVE_DIGITS(521) + +/* Fast modular reduction for p521 = 2^521 - 1. a can be r. Uses + * algorithm 2.31 from Hankerson, Menezes, Vanstone. Guide to + * Elliptic Curve Cryptography. */ +mp_err +ec_GFp_nistp521_mod(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + int a_bits = mpl_significant_bits(a); + int i; + + /* m1, m2 are statically-allocated mp_int of exactly the size we need */ + mp_int m1; + + mp_digit s1[ECP521_DIGITS] = { 0 }; + + MP_SIGN(&m1) = MP_ZPOS; + MP_ALLOC(&m1) = ECP521_DIGITS; + MP_USED(&m1) = ECP521_DIGITS; + MP_DIGITS(&m1) = s1; + + if (a_bits < 521) { + if (a==r) return MP_OKAY; + return mp_copy(a, r); + } + /* for polynomials larger than twice the field size or polynomials + * not using all words, use regular reduction */ + if (a_bits > (521*2)) { + MP_CHECKOK(mp_mod(a, &meth->irr, r)); + } else { +#define FIRST_DIGIT (ECP521_DIGITS-1) + for (i = FIRST_DIGIT; i < MP_USED(a)-1; i++) { + s1[i-FIRST_DIGIT] = (MP_DIGIT(a, i) >> 9) + | (MP_DIGIT(a, 1+i) << (MP_DIGIT_BIT-9)); + } + s1[i-FIRST_DIGIT] = MP_DIGIT(a, i) >> 9; + + if ( a != r ) { + MP_CHECKOK(s_mp_pad(r,ECP521_DIGITS)); + for (i = 0; i < ECP521_DIGITS; i++) { + MP_DIGIT(r,i) = MP_DIGIT(a, i); + } + } + MP_USED(r) = ECP521_DIGITS; + MP_DIGIT(r,FIRST_DIGIT) &= 0x1FF; + + MP_CHECKOK(s_mp_add(r, &m1)); + if (MP_DIGIT(r, FIRST_DIGIT) & 0x200) { + MP_CHECKOK(s_mp_add_d(r,1)); + MP_DIGIT(r,FIRST_DIGIT) &= 0x1FF; + } + s_mp_clamp(r); + } + + CLEANUP: + return res; +} + +/* Compute the square of polynomial a, reduce modulo p521. Store the + * result in r. r could be a. Uses optimized modular reduction for p521. + */ +mp_err +ec_GFp_nistp521_sqr(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_sqr(a, r)); + MP_CHECKOK(ec_GFp_nistp521_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Compute the product of two polynomials a and b, reduce modulo p521. + * Store the result in r. r could be a or b; a could be b. Uses + * optimized modular reduction for p521. */ +mp_err +ec_GFp_nistp521_mul(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + MP_CHECKOK(mp_mul(a, b, r)); + MP_CHECKOK(ec_GFp_nistp521_mod(r, r, meth)); + CLEANUP: + return res; +} + +/* Divides two field elements. If a is NULL, then returns the inverse of + * b. */ +mp_err +ec_GFp_nistp521_div(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + mp_int t; + + /* If a is NULL, then return the inverse of b, otherwise return a/b. */ + if (a == NULL) { + return mp_invmod(b, &meth->irr, r); + } else { + /* MPI doesn't support divmod, so we implement it using invmod and + * mulmod. */ + MP_CHECKOK(mp_init(&t, FLAG(b))); + MP_CHECKOK(mp_invmod(b, &meth->irr, &t)); + MP_CHECKOK(mp_mul(a, &t, r)); + MP_CHECKOK(ec_GFp_nistp521_mod(r, r, meth)); + CLEANUP: + mp_clear(&t); + return res; + } +} + +/* Wire in fast field arithmetic and precomputation of base point for + * named curves. */ +mp_err +ec_group_set_gfp521(ECGroup *group, ECCurveName name) +{ + if (name == ECCurve_NIST_P521) { + group->meth->field_mod = &ec_GFp_nistp521_mod; + group->meth->field_mul = &ec_GFp_nistp521_mul; + group->meth->field_sqr = &ec_GFp_nistp521_sqr; + group->meth->field_div = &ec_GFp_nistp521_div; + } + return MP_OKAY; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_aff.c b/src/share/native/sun/security/ec/impl/ecp_aff.c new file mode 100644 index 0000000000000000000000000000000000000000..f8d88d4dcbc5a201510524f858f7c3b4938bd751 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_aff.c @@ -0,0 +1,379 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang-Shantz , + * Stephen Fung , and + * Douglas Stebila , Sun Microsystems Laboratories. + * Bodo Moeller , + * Nils Larsch , and + * Lenka Fibikova , the OpenSSL Project + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mplogic.h" +#ifndef _KERNEL +#include +#endif + +/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */ +mp_err +ec_GFp_pt_is_inf_aff(const mp_int *px, const mp_int *py) +{ + + if ((mp_cmp_z(px) == 0) && (mp_cmp_z(py) == 0)) { + return MP_YES; + } else { + return MP_NO; + } + +} + +/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */ +mp_err +ec_GFp_pt_set_inf_aff(mp_int *px, mp_int *py) +{ + mp_zero(px); + mp_zero(py); + return MP_OKAY; +} + +/* Computes R = P + Q based on IEEE P1363 A.10.1. Elliptic curve points P, + * Q, and R can all be identical. Uses affine coordinates. Assumes input + * is already field-encoded using field_enc, and returns output that is + * still field-encoded. */ +mp_err +ec_GFp_pt_add_aff(const mp_int *px, const mp_int *py, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int lambda, temp, tempx, tempy; + + MP_DIGITS(&lambda) = 0; + MP_DIGITS(&temp) = 0; + MP_DIGITS(&tempx) = 0; + MP_DIGITS(&tempy) = 0; + MP_CHECKOK(mp_init(&lambda, FLAG(px))); + MP_CHECKOK(mp_init(&temp, FLAG(px))); + MP_CHECKOK(mp_init(&tempx, FLAG(px))); + MP_CHECKOK(mp_init(&tempy, FLAG(px))); + /* if P = inf, then R = Q */ + if (ec_GFp_pt_is_inf_aff(px, py) == 0) { + MP_CHECKOK(mp_copy(qx, rx)); + MP_CHECKOK(mp_copy(qy, ry)); + res = MP_OKAY; + goto CLEANUP; + } + /* if Q = inf, then R = P */ + if (ec_GFp_pt_is_inf_aff(qx, qy) == 0) { + MP_CHECKOK(mp_copy(px, rx)); + MP_CHECKOK(mp_copy(py, ry)); + res = MP_OKAY; + goto CLEANUP; + } + /* if px != qx, then lambda = (py-qy) / (px-qx) */ + if (mp_cmp(px, qx) != 0) { + MP_CHECKOK(group->meth->field_sub(py, qy, &tempy, group->meth)); + MP_CHECKOK(group->meth->field_sub(px, qx, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_div(&tempy, &tempx, &lambda, group->meth)); + } else { + /* if py != qy or qy = 0, then R = inf */ + if (((mp_cmp(py, qy) != 0)) || (mp_cmp_z(qy) == 0)) { + mp_zero(rx); + mp_zero(ry); + res = MP_OKAY; + goto CLEANUP; + } + /* lambda = (3qx^2+a) / (2qy) */ + MP_CHECKOK(group->meth->field_sqr(qx, &tempx, group->meth)); + MP_CHECKOK(mp_set_int(&temp, 3)); + if (group->meth->field_enc) { + MP_CHECKOK(group->meth->field_enc(&temp, &temp, group->meth)); + } + MP_CHECKOK(group->meth-> + field_mul(&tempx, &temp, &tempx, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&tempx, &group->curvea, &tempx, group->meth)); + MP_CHECKOK(mp_set_int(&temp, 2)); + if (group->meth->field_enc) { + MP_CHECKOK(group->meth->field_enc(&temp, &temp, group->meth)); + } + MP_CHECKOK(group->meth->field_mul(qy, &temp, &tempy, group->meth)); + MP_CHECKOK(group->meth-> + field_div(&tempx, &tempy, &lambda, group->meth)); + } + /* rx = lambda^2 - px - qx */ + MP_CHECKOK(group->meth->field_sqr(&lambda, &tempx, group->meth)); + MP_CHECKOK(group->meth->field_sub(&tempx, px, &tempx, group->meth)); + MP_CHECKOK(group->meth->field_sub(&tempx, qx, &tempx, group->meth)); + /* ry = (x1-x2) * lambda - y1 */ + MP_CHECKOK(group->meth->field_sub(qx, &tempx, &tempy, group->meth)); + MP_CHECKOK(group->meth-> + field_mul(&tempy, &lambda, &tempy, group->meth)); + MP_CHECKOK(group->meth->field_sub(&tempy, qy, &tempy, group->meth)); + MP_CHECKOK(mp_copy(&tempx, rx)); + MP_CHECKOK(mp_copy(&tempy, ry)); + + CLEANUP: + mp_clear(&lambda); + mp_clear(&temp); + mp_clear(&tempx); + mp_clear(&tempy); + return res; +} + +/* Computes R = P - Q. Elliptic curve points P, Q, and R can all be + * identical. Uses affine coordinates. Assumes input is already + * field-encoded using field_enc, and returns output that is still + * field-encoded. */ +mp_err +ec_GFp_pt_sub_aff(const mp_int *px, const mp_int *py, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int nqy; + + MP_DIGITS(&nqy) = 0; + MP_CHECKOK(mp_init(&nqy, FLAG(px))); + /* nqy = -qy */ + MP_CHECKOK(group->meth->field_neg(qy, &nqy, group->meth)); + res = group->point_add(px, py, qx, &nqy, rx, ry, group); + CLEANUP: + mp_clear(&nqy); + return res; +} + +/* Computes R = 2P. Elliptic curve points P and R can be identical. Uses + * affine coordinates. Assumes input is already field-encoded using + * field_enc, and returns output that is still field-encoded. */ +mp_err +ec_GFp_pt_dbl_aff(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, const ECGroup *group) +{ + return ec_GFp_pt_add_aff(px, py, px, py, rx, ry, group); +} + +/* by default, this routine is unused and thus doesn't need to be compiled */ +#ifdef ECL_ENABLE_GFP_PT_MUL_AFF +/* Computes R = nP based on IEEE P1363 A.10.3. Elliptic curve points P and + * R can be identical. Uses affine coordinates. Assumes input is already + * field-encoded using field_enc, and returns output that is still + * field-encoded. */ +mp_err +ec_GFp_pt_mul_aff(const mp_int *n, const mp_int *px, const mp_int *py, + mp_int *rx, mp_int *ry, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int k, k3, qx, qy, sx, sy; + int b1, b3, i, l; + + MP_DIGITS(&k) = 0; + MP_DIGITS(&k3) = 0; + MP_DIGITS(&qx) = 0; + MP_DIGITS(&qy) = 0; + MP_DIGITS(&sx) = 0; + MP_DIGITS(&sy) = 0; + MP_CHECKOK(mp_init(&k)); + MP_CHECKOK(mp_init(&k3)); + MP_CHECKOK(mp_init(&qx)); + MP_CHECKOK(mp_init(&qy)); + MP_CHECKOK(mp_init(&sx)); + MP_CHECKOK(mp_init(&sy)); + + /* if n = 0 then r = inf */ + if (mp_cmp_z(n) == 0) { + mp_zero(rx); + mp_zero(ry); + res = MP_OKAY; + goto CLEANUP; + } + /* Q = P, k = n */ + MP_CHECKOK(mp_copy(px, &qx)); + MP_CHECKOK(mp_copy(py, &qy)); + MP_CHECKOK(mp_copy(n, &k)); + /* if n < 0 then Q = -Q, k = -k */ + if (mp_cmp_z(n) < 0) { + MP_CHECKOK(group->meth->field_neg(&qy, &qy, group->meth)); + MP_CHECKOK(mp_neg(&k, &k)); + } +#ifdef ECL_DEBUG /* basic double and add method */ + l = mpl_significant_bits(&k) - 1; + MP_CHECKOK(mp_copy(&qx, &sx)); + MP_CHECKOK(mp_copy(&qy, &sy)); + for (i = l - 1; i >= 0; i--) { + /* S = 2S */ + MP_CHECKOK(group->point_dbl(&sx, &sy, &sx, &sy, group)); + /* if k_i = 1, then S = S + Q */ + if (mpl_get_bit(&k, i) != 0) { + MP_CHECKOK(group-> + point_add(&sx, &sy, &qx, &qy, &sx, &sy, group)); + } + } +#else /* double and add/subtract method from + * standard */ + /* k3 = 3 * k */ + MP_CHECKOK(mp_set_int(&k3, 3)); + MP_CHECKOK(mp_mul(&k, &k3, &k3)); + /* S = Q */ + MP_CHECKOK(mp_copy(&qx, &sx)); + MP_CHECKOK(mp_copy(&qy, &sy)); + /* l = index of high order bit in binary representation of 3*k */ + l = mpl_significant_bits(&k3) - 1; + /* for i = l-1 downto 1 */ + for (i = l - 1; i >= 1; i--) { + /* S = 2S */ + MP_CHECKOK(group->point_dbl(&sx, &sy, &sx, &sy, group)); + b3 = MP_GET_BIT(&k3, i); + b1 = MP_GET_BIT(&k, i); + /* if k3_i = 1 and k_i = 0, then S = S + Q */ + if ((b3 == 1) && (b1 == 0)) { + MP_CHECKOK(group-> + point_add(&sx, &sy, &qx, &qy, &sx, &sy, group)); + /* if k3_i = 0 and k_i = 1, then S = S - Q */ + } else if ((b3 == 0) && (b1 == 1)) { + MP_CHECKOK(group-> + point_sub(&sx, &sy, &qx, &qy, &sx, &sy, group)); + } + } +#endif + /* output S */ + MP_CHECKOK(mp_copy(&sx, rx)); + MP_CHECKOK(mp_copy(&sy, ry)); + + CLEANUP: + mp_clear(&k); + mp_clear(&k3); + mp_clear(&qx); + mp_clear(&qy); + mp_clear(&sx); + mp_clear(&sy); + return res; +} +#endif + +/* Validates a point on a GFp curve. */ +mp_err +ec_GFp_validate_point(const mp_int *px, const mp_int *py, const ECGroup *group) +{ + mp_err res = MP_NO; + mp_int accl, accr, tmp, pxt, pyt; + + MP_DIGITS(&accl) = 0; + MP_DIGITS(&accr) = 0; + MP_DIGITS(&tmp) = 0; + MP_DIGITS(&pxt) = 0; + MP_DIGITS(&pyt) = 0; + MP_CHECKOK(mp_init(&accl, FLAG(px))); + MP_CHECKOK(mp_init(&accr, FLAG(px))); + MP_CHECKOK(mp_init(&tmp, FLAG(px))); + MP_CHECKOK(mp_init(&pxt, FLAG(px))); + MP_CHECKOK(mp_init(&pyt, FLAG(px))); + + /* 1: Verify that publicValue is not the point at infinity */ + if (ec_GFp_pt_is_inf_aff(px, py) == MP_YES) { + res = MP_NO; + goto CLEANUP; + } + /* 2: Verify that the coordinates of publicValue are elements + * of the field. + */ + if ((MP_SIGN(px) == MP_NEG) || (mp_cmp(px, &group->meth->irr) >= 0) || + (MP_SIGN(py) == MP_NEG) || (mp_cmp(py, &group->meth->irr) >= 0)) { + res = MP_NO; + goto CLEANUP; + } + /* 3: Verify that publicValue is on the curve. */ + if (group->meth->field_enc) { + group->meth->field_enc(px, &pxt, group->meth); + group->meth->field_enc(py, &pyt, group->meth); + } else { + mp_copy(px, &pxt); + mp_copy(py, &pyt); + } + /* left-hand side: y^2 */ + MP_CHECKOK( group->meth->field_sqr(&pyt, &accl, group->meth) ); + /* right-hand side: x^3 + a*x + b */ + MP_CHECKOK( group->meth->field_sqr(&pxt, &tmp, group->meth) ); + MP_CHECKOK( group->meth->field_mul(&pxt, &tmp, &accr, group->meth) ); + MP_CHECKOK( group->meth->field_mul(&group->curvea, &pxt, &tmp, group->meth) ); + MP_CHECKOK( group->meth->field_add(&tmp, &accr, &accr, group->meth) ); + MP_CHECKOK( group->meth->field_add(&accr, &group->curveb, &accr, group->meth) ); + /* check LHS - RHS == 0 */ + MP_CHECKOK( group->meth->field_sub(&accl, &accr, &accr, group->meth) ); + if (mp_cmp_z(&accr) != 0) { + res = MP_NO; + goto CLEANUP; + } + /* 4: Verify that the order of the curve times the publicValue + * is the point at infinity. + */ + MP_CHECKOK( ECPoint_mul(group, &group->order, px, py, &pxt, &pyt) ); + if (ec_GFp_pt_is_inf_aff(&pxt, &pyt) != MP_YES) { + res = MP_NO; + goto CLEANUP; + } + + res = MP_YES; + +CLEANUP: + mp_clear(&accl); + mp_clear(&accr); + mp_clear(&tmp); + mp_clear(&pxt); + mp_clear(&pyt); + return res; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_jac.c b/src/share/native/sun/security/ec/impl/ecp_jac.c new file mode 100644 index 0000000000000000000000000000000000000000..47c0e195dc16abb84044c9368cef470f3d554916 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_jac.c @@ -0,0 +1,575 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang-Shantz , + * Stephen Fung , and + * Douglas Stebila , Sun Microsystems Laboratories. + * Bodo Moeller , + * Nils Larsch , and + * Lenka Fibikova , the OpenSSL Project + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "mplogic.h" +#ifndef _KERNEL +#include +#endif +#ifdef ECL_DEBUG +#include +#endif + +/* Converts a point P(px, py) from affine coordinates to Jacobian + * projective coordinates R(rx, ry, rz). Assumes input is already + * field-encoded using field_enc, and returns output that is still + * field-encoded. */ +mp_err +ec_GFp_pt_aff2jac(const mp_int *px, const mp_int *py, mp_int *rx, + mp_int *ry, mp_int *rz, const ECGroup *group) +{ + mp_err res = MP_OKAY; + + if (ec_GFp_pt_is_inf_aff(px, py) == MP_YES) { + MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, rz)); + } else { + MP_CHECKOK(mp_copy(px, rx)); + MP_CHECKOK(mp_copy(py, ry)); + MP_CHECKOK(mp_set_int(rz, 1)); + if (group->meth->field_enc) { + MP_CHECKOK(group->meth->field_enc(rz, rz, group->meth)); + } + } + CLEANUP: + return res; +} + +/* Converts a point P(px, py, pz) from Jacobian projective coordinates to + * affine coordinates R(rx, ry). P and R can share x and y coordinates. + * Assumes input is already field-encoded using field_enc, and returns + * output that is still field-encoded. */ +mp_err +ec_GFp_pt_jac2aff(const mp_int *px, const mp_int *py, const mp_int *pz, + mp_int *rx, mp_int *ry, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int z1, z2, z3; + + MP_DIGITS(&z1) = 0; + MP_DIGITS(&z2) = 0; + MP_DIGITS(&z3) = 0; + MP_CHECKOK(mp_init(&z1, FLAG(px))); + MP_CHECKOK(mp_init(&z2, FLAG(px))); + MP_CHECKOK(mp_init(&z3, FLAG(px))); + + /* if point at infinity, then set point at infinity and exit */ + if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { + MP_CHECKOK(ec_GFp_pt_set_inf_aff(rx, ry)); + goto CLEANUP; + } + + /* transform (px, py, pz) into (px / pz^2, py / pz^3) */ + if (mp_cmp_d(pz, 1) == 0) { + MP_CHECKOK(mp_copy(px, rx)); + MP_CHECKOK(mp_copy(py, ry)); + } else { + MP_CHECKOK(group->meth->field_div(NULL, pz, &z1, group->meth)); + MP_CHECKOK(group->meth->field_sqr(&z1, &z2, group->meth)); + MP_CHECKOK(group->meth->field_mul(&z1, &z2, &z3, group->meth)); + MP_CHECKOK(group->meth->field_mul(px, &z2, rx, group->meth)); + MP_CHECKOK(group->meth->field_mul(py, &z3, ry, group->meth)); + } + + CLEANUP: + mp_clear(&z1); + mp_clear(&z2); + mp_clear(&z3); + return res; +} + +/* Checks if point P(px, py, pz) is at infinity. Uses Jacobian + * coordinates. */ +mp_err +ec_GFp_pt_is_inf_jac(const mp_int *px, const mp_int *py, const mp_int *pz) +{ + return mp_cmp_z(pz); +} + +/* Sets P(px, py, pz) to be the point at infinity. Uses Jacobian + * coordinates. */ +mp_err +ec_GFp_pt_set_inf_jac(mp_int *px, mp_int *py, mp_int *pz) +{ + mp_zero(pz); + return MP_OKAY; +} + +/* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and Q is + * (qx, qy, 1). Elliptic curve points P, Q, and R can all be identical. + * Uses mixed Jacobian-affine coordinates. Assumes input is already + * field-encoded using field_enc, and returns output that is still + * field-encoded. Uses equation (2) from Brown, Hankerson, Lopez, and + * Menezes. Software Implementation of the NIST Elliptic Curves Over Prime + * Fields. */ +mp_err +ec_GFp_pt_add_jac_aff(const mp_int *px, const mp_int *py, const mp_int *pz, + const mp_int *qx, const mp_int *qy, mp_int *rx, + mp_int *ry, mp_int *rz, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int A, B, C, D, C2, C3; + + MP_DIGITS(&A) = 0; + MP_DIGITS(&B) = 0; + MP_DIGITS(&C) = 0; + MP_DIGITS(&D) = 0; + MP_DIGITS(&C2) = 0; + MP_DIGITS(&C3) = 0; + MP_CHECKOK(mp_init(&A, FLAG(px))); + MP_CHECKOK(mp_init(&B, FLAG(px))); + MP_CHECKOK(mp_init(&C, FLAG(px))); + MP_CHECKOK(mp_init(&D, FLAG(px))); + MP_CHECKOK(mp_init(&C2, FLAG(px))); + MP_CHECKOK(mp_init(&C3, FLAG(px))); + + /* If either P or Q is the point at infinity, then return the other + * point */ + if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { + MP_CHECKOK(ec_GFp_pt_aff2jac(qx, qy, rx, ry, rz, group)); + goto CLEANUP; + } + if (ec_GFp_pt_is_inf_aff(qx, qy) == MP_YES) { + MP_CHECKOK(mp_copy(px, rx)); + MP_CHECKOK(mp_copy(py, ry)); + MP_CHECKOK(mp_copy(pz, rz)); + goto CLEANUP; + } + + /* A = qx * pz^2, B = qy * pz^3 */ + MP_CHECKOK(group->meth->field_sqr(pz, &A, group->meth)); + MP_CHECKOK(group->meth->field_mul(&A, pz, &B, group->meth)); + MP_CHECKOK(group->meth->field_mul(&A, qx, &A, group->meth)); + MP_CHECKOK(group->meth->field_mul(&B, qy, &B, group->meth)); + + /* C = A - px, D = B - py */ + MP_CHECKOK(group->meth->field_sub(&A, px, &C, group->meth)); + MP_CHECKOK(group->meth->field_sub(&B, py, &D, group->meth)); + + /* C2 = C^2, C3 = C^3 */ + MP_CHECKOK(group->meth->field_sqr(&C, &C2, group->meth)); + MP_CHECKOK(group->meth->field_mul(&C, &C2, &C3, group->meth)); + + /* rz = pz * C */ + MP_CHECKOK(group->meth->field_mul(pz, &C, rz, group->meth)); + + /* C = px * C^2 */ + MP_CHECKOK(group->meth->field_mul(px, &C2, &C, group->meth)); + /* A = D^2 */ + MP_CHECKOK(group->meth->field_sqr(&D, &A, group->meth)); + + /* rx = D^2 - (C^3 + 2 * (px * C^2)) */ + MP_CHECKOK(group->meth->field_add(&C, &C, rx, group->meth)); + MP_CHECKOK(group->meth->field_add(&C3, rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_sub(&A, rx, rx, group->meth)); + + /* C3 = py * C^3 */ + MP_CHECKOK(group->meth->field_mul(py, &C3, &C3, group->meth)); + + /* ry = D * (px * C^2 - rx) - py * C^3 */ + MP_CHECKOK(group->meth->field_sub(&C, rx, ry, group->meth)); + MP_CHECKOK(group->meth->field_mul(&D, ry, ry, group->meth)); + MP_CHECKOK(group->meth->field_sub(ry, &C3, ry, group->meth)); + + CLEANUP: + mp_clear(&A); + mp_clear(&B); + mp_clear(&C); + mp_clear(&D); + mp_clear(&C2); + mp_clear(&C3); + return res; +} + +/* Computes R = 2P. Elliptic curve points P and R can be identical. Uses + * Jacobian coordinates. + * + * Assumes input is already field-encoded using field_enc, and returns + * output that is still field-encoded. + * + * This routine implements Point Doubling in the Jacobian Projective + * space as described in the paper "Efficient elliptic curve exponentiation + * using mixed coordinates", by H. Cohen, A Miyaji, T. Ono. + */ +mp_err +ec_GFp_pt_dbl_jac(const mp_int *px, const mp_int *py, const mp_int *pz, + mp_int *rx, mp_int *ry, mp_int *rz, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int t0, t1, M, S; + + MP_DIGITS(&t0) = 0; + MP_DIGITS(&t1) = 0; + MP_DIGITS(&M) = 0; + MP_DIGITS(&S) = 0; + MP_CHECKOK(mp_init(&t0, FLAG(px))); + MP_CHECKOK(mp_init(&t1, FLAG(px))); + MP_CHECKOK(mp_init(&M, FLAG(px))); + MP_CHECKOK(mp_init(&S, FLAG(px))); + + if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { + MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, rz)); + goto CLEANUP; + } + + if (mp_cmp_d(pz, 1) == 0) { + /* M = 3 * px^2 + a */ + MP_CHECKOK(group->meth->field_sqr(px, &t0, group->meth)); + MP_CHECKOK(group->meth->field_add(&t0, &t0, &M, group->meth)); + MP_CHECKOK(group->meth->field_add(&t0, &M, &t0, group->meth)); + MP_CHECKOK(group->meth-> + field_add(&t0, &group->curvea, &M, group->meth)); + } else if (mp_cmp_int(&group->curvea, -3, FLAG(px)) == 0) { + /* M = 3 * (px + pz^2) * (px - pz^2) */ + MP_CHECKOK(group->meth->field_sqr(pz, &M, group->meth)); + MP_CHECKOK(group->meth->field_add(px, &M, &t0, group->meth)); + MP_CHECKOK(group->meth->field_sub(px, &M, &t1, group->meth)); + MP_CHECKOK(group->meth->field_mul(&t0, &t1, &M, group->meth)); + MP_CHECKOK(group->meth->field_add(&M, &M, &t0, group->meth)); + MP_CHECKOK(group->meth->field_add(&t0, &M, &M, group->meth)); + } else { + /* M = 3 * (px^2) + a * (pz^4) */ + MP_CHECKOK(group->meth->field_sqr(px, &t0, group->meth)); + MP_CHECKOK(group->meth->field_add(&t0, &t0, &M, group->meth)); + MP_CHECKOK(group->meth->field_add(&t0, &M, &t0, group->meth)); + MP_CHECKOK(group->meth->field_sqr(pz, &M, group->meth)); + MP_CHECKOK(group->meth->field_sqr(&M, &M, group->meth)); + MP_CHECKOK(group->meth-> + field_mul(&M, &group->curvea, &M, group->meth)); + MP_CHECKOK(group->meth->field_add(&M, &t0, &M, group->meth)); + } + + /* rz = 2 * py * pz */ + /* t0 = 4 * py^2 */ + if (mp_cmp_d(pz, 1) == 0) { + MP_CHECKOK(group->meth->field_add(py, py, rz, group->meth)); + MP_CHECKOK(group->meth->field_sqr(rz, &t0, group->meth)); + } else { + MP_CHECKOK(group->meth->field_add(py, py, &t0, group->meth)); + MP_CHECKOK(group->meth->field_mul(&t0, pz, rz, group->meth)); + MP_CHECKOK(group->meth->field_sqr(&t0, &t0, group->meth)); + } + + /* S = 4 * px * py^2 = px * (2 * py)^2 */ + MP_CHECKOK(group->meth->field_mul(px, &t0, &S, group->meth)); + + /* rx = M^2 - 2 * S */ + MP_CHECKOK(group->meth->field_add(&S, &S, &t1, group->meth)); + MP_CHECKOK(group->meth->field_sqr(&M, rx, group->meth)); + MP_CHECKOK(group->meth->field_sub(rx, &t1, rx, group->meth)); + + /* ry = M * (S - rx) - 8 * py^4 */ + MP_CHECKOK(group->meth->field_sqr(&t0, &t1, group->meth)); + if (mp_isodd(&t1)) { + MP_CHECKOK(mp_add(&t1, &group->meth->irr, &t1)); + } + MP_CHECKOK(mp_div_2(&t1, &t1)); + MP_CHECKOK(group->meth->field_sub(&S, rx, &S, group->meth)); + MP_CHECKOK(group->meth->field_mul(&M, &S, &M, group->meth)); + MP_CHECKOK(group->meth->field_sub(&M, &t1, ry, group->meth)); + + CLEANUP: + mp_clear(&t0); + mp_clear(&t1); + mp_clear(&M); + mp_clear(&S); + return res; +} + +/* by default, this routine is unused and thus doesn't need to be compiled */ +#ifdef ECL_ENABLE_GFP_PT_MUL_JAC +/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters + * a, b and p are the elliptic curve coefficients and the prime that + * determines the field GFp. Elliptic curve points P and R can be + * identical. Uses mixed Jacobian-affine coordinates. Assumes input is + * already field-encoded using field_enc, and returns output that is still + * field-encoded. Uses 4-bit window method. */ +mp_err +ec_GFp_pt_mul_jac(const mp_int *n, const mp_int *px, const mp_int *py, + mp_int *rx, mp_int *ry, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int precomp[16][2], rz; + int i, ni, d; + + MP_DIGITS(&rz) = 0; + for (i = 0; i < 16; i++) { + MP_DIGITS(&precomp[i][0]) = 0; + MP_DIGITS(&precomp[i][1]) = 0; + } + + ARGCHK(group != NULL, MP_BADARG); + ARGCHK((n != NULL) && (px != NULL) && (py != NULL), MP_BADARG); + + /* initialize precomputation table */ + for (i = 0; i < 16; i++) { + MP_CHECKOK(mp_init(&precomp[i][0])); + MP_CHECKOK(mp_init(&precomp[i][1])); + } + + /* fill precomputation table */ + mp_zero(&precomp[0][0]); + mp_zero(&precomp[0][1]); + MP_CHECKOK(mp_copy(px, &precomp[1][0])); + MP_CHECKOK(mp_copy(py, &precomp[1][1])); + for (i = 2; i < 16; i++) { + MP_CHECKOK(group-> + point_add(&precomp[1][0], &precomp[1][1], + &precomp[i - 1][0], &precomp[i - 1][1], + &precomp[i][0], &precomp[i][1], group)); + } + + d = (mpl_significant_bits(n) + 3) / 4; + + /* R = inf */ + MP_CHECKOK(mp_init(&rz)); + MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, &rz)); + + for (i = d - 1; i >= 0; i--) { + /* compute window ni */ + ni = MP_GET_BIT(n, 4 * i + 3); + ni <<= 1; + ni |= MP_GET_BIT(n, 4 * i + 2); + ni <<= 1; + ni |= MP_GET_BIT(n, 4 * i + 1); + ni <<= 1; + ni |= MP_GET_BIT(n, 4 * i); + /* R = 2^4 * R */ + MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); + MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); + MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); + MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); + /* R = R + (ni * P) */ + MP_CHECKOK(ec_GFp_pt_add_jac_aff + (rx, ry, &rz, &precomp[ni][0], &precomp[ni][1], rx, ry, + &rz, group)); + } + + /* convert result S to affine coordinates */ + MP_CHECKOK(ec_GFp_pt_jac2aff(rx, ry, &rz, rx, ry, group)); + + CLEANUP: + mp_clear(&rz); + for (i = 0; i < 16; i++) { + mp_clear(&precomp[i][0]); + mp_clear(&precomp[i][1]); + } + return res; +} +#endif + +/* Elliptic curve scalar-point multiplication. Computes R(x, y) = k1 * G + + * k2 * P(x, y), where G is the generator (base point) of the group of + * points on the elliptic curve. Allows k1 = NULL or { k2, P } = NULL. + * Uses mixed Jacobian-affine coordinates. Input and output values are + * assumed to be NOT field-encoded. Uses algorithm 15 (simultaneous + * multiple point multiplication) from Brown, Hankerson, Lopez, Menezes. + * Software Implementation of the NIST Elliptic Curves over Prime Fields. */ +mp_err +ec_GFp_pts_mul_jac(const mp_int *k1, const mp_int *k2, const mp_int *px, + const mp_int *py, mp_int *rx, mp_int *ry, + const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int precomp[4][4][2]; + mp_int rz; + const mp_int *a, *b; + int i, j; + int ai, bi, d; + + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + MP_DIGITS(&precomp[i][j][0]) = 0; + MP_DIGITS(&precomp[i][j][1]) = 0; + } + } + MP_DIGITS(&rz) = 0; + + ARGCHK(group != NULL, MP_BADARG); + ARGCHK(!((k1 == NULL) + && ((k2 == NULL) || (px == NULL) + || (py == NULL))), MP_BADARG); + + /* if some arguments are not defined used ECPoint_mul */ + if (k1 == NULL) { + return ECPoint_mul(group, k2, px, py, rx, ry); + } else if ((k2 == NULL) || (px == NULL) || (py == NULL)) { + return ECPoint_mul(group, k1, NULL, NULL, rx, ry); + } + + /* initialize precomputation table */ + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + MP_CHECKOK(mp_init(&precomp[i][j][0], FLAG(k1))); + MP_CHECKOK(mp_init(&precomp[i][j][1], FLAG(k1))); + } + } + + /* fill precomputation table */ + /* assign {k1, k2} = {a, b} such that len(a) >= len(b) */ + if (mpl_significant_bits(k1) < mpl_significant_bits(k2)) { + a = k2; + b = k1; + if (group->meth->field_enc) { + MP_CHECKOK(group->meth-> + field_enc(px, &precomp[1][0][0], group->meth)); + MP_CHECKOK(group->meth-> + field_enc(py, &precomp[1][0][1], group->meth)); + } else { + MP_CHECKOK(mp_copy(px, &precomp[1][0][0])); + MP_CHECKOK(mp_copy(py, &precomp[1][0][1])); + } + MP_CHECKOK(mp_copy(&group->genx, &precomp[0][1][0])); + MP_CHECKOK(mp_copy(&group->geny, &precomp[0][1][1])); + } else { + a = k1; + b = k2; + MP_CHECKOK(mp_copy(&group->genx, &precomp[1][0][0])); + MP_CHECKOK(mp_copy(&group->geny, &precomp[1][0][1])); + if (group->meth->field_enc) { + MP_CHECKOK(group->meth-> + field_enc(px, &precomp[0][1][0], group->meth)); + MP_CHECKOK(group->meth-> + field_enc(py, &precomp[0][1][1], group->meth)); + } else { + MP_CHECKOK(mp_copy(px, &precomp[0][1][0])); + MP_CHECKOK(mp_copy(py, &precomp[0][1][1])); + } + } + /* precompute [*][0][*] */ + mp_zero(&precomp[0][0][0]); + mp_zero(&precomp[0][0][1]); + MP_CHECKOK(group-> + point_dbl(&precomp[1][0][0], &precomp[1][0][1], + &precomp[2][0][0], &precomp[2][0][1], group)); + MP_CHECKOK(group-> + point_add(&precomp[1][0][0], &precomp[1][0][1], + &precomp[2][0][0], &precomp[2][0][1], + &precomp[3][0][0], &precomp[3][0][1], group)); + /* precompute [*][1][*] */ + for (i = 1; i < 4; i++) { + MP_CHECKOK(group-> + point_add(&precomp[0][1][0], &precomp[0][1][1], + &precomp[i][0][0], &precomp[i][0][1], + &precomp[i][1][0], &precomp[i][1][1], group)); + } + /* precompute [*][2][*] */ + MP_CHECKOK(group-> + point_dbl(&precomp[0][1][0], &precomp[0][1][1], + &precomp[0][2][0], &precomp[0][2][1], group)); + for (i = 1; i < 4; i++) { + MP_CHECKOK(group-> + point_add(&precomp[0][2][0], &precomp[0][2][1], + &precomp[i][0][0], &precomp[i][0][1], + &precomp[i][2][0], &precomp[i][2][1], group)); + } + /* precompute [*][3][*] */ + MP_CHECKOK(group-> + point_add(&precomp[0][1][0], &precomp[0][1][1], + &precomp[0][2][0], &precomp[0][2][1], + &precomp[0][3][0], &precomp[0][3][1], group)); + for (i = 1; i < 4; i++) { + MP_CHECKOK(group-> + point_add(&precomp[0][3][0], &precomp[0][3][1], + &precomp[i][0][0], &precomp[i][0][1], + &precomp[i][3][0], &precomp[i][3][1], group)); + } + + d = (mpl_significant_bits(a) + 1) / 2; + + /* R = inf */ + MP_CHECKOK(mp_init(&rz, FLAG(k1))); + MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, &rz)); + + for (i = d - 1; i >= 0; i--) { + ai = MP_GET_BIT(a, 2 * i + 1); + ai <<= 1; + ai |= MP_GET_BIT(a, 2 * i); + bi = MP_GET_BIT(b, 2 * i + 1); + bi <<= 1; + bi |= MP_GET_BIT(b, 2 * i); + /* R = 2^2 * R */ + MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); + MP_CHECKOK(ec_GFp_pt_dbl_jac(rx, ry, &rz, rx, ry, &rz, group)); + /* R = R + (ai * A + bi * B) */ + MP_CHECKOK(ec_GFp_pt_add_jac_aff + (rx, ry, &rz, &precomp[ai][bi][0], &precomp[ai][bi][1], + rx, ry, &rz, group)); + } + + MP_CHECKOK(ec_GFp_pt_jac2aff(rx, ry, &rz, rx, ry, group)); + + if (group->meth->field_dec) { + MP_CHECKOK(group->meth->field_dec(rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_dec(ry, ry, group->meth)); + } + + CLEANUP: + mp_clear(&rz); + for (i = 0; i < 4; i++) { + for (j = 0; j < 4; j++) { + mp_clear(&precomp[i][j][0]); + mp_clear(&precomp[i][j][1]); + } + } + return res; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_jm.c b/src/share/native/sun/security/ec/impl/ecp_jm.c new file mode 100644 index 0000000000000000000000000000000000000000..a5e38db21da2eeab76181b672de1a123b0da6bdf --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_jm.c @@ -0,0 +1,353 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library for prime field curves. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Stephen Fung , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "ecp.h" +#include "ecl-priv.h" +#include "mplogic.h" +#ifndef _KERNEL +#include +#endif + +#define MAX_SCRATCH 6 + +/* Computes R = 2P. Elliptic curve points P and R can be identical. Uses + * Modified Jacobian coordinates. + * + * Assumes input is already field-encoded using field_enc, and returns + * output that is still field-encoded. + * + */ +mp_err +ec_GFp_pt_dbl_jm(const mp_int *px, const mp_int *py, const mp_int *pz, + const mp_int *paz4, mp_int *rx, mp_int *ry, mp_int *rz, + mp_int *raz4, mp_int scratch[], const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int *t0, *t1, *M, *S; + + t0 = &scratch[0]; + t1 = &scratch[1]; + M = &scratch[2]; + S = &scratch[3]; + +#if MAX_SCRATCH < 4 +#error "Scratch array defined too small " +#endif + + /* Check for point at infinity */ + if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { + /* Set r = pt at infinity by setting rz = 0 */ + + MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, rz)); + goto CLEANUP; + } + + /* M = 3 (px^2) + a*(pz^4) */ + MP_CHECKOK(group->meth->field_sqr(px, t0, group->meth)); + MP_CHECKOK(group->meth->field_add(t0, t0, M, group->meth)); + MP_CHECKOK(group->meth->field_add(t0, M, t0, group->meth)); + MP_CHECKOK(group->meth->field_add(t0, paz4, M, group->meth)); + + /* rz = 2 * py * pz */ + MP_CHECKOK(group->meth->field_mul(py, pz, S, group->meth)); + MP_CHECKOK(group->meth->field_add(S, S, rz, group->meth)); + + /* t0 = 2y^2 , t1 = 8y^4 */ + MP_CHECKOK(group->meth->field_sqr(py, t0, group->meth)); + MP_CHECKOK(group->meth->field_add(t0, t0, t0, group->meth)); + MP_CHECKOK(group->meth->field_sqr(t0, t1, group->meth)); + MP_CHECKOK(group->meth->field_add(t1, t1, t1, group->meth)); + + /* S = 4 * px * py^2 = 2 * px * t0 */ + MP_CHECKOK(group->meth->field_mul(px, t0, S, group->meth)); + MP_CHECKOK(group->meth->field_add(S, S, S, group->meth)); + + + /* rx = M^2 - 2S */ + MP_CHECKOK(group->meth->field_sqr(M, rx, group->meth)); + MP_CHECKOK(group->meth->field_sub(rx, S, rx, group->meth)); + MP_CHECKOK(group->meth->field_sub(rx, S, rx, group->meth)); + + /* ry = M * (S - rx) - t1 */ + MP_CHECKOK(group->meth->field_sub(S, rx, S, group->meth)); + MP_CHECKOK(group->meth->field_mul(S, M, ry, group->meth)); + MP_CHECKOK(group->meth->field_sub(ry, t1, ry, group->meth)); + + /* ra*z^4 = 2*t1*(apz4) */ + MP_CHECKOK(group->meth->field_mul(paz4, t1, raz4, group->meth)); + MP_CHECKOK(group->meth->field_add(raz4, raz4, raz4, group->meth)); + + + CLEANUP: + return res; +} + +/* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and Q is + * (qx, qy, 1). Elliptic curve points P, Q, and R can all be identical. + * Uses mixed Modified_Jacobian-affine coordinates. Assumes input is + * already field-encoded using field_enc, and returns output that is still + * field-encoded. */ +mp_err +ec_GFp_pt_add_jm_aff(const mp_int *px, const mp_int *py, const mp_int *pz, + const mp_int *paz4, const mp_int *qx, + const mp_int *qy, mp_int *rx, mp_int *ry, mp_int *rz, + mp_int *raz4, mp_int scratch[], const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int *A, *B, *C, *D, *C2, *C3; + + A = &scratch[0]; + B = &scratch[1]; + C = &scratch[2]; + D = &scratch[3]; + C2 = &scratch[4]; + C3 = &scratch[5]; + +#if MAX_SCRATCH < 6 +#error "Scratch array defined too small " +#endif + + /* If either P or Q is the point at infinity, then return the other + * point */ + if (ec_GFp_pt_is_inf_jac(px, py, pz) == MP_YES) { + MP_CHECKOK(ec_GFp_pt_aff2jac(qx, qy, rx, ry, rz, group)); + MP_CHECKOK(group->meth->field_sqr(rz, raz4, group->meth)); + MP_CHECKOK(group->meth->field_sqr(raz4, raz4, group->meth)); + MP_CHECKOK(group->meth-> + field_mul(raz4, &group->curvea, raz4, group->meth)); + goto CLEANUP; + } + if (ec_GFp_pt_is_inf_aff(qx, qy) == MP_YES) { + MP_CHECKOK(mp_copy(px, rx)); + MP_CHECKOK(mp_copy(py, ry)); + MP_CHECKOK(mp_copy(pz, rz)); + MP_CHECKOK(mp_copy(paz4, raz4)); + goto CLEANUP; + } + + /* A = qx * pz^2, B = qy * pz^3 */ + MP_CHECKOK(group->meth->field_sqr(pz, A, group->meth)); + MP_CHECKOK(group->meth->field_mul(A, pz, B, group->meth)); + MP_CHECKOK(group->meth->field_mul(A, qx, A, group->meth)); + MP_CHECKOK(group->meth->field_mul(B, qy, B, group->meth)); + + /* C = A - px, D = B - py */ + MP_CHECKOK(group->meth->field_sub(A, px, C, group->meth)); + MP_CHECKOK(group->meth->field_sub(B, py, D, group->meth)); + + /* C2 = C^2, C3 = C^3 */ + MP_CHECKOK(group->meth->field_sqr(C, C2, group->meth)); + MP_CHECKOK(group->meth->field_mul(C, C2, C3, group->meth)); + + /* rz = pz * C */ + MP_CHECKOK(group->meth->field_mul(pz, C, rz, group->meth)); + + /* C = px * C^2 */ + MP_CHECKOK(group->meth->field_mul(px, C2, C, group->meth)); + /* A = D^2 */ + MP_CHECKOK(group->meth->field_sqr(D, A, group->meth)); + + /* rx = D^2 - (C^3 + 2 * (px * C^2)) */ + MP_CHECKOK(group->meth->field_add(C, C, rx, group->meth)); + MP_CHECKOK(group->meth->field_add(C3, rx, rx, group->meth)); + MP_CHECKOK(group->meth->field_sub(A, rx, rx, group->meth)); + + /* C3 = py * C^3 */ + MP_CHECKOK(group->meth->field_mul(py, C3, C3, group->meth)); + + /* ry = D * (px * C^2 - rx) - py * C^3 */ + MP_CHECKOK(group->meth->field_sub(C, rx, ry, group->meth)); + MP_CHECKOK(group->meth->field_mul(D, ry, ry, group->meth)); + MP_CHECKOK(group->meth->field_sub(ry, C3, ry, group->meth)); + + /* raz4 = a * rz^4 */ + MP_CHECKOK(group->meth->field_sqr(rz, raz4, group->meth)); + MP_CHECKOK(group->meth->field_sqr(raz4, raz4, group->meth)); + MP_CHECKOK(group->meth-> + field_mul(raz4, &group->curvea, raz4, group->meth)); +CLEANUP: + return res; +} + +/* Computes R = nP where R is (rx, ry) and P is the base point. Elliptic + * curve points P and R can be identical. Uses mixed Modified-Jacobian + * co-ordinates for doubling and Chudnovsky Jacobian coordinates for + * additions. Assumes input is already field-encoded using field_enc, and + * returns output that is still field-encoded. Uses 5-bit window NAF + * method (algorithm 11) for scalar-point multiplication from Brown, + * Hankerson, Lopez, Menezes. Software Implementation of the NIST Elliptic + * Curves Over Prime Fields. */ +mp_err +ec_GFp_pt_mul_jm_wNAF(const mp_int *n, const mp_int *px, const mp_int *py, + mp_int *rx, mp_int *ry, const ECGroup *group) +{ + mp_err res = MP_OKAY; + mp_int precomp[16][2], rz, tpx, tpy; + mp_int raz4; + mp_int scratch[MAX_SCRATCH]; + signed char *naf = NULL; + int i, orderBitSize; + + MP_DIGITS(&rz) = 0; + MP_DIGITS(&raz4) = 0; + MP_DIGITS(&tpx) = 0; + MP_DIGITS(&tpy) = 0; + for (i = 0; i < 16; i++) { + MP_DIGITS(&precomp[i][0]) = 0; + MP_DIGITS(&precomp[i][1]) = 0; + } + for (i = 0; i < MAX_SCRATCH; i++) { + MP_DIGITS(&scratch[i]) = 0; + } + + ARGCHK(group != NULL, MP_BADARG); + ARGCHK((n != NULL) && (px != NULL) && (py != NULL), MP_BADARG); + + /* initialize precomputation table */ + MP_CHECKOK(mp_init(&tpx, FLAG(n))); + MP_CHECKOK(mp_init(&tpy, FLAG(n)));; + MP_CHECKOK(mp_init(&rz, FLAG(n))); + MP_CHECKOK(mp_init(&raz4, FLAG(n))); + + for (i = 0; i < 16; i++) { + MP_CHECKOK(mp_init(&precomp[i][0], FLAG(n))); + MP_CHECKOK(mp_init(&precomp[i][1], FLAG(n))); + } + for (i = 0; i < MAX_SCRATCH; i++) { + MP_CHECKOK(mp_init(&scratch[i], FLAG(n))); + } + + /* Set out[8] = P */ + MP_CHECKOK(mp_copy(px, &precomp[8][0])); + MP_CHECKOK(mp_copy(py, &precomp[8][1])); + + /* Set (tpx, tpy) = 2P */ + MP_CHECKOK(group-> + point_dbl(&precomp[8][0], &precomp[8][1], &tpx, &tpy, + group)); + + /* Set 3P, 5P, ..., 15P */ + for (i = 8; i < 15; i++) { + MP_CHECKOK(group-> + point_add(&precomp[i][0], &precomp[i][1], &tpx, &tpy, + &precomp[i + 1][0], &precomp[i + 1][1], + group)); + } + + /* Set -15P, -13P, ..., -P */ + for (i = 0; i < 8; i++) { + MP_CHECKOK(mp_copy(&precomp[15 - i][0], &precomp[i][0])); + MP_CHECKOK(group->meth-> + field_neg(&precomp[15 - i][1], &precomp[i][1], + group->meth)); + } + + /* R = inf */ + MP_CHECKOK(ec_GFp_pt_set_inf_jac(rx, ry, &rz)); + + orderBitSize = mpl_significant_bits(&group->order); + + /* Allocate memory for NAF */ +#ifdef _KERNEL + naf = (signed char *) kmem_alloc((orderBitSize + 1), FLAG(n)); +#else + naf = (signed char *) malloc(sizeof(signed char) * (orderBitSize + 1)); + if (naf == NULL) { + res = MP_MEM; + goto CLEANUP; + } +#endif + + /* Compute 5NAF */ + ec_compute_wNAF(naf, orderBitSize, n, 5); + + /* wNAF method */ + for (i = orderBitSize; i >= 0; i--) { + /* R = 2R */ + ec_GFp_pt_dbl_jm(rx, ry, &rz, &raz4, rx, ry, &rz, + &raz4, scratch, group); + if (naf[i] != 0) { + ec_GFp_pt_add_jm_aff(rx, ry, &rz, &raz4, + &precomp[(naf[i] + 15) / 2][0], + &precomp[(naf[i] + 15) / 2][1], rx, ry, + &rz, &raz4, scratch, group); + } + } + + /* convert result S to affine coordinates */ + MP_CHECKOK(ec_GFp_pt_jac2aff(rx, ry, &rz, rx, ry, group)); + + CLEANUP: + for (i = 0; i < MAX_SCRATCH; i++) { + mp_clear(&scratch[i]); + } + for (i = 0; i < 16; i++) { + mp_clear(&precomp[i][0]); + mp_clear(&precomp[i][1]); + } + mp_clear(&tpx); + mp_clear(&tpy); + mp_clear(&rz); + mp_clear(&raz4); +#ifdef _KERNEL + kmem_free(naf, (orderBitSize + 1)); +#else + free(naf); +#endif + return res; +} diff --git a/src/share/native/sun/security/ec/impl/ecp_mont.c b/src/share/native/sun/security/ec/impl/ecp_mont.c new file mode 100644 index 0000000000000000000000000000000000000000..6b4dbb29e25c95e960853eafab736ee4dfaae547 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/ecp_mont.c @@ -0,0 +1,223 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the elliptic curve math library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Douglas Stebila , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* Uses Montgomery reduction for field arithmetic. See mpi/mpmontg.c for + * code implementation. */ + +#include "mpi.h" +#include "mplogic.h" +#include "mpi-priv.h" +#include "ecl-priv.h" +#include "ecp.h" +#ifndef _KERNEL +#include +#include +#endif + +/* Construct a generic GFMethod for arithmetic over prime fields with + * irreducible irr. */ +GFMethod * +GFMethod_consGFp_mont(const mp_int *irr) +{ + mp_err res = MP_OKAY; + int i; + GFMethod *meth = NULL; + mp_mont_modulus *mmm; + + meth = GFMethod_consGFp(irr); + if (meth == NULL) + return NULL; + +#ifdef _KERNEL + mmm = (mp_mont_modulus *) kmem_alloc(sizeof(mp_mont_modulus), + FLAG(irr)); +#else + mmm = (mp_mont_modulus *) malloc(sizeof(mp_mont_modulus)); +#endif + if (mmm == NULL) { + res = MP_MEM; + goto CLEANUP; + } + + meth->field_mul = &ec_GFp_mul_mont; + meth->field_sqr = &ec_GFp_sqr_mont; + meth->field_div = &ec_GFp_div_mont; + meth->field_enc = &ec_GFp_enc_mont; + meth->field_dec = &ec_GFp_dec_mont; + meth->extra1 = mmm; + meth->extra2 = NULL; + meth->extra_free = &ec_GFp_extra_free_mont; + + mmm->N = meth->irr; + i = mpl_significant_bits(&meth->irr); + i += MP_DIGIT_BIT - 1; + mmm->b = i - i % MP_DIGIT_BIT; + mmm->n0prime = 0 - s_mp_invmod_radix(MP_DIGIT(&meth->irr, 0)); + + CLEANUP: + if (res != MP_OKAY) { + GFMethod_free(meth); + return NULL; + } + return meth; +} + +/* Wrapper functions for generic prime field arithmetic. */ + +/* Field multiplication using Montgomery reduction. */ +mp_err +ec_GFp_mul_mont(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + +#ifdef MP_MONT_USE_MP_MUL + /* if MP_MONT_USE_MP_MUL is defined, then the function s_mp_mul_mont + * is not implemented and we have to use mp_mul and s_mp_redc directly + */ + MP_CHECKOK(mp_mul(a, b, r)); + MP_CHECKOK(s_mp_redc(r, (mp_mont_modulus *) meth->extra1)); +#else + mp_int s; + + MP_DIGITS(&s) = 0; + /* s_mp_mul_mont doesn't allow source and destination to be the same */ + if ((a == r) || (b == r)) { + MP_CHECKOK(mp_init(&s, FLAG(a))); + MP_CHECKOK(s_mp_mul_mont + (a, b, &s, (mp_mont_modulus *) meth->extra1)); + MP_CHECKOK(mp_copy(&s, r)); + mp_clear(&s); + } else { + return s_mp_mul_mont(a, b, r, (mp_mont_modulus *) meth->extra1); + } +#endif + CLEANUP: + return res; +} + +/* Field squaring using Montgomery reduction. */ +mp_err +ec_GFp_sqr_mont(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + return ec_GFp_mul_mont(a, a, r, meth); +} + +/* Field division using Montgomery reduction. */ +mp_err +ec_GFp_div_mont(const mp_int *a, const mp_int *b, mp_int *r, + const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + /* if A=aZ represents a encoded in montgomery coordinates with Z and # + * and \ respectively represent multiplication and division in + * montgomery coordinates, then A\B = (a/b)Z = (A/B)Z and Binv = + * (1/b)Z = (1/B)(Z^2) where B # Binv = Z */ + MP_CHECKOK(ec_GFp_div(a, b, r, meth)); + MP_CHECKOK(ec_GFp_enc_mont(r, r, meth)); + if (a == NULL) { + MP_CHECKOK(ec_GFp_enc_mont(r, r, meth)); + } + CLEANUP: + return res; +} + +/* Encode a field element in Montgomery form. See s_mp_to_mont in + * mpi/mpmontg.c */ +mp_err +ec_GFp_enc_mont(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_mont_modulus *mmm; + mp_err res = MP_OKAY; + + mmm = (mp_mont_modulus *) meth->extra1; + MP_CHECKOK(mpl_lsh(a, r, mmm->b)); + MP_CHECKOK(mp_mod(r, &mmm->N, r)); + CLEANUP: + return res; +} + +/* Decode a field element from Montgomery form. */ +mp_err +ec_GFp_dec_mont(const mp_int *a, mp_int *r, const GFMethod *meth) +{ + mp_err res = MP_OKAY; + + if (a != r) { + MP_CHECKOK(mp_copy(a, r)); + } + MP_CHECKOK(s_mp_redc(r, (mp_mont_modulus *) meth->extra1)); + CLEANUP: + return res; +} + +/* Free the memory allocated to the extra fields of Montgomery GFMethod + * object. */ +void +ec_GFp_extra_free_mont(GFMethod *meth) +{ + if (meth->extra1 != NULL) { +#ifdef _KERNEL + kmem_free(meth->extra1, sizeof(mp_mont_modulus)); +#else + free(meth->extra1); +#endif + meth->extra1 = NULL; + } +} diff --git a/src/share/native/sun/security/ec/impl/logtab.h b/src/share/native/sun/security/ec/impl/logtab.h new file mode 100644 index 0000000000000000000000000000000000000000..6efa01995600c937a2c7f688f2a617b2d9859bf3 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/logtab.h @@ -0,0 +1,82 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1994-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Dr Vipul Gupta , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _LOGTAB_H +#define _LOGTAB_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +const float s_logv_2[] = { + 0.000000000f, 0.000000000f, 1.000000000f, 0.630929754f, /* 0 1 2 3 */ + 0.500000000f, 0.430676558f, 0.386852807f, 0.356207187f, /* 4 5 6 7 */ + 0.333333333f, 0.315464877f, 0.301029996f, 0.289064826f, /* 8 9 10 11 */ + 0.278942946f, 0.270238154f, 0.262649535f, 0.255958025f, /* 12 13 14 15 */ + 0.250000000f, 0.244650542f, 0.239812467f, 0.235408913f, /* 16 17 18 19 */ + 0.231378213f, 0.227670249f, 0.224243824f, 0.221064729f, /* 20 21 22 23 */ + 0.218104292f, 0.215338279f, 0.212746054f, 0.210309918f, /* 24 25 26 27 */ + 0.208014598f, 0.205846832f, 0.203795047f, 0.201849087f, /* 28 29 30 31 */ + 0.200000000f, 0.198239863f, 0.196561632f, 0.194959022f, /* 32 33 34 35 */ + 0.193426404f, 0.191958720f, 0.190551412f, 0.189200360f, /* 36 37 38 39 */ + 0.187901825f, 0.186652411f, 0.185449023f, 0.184288833f, /* 40 41 42 43 */ + 0.183169251f, 0.182087900f, 0.181042597f, 0.180031327f, /* 44 45 46 47 */ + 0.179052232f, 0.178103594f, 0.177183820f, 0.176291434f, /* 48 49 50 51 */ + 0.175425064f, 0.174583430f, 0.173765343f, 0.172969690f, /* 52 53 54 55 */ + 0.172195434f, 0.171441601f, 0.170707280f, 0.169991616f, /* 56 57 58 59 */ + 0.169293808f, 0.168613099f, 0.167948779f, 0.167300179f, /* 60 61 62 63 */ + 0.166666667f +}; + +#endif /* _LOGTAB_H */ diff --git a/src/share/native/sun/security/ec/impl/mp_gf2m-priv.h b/src/share/native/sun/security/ec/impl/mp_gf2m-priv.h new file mode 100644 index 0000000000000000000000000000000000000000..7a4505807fc73370dbd356eefc2ed0409dffe734 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mp_gf2m-priv.h @@ -0,0 +1,122 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Multi-precision Binary Polynomial Arithmetic Library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang Shantz and + * Douglas Stebila of Sun Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MP_GF2M_PRIV_H_ +#define _MP_GF2M_PRIV_H_ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mpi-priv.h" + +extern const mp_digit mp_gf2m_sqr_tb[16]; + +#if defined(MP_USE_UINT_DIGIT) +#define MP_DIGIT_BITS 32 +#else +#define MP_DIGIT_BITS 64 +#endif + +/* Platform-specific macros for fast binary polynomial squaring. */ +#if MP_DIGIT_BITS == 32 +#define gf2m_SQR1(w) \ + mp_gf2m_sqr_tb[(w) >> 28 & 0xF] << 24 | mp_gf2m_sqr_tb[(w) >> 24 & 0xF] << 16 | \ + mp_gf2m_sqr_tb[(w) >> 20 & 0xF] << 8 | mp_gf2m_sqr_tb[(w) >> 16 & 0xF] +#define gf2m_SQR0(w) \ + mp_gf2m_sqr_tb[(w) >> 12 & 0xF] << 24 | mp_gf2m_sqr_tb[(w) >> 8 & 0xF] << 16 | \ + mp_gf2m_sqr_tb[(w) >> 4 & 0xF] << 8 | mp_gf2m_sqr_tb[(w) & 0xF] +#else +#define gf2m_SQR1(w) \ + mp_gf2m_sqr_tb[(w) >> 60 & 0xF] << 56 | mp_gf2m_sqr_tb[(w) >> 56 & 0xF] << 48 | \ + mp_gf2m_sqr_tb[(w) >> 52 & 0xF] << 40 | mp_gf2m_sqr_tb[(w) >> 48 & 0xF] << 32 | \ + mp_gf2m_sqr_tb[(w) >> 44 & 0xF] << 24 | mp_gf2m_sqr_tb[(w) >> 40 & 0xF] << 16 | \ + mp_gf2m_sqr_tb[(w) >> 36 & 0xF] << 8 | mp_gf2m_sqr_tb[(w) >> 32 & 0xF] +#define gf2m_SQR0(w) \ + mp_gf2m_sqr_tb[(w) >> 28 & 0xF] << 56 | mp_gf2m_sqr_tb[(w) >> 24 & 0xF] << 48 | \ + mp_gf2m_sqr_tb[(w) >> 20 & 0xF] << 40 | mp_gf2m_sqr_tb[(w) >> 16 & 0xF] << 32 | \ + mp_gf2m_sqr_tb[(w) >> 12 & 0xF] << 24 | mp_gf2m_sqr_tb[(w) >> 8 & 0xF] << 16 | \ + mp_gf2m_sqr_tb[(w) >> 4 & 0xF] << 8 | mp_gf2m_sqr_tb[(w) & 0xF] +#endif + +/* Multiply two binary polynomials mp_digits a, b. + * Result is a polynomial with degree < 2 * MP_DIGIT_BITS - 1. + * Output in two mp_digits rh, rl. + */ +void s_bmul_1x1(mp_digit *rh, mp_digit *rl, const mp_digit a, const mp_digit b); + +/* Compute xor-multiply of two binary polynomials (a1, a0) x (b1, b0) + * result is a binary polynomial in 4 mp_digits r[4]. + * The caller MUST ensure that r has the right amount of space allocated. + */ +void s_bmul_2x2(mp_digit *r, const mp_digit a1, const mp_digit a0, const mp_digit b1, + const mp_digit b0); + +/* Compute xor-multiply of two binary polynomials (a2, a1, a0) x (b2, b1, b0) + * result is a binary polynomial in 6 mp_digits r[6]. + * The caller MUST ensure that r has the right amount of space allocated. + */ +void s_bmul_3x3(mp_digit *r, const mp_digit a2, const mp_digit a1, const mp_digit a0, + const mp_digit b2, const mp_digit b1, const mp_digit b0); + +/* Compute xor-multiply of two binary polynomials (a3, a2, a1, a0) x (b3, b2, b1, b0) + * result is a binary polynomial in 8 mp_digits r[8]. + * The caller MUST ensure that r has the right amount of space allocated. + */ +void s_bmul_4x4(mp_digit *r, const mp_digit a3, const mp_digit a2, const mp_digit a1, + const mp_digit a0, const mp_digit b3, const mp_digit b2, const mp_digit b1, + const mp_digit b0); + +#endif /* _MP_GF2M_PRIV_H_ */ diff --git a/src/share/native/sun/security/ec/impl/mp_gf2m.c b/src/share/native/sun/security/ec/impl/mp_gf2m.c new file mode 100644 index 0000000000000000000000000000000000000000..74b64789c96be78da9ff2d06179fd2d23df5dce2 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mp_gf2m.c @@ -0,0 +1,624 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Multi-precision Binary Polynomial Arithmetic Library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang Shantz and + * Douglas Stebila of Sun Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mp_gf2m.h" +#include "mp_gf2m-priv.h" +#include "mplogic.h" +#include "mpi-priv.h" + +const mp_digit mp_gf2m_sqr_tb[16] = +{ + 0, 1, 4, 5, 16, 17, 20, 21, + 64, 65, 68, 69, 80, 81, 84, 85 +}; + +/* Multiply two binary polynomials mp_digits a, b. + * Result is a polynomial with degree < 2 * MP_DIGIT_BITS - 1. + * Output in two mp_digits rh, rl. + */ +#if MP_DIGIT_BITS == 32 +void +s_bmul_1x1(mp_digit *rh, mp_digit *rl, const mp_digit a, const mp_digit b) +{ + register mp_digit h, l, s; + mp_digit tab[8], top2b = a >> 30; + register mp_digit a1, a2, a4; + + a1 = a & (0x3FFFFFFF); a2 = a1 << 1; a4 = a2 << 1; + + tab[0] = 0; tab[1] = a1; tab[2] = a2; tab[3] = a1^a2; + tab[4] = a4; tab[5] = a1^a4; tab[6] = a2^a4; tab[7] = a1^a2^a4; + + s = tab[b & 0x7]; l = s; + s = tab[b >> 3 & 0x7]; l ^= s << 3; h = s >> 29; + s = tab[b >> 6 & 0x7]; l ^= s << 6; h ^= s >> 26; + s = tab[b >> 9 & 0x7]; l ^= s << 9; h ^= s >> 23; + s = tab[b >> 12 & 0x7]; l ^= s << 12; h ^= s >> 20; + s = tab[b >> 15 & 0x7]; l ^= s << 15; h ^= s >> 17; + s = tab[b >> 18 & 0x7]; l ^= s << 18; h ^= s >> 14; + s = tab[b >> 21 & 0x7]; l ^= s << 21; h ^= s >> 11; + s = tab[b >> 24 & 0x7]; l ^= s << 24; h ^= s >> 8; + s = tab[b >> 27 & 0x7]; l ^= s << 27; h ^= s >> 5; + s = tab[b >> 30 ]; l ^= s << 30; h ^= s >> 2; + + /* compensate for the top two bits of a */ + + if (top2b & 01) { l ^= b << 30; h ^= b >> 2; } + if (top2b & 02) { l ^= b << 31; h ^= b >> 1; } + + *rh = h; *rl = l; +} +#else +void +s_bmul_1x1(mp_digit *rh, mp_digit *rl, const mp_digit a, const mp_digit b) +{ + register mp_digit h, l, s; + mp_digit tab[16], top3b = a >> 61; + register mp_digit a1, a2, a4, a8; + + a1 = a & (0x1FFFFFFFFFFFFFFFULL); a2 = a1 << 1; + a4 = a2 << 1; a8 = a4 << 1; + tab[ 0] = 0; tab[ 1] = a1; tab[ 2] = a2; tab[ 3] = a1^a2; + tab[ 4] = a4; tab[ 5] = a1^a4; tab[ 6] = a2^a4; tab[ 7] = a1^a2^a4; + tab[ 8] = a8; tab[ 9] = a1^a8; tab[10] = a2^a8; tab[11] = a1^a2^a8; + tab[12] = a4^a8; tab[13] = a1^a4^a8; tab[14] = a2^a4^a8; tab[15] = a1^a2^a4^a8; + + s = tab[b & 0xF]; l = s; + s = tab[b >> 4 & 0xF]; l ^= s << 4; h = s >> 60; + s = tab[b >> 8 & 0xF]; l ^= s << 8; h ^= s >> 56; + s = tab[b >> 12 & 0xF]; l ^= s << 12; h ^= s >> 52; + s = tab[b >> 16 & 0xF]; l ^= s << 16; h ^= s >> 48; + s = tab[b >> 20 & 0xF]; l ^= s << 20; h ^= s >> 44; + s = tab[b >> 24 & 0xF]; l ^= s << 24; h ^= s >> 40; + s = tab[b >> 28 & 0xF]; l ^= s << 28; h ^= s >> 36; + s = tab[b >> 32 & 0xF]; l ^= s << 32; h ^= s >> 32; + s = tab[b >> 36 & 0xF]; l ^= s << 36; h ^= s >> 28; + s = tab[b >> 40 & 0xF]; l ^= s << 40; h ^= s >> 24; + s = tab[b >> 44 & 0xF]; l ^= s << 44; h ^= s >> 20; + s = tab[b >> 48 & 0xF]; l ^= s << 48; h ^= s >> 16; + s = tab[b >> 52 & 0xF]; l ^= s << 52; h ^= s >> 12; + s = tab[b >> 56 & 0xF]; l ^= s << 56; h ^= s >> 8; + s = tab[b >> 60 ]; l ^= s << 60; h ^= s >> 4; + + /* compensate for the top three bits of a */ + + if (top3b & 01) { l ^= b << 61; h ^= b >> 3; } + if (top3b & 02) { l ^= b << 62; h ^= b >> 2; } + if (top3b & 04) { l ^= b << 63; h ^= b >> 1; } + + *rh = h; *rl = l; +} +#endif + +/* Compute xor-multiply of two binary polynomials (a1, a0) x (b1, b0) + * result is a binary polynomial in 4 mp_digits r[4]. + * The caller MUST ensure that r has the right amount of space allocated. + */ +void +s_bmul_2x2(mp_digit *r, const mp_digit a1, const mp_digit a0, const mp_digit b1, + const mp_digit b0) +{ + mp_digit m1, m0; + /* r[3] = h1, r[2] = h0; r[1] = l1; r[0] = l0 */ + s_bmul_1x1(r+3, r+2, a1, b1); + s_bmul_1x1(r+1, r, a0, b0); + s_bmul_1x1(&m1, &m0, a0 ^ a1, b0 ^ b1); + /* Correction on m1 ^= l1 ^ h1; m0 ^= l0 ^ h0; */ + r[2] ^= m1 ^ r[1] ^ r[3]; /* h0 ^= m1 ^ l1 ^ h1; */ + r[1] = r[3] ^ r[2] ^ r[0] ^ m1 ^ m0; /* l1 ^= l0 ^ h0 ^ m0; */ +} + +/* Compute xor-multiply of two binary polynomials (a2, a1, a0) x (b2, b1, b0) + * result is a binary polynomial in 6 mp_digits r[6]. + * The caller MUST ensure that r has the right amount of space allocated. + */ +void +s_bmul_3x3(mp_digit *r, const mp_digit a2, const mp_digit a1, const mp_digit a0, + const mp_digit b2, const mp_digit b1, const mp_digit b0) +{ + mp_digit zm[4]; + + s_bmul_1x1(r+5, r+4, a2, b2); /* fill top 2 words */ + s_bmul_2x2(zm, a1, a2^a0, b1, b2^b0); /* fill middle 4 words */ + s_bmul_2x2(r, a1, a0, b1, b0); /* fill bottom 4 words */ + + zm[3] ^= r[3]; + zm[2] ^= r[2]; + zm[1] ^= r[1] ^ r[5]; + zm[0] ^= r[0] ^ r[4]; + + r[5] ^= zm[3]; + r[4] ^= zm[2]; + r[3] ^= zm[1]; + r[2] ^= zm[0]; +} + +/* Compute xor-multiply of two binary polynomials (a3, a2, a1, a0) x (b3, b2, b1, b0) + * result is a binary polynomial in 8 mp_digits r[8]. + * The caller MUST ensure that r has the right amount of space allocated. + */ +void s_bmul_4x4(mp_digit *r, const mp_digit a3, const mp_digit a2, const mp_digit a1, + const mp_digit a0, const mp_digit b3, const mp_digit b2, const mp_digit b1, + const mp_digit b0) +{ + mp_digit zm[4]; + + s_bmul_2x2(r+4, a3, a2, b3, b2); /* fill top 4 words */ + s_bmul_2x2(zm, a3^a1, a2^a0, b3^b1, b2^b0); /* fill middle 4 words */ + s_bmul_2x2(r, a1, a0, b1, b0); /* fill bottom 4 words */ + + zm[3] ^= r[3] ^ r[7]; + zm[2] ^= r[2] ^ r[6]; + zm[1] ^= r[1] ^ r[5]; + zm[0] ^= r[0] ^ r[4]; + + r[5] ^= zm[3]; + r[4] ^= zm[2]; + r[3] ^= zm[1]; + r[2] ^= zm[0]; +} + +/* Compute addition of two binary polynomials a and b, + * store result in c; c could be a or b, a and b could be equal; + * c is the bitwise XOR of a and b. + */ +mp_err +mp_badd(const mp_int *a, const mp_int *b, mp_int *c) +{ + mp_digit *pa, *pb, *pc; + mp_size ix; + mp_size used_pa, used_pb; + mp_err res = MP_OKAY; + + /* Add all digits up to the precision of b. If b had more + * precision than a initially, swap a, b first + */ + if (MP_USED(a) >= MP_USED(b)) { + pa = MP_DIGITS(a); + pb = MP_DIGITS(b); + used_pa = MP_USED(a); + used_pb = MP_USED(b); + } else { + pa = MP_DIGITS(b); + pb = MP_DIGITS(a); + used_pa = MP_USED(b); + used_pb = MP_USED(a); + } + + /* Make sure c has enough precision for the output value */ + MP_CHECKOK( s_mp_pad(c, used_pa) ); + + /* Do word-by-word xor */ + pc = MP_DIGITS(c); + for (ix = 0; ix < used_pb; ix++) { + (*pc++) = (*pa++) ^ (*pb++); + } + + /* Finish the rest of digits until we're actually done */ + for (; ix < used_pa; ++ix) { + *pc++ = *pa++; + } + + MP_USED(c) = used_pa; + MP_SIGN(c) = ZPOS; + s_mp_clamp(c); + +CLEANUP: + return res; +} + +#define s_mp_div2(a) MP_CHECKOK( mpl_rsh((a), (a), 1) ); + +/* Compute binary polynomial multiply d = a * b */ +static void +s_bmul_d(const mp_digit *a, mp_size a_len, mp_digit b, mp_digit *d) +{ + mp_digit a_i, a0b0, a1b1, carry = 0; + while (a_len--) { + a_i = *a++; + s_bmul_1x1(&a1b1, &a0b0, a_i, b); + *d++ = a0b0 ^ carry; + carry = a1b1; + } + *d = carry; +} + +/* Compute binary polynomial xor multiply accumulate d ^= a * b */ +static void +s_bmul_d_add(const mp_digit *a, mp_size a_len, mp_digit b, mp_digit *d) +{ + mp_digit a_i, a0b0, a1b1, carry = 0; + while (a_len--) { + a_i = *a++; + s_bmul_1x1(&a1b1, &a0b0, a_i, b); + *d++ ^= a0b0 ^ carry; + carry = a1b1; + } + *d ^= carry; +} + +/* Compute binary polynomial xor multiply c = a * b. + * All parameters may be identical. + */ +mp_err +mp_bmul(const mp_int *a, const mp_int *b, mp_int *c) +{ + mp_digit *pb, b_i; + mp_int tmp; + mp_size ib, a_used, b_used; + mp_err res = MP_OKAY; + + MP_DIGITS(&tmp) = 0; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if (a == c) { + MP_CHECKOK( mp_init_copy(&tmp, a) ); + if (a == b) + b = &tmp; + a = &tmp; + } else if (b == c) { + MP_CHECKOK( mp_init_copy(&tmp, b) ); + b = &tmp; + } + + if (MP_USED(a) < MP_USED(b)) { + const mp_int *xch = b; /* switch a and b if b longer */ + b = a; + a = xch; + } + + MP_USED(c) = 1; MP_DIGIT(c, 0) = 0; + MP_CHECKOK( s_mp_pad(c, USED(a) + USED(b)) ); + + pb = MP_DIGITS(b); + s_bmul_d(MP_DIGITS(a), MP_USED(a), *pb++, MP_DIGITS(c)); + + /* Outer loop: Digits of b */ + a_used = MP_USED(a); + b_used = MP_USED(b); + MP_USED(c) = a_used + b_used; + for (ib = 1; ib < b_used; ib++) { + b_i = *pb++; + + /* Inner product: Digits of a */ + if (b_i) + s_bmul_d_add(MP_DIGITS(a), a_used, b_i, MP_DIGITS(c) + ib); + else + MP_DIGIT(c, ib + a_used) = b_i; + } + + s_mp_clamp(c); + + SIGN(c) = ZPOS; + +CLEANUP: + mp_clear(&tmp); + return res; +} + + +/* Compute modular reduction of a and store result in r. + * r could be a. + * For modular arithmetic, the irreducible polynomial f(t) is represented + * as an array of int[], where f(t) is of the form: + * f(t) = t^p[0] + t^p[1] + ... + t^p[k] + * where m = p[0] > p[1] > ... > p[k] = 0. + */ +mp_err +mp_bmod(const mp_int *a, const unsigned int p[], mp_int *r) +{ + int j, k; + int n, dN, d0, d1; + mp_digit zz, *z, tmp; + mp_size used; + mp_err res = MP_OKAY; + + /* The algorithm does the reduction in place in r, + * if a != r, copy a into r first so reduction can be done in r + */ + if (a != r) { + MP_CHECKOK( mp_copy(a, r) ); + } + z = MP_DIGITS(r); + + /* start reduction */ + dN = p[0] / MP_DIGIT_BITS; + used = MP_USED(r); + + for (j = used - 1; j > dN;) { + + zz = z[j]; + if (zz == 0) { + j--; continue; + } + z[j] = 0; + + for (k = 1; p[k] > 0; k++) { + /* reducing component t^p[k] */ + n = p[0] - p[k]; + d0 = n % MP_DIGIT_BITS; + d1 = MP_DIGIT_BITS - d0; + n /= MP_DIGIT_BITS; + z[j-n] ^= (zz>>d0); + if (d0) + z[j-n-1] ^= (zz<> d0); + if (d0) + z[j-n-1] ^= (zz << d1); + + } + + /* final round of reduction */ + while (j == dN) { + + d0 = p[0] % MP_DIGIT_BITS; + zz = z[dN] >> d0; + if (zz == 0) break; + d1 = MP_DIGIT_BITS - d0; + + /* clear up the top d1 bits */ + if (d0) z[dN] = (z[dN] << d1) >> d1; + *z ^= zz; /* reduction t^0 component */ + + for (k = 1; p[k] > 0; k++) { + /* reducing component t^p[k]*/ + n = p[k] / MP_DIGIT_BITS; + d0 = p[k] % MP_DIGIT_BITS; + d1 = MP_DIGIT_BITS - d0; + z[n] ^= (zz << d0); + tmp = zz >> d1; + if (d0 && tmp) + z[n+1] ^= tmp; + } + } + + s_mp_clamp(r); +CLEANUP: + return res; +} + +/* Compute the product of two polynomials a and b, reduce modulo p, + * Store the result in r. r could be a or b; a could be b. + */ +mp_err +mp_bmulmod(const mp_int *a, const mp_int *b, const unsigned int p[], mp_int *r) +{ + mp_err res; + + if (a == b) return mp_bsqrmod(a, p, r); + if ((res = mp_bmul(a, b, r) ) != MP_OKAY) + return res; + return mp_bmod(r, p, r); +} + +/* Compute binary polynomial squaring c = a*a mod p . + * Parameter r and a can be identical. + */ + +mp_err +mp_bsqrmod(const mp_int *a, const unsigned int p[], mp_int *r) +{ + mp_digit *pa, *pr, a_i; + mp_int tmp; + mp_size ia, a_used; + mp_err res; + + ARGCHK(a != NULL && r != NULL, MP_BADARG); + MP_DIGITS(&tmp) = 0; + + if (a == r) { + MP_CHECKOK( mp_init_copy(&tmp, a) ); + a = &tmp; + } + + MP_USED(r) = 1; MP_DIGIT(r, 0) = 0; + MP_CHECKOK( s_mp_pad(r, 2*USED(a)) ); + + pa = MP_DIGITS(a); + pr = MP_DIGITS(r); + a_used = MP_USED(a); + MP_USED(r) = 2 * a_used; + + for (ia = 0; ia < a_used; ia++) { + a_i = *pa++; + *pr++ = gf2m_SQR0(a_i); + *pr++ = gf2m_SQR1(a_i); + } + + MP_CHECKOK( mp_bmod(r, p, r) ); + s_mp_clamp(r); + SIGN(r) = ZPOS; + +CLEANUP: + mp_clear(&tmp); + return res; +} + +/* Compute binary polynomial y/x mod p, y divided by x, reduce modulo p. + * Store the result in r. r could be x or y, and x could equal y. + * Uses algorithm Modular_Division_GF(2^m) from + * Chang-Shantz, S. "From Euclid's GCD to Montgomery Multiplication to + * the Great Divide". + */ +int +mp_bdivmod(const mp_int *y, const mp_int *x, const mp_int *pp, + const unsigned int p[], mp_int *r) +{ + mp_int aa, bb, uu; + mp_int *a, *b, *u, *v; + mp_err res = MP_OKAY; + + MP_DIGITS(&aa) = 0; + MP_DIGITS(&bb) = 0; + MP_DIGITS(&uu) = 0; + + MP_CHECKOK( mp_init_copy(&aa, x) ); + MP_CHECKOK( mp_init_copy(&uu, y) ); + MP_CHECKOK( mp_init_copy(&bb, pp) ); + MP_CHECKOK( s_mp_pad(r, USED(pp)) ); + MP_USED(r) = 1; MP_DIGIT(r, 0) = 0; + + a = &aa; b= &bb; u=&uu; v=r; + /* reduce x and y mod p */ + MP_CHECKOK( mp_bmod(a, p, a) ); + MP_CHECKOK( mp_bmod(u, p, u) ); + + while (!mp_isodd(a)) { + s_mp_div2(a); + if (mp_isodd(u)) { + MP_CHECKOK( mp_badd(u, pp, u) ); + } + s_mp_div2(u); + } + + do { + if (mp_cmp_mag(b, a) > 0) { + MP_CHECKOK( mp_badd(b, a, b) ); + MP_CHECKOK( mp_badd(v, u, v) ); + do { + s_mp_div2(b); + if (mp_isodd(v)) { + MP_CHECKOK( mp_badd(v, pp, v) ); + } + s_mp_div2(v); + } while (!mp_isodd(b)); + } + else if ((MP_DIGIT(a,0) == 1) && (MP_USED(a) == 1)) + break; + else { + MP_CHECKOK( mp_badd(a, b, a) ); + MP_CHECKOK( mp_badd(u, v, u) ); + do { + s_mp_div2(a); + if (mp_isodd(u)) { + MP_CHECKOK( mp_badd(u, pp, u) ); + } + s_mp_div2(u); + } while (!mp_isodd(a)); + } + } while (1); + + MP_CHECKOK( mp_copy(u, r) ); + +CLEANUP: + /* XXX this appears to be a memory leak in the NSS code */ + mp_clear(&aa); + mp_clear(&bb); + mp_clear(&uu); + return res; + +} + +/* Convert the bit-string representation of a polynomial a into an array + * of integers corresponding to the bits with non-zero coefficient. + * Up to max elements of the array will be filled. Return value is total + * number of coefficients that would be extracted if array was large enough. + */ +int +mp_bpoly2arr(const mp_int *a, unsigned int p[], int max) +{ + int i, j, k; + mp_digit top_bit, mask; + + top_bit = 1; + top_bit <<= MP_DIGIT_BIT - 1; + + for (k = 0; k < max; k++) p[k] = 0; + k = 0; + + for (i = MP_USED(a) - 1; i >= 0; i--) { + mask = top_bit; + for (j = MP_DIGIT_BIT - 1; j >= 0; j--) { + if (MP_DIGITS(a)[i] & mask) { + if (k < max) p[k] = MP_DIGIT_BIT * i + j; + k++; + } + mask >>= 1; + } + } + + return k; +} + +/* Convert the coefficient array representation of a polynomial to a + * bit-string. The array must be terminated by 0. + */ +mp_err +mp_barr2poly(const unsigned int p[], mp_int *a) +{ + + mp_err res = MP_OKAY; + int i; + + mp_zero(a); + for (i = 0; p[i] > 0; i++) { + MP_CHECKOK( mpl_set_bit(a, p[i], 1) ); + } + MP_CHECKOK( mpl_set_bit(a, 0, 1) ); + +CLEANUP: + return res; +} diff --git a/src/share/native/sun/security/ec/impl/mp_gf2m.h b/src/share/native/sun/security/ec/impl/mp_gf2m.h new file mode 100644 index 0000000000000000000000000000000000000000..b09f3d343771eecc179ad89faa68317842243ff3 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mp_gf2m.h @@ -0,0 +1,83 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Multi-precision Binary Polynomial Arithmetic Library. + * + * The Initial Developer of the Original Code is + * Sun Microsystems, Inc. + * Portions created by the Initial Developer are Copyright (C) 2003 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang Shantz and + * Douglas Stebila of Sun Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MP_GF2M_H_ +#define _MP_GF2M_H_ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mpi.h" + +mp_err mp_badd(const mp_int *a, const mp_int *b, mp_int *c); +mp_err mp_bmul(const mp_int *a, const mp_int *b, mp_int *c); + +/* For modular arithmetic, the irreducible polynomial f(t) is represented + * as an array of int[], where f(t) is of the form: + * f(t) = t^p[0] + t^p[1] + ... + t^p[k] + * where m = p[0] > p[1] > ... > p[k] = 0. + */ +mp_err mp_bmod(const mp_int *a, const unsigned int p[], mp_int *r); +mp_err mp_bmulmod(const mp_int *a, const mp_int *b, const unsigned int p[], + mp_int *r); +mp_err mp_bsqrmod(const mp_int *a, const unsigned int p[], mp_int *r); +mp_err mp_bdivmod(const mp_int *y, const mp_int *x, const mp_int *pp, + const unsigned int p[], mp_int *r); + +int mp_bpoly2arr(const mp_int *a, unsigned int p[], int max); +mp_err mp_barr2poly(const unsigned int p[], mp_int *a); + +#endif /* _MP_GF2M_H_ */ diff --git a/src/share/native/sun/security/ec/impl/mpi-config.h b/src/share/native/sun/security/ec/impl/mpi-config.h new file mode 100644 index 0000000000000000000000000000000000000000..3618677a90aab2b77b40f1d62effd00cd781587d --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mpi-config.h @@ -0,0 +1,130 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1997 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Netscape Communications Corporation + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MPI_CONFIG_H +#define _MPI_CONFIG_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mpi-config.h,v 1.5 2004/04/25 15:03:10 gerv%gerv.net Exp $ */ + +/* + For boolean options, + 0 = no + 1 = yes + + Other options are documented individually. + + */ + +#ifndef MP_IOFUNC +#define MP_IOFUNC 0 /* include mp_print() ? */ +#endif + +#ifndef MP_MODARITH +#define MP_MODARITH 1 /* include modular arithmetic ? */ +#endif + +#ifndef MP_NUMTH +#define MP_NUMTH 1 /* include number theoretic functions? */ +#endif + +#ifndef MP_LOGTAB +#define MP_LOGTAB 1 /* use table of logs instead of log()? */ +#endif + +#ifndef MP_MEMSET +#define MP_MEMSET 1 /* use memset() to zero buffers? */ +#endif + +#ifndef MP_MEMCPY +#define MP_MEMCPY 1 /* use memcpy() to copy buffers? */ +#endif + +#ifndef MP_CRYPTO +#define MP_CRYPTO 1 /* erase memory on free? */ +#endif + +#ifndef MP_ARGCHK +/* + 0 = no parameter checks + 1 = runtime checks, continue execution and return an error to caller + 2 = assertions; dump core on parameter errors + */ +#ifdef DEBUG +#define MP_ARGCHK 2 /* how to check input arguments */ +#else +#define MP_ARGCHK 1 /* how to check input arguments */ +#endif +#endif + +#ifndef MP_DEBUG +#define MP_DEBUG 0 /* print diagnostic output? */ +#endif + +#ifndef MP_DEFPREC +#define MP_DEFPREC 64 /* default precision, in digits */ +#endif + +#ifndef MP_MACRO +#define MP_MACRO 0 /* use macros for frequent calls? */ +#endif + +#ifndef MP_SQUARE +#define MP_SQUARE 1 /* use separate squaring code? */ +#endif + +#endif /* _MPI_CONFIG_H */ diff --git a/src/share/native/sun/security/ec/impl/mpi-priv.h b/src/share/native/sun/security/ec/impl/mpi-priv.h new file mode 100644 index 0000000000000000000000000000000000000000..b2b07ec32108a7f8078adbb8db613d81089e4cb7 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mpi-priv.h @@ -0,0 +1,340 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Arbitrary precision integer arithmetic library + * + * NOTE WELL: the content of this header file is NOT part of the "public" + * API for the MPI library, and may change at any time. + * Application programs that use libmpi should NOT include this header file. + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Netscape Communications Corporation + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MPI_PRIV_H +#define _MPI_PRIV_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mpi-priv.h,v 1.20 2005/11/22 07:16:43 relyea%netscape.com Exp $ */ + +#include "mpi.h" +#ifndef _KERNEL +#include +#include +#include +#endif /* _KERNEL */ + +#if MP_DEBUG +#include + +#define DIAG(T,V) {fprintf(stderr,T);mp_print(V,stderr);fputc('\n',stderr);} +#else +#define DIAG(T,V) +#endif + +/* If we aren't using a wired-in logarithm table, we need to include + the math library to get the log() function + */ + +/* {{{ s_logv_2[] - log table for 2 in various bases */ + +#if MP_LOGTAB +/* + A table of the logs of 2 for various bases (the 0 and 1 entries of + this table are meaningless and should not be referenced). + + This table is used to compute output lengths for the mp_toradix() + function. Since a number n in radix r takes up about log_r(n) + digits, we estimate the output size by taking the least integer + greater than log_r(n), where: + + log_r(n) = log_2(n) * log_r(2) + + This table, therefore, is a table of log_r(2) for 2 <= r <= 36, + which are the output bases supported. + */ + +extern const float s_logv_2[]; +#define LOG_V_2(R) s_logv_2[(R)] + +#else + +/* + If MP_LOGTAB is not defined, use the math library to compute the + logarithms on the fly. Otherwise, use the table. + Pick which works best for your system. + */ + +#include +#define LOG_V_2(R) (log(2.0)/log(R)) + +#endif /* if MP_LOGTAB */ + +/* }}} */ + +/* {{{ Digit arithmetic macros */ + +/* + When adding and multiplying digits, the results can be larger than + can be contained in an mp_digit. Thus, an mp_word is used. These + macros mask off the upper and lower digits of the mp_word (the + mp_word may be more than 2 mp_digits wide, but we only concern + ourselves with the low-order 2 mp_digits) + */ + +#define CARRYOUT(W) (mp_digit)((W)>>DIGIT_BIT) +#define ACCUM(W) (mp_digit)(W) + +#define MP_MIN(a,b) (((a) < (b)) ? (a) : (b)) +#define MP_MAX(a,b) (((a) > (b)) ? (a) : (b)) +#define MP_HOWMANY(a,b) (((a) + (b) - 1)/(b)) +#define MP_ROUNDUP(a,b) (MP_HOWMANY(a,b) * (b)) + +/* }}} */ + +/* {{{ Comparison constants */ + +#define MP_LT -1 +#define MP_EQ 0 +#define MP_GT 1 + +/* }}} */ + +/* {{{ private function declarations */ + +/* + If MP_MACRO is false, these will be defined as actual functions; + otherwise, suitable macro definitions will be used. This works + around the fact that ANSI C89 doesn't support an 'inline' keyword + (although I hear C9x will ... about bloody time). At present, the + macro definitions are identical to the function bodies, but they'll + expand in place, instead of generating a function call. + + I chose these particular functions to be made into macros because + some profiling showed they are called a lot on a typical workload, + and yet they are primarily housekeeping. + */ +#if MP_MACRO == 0 + void s_mp_setz(mp_digit *dp, mp_size count); /* zero digits */ + void s_mp_copy(const mp_digit *sp, mp_digit *dp, mp_size count); /* copy */ + void *s_mp_alloc(size_t nb, size_t ni, int flag); /* general allocator */ + void s_mp_free(void *ptr, mp_size); /* general free function */ +extern unsigned long mp_allocs; +extern unsigned long mp_frees; +extern unsigned long mp_copies; +#else + + /* Even if these are defined as macros, we need to respect the settings + of the MP_MEMSET and MP_MEMCPY configuration options... + */ + #if MP_MEMSET == 0 + #define s_mp_setz(dp, count) \ + {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=0;} + #else + #define s_mp_setz(dp, count) memset(dp, 0, (count) * sizeof(mp_digit)) + #endif /* MP_MEMSET */ + + #if MP_MEMCPY == 0 + #define s_mp_copy(sp, dp, count) \ + {int ix;for(ix=0;ix<(count);ix++)(dp)[ix]=(sp)[ix];} + #else + #define s_mp_copy(sp, dp, count) memcpy(dp, sp, (count) * sizeof(mp_digit)) + #endif /* MP_MEMCPY */ + + #define s_mp_alloc(nb, ni) calloc(nb, ni) + #define s_mp_free(ptr) {if(ptr) free(ptr);} +#endif /* MP_MACRO */ + +mp_err s_mp_grow(mp_int *mp, mp_size min); /* increase allocated size */ +mp_err s_mp_pad(mp_int *mp, mp_size min); /* left pad with zeroes */ + +#if MP_MACRO == 0 + void s_mp_clamp(mp_int *mp); /* clip leading zeroes */ +#else + #define s_mp_clamp(mp)\ + { mp_size used = MP_USED(mp); \ + while (used > 1 && DIGIT(mp, used - 1) == 0) --used; \ + MP_USED(mp) = used; \ + } +#endif /* MP_MACRO */ + +void s_mp_exch(mp_int *a, mp_int *b); /* swap a and b in place */ + +mp_err s_mp_lshd(mp_int *mp, mp_size p); /* left-shift by p digits */ +void s_mp_rshd(mp_int *mp, mp_size p); /* right-shift by p digits */ +mp_err s_mp_mul_2d(mp_int *mp, mp_digit d); /* multiply by 2^d in place */ +void s_mp_div_2d(mp_int *mp, mp_digit d); /* divide by 2^d in place */ +void s_mp_mod_2d(mp_int *mp, mp_digit d); /* modulo 2^d in place */ +void s_mp_div_2(mp_int *mp); /* divide by 2 in place */ +mp_err s_mp_mul_2(mp_int *mp); /* multiply by 2 in place */ +mp_err s_mp_norm(mp_int *a, mp_int *b, mp_digit *pd); + /* normalize for division */ +mp_err s_mp_add_d(mp_int *mp, mp_digit d); /* unsigned digit addition */ +mp_err s_mp_sub_d(mp_int *mp, mp_digit d); /* unsigned digit subtract */ +mp_err s_mp_mul_d(mp_int *mp, mp_digit d); /* unsigned digit multiply */ +mp_err s_mp_div_d(mp_int *mp, mp_digit d, mp_digit *r); + /* unsigned digit divide */ +mp_err s_mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu); + /* Barrett reduction */ +mp_err s_mp_add(mp_int *a, const mp_int *b); /* magnitude addition */ +mp_err s_mp_add_3arg(const mp_int *a, const mp_int *b, mp_int *c); +mp_err s_mp_sub(mp_int *a, const mp_int *b); /* magnitude subtract */ +mp_err s_mp_sub_3arg(const mp_int *a, const mp_int *b, mp_int *c); +mp_err s_mp_add_offset(mp_int *a, mp_int *b, mp_size offset); + /* a += b * RADIX^offset */ +mp_err s_mp_mul(mp_int *a, const mp_int *b); /* magnitude multiply */ +#if MP_SQUARE +mp_err s_mp_sqr(mp_int *a); /* magnitude square */ +#else +#define s_mp_sqr(a) s_mp_mul(a, a) +#endif +mp_err s_mp_div(mp_int *rem, mp_int *div, mp_int *quot); /* magnitude div */ +mp_err s_mp_exptmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c); +mp_err s_mp_2expt(mp_int *a, mp_digit k); /* a = 2^k */ +int s_mp_cmp(const mp_int *a, const mp_int *b); /* magnitude comparison */ +int s_mp_cmp_d(const mp_int *a, mp_digit d); /* magnitude digit compare */ +int s_mp_ispow2(const mp_int *v); /* is v a power of 2? */ +int s_mp_ispow2d(mp_digit d); /* is d a power of 2? */ + +int s_mp_tovalue(char ch, int r); /* convert ch to value */ +char s_mp_todigit(mp_digit val, int r, int low); /* convert val to digit */ +int s_mp_outlen(int bits, int r); /* output length in bytes */ +mp_digit s_mp_invmod_radix(mp_digit P); /* returns (P ** -1) mod RADIX */ +mp_err s_mp_invmod_odd_m( const mp_int *a, const mp_int *m, mp_int *c); +mp_err s_mp_invmod_2d( const mp_int *a, mp_size k, mp_int *c); +mp_err s_mp_invmod_even_m(const mp_int *a, const mp_int *m, mp_int *c); + +#ifdef NSS_USE_COMBA + +#define IS_POWER_OF_2(a) ((a) && !((a) & ((a)-1))) + +void s_mp_mul_comba_4(const mp_int *A, const mp_int *B, mp_int *C); +void s_mp_mul_comba_8(const mp_int *A, const mp_int *B, mp_int *C); +void s_mp_mul_comba_16(const mp_int *A, const mp_int *B, mp_int *C); +void s_mp_mul_comba_32(const mp_int *A, const mp_int *B, mp_int *C); + +void s_mp_sqr_comba_4(const mp_int *A, mp_int *B); +void s_mp_sqr_comba_8(const mp_int *A, mp_int *B); +void s_mp_sqr_comba_16(const mp_int *A, mp_int *B); +void s_mp_sqr_comba_32(const mp_int *A, mp_int *B); + +#endif /* end NSS_USE_COMBA */ + +/* ------ mpv functions, operate on arrays of digits, not on mp_int's ------ */ +#if defined (__OS2__) && defined (__IBMC__) +#define MPI_ASM_DECL __cdecl +#else +#define MPI_ASM_DECL +#endif + +#ifdef MPI_AMD64 + +mp_digit MPI_ASM_DECL s_mpv_mul_set_vec64(mp_digit*, mp_digit *, mp_size, mp_digit); +mp_digit MPI_ASM_DECL s_mpv_mul_add_vec64(mp_digit*, const mp_digit*, mp_size, mp_digit); + +/* c = a * b */ +#define s_mpv_mul_d(a, a_len, b, c) \ + ((unsigned long*)c)[a_len] = s_mpv_mul_set_vec64(c, a, a_len, b) + +/* c += a * b */ +#define s_mpv_mul_d_add(a, a_len, b, c) \ + ((unsigned long*)c)[a_len] = s_mpv_mul_add_vec64(c, a, a_len, b) + +#else + +void MPI_ASM_DECL s_mpv_mul_d(const mp_digit *a, mp_size a_len, + mp_digit b, mp_digit *c); +void MPI_ASM_DECL s_mpv_mul_d_add(const mp_digit *a, mp_size a_len, + mp_digit b, mp_digit *c); + +#endif + +void MPI_ASM_DECL s_mpv_mul_d_add_prop(const mp_digit *a, + mp_size a_len, mp_digit b, + mp_digit *c); +void MPI_ASM_DECL s_mpv_sqr_add_prop(const mp_digit *a, + mp_size a_len, + mp_digit *sqrs); + +mp_err MPI_ASM_DECL s_mpv_div_2dx1d(mp_digit Nhi, mp_digit Nlo, + mp_digit divisor, mp_digit *quot, mp_digit *rem); + +/* c += a * b * (MP_RADIX ** offset); */ +#define s_mp_mul_d_add_offset(a, b, c, off) \ +(s_mpv_mul_d_add_prop(MP_DIGITS(a), MP_USED(a), b, MP_DIGITS(c) + off), MP_OKAY) + +typedef struct { + mp_int N; /* modulus N */ + mp_digit n0prime; /* n0' = - (n0 ** -1) mod MP_RADIX */ + mp_size b; /* R == 2 ** b, also b = # significant bits in N */ +} mp_mont_modulus; + +mp_err s_mp_mul_mont(const mp_int *a, const mp_int *b, mp_int *c, + mp_mont_modulus *mmm); +mp_err s_mp_redc(mp_int *T, mp_mont_modulus *mmm); + +/* + * s_mpi_getProcessorLineSize() returns the size in bytes of the cache line + * if a cache exists, or zero if there is no cache. If more than one + * cache line exists, it should return the smallest line size (which is + * usually the L1 cache). + * + * mp_modexp uses this information to make sure that private key information + * isn't being leaked through the cache. + * + * see mpcpucache.c for the implementation. + */ +unsigned long s_mpi_getProcessorLineSize(); + +/* }}} */ +#endif /* _MPI_PRIV_H */ diff --git a/src/share/native/sun/security/ec/impl/mpi.c b/src/share/native/sun/security/ec/impl/mpi.c new file mode 100644 index 0000000000000000000000000000000000000000..9f771882b015040c6c571fd7676ea4902c300c94 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mpi.c @@ -0,0 +1,4886 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * + * Arbitrary precision integer arithmetic library + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Netscape Communications Corporation + * Douglas Stebila of Sun Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mpi.c,v 1.45 2006/09/29 20:12:21 alexei.volkov.bugs%sun.com Exp $ */ + +#include "mpi-priv.h" +#if defined(OSF1) +#include +#endif + +#if MP_LOGTAB +/* + A table of the logs of 2 for various bases (the 0 and 1 entries of + this table are meaningless and should not be referenced). + + This table is used to compute output lengths for the mp_toradix() + function. Since a number n in radix r takes up about log_r(n) + digits, we estimate the output size by taking the least integer + greater than log_r(n), where: + + log_r(n) = log_2(n) * log_r(2) + + This table, therefore, is a table of log_r(2) for 2 <= r <= 36, + which are the output bases supported. + */ +#include "logtab.h" +#endif + +/* {{{ Constant strings */ + +/* Constant strings returned by mp_strerror() */ +static const char *mp_err_string[] = { + "unknown result code", /* say what? */ + "boolean true", /* MP_OKAY, MP_YES */ + "boolean false", /* MP_NO */ + "out of memory", /* MP_MEM */ + "argument out of range", /* MP_RANGE */ + "invalid input parameter", /* MP_BADARG */ + "result is undefined" /* MP_UNDEF */ +}; + +/* Value to digit maps for radix conversion */ + +/* s_dmap_1 - standard digits and letters */ +static const char *s_dmap_1 = + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz+/"; + +/* }}} */ + +unsigned long mp_allocs; +unsigned long mp_frees; +unsigned long mp_copies; + +/* {{{ Default precision manipulation */ + +/* Default precision for newly created mp_int's */ +static mp_size s_mp_defprec = MP_DEFPREC; + +mp_size mp_get_prec(void) +{ + return s_mp_defprec; + +} /* end mp_get_prec() */ + +void mp_set_prec(mp_size prec) +{ + if(prec == 0) + s_mp_defprec = MP_DEFPREC; + else + s_mp_defprec = prec; + +} /* end mp_set_prec() */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ mp_init(mp, kmflag) */ + +/* + mp_init(mp, kmflag) + + Initialize a new zero-valued mp_int. Returns MP_OKAY if successful, + MP_MEM if memory could not be allocated for the structure. + */ + +mp_err mp_init(mp_int *mp, int kmflag) +{ + return mp_init_size(mp, s_mp_defprec, kmflag); + +} /* end mp_init() */ + +/* }}} */ + +/* {{{ mp_init_size(mp, prec, kmflag) */ + +/* + mp_init_size(mp, prec, kmflag) + + Initialize a new zero-valued mp_int with at least the given + precision; returns MP_OKAY if successful, or MP_MEM if memory could + not be allocated for the structure. + */ + +mp_err mp_init_size(mp_int *mp, mp_size prec, int kmflag) +{ + ARGCHK(mp != NULL && prec > 0, MP_BADARG); + + prec = MP_ROUNDUP(prec, s_mp_defprec); + if((DIGITS(mp) = s_mp_alloc(prec, sizeof(mp_digit), kmflag)) == NULL) + return MP_MEM; + + SIGN(mp) = ZPOS; + USED(mp) = 1; + ALLOC(mp) = prec; + + return MP_OKAY; + +} /* end mp_init_size() */ + +/* }}} */ + +/* {{{ mp_init_copy(mp, from) */ + +/* + mp_init_copy(mp, from) + + Initialize mp as an exact copy of from. Returns MP_OKAY if + successful, MP_MEM if memory could not be allocated for the new + structure. + */ + +mp_err mp_init_copy(mp_int *mp, const mp_int *from) +{ + ARGCHK(mp != NULL && from != NULL, MP_BADARG); + + if(mp == from) + return MP_OKAY; + + if((DIGITS(mp) = s_mp_alloc(ALLOC(from), sizeof(mp_digit), FLAG(from))) == NULL) + return MP_MEM; + + s_mp_copy(DIGITS(from), DIGITS(mp), USED(from)); + USED(mp) = USED(from); + ALLOC(mp) = ALLOC(from); + SIGN(mp) = SIGN(from); + +#ifndef _WIN32 + FLAG(mp) = FLAG(from); +#endif /* _WIN32 */ + + return MP_OKAY; + +} /* end mp_init_copy() */ + +/* }}} */ + +/* {{{ mp_copy(from, to) */ + +/* + mp_copy(from, to) + + Copies the mp_int 'from' to the mp_int 'to'. It is presumed that + 'to' has already been initialized (if not, use mp_init_copy() + instead). If 'from' and 'to' are identical, nothing happens. + */ + +mp_err mp_copy(const mp_int *from, mp_int *to) +{ + ARGCHK(from != NULL && to != NULL, MP_BADARG); + + if(from == to) + return MP_OKAY; + + ++mp_copies; + { /* copy */ + mp_digit *tmp; + + /* + If the allocated buffer in 'to' already has enough space to hold + all the used digits of 'from', we'll re-use it to avoid hitting + the memory allocater more than necessary; otherwise, we'd have + to grow anyway, so we just allocate a hunk and make the copy as + usual + */ + if(ALLOC(to) >= USED(from)) { + s_mp_setz(DIGITS(to) + USED(from), ALLOC(to) - USED(from)); + s_mp_copy(DIGITS(from), DIGITS(to), USED(from)); + + } else { + if((tmp = s_mp_alloc(ALLOC(from), sizeof(mp_digit), FLAG(from))) == NULL) + return MP_MEM; + + s_mp_copy(DIGITS(from), tmp, USED(from)); + + if(DIGITS(to) != NULL) { +#if MP_CRYPTO + s_mp_setz(DIGITS(to), ALLOC(to)); +#endif + s_mp_free(DIGITS(to), ALLOC(to)); + } + + DIGITS(to) = tmp; + ALLOC(to) = ALLOC(from); + } + + /* Copy the precision and sign from the original */ + USED(to) = USED(from); + SIGN(to) = SIGN(from); + } /* end copy */ + + return MP_OKAY; + +} /* end mp_copy() */ + +/* }}} */ + +/* {{{ mp_exch(mp1, mp2) */ + +/* + mp_exch(mp1, mp2) + + Exchange mp1 and mp2 without allocating any intermediate memory + (well, unless you count the stack space needed for this call and the + locals it creates...). This cannot fail. + */ + +void mp_exch(mp_int *mp1, mp_int *mp2) +{ +#if MP_ARGCHK == 2 + assert(mp1 != NULL && mp2 != NULL); +#else + if(mp1 == NULL || mp2 == NULL) + return; +#endif + + s_mp_exch(mp1, mp2); + +} /* end mp_exch() */ + +/* }}} */ + +/* {{{ mp_clear(mp) */ + +/* + mp_clear(mp) + + Release the storage used by an mp_int, and void its fields so that + if someone calls mp_clear() again for the same int later, we won't + get tollchocked. + */ + +void mp_clear(mp_int *mp) +{ + if(mp == NULL) + return; + + if(DIGITS(mp) != NULL) { +#if MP_CRYPTO + s_mp_setz(DIGITS(mp), ALLOC(mp)); +#endif + s_mp_free(DIGITS(mp), ALLOC(mp)); + DIGITS(mp) = NULL; + } + + USED(mp) = 0; + ALLOC(mp) = 0; + +} /* end mp_clear() */ + +/* }}} */ + +/* {{{ mp_zero(mp) */ + +/* + mp_zero(mp) + + Set mp to zero. Does not change the allocated size of the structure, + and therefore cannot fail (except on a bad argument, which we ignore) + */ +void mp_zero(mp_int *mp) +{ + if(mp == NULL) + return; + + s_mp_setz(DIGITS(mp), ALLOC(mp)); + USED(mp) = 1; + SIGN(mp) = ZPOS; + +} /* end mp_zero() */ + +/* }}} */ + +/* {{{ mp_set(mp, d) */ + +void mp_set(mp_int *mp, mp_digit d) +{ + if(mp == NULL) + return; + + mp_zero(mp); + DIGIT(mp, 0) = d; + +} /* end mp_set() */ + +/* }}} */ + +/* {{{ mp_set_int(mp, z) */ + +mp_err mp_set_int(mp_int *mp, long z) +{ + int ix; + unsigned long v = labs(z); + mp_err res; + + ARGCHK(mp != NULL, MP_BADARG); + + mp_zero(mp); + if(z == 0) + return MP_OKAY; /* shortcut for zero */ + + if (sizeof v <= sizeof(mp_digit)) { + DIGIT(mp,0) = v; + } else { + for (ix = sizeof(long) - 1; ix >= 0; ix--) { + if ((res = s_mp_mul_d(mp, (UCHAR_MAX + 1))) != MP_OKAY) + return res; + + res = s_mp_add_d(mp, (mp_digit)((v >> (ix * CHAR_BIT)) & UCHAR_MAX)); + if (res != MP_OKAY) + return res; + } + } + if(z < 0) + SIGN(mp) = NEG; + + return MP_OKAY; + +} /* end mp_set_int() */ + +/* }}} */ + +/* {{{ mp_set_ulong(mp, z) */ + +mp_err mp_set_ulong(mp_int *mp, unsigned long z) +{ + int ix; + mp_err res; + + ARGCHK(mp != NULL, MP_BADARG); + + mp_zero(mp); + if(z == 0) + return MP_OKAY; /* shortcut for zero */ + + if (sizeof z <= sizeof(mp_digit)) { + DIGIT(mp,0) = z; + } else { + for (ix = sizeof(long) - 1; ix >= 0; ix--) { + if ((res = s_mp_mul_d(mp, (UCHAR_MAX + 1))) != MP_OKAY) + return res; + + res = s_mp_add_d(mp, (mp_digit)((z >> (ix * CHAR_BIT)) & UCHAR_MAX)); + if (res != MP_OKAY) + return res; + } + } + return MP_OKAY; +} /* end mp_set_ulong() */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ Digit arithmetic */ + +/* {{{ mp_add_d(a, d, b) */ + +/* + mp_add_d(a, d, b) + + Compute the sum b = a + d, for a single digit d. Respects the sign of + its primary addend (single digits are unsigned anyway). + */ + +mp_err mp_add_d(const mp_int *a, mp_digit d, mp_int *b) +{ + mp_int tmp; + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if((res = mp_init_copy(&tmp, a)) != MP_OKAY) + return res; + + if(SIGN(&tmp) == ZPOS) { + if((res = s_mp_add_d(&tmp, d)) != MP_OKAY) + goto CLEANUP; + } else if(s_mp_cmp_d(&tmp, d) >= 0) { + if((res = s_mp_sub_d(&tmp, d)) != MP_OKAY) + goto CLEANUP; + } else { + mp_neg(&tmp, &tmp); + + DIGIT(&tmp, 0) = d - DIGIT(&tmp, 0); + } + + if(s_mp_cmp_d(&tmp, 0) == 0) + SIGN(&tmp) = ZPOS; + + s_mp_exch(&tmp, b); + +CLEANUP: + mp_clear(&tmp); + return res; + +} /* end mp_add_d() */ + +/* }}} */ + +/* {{{ mp_sub_d(a, d, b) */ + +/* + mp_sub_d(a, d, b) + + Compute the difference b = a - d, for a single digit d. Respects the + sign of its subtrahend (single digits are unsigned anyway). + */ + +mp_err mp_sub_d(const mp_int *a, mp_digit d, mp_int *b) +{ + mp_int tmp; + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if((res = mp_init_copy(&tmp, a)) != MP_OKAY) + return res; + + if(SIGN(&tmp) == NEG) { + if((res = s_mp_add_d(&tmp, d)) != MP_OKAY) + goto CLEANUP; + } else if(s_mp_cmp_d(&tmp, d) >= 0) { + if((res = s_mp_sub_d(&tmp, d)) != MP_OKAY) + goto CLEANUP; + } else { + mp_neg(&tmp, &tmp); + + DIGIT(&tmp, 0) = d - DIGIT(&tmp, 0); + SIGN(&tmp) = NEG; + } + + if(s_mp_cmp_d(&tmp, 0) == 0) + SIGN(&tmp) = ZPOS; + + s_mp_exch(&tmp, b); + +CLEANUP: + mp_clear(&tmp); + return res; + +} /* end mp_sub_d() */ + +/* }}} */ + +/* {{{ mp_mul_d(a, d, b) */ + +/* + mp_mul_d(a, d, b) + + Compute the product b = a * d, for a single digit d. Respects the sign + of its multiplicand (single digits are unsigned anyway) + */ + +mp_err mp_mul_d(const mp_int *a, mp_digit d, mp_int *b) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if(d == 0) { + mp_zero(b); + return MP_OKAY; + } + + if((res = mp_copy(a, b)) != MP_OKAY) + return res; + + res = s_mp_mul_d(b, d); + + return res; + +} /* end mp_mul_d() */ + +/* }}} */ + +/* {{{ mp_mul_2(a, c) */ + +mp_err mp_mul_2(const mp_int *a, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && c != NULL, MP_BADARG); + + if((res = mp_copy(a, c)) != MP_OKAY) + return res; + + return s_mp_mul_2(c); + +} /* end mp_mul_2() */ + +/* }}} */ + +/* {{{ mp_div_d(a, d, q, r) */ + +/* + mp_div_d(a, d, q, r) + + Compute the quotient q = a / d and remainder r = a mod d, for a + single digit d. Respects the sign of its divisor (single digits are + unsigned anyway). + */ + +mp_err mp_div_d(const mp_int *a, mp_digit d, mp_int *q, mp_digit *r) +{ + mp_err res; + mp_int qp; + mp_digit rem; + int pow; + + ARGCHK(a != NULL, MP_BADARG); + + if(d == 0) + return MP_RANGE; + + /* Shortcut for powers of two ... */ + if((pow = s_mp_ispow2d(d)) >= 0) { + mp_digit mask; + + mask = ((mp_digit)1 << pow) - 1; + rem = DIGIT(a, 0) & mask; + + if(q) { + mp_copy(a, q); + s_mp_div_2d(q, pow); + } + + if(r) + *r = rem; + + return MP_OKAY; + } + + if((res = mp_init_copy(&qp, a)) != MP_OKAY) + return res; + + res = s_mp_div_d(&qp, d, &rem); + + if(s_mp_cmp_d(&qp, 0) == 0) + SIGN(q) = ZPOS; + + if(r) + *r = rem; + + if(q) + s_mp_exch(&qp, q); + + mp_clear(&qp); + return res; + +} /* end mp_div_d() */ + +/* }}} */ + +/* {{{ mp_div_2(a, c) */ + +/* + mp_div_2(a, c) + + Compute c = a / 2, disregarding the remainder. + */ + +mp_err mp_div_2(const mp_int *a, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && c != NULL, MP_BADARG); + + if((res = mp_copy(a, c)) != MP_OKAY) + return res; + + s_mp_div_2(c); + + return MP_OKAY; + +} /* end mp_div_2() */ + +/* }}} */ + +/* {{{ mp_expt_d(a, d, b) */ + +mp_err mp_expt_d(const mp_int *a, mp_digit d, mp_int *c) +{ + mp_int s, x; + mp_err res; + + ARGCHK(a != NULL && c != NULL, MP_BADARG); + + if((res = mp_init(&s, FLAG(a))) != MP_OKAY) + return res; + if((res = mp_init_copy(&x, a)) != MP_OKAY) + goto X; + + DIGIT(&s, 0) = 1; + + while(d != 0) { + if(d & 1) { + if((res = s_mp_mul(&s, &x)) != MP_OKAY) + goto CLEANUP; + } + + d /= 2; + + if((res = s_mp_sqr(&x)) != MP_OKAY) + goto CLEANUP; + } + + s_mp_exch(&s, c); + +CLEANUP: + mp_clear(&x); +X: + mp_clear(&s); + + return res; + +} /* end mp_expt_d() */ + +/* }}} */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ Full arithmetic */ + +/* {{{ mp_abs(a, b) */ + +/* + mp_abs(a, b) + + Compute b = |a|. 'a' and 'b' may be identical. + */ + +mp_err mp_abs(const mp_int *a, mp_int *b) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if((res = mp_copy(a, b)) != MP_OKAY) + return res; + + SIGN(b) = ZPOS; + + return MP_OKAY; + +} /* end mp_abs() */ + +/* }}} */ + +/* {{{ mp_neg(a, b) */ + +/* + mp_neg(a, b) + + Compute b = -a. 'a' and 'b' may be identical. + */ + +mp_err mp_neg(const mp_int *a, mp_int *b) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if((res = mp_copy(a, b)) != MP_OKAY) + return res; + + if(s_mp_cmp_d(b, 0) == MP_EQ) + SIGN(b) = ZPOS; + else + SIGN(b) = (SIGN(b) == NEG) ? ZPOS : NEG; + + return MP_OKAY; + +} /* end mp_neg() */ + +/* }}} */ + +/* {{{ mp_add(a, b, c) */ + +/* + mp_add(a, b, c) + + Compute c = a + b. All parameters may be identical. + */ + +mp_err mp_add(const mp_int *a, const mp_int *b, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if(SIGN(a) == SIGN(b)) { /* same sign: add values, keep sign */ + MP_CHECKOK( s_mp_add_3arg(a, b, c) ); + } else if(s_mp_cmp(a, b) >= 0) { /* different sign: |a| >= |b| */ + MP_CHECKOK( s_mp_sub_3arg(a, b, c) ); + } else { /* different sign: |a| < |b| */ + MP_CHECKOK( s_mp_sub_3arg(b, a, c) ); + } + + if (s_mp_cmp_d(c, 0) == MP_EQ) + SIGN(c) = ZPOS; + +CLEANUP: + return res; + +} /* end mp_add() */ + +/* }}} */ + +/* {{{ mp_sub(a, b, c) */ + +/* + mp_sub(a, b, c) + + Compute c = a - b. All parameters may be identical. + */ + +mp_err mp_sub(const mp_int *a, const mp_int *b, mp_int *c) +{ + mp_err res; + int magDiff; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if (a == b) { + mp_zero(c); + return MP_OKAY; + } + + if (MP_SIGN(a) != MP_SIGN(b)) { + MP_CHECKOK( s_mp_add_3arg(a, b, c) ); + } else if (!(magDiff = s_mp_cmp(a, b))) { + mp_zero(c); + res = MP_OKAY; + } else if (magDiff > 0) { + MP_CHECKOK( s_mp_sub_3arg(a, b, c) ); + } else { + MP_CHECKOK( s_mp_sub_3arg(b, a, c) ); + MP_SIGN(c) = !MP_SIGN(a); + } + + if (s_mp_cmp_d(c, 0) == MP_EQ) + MP_SIGN(c) = MP_ZPOS; + +CLEANUP: + return res; + +} /* end mp_sub() */ + +/* }}} */ + +/* {{{ mp_mul(a, b, c) */ + +/* + mp_mul(a, b, c) + + Compute c = a * b. All parameters may be identical. + */ +mp_err mp_mul(const mp_int *a, const mp_int *b, mp_int * c) +{ + mp_digit *pb; + mp_int tmp; + mp_err res; + mp_size ib; + mp_size useda, usedb; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if (a == c) { + if ((res = mp_init_copy(&tmp, a)) != MP_OKAY) + return res; + if (a == b) + b = &tmp; + a = &tmp; + } else if (b == c) { + if ((res = mp_init_copy(&tmp, b)) != MP_OKAY) + return res; + b = &tmp; + } else { + MP_DIGITS(&tmp) = 0; + } + + if (MP_USED(a) < MP_USED(b)) { + const mp_int *xch = b; /* switch a and b, to do fewer outer loops */ + b = a; + a = xch; + } + + MP_USED(c) = 1; MP_DIGIT(c, 0) = 0; + if((res = s_mp_pad(c, USED(a) + USED(b))) != MP_OKAY) + goto CLEANUP; + +#ifdef NSS_USE_COMBA + if ((MP_USED(a) == MP_USED(b)) && IS_POWER_OF_2(MP_USED(b))) { + if (MP_USED(a) == 4) { + s_mp_mul_comba_4(a, b, c); + goto CLEANUP; + } + if (MP_USED(a) == 8) { + s_mp_mul_comba_8(a, b, c); + goto CLEANUP; + } + if (MP_USED(a) == 16) { + s_mp_mul_comba_16(a, b, c); + goto CLEANUP; + } + if (MP_USED(a) == 32) { + s_mp_mul_comba_32(a, b, c); + goto CLEANUP; + } + } +#endif + + pb = MP_DIGITS(b); + s_mpv_mul_d(MP_DIGITS(a), MP_USED(a), *pb++, MP_DIGITS(c)); + + /* Outer loop: Digits of b */ + useda = MP_USED(a); + usedb = MP_USED(b); + for (ib = 1; ib < usedb; ib++) { + mp_digit b_i = *pb++; + + /* Inner product: Digits of a */ + if (b_i) + s_mpv_mul_d_add(MP_DIGITS(a), useda, b_i, MP_DIGITS(c) + ib); + else + MP_DIGIT(c, ib + useda) = b_i; + } + + s_mp_clamp(c); + + if(SIGN(a) == SIGN(b) || s_mp_cmp_d(c, 0) == MP_EQ) + SIGN(c) = ZPOS; + else + SIGN(c) = NEG; + +CLEANUP: + mp_clear(&tmp); + return res; +} /* end mp_mul() */ + +/* }}} */ + +/* {{{ mp_sqr(a, sqr) */ + +#if MP_SQUARE +/* + Computes the square of a. This can be done more + efficiently than a general multiplication, because many of the + computation steps are redundant when squaring. The inner product + step is a bit more complicated, but we save a fair number of + iterations of the multiplication loop. + */ + +/* sqr = a^2; Caller provides both a and tmp; */ +mp_err mp_sqr(const mp_int *a, mp_int *sqr) +{ + mp_digit *pa; + mp_digit d; + mp_err res; + mp_size ix; + mp_int tmp; + int count; + + ARGCHK(a != NULL && sqr != NULL, MP_BADARG); + + if (a == sqr) { + if((res = mp_init_copy(&tmp, a)) != MP_OKAY) + return res; + a = &tmp; + } else { + DIGITS(&tmp) = 0; + res = MP_OKAY; + } + + ix = 2 * MP_USED(a); + if (ix > MP_ALLOC(sqr)) { + MP_USED(sqr) = 1; + MP_CHECKOK( s_mp_grow(sqr, ix) ); + } + MP_USED(sqr) = ix; + MP_DIGIT(sqr, 0) = 0; + +#ifdef NSS_USE_COMBA + if (IS_POWER_OF_2(MP_USED(a))) { + if (MP_USED(a) == 4) { + s_mp_sqr_comba_4(a, sqr); + goto CLEANUP; + } + if (MP_USED(a) == 8) { + s_mp_sqr_comba_8(a, sqr); + goto CLEANUP; + } + if (MP_USED(a) == 16) { + s_mp_sqr_comba_16(a, sqr); + goto CLEANUP; + } + if (MP_USED(a) == 32) { + s_mp_sqr_comba_32(a, sqr); + goto CLEANUP; + } + } +#endif + + pa = MP_DIGITS(a); + count = MP_USED(a) - 1; + if (count > 0) { + d = *pa++; + s_mpv_mul_d(pa, count, d, MP_DIGITS(sqr) + 1); + for (ix = 3; --count > 0; ix += 2) { + d = *pa++; + s_mpv_mul_d_add(pa, count, d, MP_DIGITS(sqr) + ix); + } /* for(ix ...) */ + MP_DIGIT(sqr, MP_USED(sqr)-1) = 0; /* above loop stopped short of this. */ + + /* now sqr *= 2 */ + s_mp_mul_2(sqr); + } else { + MP_DIGIT(sqr, 1) = 0; + } + + /* now add the squares of the digits of a to sqr. */ + s_mpv_sqr_add_prop(MP_DIGITS(a), MP_USED(a), MP_DIGITS(sqr)); + + SIGN(sqr) = ZPOS; + s_mp_clamp(sqr); + +CLEANUP: + mp_clear(&tmp); + return res; + +} /* end mp_sqr() */ +#endif + +/* }}} */ + +/* {{{ mp_div(a, b, q, r) */ + +/* + mp_div(a, b, q, r) + + Compute q = a / b and r = a mod b. Input parameters may be re-used + as output parameters. If q or r is NULL, that portion of the + computation will be discarded (although it will still be computed) + */ +mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *q, mp_int *r) +{ + mp_err res; + mp_int *pQ, *pR; + mp_int qtmp, rtmp, btmp; + int cmp; + mp_sign signA; + mp_sign signB; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + signA = MP_SIGN(a); + signB = MP_SIGN(b); + + if(mp_cmp_z(b) == MP_EQ) + return MP_RANGE; + + DIGITS(&qtmp) = 0; + DIGITS(&rtmp) = 0; + DIGITS(&btmp) = 0; + + /* Set up some temporaries... */ + if (!r || r == a || r == b) { + MP_CHECKOK( mp_init_copy(&rtmp, a) ); + pR = &rtmp; + } else { + MP_CHECKOK( mp_copy(a, r) ); + pR = r; + } + + if (!q || q == a || q == b) { + MP_CHECKOK( mp_init_size(&qtmp, MP_USED(a), FLAG(a)) ); + pQ = &qtmp; + } else { + MP_CHECKOK( s_mp_pad(q, MP_USED(a)) ); + pQ = q; + mp_zero(pQ); + } + + /* + If |a| <= |b|, we can compute the solution without division; + otherwise, we actually do the work required. + */ + if ((cmp = s_mp_cmp(a, b)) <= 0) { + if (cmp) { + /* r was set to a above. */ + mp_zero(pQ); + } else { + mp_set(pQ, 1); + mp_zero(pR); + } + } else { + MP_CHECKOK( mp_init_copy(&btmp, b) ); + MP_CHECKOK( s_mp_div(pR, &btmp, pQ) ); + } + + /* Compute the signs for the output */ + MP_SIGN(pR) = signA; /* Sr = Sa */ + /* Sq = ZPOS if Sa == Sb */ /* Sq = NEG if Sa != Sb */ + MP_SIGN(pQ) = (signA == signB) ? ZPOS : NEG; + + if(s_mp_cmp_d(pQ, 0) == MP_EQ) + SIGN(pQ) = ZPOS; + if(s_mp_cmp_d(pR, 0) == MP_EQ) + SIGN(pR) = ZPOS; + + /* Copy output, if it is needed */ + if(q && q != pQ) + s_mp_exch(pQ, q); + + if(r && r != pR) + s_mp_exch(pR, r); + +CLEANUP: + mp_clear(&btmp); + mp_clear(&rtmp); + mp_clear(&qtmp); + + return res; + +} /* end mp_div() */ + +/* }}} */ + +/* {{{ mp_div_2d(a, d, q, r) */ + +mp_err mp_div_2d(const mp_int *a, mp_digit d, mp_int *q, mp_int *r) +{ + mp_err res; + + ARGCHK(a != NULL, MP_BADARG); + + if(q) { + if((res = mp_copy(a, q)) != MP_OKAY) + return res; + } + if(r) { + if((res = mp_copy(a, r)) != MP_OKAY) + return res; + } + if(q) { + s_mp_div_2d(q, d); + } + if(r) { + s_mp_mod_2d(r, d); + } + + return MP_OKAY; + +} /* end mp_div_2d() */ + +/* }}} */ + +/* {{{ mp_expt(a, b, c) */ + +/* + mp_expt(a, b, c) + + Compute c = a ** b, that is, raise a to the b power. Uses a + standard iterative square-and-multiply technique. + */ + +mp_err mp_expt(mp_int *a, mp_int *b, mp_int *c) +{ + mp_int s, x; + mp_err res; + mp_digit d; + int dig, bit; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if(mp_cmp_z(b) < 0) + return MP_RANGE; + + if((res = mp_init(&s, FLAG(a))) != MP_OKAY) + return res; + + mp_set(&s, 1); + + if((res = mp_init_copy(&x, a)) != MP_OKAY) + goto X; + + /* Loop over low-order digits in ascending order */ + for(dig = 0; dig < (USED(b) - 1); dig++) { + d = DIGIT(b, dig); + + /* Loop over bits of each non-maximal digit */ + for(bit = 0; bit < DIGIT_BIT; bit++) { + if(d & 1) { + if((res = s_mp_mul(&s, &x)) != MP_OKAY) + goto CLEANUP; + } + + d >>= 1; + + if((res = s_mp_sqr(&x)) != MP_OKAY) + goto CLEANUP; + } + } + + /* Consider now the last digit... */ + d = DIGIT(b, dig); + + while(d) { + if(d & 1) { + if((res = s_mp_mul(&s, &x)) != MP_OKAY) + goto CLEANUP; + } + + d >>= 1; + + if((res = s_mp_sqr(&x)) != MP_OKAY) + goto CLEANUP; + } + + if(mp_iseven(b)) + SIGN(&s) = SIGN(a); + + res = mp_copy(&s, c); + +CLEANUP: + mp_clear(&x); +X: + mp_clear(&s); + + return res; + +} /* end mp_expt() */ + +/* }}} */ + +/* {{{ mp_2expt(a, k) */ + +/* Compute a = 2^k */ + +mp_err mp_2expt(mp_int *a, mp_digit k) +{ + ARGCHK(a != NULL, MP_BADARG); + + return s_mp_2expt(a, k); + +} /* end mp_2expt() */ + +/* }}} */ + +/* {{{ mp_mod(a, m, c) */ + +/* + mp_mod(a, m, c) + + Compute c = a (mod m). Result will always be 0 <= c < m. + */ + +mp_err mp_mod(const mp_int *a, const mp_int *m, mp_int *c) +{ + mp_err res; + int mag; + + ARGCHK(a != NULL && m != NULL && c != NULL, MP_BADARG); + + if(SIGN(m) == NEG) + return MP_RANGE; + + /* + If |a| > m, we need to divide to get the remainder and take the + absolute value. + + If |a| < m, we don't need to do any division, just copy and adjust + the sign (if a is negative). + + If |a| == m, we can simply set the result to zero. + + This order is intended to minimize the average path length of the + comparison chain on common workloads -- the most frequent cases are + that |a| != m, so we do those first. + */ + if((mag = s_mp_cmp(a, m)) > 0) { + if((res = mp_div(a, m, NULL, c)) != MP_OKAY) + return res; + + if(SIGN(c) == NEG) { + if((res = mp_add(c, m, c)) != MP_OKAY) + return res; + } + + } else if(mag < 0) { + if((res = mp_copy(a, c)) != MP_OKAY) + return res; + + if(mp_cmp_z(a) < 0) { + if((res = mp_add(c, m, c)) != MP_OKAY) + return res; + + } + + } else { + mp_zero(c); + + } + + return MP_OKAY; + +} /* end mp_mod() */ + +/* }}} */ + +/* {{{ mp_mod_d(a, d, c) */ + +/* + mp_mod_d(a, d, c) + + Compute c = a (mod d). Result will always be 0 <= c < d + */ +mp_err mp_mod_d(const mp_int *a, mp_digit d, mp_digit *c) +{ + mp_err res; + mp_digit rem; + + ARGCHK(a != NULL && c != NULL, MP_BADARG); + + if(s_mp_cmp_d(a, d) > 0) { + if((res = mp_div_d(a, d, NULL, &rem)) != MP_OKAY) + return res; + + } else { + if(SIGN(a) == NEG) + rem = d - DIGIT(a, 0); + else + rem = DIGIT(a, 0); + } + + if(c) + *c = rem; + + return MP_OKAY; + +} /* end mp_mod_d() */ + +/* }}} */ + +/* {{{ mp_sqrt(a, b) */ + +/* + mp_sqrt(a, b) + + Compute the integer square root of a, and store the result in b. + Uses an integer-arithmetic version of Newton's iterative linear + approximation technique to determine this value; the result has the + following two properties: + + b^2 <= a + (b+1)^2 >= a + + It is a range error to pass a negative value. + */ +mp_err mp_sqrt(const mp_int *a, mp_int *b) +{ + mp_int x, t; + mp_err res; + mp_size used; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + /* Cannot take square root of a negative value */ + if(SIGN(a) == NEG) + return MP_RANGE; + + /* Special cases for zero and one, trivial */ + if(mp_cmp_d(a, 1) <= 0) + return mp_copy(a, b); + + /* Initialize the temporaries we'll use below */ + if((res = mp_init_size(&t, USED(a), FLAG(a))) != MP_OKAY) + return res; + + /* Compute an initial guess for the iteration as a itself */ + if((res = mp_init_copy(&x, a)) != MP_OKAY) + goto X; + + used = MP_USED(&x); + if (used > 1) { + s_mp_rshd(&x, used / 2); + } + + for(;;) { + /* t = (x * x) - a */ + mp_copy(&x, &t); /* can't fail, t is big enough for original x */ + if((res = mp_sqr(&t, &t)) != MP_OKAY || + (res = mp_sub(&t, a, &t)) != MP_OKAY) + goto CLEANUP; + + /* t = t / 2x */ + s_mp_mul_2(&x); + if((res = mp_div(&t, &x, &t, NULL)) != MP_OKAY) + goto CLEANUP; + s_mp_div_2(&x); + + /* Terminate the loop, if the quotient is zero */ + if(mp_cmp_z(&t) == MP_EQ) + break; + + /* x = x - t */ + if((res = mp_sub(&x, &t, &x)) != MP_OKAY) + goto CLEANUP; + + } + + /* Copy result to output parameter */ + mp_sub_d(&x, 1, &x); + s_mp_exch(&x, b); + + CLEANUP: + mp_clear(&x); + X: + mp_clear(&t); + + return res; + +} /* end mp_sqrt() */ + +/* }}} */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ Modular arithmetic */ + +#if MP_MODARITH +/* {{{ mp_addmod(a, b, m, c) */ + +/* + mp_addmod(a, b, m, c) + + Compute c = (a + b) mod m + */ + +mp_err mp_addmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG); + + if((res = mp_add(a, b, c)) != MP_OKAY) + return res; + if((res = mp_mod(c, m, c)) != MP_OKAY) + return res; + + return MP_OKAY; + +} + +/* }}} */ + +/* {{{ mp_submod(a, b, m, c) */ + +/* + mp_submod(a, b, m, c) + + Compute c = (a - b) mod m + */ + +mp_err mp_submod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG); + + if((res = mp_sub(a, b, c)) != MP_OKAY) + return res; + if((res = mp_mod(c, m, c)) != MP_OKAY) + return res; + + return MP_OKAY; + +} + +/* }}} */ + +/* {{{ mp_mulmod(a, b, m, c) */ + +/* + mp_mulmod(a, b, m, c) + + Compute c = (a * b) mod m + */ + +mp_err mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL && m != NULL && c != NULL, MP_BADARG); + + if((res = mp_mul(a, b, c)) != MP_OKAY) + return res; + if((res = mp_mod(c, m, c)) != MP_OKAY) + return res; + + return MP_OKAY; + +} + +/* }}} */ + +/* {{{ mp_sqrmod(a, m, c) */ + +#if MP_SQUARE +mp_err mp_sqrmod(const mp_int *a, const mp_int *m, mp_int *c) +{ + mp_err res; + + ARGCHK(a != NULL && m != NULL && c != NULL, MP_BADARG); + + if((res = mp_sqr(a, c)) != MP_OKAY) + return res; + if((res = mp_mod(c, m, c)) != MP_OKAY) + return res; + + return MP_OKAY; + +} /* end mp_sqrmod() */ +#endif + +/* }}} */ + +/* {{{ s_mp_exptmod(a, b, m, c) */ + +/* + s_mp_exptmod(a, b, m, c) + + Compute c = (a ** b) mod m. Uses a standard square-and-multiply + method with modular reductions at each step. (This is basically the + same code as mp_expt(), except for the addition of the reductions) + + The modular reductions are done using Barrett's algorithm (see + s_mp_reduce() below for details) + */ + +mp_err s_mp_exptmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c) +{ + mp_int s, x, mu; + mp_err res; + mp_digit d; + int dig, bit; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if(mp_cmp_z(b) < 0 || mp_cmp_z(m) <= 0) + return MP_RANGE; + + if((res = mp_init(&s, FLAG(a))) != MP_OKAY) + return res; + if((res = mp_init_copy(&x, a)) != MP_OKAY || + (res = mp_mod(&x, m, &x)) != MP_OKAY) + goto X; + if((res = mp_init(&mu, FLAG(a))) != MP_OKAY) + goto MU; + + mp_set(&s, 1); + + /* mu = b^2k / m */ + s_mp_add_d(&mu, 1); + s_mp_lshd(&mu, 2 * USED(m)); + if((res = mp_div(&mu, m, &mu, NULL)) != MP_OKAY) + goto CLEANUP; + + /* Loop over digits of b in ascending order, except highest order */ + for(dig = 0; dig < (USED(b) - 1); dig++) { + d = DIGIT(b, dig); + + /* Loop over the bits of the lower-order digits */ + for(bit = 0; bit < DIGIT_BIT; bit++) { + if(d & 1) { + if((res = s_mp_mul(&s, &x)) != MP_OKAY) + goto CLEANUP; + if((res = s_mp_reduce(&s, m, &mu)) != MP_OKAY) + goto CLEANUP; + } + + d >>= 1; + + if((res = s_mp_sqr(&x)) != MP_OKAY) + goto CLEANUP; + if((res = s_mp_reduce(&x, m, &mu)) != MP_OKAY) + goto CLEANUP; + } + } + + /* Now do the last digit... */ + d = DIGIT(b, dig); + + while(d) { + if(d & 1) { + if((res = s_mp_mul(&s, &x)) != MP_OKAY) + goto CLEANUP; + if((res = s_mp_reduce(&s, m, &mu)) != MP_OKAY) + goto CLEANUP; + } + + d >>= 1; + + if((res = s_mp_sqr(&x)) != MP_OKAY) + goto CLEANUP; + if((res = s_mp_reduce(&x, m, &mu)) != MP_OKAY) + goto CLEANUP; + } + + s_mp_exch(&s, c); + + CLEANUP: + mp_clear(&mu); + MU: + mp_clear(&x); + X: + mp_clear(&s); + + return res; + +} /* end s_mp_exptmod() */ + +/* }}} */ + +/* {{{ mp_exptmod_d(a, d, m, c) */ + +mp_err mp_exptmod_d(const mp_int *a, mp_digit d, const mp_int *m, mp_int *c) +{ + mp_int s, x; + mp_err res; + + ARGCHK(a != NULL && c != NULL, MP_BADARG); + + if((res = mp_init(&s, FLAG(a))) != MP_OKAY) + return res; + if((res = mp_init_copy(&x, a)) != MP_OKAY) + goto X; + + mp_set(&s, 1); + + while(d != 0) { + if(d & 1) { + if((res = s_mp_mul(&s, &x)) != MP_OKAY || + (res = mp_mod(&s, m, &s)) != MP_OKAY) + goto CLEANUP; + } + + d /= 2; + + if((res = s_mp_sqr(&x)) != MP_OKAY || + (res = mp_mod(&x, m, &x)) != MP_OKAY) + goto CLEANUP; + } + + s_mp_exch(&s, c); + +CLEANUP: + mp_clear(&x); +X: + mp_clear(&s); + + return res; + +} /* end mp_exptmod_d() */ + +/* }}} */ +#endif /* if MP_MODARITH */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ Comparison functions */ + +/* {{{ mp_cmp_z(a) */ + +/* + mp_cmp_z(a) + + Compare a <=> 0. Returns <0 if a<0, 0 if a=0, >0 if a>0. + */ + +int mp_cmp_z(const mp_int *a) +{ + if(SIGN(a) == NEG) + return MP_LT; + else if(USED(a) == 1 && DIGIT(a, 0) == 0) + return MP_EQ; + else + return MP_GT; + +} /* end mp_cmp_z() */ + +/* }}} */ + +/* {{{ mp_cmp_d(a, d) */ + +/* + mp_cmp_d(a, d) + + Compare a <=> d. Returns <0 if a0 if a>d + */ + +int mp_cmp_d(const mp_int *a, mp_digit d) +{ + ARGCHK(a != NULL, MP_EQ); + + if(SIGN(a) == NEG) + return MP_LT; + + return s_mp_cmp_d(a, d); + +} /* end mp_cmp_d() */ + +/* }}} */ + +/* {{{ mp_cmp(a, b) */ + +int mp_cmp(const mp_int *a, const mp_int *b) +{ + ARGCHK(a != NULL && b != NULL, MP_EQ); + + if(SIGN(a) == SIGN(b)) { + int mag; + + if((mag = s_mp_cmp(a, b)) == MP_EQ) + return MP_EQ; + + if(SIGN(a) == ZPOS) + return mag; + else + return -mag; + + } else if(SIGN(a) == ZPOS) { + return MP_GT; + } else { + return MP_LT; + } + +} /* end mp_cmp() */ + +/* }}} */ + +/* {{{ mp_cmp_mag(a, b) */ + +/* + mp_cmp_mag(a, b) + + Compares |a| <=> |b|, and returns an appropriate comparison result + */ + +int mp_cmp_mag(mp_int *a, mp_int *b) +{ + ARGCHK(a != NULL && b != NULL, MP_EQ); + + return s_mp_cmp(a, b); + +} /* end mp_cmp_mag() */ + +/* }}} */ + +/* {{{ mp_cmp_int(a, z, kmflag) */ + +/* + This just converts z to an mp_int, and uses the existing comparison + routines. This is sort of inefficient, but it's not clear to me how + frequently this wil get used anyway. For small positive constants, + you can always use mp_cmp_d(), and for zero, there is mp_cmp_z(). + */ +int mp_cmp_int(const mp_int *a, long z, int kmflag) +{ + mp_int tmp; + int out; + + ARGCHK(a != NULL, MP_EQ); + + mp_init(&tmp, kmflag); mp_set_int(&tmp, z); + out = mp_cmp(a, &tmp); + mp_clear(&tmp); + + return out; + +} /* end mp_cmp_int() */ + +/* }}} */ + +/* {{{ mp_isodd(a) */ + +/* + mp_isodd(a) + + Returns a true (non-zero) value if a is odd, false (zero) otherwise. + */ +int mp_isodd(const mp_int *a) +{ + ARGCHK(a != NULL, 0); + + return (int)(DIGIT(a, 0) & 1); + +} /* end mp_isodd() */ + +/* }}} */ + +/* {{{ mp_iseven(a) */ + +int mp_iseven(const mp_int *a) +{ + return !mp_isodd(a); + +} /* end mp_iseven() */ + +/* }}} */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ Number theoretic functions */ + +#if MP_NUMTH +/* {{{ mp_gcd(a, b, c) */ + +/* + Like the old mp_gcd() function, except computes the GCD using the + binary algorithm due to Josef Stein in 1961 (via Knuth). + */ +mp_err mp_gcd(mp_int *a, mp_int *b, mp_int *c) +{ + mp_err res; + mp_int u, v, t; + mp_size k = 0; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if(mp_cmp_z(a) == MP_EQ && mp_cmp_z(b) == MP_EQ) + return MP_RANGE; + if(mp_cmp_z(a) == MP_EQ) { + return mp_copy(b, c); + } else if(mp_cmp_z(b) == MP_EQ) { + return mp_copy(a, c); + } + + if((res = mp_init(&t, FLAG(a))) != MP_OKAY) + return res; + if((res = mp_init_copy(&u, a)) != MP_OKAY) + goto U; + if((res = mp_init_copy(&v, b)) != MP_OKAY) + goto V; + + SIGN(&u) = ZPOS; + SIGN(&v) = ZPOS; + + /* Divide out common factors of 2 until at least 1 of a, b is even */ + while(mp_iseven(&u) && mp_iseven(&v)) { + s_mp_div_2(&u); + s_mp_div_2(&v); + ++k; + } + + /* Initialize t */ + if(mp_isodd(&u)) { + if((res = mp_copy(&v, &t)) != MP_OKAY) + goto CLEANUP; + + /* t = -v */ + if(SIGN(&v) == ZPOS) + SIGN(&t) = NEG; + else + SIGN(&t) = ZPOS; + + } else { + if((res = mp_copy(&u, &t)) != MP_OKAY) + goto CLEANUP; + + } + + for(;;) { + while(mp_iseven(&t)) { + s_mp_div_2(&t); + } + + if(mp_cmp_z(&t) == MP_GT) { + if((res = mp_copy(&t, &u)) != MP_OKAY) + goto CLEANUP; + + } else { + if((res = mp_copy(&t, &v)) != MP_OKAY) + goto CLEANUP; + + /* v = -t */ + if(SIGN(&t) == ZPOS) + SIGN(&v) = NEG; + else + SIGN(&v) = ZPOS; + } + + if((res = mp_sub(&u, &v, &t)) != MP_OKAY) + goto CLEANUP; + + if(s_mp_cmp_d(&t, 0) == MP_EQ) + break; + } + + s_mp_2expt(&v, k); /* v = 2^k */ + res = mp_mul(&u, &v, c); /* c = u * v */ + + CLEANUP: + mp_clear(&v); + V: + mp_clear(&u); + U: + mp_clear(&t); + + return res; + +} /* end mp_gcd() */ + +/* }}} */ + +/* {{{ mp_lcm(a, b, c) */ + +/* We compute the least common multiple using the rule: + + ab = [a, b](a, b) + + ... by computing the product, and dividing out the gcd. + */ + +mp_err mp_lcm(mp_int *a, mp_int *b, mp_int *c) +{ + mp_int gcd, prod; + mp_err res; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + /* Set up temporaries */ + if((res = mp_init(&gcd, FLAG(a))) != MP_OKAY) + return res; + if((res = mp_init(&prod, FLAG(a))) != MP_OKAY) + goto GCD; + + if((res = mp_mul(a, b, &prod)) != MP_OKAY) + goto CLEANUP; + if((res = mp_gcd(a, b, &gcd)) != MP_OKAY) + goto CLEANUP; + + res = mp_div(&prod, &gcd, c, NULL); + + CLEANUP: + mp_clear(&prod); + GCD: + mp_clear(&gcd); + + return res; + +} /* end mp_lcm() */ + +/* }}} */ + +/* {{{ mp_xgcd(a, b, g, x, y) */ + +/* + mp_xgcd(a, b, g, x, y) + + Compute g = (a, b) and values x and y satisfying Bezout's identity + (that is, ax + by = g). This uses the binary extended GCD algorithm + based on the Stein algorithm used for mp_gcd() + See algorithm 14.61 in Handbook of Applied Cryptogrpahy. + */ + +mp_err mp_xgcd(const mp_int *a, const mp_int *b, mp_int *g, mp_int *x, mp_int *y) +{ + mp_int gx, xc, yc, u, v, A, B, C, D; + mp_int *clean[9]; + mp_err res; + int last = -1; + + if(mp_cmp_z(b) == 0) + return MP_RANGE; + + /* Initialize all these variables we need */ + MP_CHECKOK( mp_init(&u, FLAG(a)) ); + clean[++last] = &u; + MP_CHECKOK( mp_init(&v, FLAG(a)) ); + clean[++last] = &v; + MP_CHECKOK( mp_init(&gx, FLAG(a)) ); + clean[++last] = &gx; + MP_CHECKOK( mp_init(&A, FLAG(a)) ); + clean[++last] = &A; + MP_CHECKOK( mp_init(&B, FLAG(a)) ); + clean[++last] = &B; + MP_CHECKOK( mp_init(&C, FLAG(a)) ); + clean[++last] = &C; + MP_CHECKOK( mp_init(&D, FLAG(a)) ); + clean[++last] = &D; + MP_CHECKOK( mp_init_copy(&xc, a) ); + clean[++last] = &xc; + mp_abs(&xc, &xc); + MP_CHECKOK( mp_init_copy(&yc, b) ); + clean[++last] = &yc; + mp_abs(&yc, &yc); + + mp_set(&gx, 1); + + /* Divide by two until at least one of them is odd */ + while(mp_iseven(&xc) && mp_iseven(&yc)) { + mp_size nx = mp_trailing_zeros(&xc); + mp_size ny = mp_trailing_zeros(&yc); + mp_size n = MP_MIN(nx, ny); + s_mp_div_2d(&xc,n); + s_mp_div_2d(&yc,n); + MP_CHECKOK( s_mp_mul_2d(&gx,n) ); + } + + mp_copy(&xc, &u); + mp_copy(&yc, &v); + mp_set(&A, 1); mp_set(&D, 1); + + /* Loop through binary GCD algorithm */ + do { + while(mp_iseven(&u)) { + s_mp_div_2(&u); + + if(mp_iseven(&A) && mp_iseven(&B)) { + s_mp_div_2(&A); s_mp_div_2(&B); + } else { + MP_CHECKOK( mp_add(&A, &yc, &A) ); + s_mp_div_2(&A); + MP_CHECKOK( mp_sub(&B, &xc, &B) ); + s_mp_div_2(&B); + } + } + + while(mp_iseven(&v)) { + s_mp_div_2(&v); + + if(mp_iseven(&C) && mp_iseven(&D)) { + s_mp_div_2(&C); s_mp_div_2(&D); + } else { + MP_CHECKOK( mp_add(&C, &yc, &C) ); + s_mp_div_2(&C); + MP_CHECKOK( mp_sub(&D, &xc, &D) ); + s_mp_div_2(&D); + } + } + + if(mp_cmp(&u, &v) >= 0) { + MP_CHECKOK( mp_sub(&u, &v, &u) ); + MP_CHECKOK( mp_sub(&A, &C, &A) ); + MP_CHECKOK( mp_sub(&B, &D, &B) ); + } else { + MP_CHECKOK( mp_sub(&v, &u, &v) ); + MP_CHECKOK( mp_sub(&C, &A, &C) ); + MP_CHECKOK( mp_sub(&D, &B, &D) ); + } + } while (mp_cmp_z(&u) != 0); + + /* copy results to output */ + if(x) + MP_CHECKOK( mp_copy(&C, x) ); + + if(y) + MP_CHECKOK( mp_copy(&D, y) ); + + if(g) + MP_CHECKOK( mp_mul(&gx, &v, g) ); + + CLEANUP: + while(last >= 0) + mp_clear(clean[last--]); + + return res; + +} /* end mp_xgcd() */ + +/* }}} */ + +mp_size mp_trailing_zeros(const mp_int *mp) +{ + mp_digit d; + mp_size n = 0; + int ix; + + if (!mp || !MP_DIGITS(mp) || !mp_cmp_z(mp)) + return n; + + for (ix = 0; !(d = MP_DIGIT(mp,ix)) && (ix < MP_USED(mp)); ++ix) + n += MP_DIGIT_BIT; + if (!d) + return 0; /* shouldn't happen, but ... */ +#if !defined(MP_USE_UINT_DIGIT) + if (!(d & 0xffffffffU)) { + d >>= 32; + n += 32; + } +#endif + if (!(d & 0xffffU)) { + d >>= 16; + n += 16; + } + if (!(d & 0xffU)) { + d >>= 8; + n += 8; + } + if (!(d & 0xfU)) { + d >>= 4; + n += 4; + } + if (!(d & 0x3U)) { + d >>= 2; + n += 2; + } + if (!(d & 0x1U)) { + d >>= 1; + n += 1; + } +#if MP_ARGCHK == 2 + assert(0 != (d & 1)); +#endif + return n; +} + +/* Given a and prime p, computes c and k such that a*c == 2**k (mod p). +** Returns k (positive) or error (negative). +** This technique from the paper "Fast Modular Reciprocals" (unpublished) +** by Richard Schroeppel (a.k.a. Captain Nemo). +*/ +mp_err s_mp_almost_inverse(const mp_int *a, const mp_int *p, mp_int *c) +{ + mp_err res; + mp_err k = 0; + mp_int d, f, g; + + ARGCHK(a && p && c, MP_BADARG); + + MP_DIGITS(&d) = 0; + MP_DIGITS(&f) = 0; + MP_DIGITS(&g) = 0; + MP_CHECKOK( mp_init(&d, FLAG(a)) ); + MP_CHECKOK( mp_init_copy(&f, a) ); /* f = a */ + MP_CHECKOK( mp_init_copy(&g, p) ); /* g = p */ + + mp_set(c, 1); + mp_zero(&d); + + if (mp_cmp_z(&f) == 0) { + res = MP_UNDEF; + } else + for (;;) { + int diff_sign; + while (mp_iseven(&f)) { + mp_size n = mp_trailing_zeros(&f); + if (!n) { + res = MP_UNDEF; + goto CLEANUP; + } + s_mp_div_2d(&f, n); + MP_CHECKOK( s_mp_mul_2d(&d, n) ); + k += n; + } + if (mp_cmp_d(&f, 1) == MP_EQ) { /* f == 1 */ + res = k; + break; + } + diff_sign = mp_cmp(&f, &g); + if (diff_sign < 0) { /* f < g */ + s_mp_exch(&f, &g); + s_mp_exch(c, &d); + } else if (diff_sign == 0) { /* f == g */ + res = MP_UNDEF; /* a and p are not relatively prime */ + break; + } + if ((MP_DIGIT(&f,0) % 4) == (MP_DIGIT(&g,0) % 4)) { + MP_CHECKOK( mp_sub(&f, &g, &f) ); /* f = f - g */ + MP_CHECKOK( mp_sub(c, &d, c) ); /* c = c - d */ + } else { + MP_CHECKOK( mp_add(&f, &g, &f) ); /* f = f + g */ + MP_CHECKOK( mp_add(c, &d, c) ); /* c = c + d */ + } + } + if (res >= 0) { + while (MP_SIGN(c) != MP_ZPOS) { + MP_CHECKOK( mp_add(c, p, c) ); + } + res = k; + } + +CLEANUP: + mp_clear(&d); + mp_clear(&f); + mp_clear(&g); + return res; +} + +/* Compute T = (P ** -1) mod MP_RADIX. Also works for 16-bit mp_digits. +** This technique from the paper "Fast Modular Reciprocals" (unpublished) +** by Richard Schroeppel (a.k.a. Captain Nemo). +*/ +mp_digit s_mp_invmod_radix(mp_digit P) +{ + mp_digit T = P; + T *= 2 - (P * T); + T *= 2 - (P * T); + T *= 2 - (P * T); + T *= 2 - (P * T); +#if !defined(MP_USE_UINT_DIGIT) + T *= 2 - (P * T); + T *= 2 - (P * T); +#endif + return T; +} + +/* Given c, k, and prime p, where a*c == 2**k (mod p), +** Compute x = (a ** -1) mod p. This is similar to Montgomery reduction. +** This technique from the paper "Fast Modular Reciprocals" (unpublished) +** by Richard Schroeppel (a.k.a. Captain Nemo). +*/ +mp_err s_mp_fixup_reciprocal(const mp_int *c, const mp_int *p, int k, mp_int *x) +{ + int k_orig = k; + mp_digit r; + mp_size ix; + mp_err res; + + if (mp_cmp_z(c) < 0) { /* c < 0 */ + MP_CHECKOK( mp_add(c, p, x) ); /* x = c + p */ + } else { + MP_CHECKOK( mp_copy(c, x) ); /* x = c */ + } + + /* make sure x is large enough */ + ix = MP_HOWMANY(k, MP_DIGIT_BIT) + MP_USED(p) + 1; + ix = MP_MAX(ix, MP_USED(x)); + MP_CHECKOK( s_mp_pad(x, ix) ); + + r = 0 - s_mp_invmod_radix(MP_DIGIT(p,0)); + + for (ix = 0; k > 0; ix++) { + int j = MP_MIN(k, MP_DIGIT_BIT); + mp_digit v = r * MP_DIGIT(x, ix); + if (j < MP_DIGIT_BIT) { + v &= ((mp_digit)1 << j) - 1; /* v = v mod (2 ** j) */ + } + s_mp_mul_d_add_offset(p, v, x, ix); /* x += p * v * (RADIX ** ix) */ + k -= j; + } + s_mp_clamp(x); + s_mp_div_2d(x, k_orig); + res = MP_OKAY; + +CLEANUP: + return res; +} + +/* compute mod inverse using Schroeppel's method, only if m is odd */ +mp_err s_mp_invmod_odd_m(const mp_int *a, const mp_int *m, mp_int *c) +{ + int k; + mp_err res; + mp_int x; + + ARGCHK(a && m && c, MP_BADARG); + + if(mp_cmp_z(a) == 0 || mp_cmp_z(m) == 0) + return MP_RANGE; + if (mp_iseven(m)) + return MP_UNDEF; + + MP_DIGITS(&x) = 0; + + if (a == c) { + if ((res = mp_init_copy(&x, a)) != MP_OKAY) + return res; + if (a == m) + m = &x; + a = &x; + } else if (m == c) { + if ((res = mp_init_copy(&x, m)) != MP_OKAY) + return res; + m = &x; + } else { + MP_DIGITS(&x) = 0; + } + + MP_CHECKOK( s_mp_almost_inverse(a, m, c) ); + k = res; + MP_CHECKOK( s_mp_fixup_reciprocal(c, m, k, c) ); +CLEANUP: + mp_clear(&x); + return res; +} + +/* Known good algorithm for computing modular inverse. But slow. */ +mp_err mp_invmod_xgcd(const mp_int *a, const mp_int *m, mp_int *c) +{ + mp_int g, x; + mp_err res; + + ARGCHK(a && m && c, MP_BADARG); + + if(mp_cmp_z(a) == 0 || mp_cmp_z(m) == 0) + return MP_RANGE; + + MP_DIGITS(&g) = 0; + MP_DIGITS(&x) = 0; + MP_CHECKOK( mp_init(&x, FLAG(a)) ); + MP_CHECKOK( mp_init(&g, FLAG(a)) ); + + MP_CHECKOK( mp_xgcd(a, m, &g, &x, NULL) ); + + if (mp_cmp_d(&g, 1) != MP_EQ) { + res = MP_UNDEF; + goto CLEANUP; + } + + res = mp_mod(&x, m, c); + SIGN(c) = SIGN(a); + +CLEANUP: + mp_clear(&x); + mp_clear(&g); + + return res; +} + +/* modular inverse where modulus is 2**k. */ +/* c = a**-1 mod 2**k */ +mp_err s_mp_invmod_2d(const mp_int *a, mp_size k, mp_int *c) +{ + mp_err res; + mp_size ix = k + 4; + mp_int t0, t1, val, tmp, two2k; + + static const mp_digit d2 = 2; + static const mp_int two = { 0, MP_ZPOS, 1, 1, (mp_digit *)&d2 }; + + if (mp_iseven(a)) + return MP_UNDEF; + if (k <= MP_DIGIT_BIT) { + mp_digit i = s_mp_invmod_radix(MP_DIGIT(a,0)); + if (k < MP_DIGIT_BIT) + i &= ((mp_digit)1 << k) - (mp_digit)1; + mp_set(c, i); + return MP_OKAY; + } + MP_DIGITS(&t0) = 0; + MP_DIGITS(&t1) = 0; + MP_DIGITS(&val) = 0; + MP_DIGITS(&tmp) = 0; + MP_DIGITS(&two2k) = 0; + MP_CHECKOK( mp_init_copy(&val, a) ); + s_mp_mod_2d(&val, k); + MP_CHECKOK( mp_init_copy(&t0, &val) ); + MP_CHECKOK( mp_init_copy(&t1, &t0) ); + MP_CHECKOK( mp_init(&tmp, FLAG(a)) ); + MP_CHECKOK( mp_init(&two2k, FLAG(a)) ); + MP_CHECKOK( s_mp_2expt(&two2k, k) ); + do { + MP_CHECKOK( mp_mul(&val, &t1, &tmp) ); + MP_CHECKOK( mp_sub(&two, &tmp, &tmp) ); + MP_CHECKOK( mp_mul(&t1, &tmp, &t1) ); + s_mp_mod_2d(&t1, k); + while (MP_SIGN(&t1) != MP_ZPOS) { + MP_CHECKOK( mp_add(&t1, &two2k, &t1) ); + } + if (mp_cmp(&t1, &t0) == MP_EQ) + break; + MP_CHECKOK( mp_copy(&t1, &t0) ); + } while (--ix > 0); + if (!ix) { + res = MP_UNDEF; + } else { + mp_exch(c, &t1); + } + +CLEANUP: + mp_clear(&t0); + mp_clear(&t1); + mp_clear(&val); + mp_clear(&tmp); + mp_clear(&two2k); + return res; +} + +mp_err s_mp_invmod_even_m(const mp_int *a, const mp_int *m, mp_int *c) +{ + mp_err res; + mp_size k; + mp_int oddFactor, evenFactor; /* factors of the modulus */ + mp_int oddPart, evenPart; /* parts to combine via CRT. */ + mp_int C2, tmp1, tmp2; + + /*static const mp_digit d1 = 1; */ + /*static const mp_int one = { MP_ZPOS, 1, 1, (mp_digit *)&d1 }; */ + + if ((res = s_mp_ispow2(m)) >= 0) { + k = res; + return s_mp_invmod_2d(a, k, c); + } + MP_DIGITS(&oddFactor) = 0; + MP_DIGITS(&evenFactor) = 0; + MP_DIGITS(&oddPart) = 0; + MP_DIGITS(&evenPart) = 0; + MP_DIGITS(&C2) = 0; + MP_DIGITS(&tmp1) = 0; + MP_DIGITS(&tmp2) = 0; + + MP_CHECKOK( mp_init_copy(&oddFactor, m) ); /* oddFactor = m */ + MP_CHECKOK( mp_init(&evenFactor, FLAG(m)) ); + MP_CHECKOK( mp_init(&oddPart, FLAG(m)) ); + MP_CHECKOK( mp_init(&evenPart, FLAG(m)) ); + MP_CHECKOK( mp_init(&C2, FLAG(m)) ); + MP_CHECKOK( mp_init(&tmp1, FLAG(m)) ); + MP_CHECKOK( mp_init(&tmp2, FLAG(m)) ); + + k = mp_trailing_zeros(m); + s_mp_div_2d(&oddFactor, k); + MP_CHECKOK( s_mp_2expt(&evenFactor, k) ); + + /* compute a**-1 mod oddFactor. */ + MP_CHECKOK( s_mp_invmod_odd_m(a, &oddFactor, &oddPart) ); + /* compute a**-1 mod evenFactor, where evenFactor == 2**k. */ + MP_CHECKOK( s_mp_invmod_2d( a, k, &evenPart) ); + + /* Use Chinese Remainer theorem to compute a**-1 mod m. */ + /* let m1 = oddFactor, v1 = oddPart, + * let m2 = evenFactor, v2 = evenPart. + */ + + /* Compute C2 = m1**-1 mod m2. */ + MP_CHECKOK( s_mp_invmod_2d(&oddFactor, k, &C2) ); + + /* compute u = (v2 - v1)*C2 mod m2 */ + MP_CHECKOK( mp_sub(&evenPart, &oddPart, &tmp1) ); + MP_CHECKOK( mp_mul(&tmp1, &C2, &tmp2) ); + s_mp_mod_2d(&tmp2, k); + while (MP_SIGN(&tmp2) != MP_ZPOS) { + MP_CHECKOK( mp_add(&tmp2, &evenFactor, &tmp2) ); + } + + /* compute answer = v1 + u*m1 */ + MP_CHECKOK( mp_mul(&tmp2, &oddFactor, c) ); + MP_CHECKOK( mp_add(&oddPart, c, c) ); + /* not sure this is necessary, but it's low cost if not. */ + MP_CHECKOK( mp_mod(c, m, c) ); + +CLEANUP: + mp_clear(&oddFactor); + mp_clear(&evenFactor); + mp_clear(&oddPart); + mp_clear(&evenPart); + mp_clear(&C2); + mp_clear(&tmp1); + mp_clear(&tmp2); + return res; +} + + +/* {{{ mp_invmod(a, m, c) */ + +/* + mp_invmod(a, m, c) + + Compute c = a^-1 (mod m), if there is an inverse for a (mod m). + This is equivalent to the question of whether (a, m) = 1. If not, + MP_UNDEF is returned, and there is no inverse. + */ + +mp_err mp_invmod(const mp_int *a, const mp_int *m, mp_int *c) +{ + + ARGCHK(a && m && c, MP_BADARG); + + if(mp_cmp_z(a) == 0 || mp_cmp_z(m) == 0) + return MP_RANGE; + + if (mp_isodd(m)) { + return s_mp_invmod_odd_m(a, m, c); + } + if (mp_iseven(a)) + return MP_UNDEF; /* not invertable */ + + return s_mp_invmod_even_m(a, m, c); + +} /* end mp_invmod() */ + +/* }}} */ +#endif /* if MP_NUMTH */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ mp_print(mp, ofp) */ + +#if MP_IOFUNC +/* + mp_print(mp, ofp) + + Print a textual representation of the given mp_int on the output + stream 'ofp'. Output is generated using the internal radix. + */ + +void mp_print(mp_int *mp, FILE *ofp) +{ + int ix; + + if(mp == NULL || ofp == NULL) + return; + + fputc((SIGN(mp) == NEG) ? '-' : '+', ofp); + + for(ix = USED(mp) - 1; ix >= 0; ix--) { + fprintf(ofp, DIGIT_FMT, DIGIT(mp, ix)); + } + +} /* end mp_print() */ + +#endif /* if MP_IOFUNC */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* {{{ More I/O Functions */ + +/* {{{ mp_read_raw(mp, str, len) */ + +/* + mp_read_raw(mp, str, len) + + Read in a raw value (base 256) into the given mp_int + */ + +mp_err mp_read_raw(mp_int *mp, char *str, int len) +{ + int ix; + mp_err res; + unsigned char *ustr = (unsigned char *)str; + + ARGCHK(mp != NULL && str != NULL && len > 0, MP_BADARG); + + mp_zero(mp); + + /* Get sign from first byte */ + if(ustr[0]) + SIGN(mp) = NEG; + else + SIGN(mp) = ZPOS; + + /* Read the rest of the digits */ + for(ix = 1; ix < len; ix++) { + if((res = mp_mul_d(mp, 256, mp)) != MP_OKAY) + return res; + if((res = mp_add_d(mp, ustr[ix], mp)) != MP_OKAY) + return res; + } + + return MP_OKAY; + +} /* end mp_read_raw() */ + +/* }}} */ + +/* {{{ mp_raw_size(mp) */ + +int mp_raw_size(mp_int *mp) +{ + ARGCHK(mp != NULL, 0); + + return (USED(mp) * sizeof(mp_digit)) + 1; + +} /* end mp_raw_size() */ + +/* }}} */ + +/* {{{ mp_toraw(mp, str) */ + +mp_err mp_toraw(mp_int *mp, char *str) +{ + int ix, jx, pos = 1; + + ARGCHK(mp != NULL && str != NULL, MP_BADARG); + + str[0] = (char)SIGN(mp); + + /* Iterate over each digit... */ + for(ix = USED(mp) - 1; ix >= 0; ix--) { + mp_digit d = DIGIT(mp, ix); + + /* Unpack digit bytes, high order first */ + for(jx = sizeof(mp_digit) - 1; jx >= 0; jx--) { + str[pos++] = (char)(d >> (jx * CHAR_BIT)); + } + } + + return MP_OKAY; + +} /* end mp_toraw() */ + +/* }}} */ + +/* {{{ mp_read_radix(mp, str, radix) */ + +/* + mp_read_radix(mp, str, radix) + + Read an integer from the given string, and set mp to the resulting + value. The input is presumed to be in base 10. Leading non-digit + characters are ignored, and the function reads until a non-digit + character or the end of the string. + */ + +mp_err mp_read_radix(mp_int *mp, const char *str, int radix) +{ + int ix = 0, val = 0; + mp_err res; + mp_sign sig = ZPOS; + + ARGCHK(mp != NULL && str != NULL && radix >= 2 && radix <= MAX_RADIX, + MP_BADARG); + + mp_zero(mp); + + /* Skip leading non-digit characters until a digit or '-' or '+' */ + while(str[ix] && + (s_mp_tovalue(str[ix], radix) < 0) && + str[ix] != '-' && + str[ix] != '+') { + ++ix; + } + + if(str[ix] == '-') { + sig = NEG; + ++ix; + } else if(str[ix] == '+') { + sig = ZPOS; /* this is the default anyway... */ + ++ix; + } + + while((val = s_mp_tovalue(str[ix], radix)) >= 0) { + if((res = s_mp_mul_d(mp, radix)) != MP_OKAY) + return res; + if((res = s_mp_add_d(mp, val)) != MP_OKAY) + return res; + ++ix; + } + + if(s_mp_cmp_d(mp, 0) == MP_EQ) + SIGN(mp) = ZPOS; + else + SIGN(mp) = sig; + + return MP_OKAY; + +} /* end mp_read_radix() */ + +mp_err mp_read_variable_radix(mp_int *a, const char * str, int default_radix) +{ + int radix = default_radix; + int cx; + mp_sign sig = ZPOS; + mp_err res; + + /* Skip leading non-digit characters until a digit or '-' or '+' */ + while ((cx = *str) != 0 && + (s_mp_tovalue(cx, radix) < 0) && + cx != '-' && + cx != '+') { + ++str; + } + + if (cx == '-') { + sig = NEG; + ++str; + } else if (cx == '+') { + sig = ZPOS; /* this is the default anyway... */ + ++str; + } + + if (str[0] == '0') { + if ((str[1] | 0x20) == 'x') { + radix = 16; + str += 2; + } else { + radix = 8; + str++; + } + } + res = mp_read_radix(a, str, radix); + if (res == MP_OKAY) { + MP_SIGN(a) = (s_mp_cmp_d(a, 0) == MP_EQ) ? ZPOS : sig; + } + return res; +} + +/* }}} */ + +/* {{{ mp_radix_size(mp, radix) */ + +int mp_radix_size(mp_int *mp, int radix) +{ + int bits; + + if(!mp || radix < 2 || radix > MAX_RADIX) + return 0; + + bits = USED(mp) * DIGIT_BIT - 1; + + return s_mp_outlen(bits, radix); + +} /* end mp_radix_size() */ + +/* }}} */ + +/* {{{ mp_toradix(mp, str, radix) */ + +mp_err mp_toradix(mp_int *mp, char *str, int radix) +{ + int ix, pos = 0; + + ARGCHK(mp != NULL && str != NULL, MP_BADARG); + ARGCHK(radix > 1 && radix <= MAX_RADIX, MP_RANGE); + + if(mp_cmp_z(mp) == MP_EQ) { + str[0] = '0'; + str[1] = '\0'; + } else { + mp_err res; + mp_int tmp; + mp_sign sgn; + mp_digit rem, rdx = (mp_digit)radix; + char ch; + + if((res = mp_init_copy(&tmp, mp)) != MP_OKAY) + return res; + + /* Save sign for later, and take absolute value */ + sgn = SIGN(&tmp); SIGN(&tmp) = ZPOS; + + /* Generate output digits in reverse order */ + while(mp_cmp_z(&tmp) != 0) { + if((res = mp_div_d(&tmp, rdx, &tmp, &rem)) != MP_OKAY) { + mp_clear(&tmp); + return res; + } + + /* Generate digits, use capital letters */ + ch = s_mp_todigit(rem, radix, 0); + + str[pos++] = ch; + } + + /* Add - sign if original value was negative */ + if(sgn == NEG) + str[pos++] = '-'; + + /* Add trailing NUL to end the string */ + str[pos--] = '\0'; + + /* Reverse the digits and sign indicator */ + ix = 0; + while(ix < pos) { + char tmp = str[ix]; + + str[ix] = str[pos]; + str[pos] = tmp; + ++ix; + --pos; + } + + mp_clear(&tmp); + } + + return MP_OKAY; + +} /* end mp_toradix() */ + +/* }}} */ + +/* {{{ mp_tovalue(ch, r) */ + +int mp_tovalue(char ch, int r) +{ + return s_mp_tovalue(ch, r); + +} /* end mp_tovalue() */ + +/* }}} */ + +/* }}} */ + +/* {{{ mp_strerror(ec) */ + +/* + mp_strerror(ec) + + Return a string describing the meaning of error code 'ec'. The + string returned is allocated in static memory, so the caller should + not attempt to modify or free the memory associated with this + string. + */ +const char *mp_strerror(mp_err ec) +{ + int aec = (ec < 0) ? -ec : ec; + + /* Code values are negative, so the senses of these comparisons + are accurate */ + if(ec < MP_LAST_CODE || ec > MP_OKAY) { + return mp_err_string[0]; /* unknown error code */ + } else { + return mp_err_string[aec + 1]; + } + +} /* end mp_strerror() */ + +/* }}} */ + +/*========================================================================*/ +/*------------------------------------------------------------------------*/ +/* Static function definitions (internal use only) */ + +/* {{{ Memory management */ + +/* {{{ s_mp_grow(mp, min) */ + +/* Make sure there are at least 'min' digits allocated to mp */ +mp_err s_mp_grow(mp_int *mp, mp_size min) +{ + if(min > ALLOC(mp)) { + mp_digit *tmp; + + /* Set min to next nearest default precision block size */ + min = MP_ROUNDUP(min, s_mp_defprec); + + if((tmp = s_mp_alloc(min, sizeof(mp_digit), FLAG(mp))) == NULL) + return MP_MEM; + + s_mp_copy(DIGITS(mp), tmp, USED(mp)); + +#if MP_CRYPTO + s_mp_setz(DIGITS(mp), ALLOC(mp)); +#endif + s_mp_free(DIGITS(mp), ALLOC(mp)); + DIGITS(mp) = tmp; + ALLOC(mp) = min; + } + + return MP_OKAY; + +} /* end s_mp_grow() */ + +/* }}} */ + +/* {{{ s_mp_pad(mp, min) */ + +/* Make sure the used size of mp is at least 'min', growing if needed */ +mp_err s_mp_pad(mp_int *mp, mp_size min) +{ + if(min > USED(mp)) { + mp_err res; + + /* Make sure there is room to increase precision */ + if (min > ALLOC(mp)) { + if ((res = s_mp_grow(mp, min)) != MP_OKAY) + return res; + } else { + s_mp_setz(DIGITS(mp) + USED(mp), min - USED(mp)); + } + + /* Increase precision; should already be 0-filled */ + USED(mp) = min; + } + + return MP_OKAY; + +} /* end s_mp_pad() */ + +/* }}} */ + +/* {{{ s_mp_setz(dp, count) */ + +#if MP_MACRO == 0 +/* Set 'count' digits pointed to by dp to be zeroes */ +void s_mp_setz(mp_digit *dp, mp_size count) +{ +#if MP_MEMSET == 0 + int ix; + + for(ix = 0; ix < count; ix++) + dp[ix] = 0; +#else + memset(dp, 0, count * sizeof(mp_digit)); +#endif + +} /* end s_mp_setz() */ +#endif + +/* }}} */ + +/* {{{ s_mp_copy(sp, dp, count) */ + +#if MP_MACRO == 0 +/* Copy 'count' digits from sp to dp */ +void s_mp_copy(const mp_digit *sp, mp_digit *dp, mp_size count) +{ +#if MP_MEMCPY == 0 + int ix; + + for(ix = 0; ix < count; ix++) + dp[ix] = sp[ix]; +#else + memcpy(dp, sp, count * sizeof(mp_digit)); +#endif + +} /* end s_mp_copy() */ +#endif + +/* }}} */ + +/* {{{ s_mp_alloc(nb, ni, kmflag) */ + +#if MP_MACRO == 0 +/* Allocate ni records of nb bytes each, and return a pointer to that */ +void *s_mp_alloc(size_t nb, size_t ni, int kmflag) +{ + mp_int *mp; + ++mp_allocs; +#ifdef _KERNEL + mp = kmem_zalloc(nb * ni, kmflag); + if (mp != NULL) + FLAG(mp) = kmflag; + return (mp); +#else + return calloc(nb, ni); +#endif + +} /* end s_mp_alloc() */ +#endif + +/* }}} */ + +/* {{{ s_mp_free(ptr) */ + +#if MP_MACRO == 0 +/* Free the memory pointed to by ptr */ +void s_mp_free(void *ptr, mp_size alloc) +{ + if(ptr) { + ++mp_frees; +#ifdef _KERNEL + kmem_free(ptr, alloc * sizeof (mp_digit)); +#else + free(ptr); +#endif + } +} /* end s_mp_free() */ +#endif + +/* }}} */ + +/* {{{ s_mp_clamp(mp) */ + +#if MP_MACRO == 0 +/* Remove leading zeroes from the given value */ +void s_mp_clamp(mp_int *mp) +{ + mp_size used = MP_USED(mp); + while (used > 1 && DIGIT(mp, used - 1) == 0) + --used; + MP_USED(mp) = used; +} /* end s_mp_clamp() */ +#endif + +/* }}} */ + +/* {{{ s_mp_exch(a, b) */ + +/* Exchange the data for a and b; (b, a) = (a, b) */ +void s_mp_exch(mp_int *a, mp_int *b) +{ + mp_int tmp; + + tmp = *a; + *a = *b; + *b = tmp; + +} /* end s_mp_exch() */ + +/* }}} */ + +/* }}} */ + +/* {{{ Arithmetic helpers */ + +/* {{{ s_mp_lshd(mp, p) */ + +/* + Shift mp leftward by p digits, growing if needed, and zero-filling + the in-shifted digits at the right end. This is a convenient + alternative to multiplication by powers of the radix + The value of USED(mp) must already have been set to the value for + the shifted result. + */ + +mp_err s_mp_lshd(mp_int *mp, mp_size p) +{ + mp_err res; + mp_size pos; + int ix; + + if(p == 0) + return MP_OKAY; + + if (MP_USED(mp) == 1 && MP_DIGIT(mp, 0) == 0) + return MP_OKAY; + + if((res = s_mp_pad(mp, USED(mp) + p)) != MP_OKAY) + return res; + + pos = USED(mp) - 1; + + /* Shift all the significant figures over as needed */ + for(ix = pos - p; ix >= 0; ix--) + DIGIT(mp, ix + p) = DIGIT(mp, ix); + + /* Fill the bottom digits with zeroes */ + for(ix = 0; ix < p; ix++) + DIGIT(mp, ix) = 0; + + return MP_OKAY; + +} /* end s_mp_lshd() */ + +/* }}} */ + +/* {{{ s_mp_mul_2d(mp, d) */ + +/* + Multiply the integer by 2^d, where d is a number of bits. This + amounts to a bitwise shift of the value. + */ +mp_err s_mp_mul_2d(mp_int *mp, mp_digit d) +{ + mp_err res; + mp_digit dshift, bshift; + mp_digit mask; + + ARGCHK(mp != NULL, MP_BADARG); + + dshift = d / MP_DIGIT_BIT; + bshift = d % MP_DIGIT_BIT; + /* bits to be shifted out of the top word */ + mask = ((mp_digit)~0 << (MP_DIGIT_BIT - bshift)); + mask &= MP_DIGIT(mp, MP_USED(mp) - 1); + + if (MP_OKAY != (res = s_mp_pad(mp, MP_USED(mp) + dshift + (mask != 0) ))) + return res; + + if (dshift && MP_OKAY != (res = s_mp_lshd(mp, dshift))) + return res; + + if (bshift) { + mp_digit *pa = MP_DIGITS(mp); + mp_digit *alim = pa + MP_USED(mp); + mp_digit prev = 0; + + for (pa += dshift; pa < alim; ) { + mp_digit x = *pa; + *pa++ = (x << bshift) | prev; + prev = x >> (DIGIT_BIT - bshift); + } + } + + s_mp_clamp(mp); + return MP_OKAY; +} /* end s_mp_mul_2d() */ + +/* {{{ s_mp_rshd(mp, p) */ + +/* + Shift mp rightward by p digits. Maintains the invariant that + digits above the precision are all zero. Digits shifted off the + end are lost. Cannot fail. + */ + +void s_mp_rshd(mp_int *mp, mp_size p) +{ + mp_size ix; + mp_digit *src, *dst; + + if(p == 0) + return; + + /* Shortcut when all digits are to be shifted off */ + if(p >= USED(mp)) { + s_mp_setz(DIGITS(mp), ALLOC(mp)); + USED(mp) = 1; + SIGN(mp) = ZPOS; + return; + } + + /* Shift all the significant figures over as needed */ + dst = MP_DIGITS(mp); + src = dst + p; + for (ix = USED(mp) - p; ix > 0; ix--) + *dst++ = *src++; + + MP_USED(mp) -= p; + /* Fill the top digits with zeroes */ + while (p-- > 0) + *dst++ = 0; + +#if 0 + /* Strip off any leading zeroes */ + s_mp_clamp(mp); +#endif + +} /* end s_mp_rshd() */ + +/* }}} */ + +/* {{{ s_mp_div_2(mp) */ + +/* Divide by two -- take advantage of radix properties to do it fast */ +void s_mp_div_2(mp_int *mp) +{ + s_mp_div_2d(mp, 1); + +} /* end s_mp_div_2() */ + +/* }}} */ + +/* {{{ s_mp_mul_2(mp) */ + +mp_err s_mp_mul_2(mp_int *mp) +{ + mp_digit *pd; + int ix, used; + mp_digit kin = 0; + + /* Shift digits leftward by 1 bit */ + used = MP_USED(mp); + pd = MP_DIGITS(mp); + for (ix = 0; ix < used; ix++) { + mp_digit d = *pd; + *pd++ = (d << 1) | kin; + kin = (d >> (DIGIT_BIT - 1)); + } + + /* Deal with rollover from last digit */ + if (kin) { + if (ix >= ALLOC(mp)) { + mp_err res; + if((res = s_mp_grow(mp, ALLOC(mp) + 1)) != MP_OKAY) + return res; + } + + DIGIT(mp, ix) = kin; + USED(mp) += 1; + } + + return MP_OKAY; + +} /* end s_mp_mul_2() */ + +/* }}} */ + +/* {{{ s_mp_mod_2d(mp, d) */ + +/* + Remainder the integer by 2^d, where d is a number of bits. This + amounts to a bitwise AND of the value, and does not require the full + division code + */ +void s_mp_mod_2d(mp_int *mp, mp_digit d) +{ + mp_size ndig = (d / DIGIT_BIT), nbit = (d % DIGIT_BIT); + mp_size ix; + mp_digit dmask; + + if(ndig >= USED(mp)) + return; + + /* Flush all the bits above 2^d in its digit */ + dmask = ((mp_digit)1 << nbit) - 1; + DIGIT(mp, ndig) &= dmask; + + /* Flush all digits above the one with 2^d in it */ + for(ix = ndig + 1; ix < USED(mp); ix++) + DIGIT(mp, ix) = 0; + + s_mp_clamp(mp); + +} /* end s_mp_mod_2d() */ + +/* }}} */ + +/* {{{ s_mp_div_2d(mp, d) */ + +/* + Divide the integer by 2^d, where d is a number of bits. This + amounts to a bitwise shift of the value, and does not require the + full division code (used in Barrett reduction, see below) + */ +void s_mp_div_2d(mp_int *mp, mp_digit d) +{ + int ix; + mp_digit save, next, mask; + + s_mp_rshd(mp, d / DIGIT_BIT); + d %= DIGIT_BIT; + if (d) { + mask = ((mp_digit)1 << d) - 1; + save = 0; + for(ix = USED(mp) - 1; ix >= 0; ix--) { + next = DIGIT(mp, ix) & mask; + DIGIT(mp, ix) = (DIGIT(mp, ix) >> d) | (save << (DIGIT_BIT - d)); + save = next; + } + } + s_mp_clamp(mp); + +} /* end s_mp_div_2d() */ + +/* }}} */ + +/* {{{ s_mp_norm(a, b, *d) */ + +/* + s_mp_norm(a, b, *d) + + Normalize a and b for division, where b is the divisor. In order + that we might make good guesses for quotient digits, we want the + leading digit of b to be at least half the radix, which we + accomplish by multiplying a and b by a power of 2. The exponent + (shift count) is placed in *pd, so that the remainder can be shifted + back at the end of the division process. + */ + +mp_err s_mp_norm(mp_int *a, mp_int *b, mp_digit *pd) +{ + mp_digit d; + mp_digit mask; + mp_digit b_msd; + mp_err res = MP_OKAY; + + d = 0; + mask = DIGIT_MAX & ~(DIGIT_MAX >> 1); /* mask is msb of digit */ + b_msd = DIGIT(b, USED(b) - 1); + while (!(b_msd & mask)) { + b_msd <<= 1; + ++d; + } + + if (d) { + MP_CHECKOK( s_mp_mul_2d(a, d) ); + MP_CHECKOK( s_mp_mul_2d(b, d) ); + } + + *pd = d; +CLEANUP: + return res; + +} /* end s_mp_norm() */ + +/* }}} */ + +/* }}} */ + +/* {{{ Primitive digit arithmetic */ + +/* {{{ s_mp_add_d(mp, d) */ + +/* Add d to |mp| in place */ +mp_err s_mp_add_d(mp_int *mp, mp_digit d) /* unsigned digit addition */ +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + mp_word w, k = 0; + mp_size ix = 1; + + w = (mp_word)DIGIT(mp, 0) + d; + DIGIT(mp, 0) = ACCUM(w); + k = CARRYOUT(w); + + while(ix < USED(mp) && k) { + w = (mp_word)DIGIT(mp, ix) + k; + DIGIT(mp, ix) = ACCUM(w); + k = CARRYOUT(w); + ++ix; + } + + if(k != 0) { + mp_err res; + + if((res = s_mp_pad(mp, USED(mp) + 1)) != MP_OKAY) + return res; + + DIGIT(mp, ix) = (mp_digit)k; + } + + return MP_OKAY; +#else + mp_digit * pmp = MP_DIGITS(mp); + mp_digit sum, mp_i, carry = 0; + mp_err res = MP_OKAY; + int used = (int)MP_USED(mp); + + mp_i = *pmp; + *pmp++ = sum = d + mp_i; + carry = (sum < d); + while (carry && --used > 0) { + mp_i = *pmp; + *pmp++ = sum = carry + mp_i; + carry = !sum; + } + if (carry && !used) { + /* mp is growing */ + used = MP_USED(mp); + MP_CHECKOK( s_mp_pad(mp, used + 1) ); + MP_DIGIT(mp, used) = carry; + } +CLEANUP: + return res; +#endif +} /* end s_mp_add_d() */ + +/* }}} */ + +/* {{{ s_mp_sub_d(mp, d) */ + +/* Subtract d from |mp| in place, assumes |mp| > d */ +mp_err s_mp_sub_d(mp_int *mp, mp_digit d) /* unsigned digit subtract */ +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + mp_word w, b = 0; + mp_size ix = 1; + + /* Compute initial subtraction */ + w = (RADIX + (mp_word)DIGIT(mp, 0)) - d; + b = CARRYOUT(w) ? 0 : 1; + DIGIT(mp, 0) = ACCUM(w); + + /* Propagate borrows leftward */ + while(b && ix < USED(mp)) { + w = (RADIX + (mp_word)DIGIT(mp, ix)) - b; + b = CARRYOUT(w) ? 0 : 1; + DIGIT(mp, ix) = ACCUM(w); + ++ix; + } + + /* Remove leading zeroes */ + s_mp_clamp(mp); + + /* If we have a borrow out, it's a violation of the input invariant */ + if(b) + return MP_RANGE; + else + return MP_OKAY; +#else + mp_digit *pmp = MP_DIGITS(mp); + mp_digit mp_i, diff, borrow; + mp_size used = MP_USED(mp); + + mp_i = *pmp; + *pmp++ = diff = mp_i - d; + borrow = (diff > mp_i); + while (borrow && --used) { + mp_i = *pmp; + *pmp++ = diff = mp_i - borrow; + borrow = (diff > mp_i); + } + s_mp_clamp(mp); + return (borrow && !used) ? MP_RANGE : MP_OKAY; +#endif +} /* end s_mp_sub_d() */ + +/* }}} */ + +/* {{{ s_mp_mul_d(a, d) */ + +/* Compute a = a * d, single digit multiplication */ +mp_err s_mp_mul_d(mp_int *a, mp_digit d) +{ + mp_err res; + mp_size used; + int pow; + + if (!d) { + mp_zero(a); + return MP_OKAY; + } + if (d == 1) + return MP_OKAY; + if (0 <= (pow = s_mp_ispow2d(d))) { + return s_mp_mul_2d(a, (mp_digit)pow); + } + + used = MP_USED(a); + MP_CHECKOK( s_mp_pad(a, used + 1) ); + + s_mpv_mul_d(MP_DIGITS(a), used, d, MP_DIGITS(a)); + + s_mp_clamp(a); + +CLEANUP: + return res; + +} /* end s_mp_mul_d() */ + +/* }}} */ + +/* {{{ s_mp_div_d(mp, d, r) */ + +/* + s_mp_div_d(mp, d, r) + + Compute the quotient mp = mp / d and remainder r = mp mod d, for a + single digit d. If r is null, the remainder will be discarded. + */ + +mp_err s_mp_div_d(mp_int *mp, mp_digit d, mp_digit *r) +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_DIV_WORD) + mp_word w = 0, q; +#else + mp_digit w, q; +#endif + int ix; + mp_err res; + mp_int quot; + mp_int rem; + + if(d == 0) + return MP_RANGE; + if (d == 1) { + if (r) + *r = 0; + return MP_OKAY; + } + /* could check for power of 2 here, but mp_div_d does that. */ + if (MP_USED(mp) == 1) { + mp_digit n = MP_DIGIT(mp,0); + mp_digit rem; + + q = n / d; + rem = n % d; + MP_DIGIT(mp,0) = q; + if (r) + *r = rem; + return MP_OKAY; + } + + MP_DIGITS(&rem) = 0; + MP_DIGITS(") = 0; + /* Make room for the quotient */ + MP_CHECKOK( mp_init_size(", USED(mp), FLAG(mp)) ); + +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_DIV_WORD) + for(ix = USED(mp) - 1; ix >= 0; ix--) { + w = (w << DIGIT_BIT) | DIGIT(mp, ix); + + if(w >= d) { + q = w / d; + w = w % d; + } else { + q = 0; + } + + s_mp_lshd(", 1); + DIGIT(", 0) = (mp_digit)q; + } +#else + { + mp_digit p; +#if !defined(MP_ASSEMBLY_DIV_2DX1D) + mp_digit norm; +#endif + + MP_CHECKOK( mp_init_copy(&rem, mp) ); + +#if !defined(MP_ASSEMBLY_DIV_2DX1D) + MP_DIGIT(", 0) = d; + MP_CHECKOK( s_mp_norm(&rem, ", &norm) ); + if (norm) + d <<= norm; + MP_DIGIT(", 0) = 0; +#endif + + p = 0; + for (ix = USED(&rem) - 1; ix >= 0; ix--) { + w = DIGIT(&rem, ix); + + if (p) { + MP_CHECKOK( s_mpv_div_2dx1d(p, w, d, &q, &w) ); + } else if (w >= d) { + q = w / d; + w = w % d; + } else { + q = 0; + } + + MP_CHECKOK( s_mp_lshd(", 1) ); + DIGIT(", 0) = q; + p = w; + } +#if !defined(MP_ASSEMBLY_DIV_2DX1D) + if (norm) + w >>= norm; +#endif + } +#endif + + /* Deliver the remainder, if desired */ + if(r) + *r = (mp_digit)w; + + s_mp_clamp("); + mp_exch(", mp); +CLEANUP: + mp_clear("); + mp_clear(&rem); + + return res; +} /* end s_mp_div_d() */ + +/* }}} */ + + +/* }}} */ + +/* {{{ Primitive full arithmetic */ + +/* {{{ s_mp_add(a, b) */ + +/* Compute a = |a| + |b| */ +mp_err s_mp_add(mp_int *a, const mp_int *b) /* magnitude addition */ +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + mp_word w = 0; +#else + mp_digit d, sum, carry = 0; +#endif + mp_digit *pa, *pb; + mp_size ix; + mp_size used; + mp_err res; + + /* Make sure a has enough precision for the output value */ + if((USED(b) > USED(a)) && (res = s_mp_pad(a, USED(b))) != MP_OKAY) + return res; + + /* + Add up all digits up to the precision of b. If b had initially + the same precision as a, or greater, we took care of it by the + padding step above, so there is no problem. If b had initially + less precision, we'll have to make sure the carry out is duly + propagated upward among the higher-order digits of the sum. + */ + pa = MP_DIGITS(a); + pb = MP_DIGITS(b); + used = MP_USED(b); + for(ix = 0; ix < used; ix++) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + w = w + *pa + *pb++; + *pa++ = ACCUM(w); + w = CARRYOUT(w); +#else + d = *pa; + sum = d + *pb++; + d = (sum < d); /* detect overflow */ + *pa++ = sum += carry; + carry = d + (sum < carry); /* detect overflow */ +#endif + } + + /* If we run out of 'b' digits before we're actually done, make + sure the carries get propagated upward... + */ + used = MP_USED(a); +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + while (w && ix < used) { + w = w + *pa; + *pa++ = ACCUM(w); + w = CARRYOUT(w); + ++ix; + } +#else + while (carry && ix < used) { + sum = carry + *pa; + *pa++ = sum; + carry = !sum; + ++ix; + } +#endif + + /* If there's an overall carry out, increase precision and include + it. We could have done this initially, but why touch the memory + allocator unless we're sure we have to? + */ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + if (w) { + if((res = s_mp_pad(a, used + 1)) != MP_OKAY) + return res; + + DIGIT(a, ix) = (mp_digit)w; + } +#else + if (carry) { + if((res = s_mp_pad(a, used + 1)) != MP_OKAY) + return res; + + DIGIT(a, used) = carry; + } +#endif + + return MP_OKAY; +} /* end s_mp_add() */ + +/* }}} */ + +/* Compute c = |a| + |b| */ /* magnitude addition */ +mp_err s_mp_add_3arg(const mp_int *a, const mp_int *b, mp_int *c) +{ + mp_digit *pa, *pb, *pc; +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + mp_word w = 0; +#else + mp_digit sum, carry = 0, d; +#endif + mp_size ix; + mp_size used; + mp_err res; + + MP_SIGN(c) = MP_SIGN(a); + if (MP_USED(a) < MP_USED(b)) { + const mp_int *xch = a; + a = b; + b = xch; + } + + /* Make sure a has enough precision for the output value */ + if (MP_OKAY != (res = s_mp_pad(c, MP_USED(a)))) + return res; + + /* + Add up all digits up to the precision of b. If b had initially + the same precision as a, or greater, we took care of it by the + exchange step above, so there is no problem. If b had initially + less precision, we'll have to make sure the carry out is duly + propagated upward among the higher-order digits of the sum. + */ + pa = MP_DIGITS(a); + pb = MP_DIGITS(b); + pc = MP_DIGITS(c); + used = MP_USED(b); + for (ix = 0; ix < used; ix++) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + w = w + *pa++ + *pb++; + *pc++ = ACCUM(w); + w = CARRYOUT(w); +#else + d = *pa++; + sum = d + *pb++; + d = (sum < d); /* detect overflow */ + *pc++ = sum += carry; + carry = d + (sum < carry); /* detect overflow */ +#endif + } + + /* If we run out of 'b' digits before we're actually done, make + sure the carries get propagated upward... + */ + for (used = MP_USED(a); ix < used; ++ix) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + w = w + *pa++; + *pc++ = ACCUM(w); + w = CARRYOUT(w); +#else + *pc++ = sum = carry + *pa++; + carry = (sum < carry); +#endif + } + + /* If there's an overall carry out, increase precision and include + it. We could have done this initially, but why touch the memory + allocator unless we're sure we have to? + */ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + if (w) { + if((res = s_mp_pad(c, used + 1)) != MP_OKAY) + return res; + + DIGIT(c, used) = (mp_digit)w; + ++used; + } +#else + if (carry) { + if((res = s_mp_pad(c, used + 1)) != MP_OKAY) + return res; + + DIGIT(c, used) = carry; + ++used; + } +#endif + MP_USED(c) = used; + return MP_OKAY; +} +/* {{{ s_mp_add_offset(a, b, offset) */ + +/* Compute a = |a| + ( |b| * (RADIX ** offset) ) */ +mp_err s_mp_add_offset(mp_int *a, mp_int *b, mp_size offset) +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + mp_word w, k = 0; +#else + mp_digit d, sum, carry = 0; +#endif + mp_size ib; + mp_size ia; + mp_size lim; + mp_err res; + + /* Make sure a has enough precision for the output value */ + lim = MP_USED(b) + offset; + if((lim > USED(a)) && (res = s_mp_pad(a, lim)) != MP_OKAY) + return res; + + /* + Add up all digits up to the precision of b. If b had initially + the same precision as a, or greater, we took care of it by the + padding step above, so there is no problem. If b had initially + less precision, we'll have to make sure the carry out is duly + propagated upward among the higher-order digits of the sum. + */ + lim = USED(b); + for(ib = 0, ia = offset; ib < lim; ib++, ia++) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + w = (mp_word)DIGIT(a, ia) + DIGIT(b, ib) + k; + DIGIT(a, ia) = ACCUM(w); + k = CARRYOUT(w); +#else + d = MP_DIGIT(a, ia); + sum = d + MP_DIGIT(b, ib); + d = (sum < d); + MP_DIGIT(a,ia) = sum += carry; + carry = d + (sum < carry); +#endif + } + + /* If we run out of 'b' digits before we're actually done, make + sure the carries get propagated upward... + */ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + for (lim = MP_USED(a); k && (ia < lim); ++ia) { + w = (mp_word)DIGIT(a, ia) + k; + DIGIT(a, ia) = ACCUM(w); + k = CARRYOUT(w); + } +#else + for (lim = MP_USED(a); carry && (ia < lim); ++ia) { + d = MP_DIGIT(a, ia); + MP_DIGIT(a,ia) = sum = d + carry; + carry = (sum < d); + } +#endif + + /* If there's an overall carry out, increase precision and include + it. We could have done this initially, but why touch the memory + allocator unless we're sure we have to? + */ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_ADD_WORD) + if(k) { + if((res = s_mp_pad(a, USED(a) + 1)) != MP_OKAY) + return res; + + DIGIT(a, ia) = (mp_digit)k; + } +#else + if (carry) { + if((res = s_mp_pad(a, lim + 1)) != MP_OKAY) + return res; + + DIGIT(a, lim) = carry; + } +#endif + s_mp_clamp(a); + + return MP_OKAY; + +} /* end s_mp_add_offset() */ + +/* }}} */ + +/* {{{ s_mp_sub(a, b) */ + +/* Compute a = |a| - |b|, assumes |a| >= |b| */ +mp_err s_mp_sub(mp_int *a, const mp_int *b) /* magnitude subtract */ +{ + mp_digit *pa, *pb, *limit; +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + mp_sword w = 0; +#else + mp_digit d, diff, borrow = 0; +#endif + + /* + Subtract and propagate borrow. Up to the precision of b, this + accounts for the digits of b; after that, we just make sure the + carries get to the right place. This saves having to pad b out to + the precision of a just to make the loops work right... + */ + pa = MP_DIGITS(a); + pb = MP_DIGITS(b); + limit = pb + MP_USED(b); + while (pb < limit) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + w = w + *pa - *pb++; + *pa++ = ACCUM(w); + w >>= MP_DIGIT_BIT; +#else + d = *pa; + diff = d - *pb++; + d = (diff > d); /* detect borrow */ + if (borrow && --diff == MP_DIGIT_MAX) + ++d; + *pa++ = diff; + borrow = d; +#endif + } + limit = MP_DIGITS(a) + MP_USED(a); +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + while (w && pa < limit) { + w = w + *pa; + *pa++ = ACCUM(w); + w >>= MP_DIGIT_BIT; + } +#else + while (borrow && pa < limit) { + d = *pa; + *pa++ = diff = d - borrow; + borrow = (diff > d); + } +#endif + + /* Clobber any leading zeroes we created */ + s_mp_clamp(a); + + /* + If there was a borrow out, then |b| > |a| in violation + of our input invariant. We've already done the work, + but we'll at least complain about it... + */ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + return w ? MP_RANGE : MP_OKAY; +#else + return borrow ? MP_RANGE : MP_OKAY; +#endif +} /* end s_mp_sub() */ + +/* }}} */ + +/* Compute c = |a| - |b|, assumes |a| >= |b| */ /* magnitude subtract */ +mp_err s_mp_sub_3arg(const mp_int *a, const mp_int *b, mp_int *c) +{ + mp_digit *pa, *pb, *pc; +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + mp_sword w = 0; +#else + mp_digit d, diff, borrow = 0; +#endif + int ix, limit; + mp_err res; + + MP_SIGN(c) = MP_SIGN(a); + + /* Make sure a has enough precision for the output value */ + if (MP_OKAY != (res = s_mp_pad(c, MP_USED(a)))) + return res; + + /* + Subtract and propagate borrow. Up to the precision of b, this + accounts for the digits of b; after that, we just make sure the + carries get to the right place. This saves having to pad b out to + the precision of a just to make the loops work right... + */ + pa = MP_DIGITS(a); + pb = MP_DIGITS(b); + pc = MP_DIGITS(c); + limit = MP_USED(b); + for (ix = 0; ix < limit; ++ix) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + w = w + *pa++ - *pb++; + *pc++ = ACCUM(w); + w >>= MP_DIGIT_BIT; +#else + d = *pa++; + diff = d - *pb++; + d = (diff > d); + if (borrow && --diff == MP_DIGIT_MAX) + ++d; + *pc++ = diff; + borrow = d; +#endif + } + for (limit = MP_USED(a); ix < limit; ++ix) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + w = w + *pa++; + *pc++ = ACCUM(w); + w >>= MP_DIGIT_BIT; +#else + d = *pa++; + *pc++ = diff = d - borrow; + borrow = (diff > d); +#endif + } + + /* Clobber any leading zeroes we created */ + MP_USED(c) = ix; + s_mp_clamp(c); + + /* + If there was a borrow out, then |b| > |a| in violation + of our input invariant. We've already done the work, + but we'll at least complain about it... + */ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_SUB_WORD) + return w ? MP_RANGE : MP_OKAY; +#else + return borrow ? MP_RANGE : MP_OKAY; +#endif +} +/* {{{ s_mp_mul(a, b) */ + +/* Compute a = |a| * |b| */ +mp_err s_mp_mul(mp_int *a, const mp_int *b) +{ + return mp_mul(a, b, a); +} /* end s_mp_mul() */ + +/* }}} */ + +#if defined(MP_USE_UINT_DIGIT) && defined(MP_USE_LONG_LONG_MULTIPLY) +/* This trick works on Sparc V8 CPUs with the Workshop compilers. */ +#define MP_MUL_DxD(a, b, Phi, Plo) \ + { unsigned long long product = (unsigned long long)a * b; \ + Plo = (mp_digit)product; \ + Phi = (mp_digit)(product >> MP_DIGIT_BIT); } +#elif defined(OSF1) +#define MP_MUL_DxD(a, b, Phi, Plo) \ + { Plo = asm ("mulq %a0, %a1, %v0", a, b);\ + Phi = asm ("umulh %a0, %a1, %v0", a, b); } +#else +#define MP_MUL_DxD(a, b, Phi, Plo) \ + { mp_digit a0b1, a1b0; \ + Plo = (a & MP_HALF_DIGIT_MAX) * (b & MP_HALF_DIGIT_MAX); \ + Phi = (a >> MP_HALF_DIGIT_BIT) * (b >> MP_HALF_DIGIT_BIT); \ + a0b1 = (a & MP_HALF_DIGIT_MAX) * (b >> MP_HALF_DIGIT_BIT); \ + a1b0 = (a >> MP_HALF_DIGIT_BIT) * (b & MP_HALF_DIGIT_MAX); \ + a1b0 += a0b1; \ + Phi += a1b0 >> MP_HALF_DIGIT_BIT; \ + if (a1b0 < a0b1) \ + Phi += MP_HALF_RADIX; \ + a1b0 <<= MP_HALF_DIGIT_BIT; \ + Plo += a1b0; \ + if (Plo < a1b0) \ + ++Phi; \ + } +#endif + +#if !defined(MP_ASSEMBLY_MULTIPLY) +/* c = a * b */ +void s_mpv_mul_d(const mp_digit *a, mp_size a_len, mp_digit b, mp_digit *c) +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_MUL_WORD) + mp_digit d = 0; + + /* Inner product: Digits of a */ + while (a_len--) { + mp_word w = ((mp_word)b * *a++) + d; + *c++ = ACCUM(w); + d = CARRYOUT(w); + } + *c = d; +#else + mp_digit carry = 0; + while (a_len--) { + mp_digit a_i = *a++; + mp_digit a0b0, a1b1; + + MP_MUL_DxD(a_i, b, a1b1, a0b0); + + a0b0 += carry; + if (a0b0 < carry) + ++a1b1; + *c++ = a0b0; + carry = a1b1; + } + *c = carry; +#endif +} + +/* c += a * b */ +void s_mpv_mul_d_add(const mp_digit *a, mp_size a_len, mp_digit b, + mp_digit *c) +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_MUL_WORD) + mp_digit d = 0; + + /* Inner product: Digits of a */ + while (a_len--) { + mp_word w = ((mp_word)b * *a++) + *c + d; + *c++ = ACCUM(w); + d = CARRYOUT(w); + } + *c = d; +#else + mp_digit carry = 0; + while (a_len--) { + mp_digit a_i = *a++; + mp_digit a0b0, a1b1; + + MP_MUL_DxD(a_i, b, a1b1, a0b0); + + a0b0 += carry; + if (a0b0 < carry) + ++a1b1; + a0b0 += a_i = *c; + if (a0b0 < a_i) + ++a1b1; + *c++ = a0b0; + carry = a1b1; + } + *c = carry; +#endif +} + +/* Presently, this is only used by the Montgomery arithmetic code. */ +/* c += a * b */ +void s_mpv_mul_d_add_prop(const mp_digit *a, mp_size a_len, mp_digit b, mp_digit *c) +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_MUL_WORD) + mp_digit d = 0; + + /* Inner product: Digits of a */ + while (a_len--) { + mp_word w = ((mp_word)b * *a++) + *c + d; + *c++ = ACCUM(w); + d = CARRYOUT(w); + } + + while (d) { + mp_word w = (mp_word)*c + d; + *c++ = ACCUM(w); + d = CARRYOUT(w); + } +#else + mp_digit carry = 0; + while (a_len--) { + mp_digit a_i = *a++; + mp_digit a0b0, a1b1; + + MP_MUL_DxD(a_i, b, a1b1, a0b0); + + a0b0 += carry; + if (a0b0 < carry) + ++a1b1; + + a0b0 += a_i = *c; + if (a0b0 < a_i) + ++a1b1; + + *c++ = a0b0; + carry = a1b1; + } + while (carry) { + mp_digit c_i = *c; + carry += c_i; + *c++ = carry; + carry = carry < c_i; + } +#endif +} +#endif + +#if defined(MP_USE_UINT_DIGIT) && defined(MP_USE_LONG_LONG_MULTIPLY) +/* This trick works on Sparc V8 CPUs with the Workshop compilers. */ +#define MP_SQR_D(a, Phi, Plo) \ + { unsigned long long square = (unsigned long long)a * a; \ + Plo = (mp_digit)square; \ + Phi = (mp_digit)(square >> MP_DIGIT_BIT); } +#elif defined(OSF1) +#define MP_SQR_D(a, Phi, Plo) \ + { Plo = asm ("mulq %a0, %a0, %v0", a);\ + Phi = asm ("umulh %a0, %a0, %v0", a); } +#else +#define MP_SQR_D(a, Phi, Plo) \ + { mp_digit Pmid; \ + Plo = (a & MP_HALF_DIGIT_MAX) * (a & MP_HALF_DIGIT_MAX); \ + Phi = (a >> MP_HALF_DIGIT_BIT) * (a >> MP_HALF_DIGIT_BIT); \ + Pmid = (a & MP_HALF_DIGIT_MAX) * (a >> MP_HALF_DIGIT_BIT); \ + Phi += Pmid >> (MP_HALF_DIGIT_BIT - 1); \ + Pmid <<= (MP_HALF_DIGIT_BIT + 1); \ + Plo += Pmid; \ + if (Plo < Pmid) \ + ++Phi; \ + } +#endif + +#if !defined(MP_ASSEMBLY_SQUARE) +/* Add the squares of the digits of a to the digits of b. */ +void s_mpv_sqr_add_prop(const mp_digit *pa, mp_size a_len, mp_digit *ps) +{ +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_MUL_WORD) + mp_word w; + mp_digit d; + mp_size ix; + + w = 0; +#define ADD_SQUARE(n) \ + d = pa[n]; \ + w += (d * (mp_word)d) + ps[2*n]; \ + ps[2*n] = ACCUM(w); \ + w = (w >> DIGIT_BIT) + ps[2*n+1]; \ + ps[2*n+1] = ACCUM(w); \ + w = (w >> DIGIT_BIT) + + for (ix = a_len; ix >= 4; ix -= 4) { + ADD_SQUARE(0); + ADD_SQUARE(1); + ADD_SQUARE(2); + ADD_SQUARE(3); + pa += 4; + ps += 8; + } + if (ix) { + ps += 2*ix; + pa += ix; + switch (ix) { + case 3: ADD_SQUARE(-3); /* FALLTHRU */ + case 2: ADD_SQUARE(-2); /* FALLTHRU */ + case 1: ADD_SQUARE(-1); /* FALLTHRU */ + case 0: break; + } + } + while (w) { + w += *ps; + *ps++ = ACCUM(w); + w = (w >> DIGIT_BIT); + } +#else + mp_digit carry = 0; + while (a_len--) { + mp_digit a_i = *pa++; + mp_digit a0a0, a1a1; + + MP_SQR_D(a_i, a1a1, a0a0); + + /* here a1a1 and a0a0 constitute a_i ** 2 */ + a0a0 += carry; + if (a0a0 < carry) + ++a1a1; + + /* now add to ps */ + a0a0 += a_i = *ps; + if (a0a0 < a_i) + ++a1a1; + *ps++ = a0a0; + a1a1 += a_i = *ps; + carry = (a1a1 < a_i); + *ps++ = a1a1; + } + while (carry) { + mp_digit s_i = *ps; + carry += s_i; + *ps++ = carry; + carry = carry < s_i; + } +#endif +} +#endif + +#if (defined(MP_NO_MP_WORD) || defined(MP_NO_DIV_WORD)) \ +&& !defined(MP_ASSEMBLY_DIV_2DX1D) +/* +** Divide 64-bit (Nhi,Nlo) by 32-bit divisor, which must be normalized +** so its high bit is 1. This code is from NSPR. +*/ +mp_err s_mpv_div_2dx1d(mp_digit Nhi, mp_digit Nlo, mp_digit divisor, + mp_digit *qp, mp_digit *rp) +{ + mp_digit d1, d0, q1, q0; + mp_digit r1, r0, m; + + d1 = divisor >> MP_HALF_DIGIT_BIT; + d0 = divisor & MP_HALF_DIGIT_MAX; + r1 = Nhi % d1; + q1 = Nhi / d1; + m = q1 * d0; + r1 = (r1 << MP_HALF_DIGIT_BIT) | (Nlo >> MP_HALF_DIGIT_BIT); + if (r1 < m) { + q1--, r1 += divisor; + if (r1 >= divisor && r1 < m) { + q1--, r1 += divisor; + } + } + r1 -= m; + r0 = r1 % d1; + q0 = r1 / d1; + m = q0 * d0; + r0 = (r0 << MP_HALF_DIGIT_BIT) | (Nlo & MP_HALF_DIGIT_MAX); + if (r0 < m) { + q0--, r0 += divisor; + if (r0 >= divisor && r0 < m) { + q0--, r0 += divisor; + } + } + if (qp) + *qp = (q1 << MP_HALF_DIGIT_BIT) | q0; + if (rp) + *rp = r0 - m; + return MP_OKAY; +} +#endif + +#if MP_SQUARE +/* {{{ s_mp_sqr(a) */ + +mp_err s_mp_sqr(mp_int *a) +{ + mp_err res; + mp_int tmp; + + if((res = mp_init_size(&tmp, 2 * USED(a), FLAG(a))) != MP_OKAY) + return res; + res = mp_sqr(a, &tmp); + if (res == MP_OKAY) { + s_mp_exch(&tmp, a); + } + mp_clear(&tmp); + return res; +} + +/* }}} */ +#endif + +/* {{{ s_mp_div(a, b) */ + +/* + s_mp_div(a, b) + + Compute a = a / b and b = a mod b. Assumes b > a. + */ + +mp_err s_mp_div(mp_int *rem, /* i: dividend, o: remainder */ + mp_int *div, /* i: divisor */ + mp_int *quot) /* i: 0; o: quotient */ +{ + mp_int part, t; +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_DIV_WORD) + mp_word q_msd; +#else + mp_digit q_msd; +#endif + mp_err res; + mp_digit d; + mp_digit div_msd; + int ix; + + if(mp_cmp_z(div) == 0) + return MP_RANGE; + + /* Shortcut if divisor is power of two */ + if((ix = s_mp_ispow2(div)) >= 0) { + MP_CHECKOK( mp_copy(rem, quot) ); + s_mp_div_2d(quot, (mp_digit)ix); + s_mp_mod_2d(rem, (mp_digit)ix); + + return MP_OKAY; + } + + DIGITS(&t) = 0; + MP_SIGN(rem) = ZPOS; + MP_SIGN(div) = ZPOS; + + /* A working temporary for division */ + MP_CHECKOK( mp_init_size(&t, MP_ALLOC(rem), FLAG(rem))); + + /* Normalize to optimize guessing */ + MP_CHECKOK( s_mp_norm(rem, div, &d) ); + + part = *rem; + + /* Perform the division itself...woo! */ + MP_USED(quot) = MP_ALLOC(quot); + + /* Find a partial substring of rem which is at least div */ + /* If we didn't find one, we're finished dividing */ + while (MP_USED(rem) > MP_USED(div) || s_mp_cmp(rem, div) >= 0) { + int i; + int unusedRem; + + unusedRem = MP_USED(rem) - MP_USED(div); + MP_DIGITS(&part) = MP_DIGITS(rem) + unusedRem; + MP_ALLOC(&part) = MP_ALLOC(rem) - unusedRem; + MP_USED(&part) = MP_USED(div); + if (s_mp_cmp(&part, div) < 0) { + -- unusedRem; +#if MP_ARGCHK == 2 + assert(unusedRem >= 0); +#endif + -- MP_DIGITS(&part); + ++ MP_USED(&part); + ++ MP_ALLOC(&part); + } + + /* Compute a guess for the next quotient digit */ + q_msd = MP_DIGIT(&part, MP_USED(&part) - 1); + div_msd = MP_DIGIT(div, MP_USED(div) - 1); + if (q_msd >= div_msd) { + q_msd = 1; + } else if (MP_USED(&part) > 1) { +#if !defined(MP_NO_MP_WORD) && !defined(MP_NO_DIV_WORD) + q_msd = (q_msd << MP_DIGIT_BIT) | MP_DIGIT(&part, MP_USED(&part) - 2); + q_msd /= div_msd; + if (q_msd == RADIX) + --q_msd; +#else + mp_digit r; + MP_CHECKOK( s_mpv_div_2dx1d(q_msd, MP_DIGIT(&part, MP_USED(&part) - 2), + div_msd, &q_msd, &r) ); +#endif + } else { + q_msd = 0; + } +#if MP_ARGCHK == 2 + assert(q_msd > 0); /* This case should never occur any more. */ +#endif + if (q_msd <= 0) + break; + + /* See what that multiplies out to */ + mp_copy(div, &t); + MP_CHECKOK( s_mp_mul_d(&t, (mp_digit)q_msd) ); + + /* + If it's too big, back it off. We should not have to do this + more than once, or, in rare cases, twice. Knuth describes a + method by which this could be reduced to a maximum of once, but + I didn't implement that here. + * When using s_mpv_div_2dx1d, we may have to do this 3 times. + */ + for (i = 4; s_mp_cmp(&t, &part) > 0 && i > 0; --i) { + --q_msd; + s_mp_sub(&t, div); /* t -= div */ + } + if (i < 0) { + res = MP_RANGE; + goto CLEANUP; + } + + /* At this point, q_msd should be the right next digit */ + MP_CHECKOK( s_mp_sub(&part, &t) ); /* part -= t */ + s_mp_clamp(rem); + + /* + Include the digit in the quotient. We allocated enough memory + for any quotient we could ever possibly get, so we should not + have to check for failures here + */ + MP_DIGIT(quot, unusedRem) = (mp_digit)q_msd; + } + + /* Denormalize remainder */ + if (d) { + s_mp_div_2d(rem, d); + } + + s_mp_clamp(quot); + +CLEANUP: + mp_clear(&t); + + return res; + +} /* end s_mp_div() */ + + +/* }}} */ + +/* {{{ s_mp_2expt(a, k) */ + +mp_err s_mp_2expt(mp_int *a, mp_digit k) +{ + mp_err res; + mp_size dig, bit; + + dig = k / DIGIT_BIT; + bit = k % DIGIT_BIT; + + mp_zero(a); + if((res = s_mp_pad(a, dig + 1)) != MP_OKAY) + return res; + + DIGIT(a, dig) |= ((mp_digit)1 << bit); + + return MP_OKAY; + +} /* end s_mp_2expt() */ + +/* }}} */ + +/* {{{ s_mp_reduce(x, m, mu) */ + +/* + Compute Barrett reduction, x (mod m), given a precomputed value for + mu = b^2k / m, where b = RADIX and k = #digits(m). This should be + faster than straight division, when many reductions by the same + value of m are required (such as in modular exponentiation). This + can nearly halve the time required to do modular exponentiation, + as compared to using the full integer divide to reduce. + + This algorithm was derived from the _Handbook of Applied + Cryptography_ by Menezes, Oorschot and VanStone, Ch. 14, + pp. 603-604. + */ + +mp_err s_mp_reduce(mp_int *x, const mp_int *m, const mp_int *mu) +{ + mp_int q; + mp_err res; + + if((res = mp_init_copy(&q, x)) != MP_OKAY) + return res; + + s_mp_rshd(&q, USED(m) - 1); /* q1 = x / b^(k-1) */ + s_mp_mul(&q, mu); /* q2 = q1 * mu */ + s_mp_rshd(&q, USED(m) + 1); /* q3 = q2 / b^(k+1) */ + + /* x = x mod b^(k+1), quick (no division) */ + s_mp_mod_2d(x, DIGIT_BIT * (USED(m) + 1)); + + /* q = q * m mod b^(k+1), quick (no division) */ + s_mp_mul(&q, m); + s_mp_mod_2d(&q, DIGIT_BIT * (USED(m) + 1)); + + /* x = x - q */ + if((res = mp_sub(x, &q, x)) != MP_OKAY) + goto CLEANUP; + + /* If x < 0, add b^(k+1) to it */ + if(mp_cmp_z(x) < 0) { + mp_set(&q, 1); + if((res = s_mp_lshd(&q, USED(m) + 1)) != MP_OKAY) + goto CLEANUP; + if((res = mp_add(x, &q, x)) != MP_OKAY) + goto CLEANUP; + } + + /* Back off if it's too big */ + while(mp_cmp(x, m) >= 0) { + if((res = s_mp_sub(x, m)) != MP_OKAY) + break; + } + + CLEANUP: + mp_clear(&q); + + return res; + +} /* end s_mp_reduce() */ + +/* }}} */ + +/* }}} */ + +/* {{{ Primitive comparisons */ + +/* {{{ s_mp_cmp(a, b) */ + +/* Compare |a| <=> |b|, return 0 if equal, <0 if a0 if a>b */ +int s_mp_cmp(const mp_int *a, const mp_int *b) +{ + mp_size used_a = MP_USED(a); + { + mp_size used_b = MP_USED(b); + + if (used_a > used_b) + goto IS_GT; + if (used_a < used_b) + goto IS_LT; + } + { + mp_digit *pa, *pb; + mp_digit da = 0, db = 0; + +#define CMP_AB(n) if ((da = pa[n]) != (db = pb[n])) goto done + + pa = MP_DIGITS(a) + used_a; + pb = MP_DIGITS(b) + used_a; + while (used_a >= 4) { + pa -= 4; + pb -= 4; + used_a -= 4; + CMP_AB(3); + CMP_AB(2); + CMP_AB(1); + CMP_AB(0); + } + while (used_a-- > 0 && ((da = *--pa) == (db = *--pb))) + /* do nothing */; +done: + if (da > db) + goto IS_GT; + if (da < db) + goto IS_LT; + } + return MP_EQ; +IS_LT: + return MP_LT; +IS_GT: + return MP_GT; +} /* end s_mp_cmp() */ + +/* }}} */ + +/* {{{ s_mp_cmp_d(a, d) */ + +/* Compare |a| <=> d, return 0 if equal, <0 if a0 if a>d */ +int s_mp_cmp_d(const mp_int *a, mp_digit d) +{ + if(USED(a) > 1) + return MP_GT; + + if(DIGIT(a, 0) < d) + return MP_LT; + else if(DIGIT(a, 0) > d) + return MP_GT; + else + return MP_EQ; + +} /* end s_mp_cmp_d() */ + +/* }}} */ + +/* {{{ s_mp_ispow2(v) */ + +/* + Returns -1 if the value is not a power of two; otherwise, it returns + k such that v = 2^k, i.e. lg(v). + */ +int s_mp_ispow2(const mp_int *v) +{ + mp_digit d; + int extra = 0, ix; + + ix = MP_USED(v) - 1; + d = MP_DIGIT(v, ix); /* most significant digit of v */ + + extra = s_mp_ispow2d(d); + if (extra < 0 || ix == 0) + return extra; + + while (--ix >= 0) { + if (DIGIT(v, ix) != 0) + return -1; /* not a power of two */ + extra += MP_DIGIT_BIT; + } + + return extra; + +} /* end s_mp_ispow2() */ + +/* }}} */ + +/* {{{ s_mp_ispow2d(d) */ + +int s_mp_ispow2d(mp_digit d) +{ + if ((d != 0) && ((d & (d-1)) == 0)) { /* d is a power of 2 */ + int pow = 0; +#if defined (MP_USE_UINT_DIGIT) + if (d & 0xffff0000U) + pow += 16; + if (d & 0xff00ff00U) + pow += 8; + if (d & 0xf0f0f0f0U) + pow += 4; + if (d & 0xccccccccU) + pow += 2; + if (d & 0xaaaaaaaaU) + pow += 1; +#elif defined(MP_USE_LONG_LONG_DIGIT) + if (d & 0xffffffff00000000ULL) + pow += 32; + if (d & 0xffff0000ffff0000ULL) + pow += 16; + if (d & 0xff00ff00ff00ff00ULL) + pow += 8; + if (d & 0xf0f0f0f0f0f0f0f0ULL) + pow += 4; + if (d & 0xccccccccccccccccULL) + pow += 2; + if (d & 0xaaaaaaaaaaaaaaaaULL) + pow += 1; +#elif defined(MP_USE_LONG_DIGIT) + if (d & 0xffffffff00000000UL) + pow += 32; + if (d & 0xffff0000ffff0000UL) + pow += 16; + if (d & 0xff00ff00ff00ff00UL) + pow += 8; + if (d & 0xf0f0f0f0f0f0f0f0UL) + pow += 4; + if (d & 0xccccccccccccccccUL) + pow += 2; + if (d & 0xaaaaaaaaaaaaaaaaUL) + pow += 1; +#else +#error "unknown type for mp_digit" +#endif + return pow; + } + return -1; + +} /* end s_mp_ispow2d() */ + +/* }}} */ + +/* }}} */ + +/* {{{ Primitive I/O helpers */ + +/* {{{ s_mp_tovalue(ch, r) */ + +/* + Convert the given character to its digit value, in the given radix. + If the given character is not understood in the given radix, -1 is + returned. Otherwise the digit's numeric value is returned. + + The results will be odd if you use a radix < 2 or > 62, you are + expected to know what you're up to. + */ +int s_mp_tovalue(char ch, int r) +{ + int val, xch; + + if(r > 36) + xch = ch; + else + xch = toupper(ch); + + if(isdigit(xch)) + val = xch - '0'; + else if(isupper(xch)) + val = xch - 'A' + 10; + else if(islower(xch)) + val = xch - 'a' + 36; + else if(xch == '+') + val = 62; + else if(xch == '/') + val = 63; + else + return -1; + + if(val < 0 || val >= r) + return -1; + + return val; + +} /* end s_mp_tovalue() */ + +/* }}} */ + +/* {{{ s_mp_todigit(val, r, low) */ + +/* + Convert val to a radix-r digit, if possible. If val is out of range + for r, returns zero. Otherwise, returns an ASCII character denoting + the value in the given radix. + + The results may be odd if you use a radix < 2 or > 64, you are + expected to know what you're doing. + */ + +char s_mp_todigit(mp_digit val, int r, int low) +{ + char ch; + + if(val >= r) + return 0; + + ch = s_dmap_1[val]; + + if(r <= 36 && low) + ch = tolower(ch); + + return ch; + +} /* end s_mp_todigit() */ + +/* }}} */ + +/* {{{ s_mp_outlen(bits, radix) */ + +/* + Return an estimate for how long a string is needed to hold a radix + r representation of a number with 'bits' significant bits, plus an + extra for a zero terminator (assuming C style strings here) + */ +int s_mp_outlen(int bits, int r) +{ + return (int)((double)bits * LOG_V_2(r) + 1.5) + 1; + +} /* end s_mp_outlen() */ + +/* }}} */ + +/* }}} */ + +/* {{{ mp_read_unsigned_octets(mp, str, len) */ +/* mp_read_unsigned_octets(mp, str, len) + Read in a raw value (base 256) into the given mp_int + No sign bit, number is positive. Leading zeros ignored. + */ + +mp_err +mp_read_unsigned_octets(mp_int *mp, const unsigned char *str, mp_size len) +{ + int count; + mp_err res; + mp_digit d; + + ARGCHK(mp != NULL && str != NULL && len > 0, MP_BADARG); + + mp_zero(mp); + + count = len % sizeof(mp_digit); + if (count) { + for (d = 0; count-- > 0; --len) { + d = (d << 8) | *str++; + } + MP_DIGIT(mp, 0) = d; + } + + /* Read the rest of the digits */ + for(; len > 0; len -= sizeof(mp_digit)) { + for (d = 0, count = sizeof(mp_digit); count > 0; --count) { + d = (d << 8) | *str++; + } + if (MP_EQ == mp_cmp_z(mp)) { + if (!d) + continue; + } else { + if((res = s_mp_lshd(mp, 1)) != MP_OKAY) + return res; + } + MP_DIGIT(mp, 0) = d; + } + return MP_OKAY; +} /* end mp_read_unsigned_octets() */ +/* }}} */ + +/* {{{ mp_unsigned_octet_size(mp) */ +int +mp_unsigned_octet_size(const mp_int *mp) +{ + int bytes; + int ix; + mp_digit d = 0; + + ARGCHK(mp != NULL, MP_BADARG); + ARGCHK(MP_ZPOS == SIGN(mp), MP_BADARG); + + bytes = (USED(mp) * sizeof(mp_digit)); + + /* subtract leading zeros. */ + /* Iterate over each digit... */ + for(ix = USED(mp) - 1; ix >= 0; ix--) { + d = DIGIT(mp, ix); + if (d) + break; + bytes -= sizeof(d); + } + if (!bytes) + return 1; + + /* Have MSD, check digit bytes, high order first */ + for(ix = sizeof(mp_digit) - 1; ix >= 0; ix--) { + unsigned char x = (unsigned char)(d >> (ix * CHAR_BIT)); + if (x) + break; + --bytes; + } + return bytes; +} /* end mp_unsigned_octet_size() */ +/* }}} */ + +/* {{{ mp_to_unsigned_octets(mp, str) */ +/* output a buffer of big endian octets no longer than specified. */ +mp_err +mp_to_unsigned_octets(const mp_int *mp, unsigned char *str, mp_size maxlen) +{ + int ix, pos = 0; + int bytes; + + ARGCHK(mp != NULL && str != NULL && !SIGN(mp), MP_BADARG); + + bytes = mp_unsigned_octet_size(mp); + ARGCHK(bytes <= maxlen, MP_BADARG); + + /* Iterate over each digit... */ + for(ix = USED(mp) - 1; ix >= 0; ix--) { + mp_digit d = DIGIT(mp, ix); + int jx; + + /* Unpack digit bytes, high order first */ + for(jx = sizeof(mp_digit) - 1; jx >= 0; jx--) { + unsigned char x = (unsigned char)(d >> (jx * CHAR_BIT)); + if (!pos && !x) /* suppress leading zeros */ + continue; + str[pos++] = x; + } + } + if (!pos) + str[pos++] = 0; + return pos; +} /* end mp_to_unsigned_octets() */ +/* }}} */ + +/* {{{ mp_to_signed_octets(mp, str) */ +/* output a buffer of big endian octets no longer than specified. */ +mp_err +mp_to_signed_octets(const mp_int *mp, unsigned char *str, mp_size maxlen) +{ + int ix, pos = 0; + int bytes; + + ARGCHK(mp != NULL && str != NULL && !SIGN(mp), MP_BADARG); + + bytes = mp_unsigned_octet_size(mp); + ARGCHK(bytes <= maxlen, MP_BADARG); + + /* Iterate over each digit... */ + for(ix = USED(mp) - 1; ix >= 0; ix--) { + mp_digit d = DIGIT(mp, ix); + int jx; + + /* Unpack digit bytes, high order first */ + for(jx = sizeof(mp_digit) - 1; jx >= 0; jx--) { + unsigned char x = (unsigned char)(d >> (jx * CHAR_BIT)); + if (!pos) { + if (!x) /* suppress leading zeros */ + continue; + if (x & 0x80) { /* add one leading zero to make output positive. */ + ARGCHK(bytes + 1 <= maxlen, MP_BADARG); + if (bytes + 1 > maxlen) + return MP_BADARG; + str[pos++] = 0; + } + } + str[pos++] = x; + } + } + if (!pos) + str[pos++] = 0; + return pos; +} /* end mp_to_signed_octets() */ +/* }}} */ + +/* {{{ mp_to_fixlen_octets(mp, str) */ +/* output a buffer of big endian octets exactly as long as requested. */ +mp_err +mp_to_fixlen_octets(const mp_int *mp, unsigned char *str, mp_size length) +{ + int ix, pos = 0; + int bytes; + + ARGCHK(mp != NULL && str != NULL && !SIGN(mp), MP_BADARG); + + bytes = mp_unsigned_octet_size(mp); + ARGCHK(bytes <= length, MP_BADARG); + + /* place any needed leading zeros */ + for (;length > bytes; --length) { + *str++ = 0; + } + + /* Iterate over each digit... */ + for(ix = USED(mp) - 1; ix >= 0; ix--) { + mp_digit d = DIGIT(mp, ix); + int jx; + + /* Unpack digit bytes, high order first */ + for(jx = sizeof(mp_digit) - 1; jx >= 0; jx--) { + unsigned char x = (unsigned char)(d >> (jx * CHAR_BIT)); + if (!pos && !x) /* suppress leading zeros */ + continue; + str[pos++] = x; + } + } + if (!pos) + str[pos++] = 0; + return MP_OKAY; +} /* end mp_to_fixlen_octets() */ +/* }}} */ + + +/*------------------------------------------------------------------------*/ +/* HERE THERE BE DRAGONS */ diff --git a/src/share/native/sun/security/ec/impl/mpi.h b/src/share/native/sun/security/ec/impl/mpi.h new file mode 100644 index 0000000000000000000000000000000000000000..5f70b763209b1c1e5427c2dd664f3ad270d86d97 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mpi.h @@ -0,0 +1,409 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * + * Arbitrary precision integer arithmetic library + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Netscape Communications Corporation + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MPI_H +#define _MPI_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mpi.h,v 1.22 2004/04/27 23:04:36 gerv%gerv.net Exp $ */ + +#include "mpi-config.h" + +#ifndef _WIN32 +#include +#endif /* _WIN32 */ + +#ifdef _KERNEL +#include +#include +#define assert ASSERT +#define labs(a) (a >= 0 ? a : -a) +#define UCHAR_MAX 255 +#define memset(s, c, n) bzero(s, n) +#define memcpy(a,b,c) bcopy((caddr_t)b, (caddr_t)a, c) +/* + * Generic #define's to cover missing things in the kernel + */ +#ifndef isdigit +#define isdigit(x) ((x) >= '0' && (x) <= '9') +#endif +#ifndef isupper +#define isupper(x) (((unsigned)(x) >= 'A') && ((unsigned)(x) <= 'Z')) +#endif +#ifndef islower +#define islower(x) (((unsigned)(x) >= 'a') && ((unsigned)(x) <= 'z')) +#endif +#ifndef isalpha +#define isalpha(x) (isupper(x) || islower(x)) +#endif +#ifndef toupper +#define toupper(x) (islower(x) ? (x) - 'a' + 'A' : (x)) +#endif +#ifndef tolower +#define tolower(x) (isupper(x) ? (x) + 'a' - 'A' : (x)) +#endif +#ifndef isspace +#define isspace(x) (((x) == ' ') || ((x) == '\r') || ((x) == '\n') || \ + ((x) == '\t') || ((x) == '\b')) +#endif +#endif /* _KERNEL */ + +#if MP_DEBUG +#undef MP_IOFUNC +#define MP_IOFUNC 1 +#endif + +#if MP_IOFUNC +#include +#include +#endif + +#ifndef _KERNEL +#include +#endif + +#if defined(BSDI) +#undef ULLONG_MAX +#endif + +#if defined( macintosh ) +#include +#elif defined( _WIN32_WCE) +/* #include What do we need here ?? */ +#else +#include +#endif + +#define MP_NEG 1 +#define MP_ZPOS 0 + +#define MP_OKAY 0 /* no error, all is well */ +#define MP_YES 0 /* yes (boolean result) */ +#define MP_NO -1 /* no (boolean result) */ +#define MP_MEM -2 /* out of memory */ +#define MP_RANGE -3 /* argument out of range */ +#define MP_BADARG -4 /* invalid parameter */ +#define MP_UNDEF -5 /* answer is undefined */ +#define MP_LAST_CODE MP_UNDEF + +typedef unsigned int mp_sign; +typedef unsigned int mp_size; +typedef int mp_err; +typedef int mp_flag; + +#define MP_32BIT_MAX 4294967295U + +#if !defined(ULONG_MAX) +#error "ULONG_MAX not defined" +#elif !defined(UINT_MAX) +#error "UINT_MAX not defined" +#elif !defined(USHRT_MAX) +#error "USHRT_MAX not defined" +#endif + +#if defined(ULONG_LONG_MAX) /* GCC, HPUX */ +#define MP_ULONG_LONG_MAX ULONG_LONG_MAX +#elif defined(ULLONG_MAX) /* Solaris */ +#define MP_ULONG_LONG_MAX ULLONG_MAX +/* MP_ULONG_LONG_MAX was defined to be ULLONG_MAX */ +#elif defined(ULONGLONG_MAX) /* IRIX, AIX */ +#define MP_ULONG_LONG_MAX ULONGLONG_MAX +#endif + +/* We only use unsigned long for mp_digit iff long is more than 32 bits. */ +#if !defined(MP_USE_UINT_DIGIT) && ULONG_MAX > MP_32BIT_MAX +typedef unsigned long mp_digit; +#define MP_DIGIT_MAX ULONG_MAX +#define MP_DIGIT_FMT "%016lX" /* printf() format for 1 digit */ +#define MP_HALF_DIGIT_MAX UINT_MAX +#undef MP_NO_MP_WORD +#define MP_NO_MP_WORD 1 +#undef MP_USE_LONG_DIGIT +#define MP_USE_LONG_DIGIT 1 +#undef MP_USE_LONG_LONG_DIGIT + +#elif !defined(MP_USE_UINT_DIGIT) && defined(MP_ULONG_LONG_MAX) +typedef unsigned long long mp_digit; +#define MP_DIGIT_MAX MP_ULONG_LONG_MAX +#define MP_DIGIT_FMT "%016llX" /* printf() format for 1 digit */ +#define MP_HALF_DIGIT_MAX UINT_MAX +#undef MP_NO_MP_WORD +#define MP_NO_MP_WORD 1 +#undef MP_USE_LONG_LONG_DIGIT +#define MP_USE_LONG_LONG_DIGIT 1 +#undef MP_USE_LONG_DIGIT + +#else +typedef unsigned int mp_digit; +#define MP_DIGIT_MAX UINT_MAX +#define MP_DIGIT_FMT "%08X" /* printf() format for 1 digit */ +#define MP_HALF_DIGIT_MAX USHRT_MAX +#undef MP_USE_UINT_DIGIT +#define MP_USE_UINT_DIGIT 1 +#undef MP_USE_LONG_LONG_DIGIT +#undef MP_USE_LONG_DIGIT +#endif + +#if !defined(MP_NO_MP_WORD) +#if defined(MP_USE_UINT_DIGIT) && \ + (defined(MP_ULONG_LONG_MAX) || (ULONG_MAX > UINT_MAX)) + +#if (ULONG_MAX > UINT_MAX) +typedef unsigned long mp_word; +typedef long mp_sword; +#define MP_WORD_MAX ULONG_MAX + +#else +typedef unsigned long long mp_word; +typedef long long mp_sword; +#define MP_WORD_MAX MP_ULONG_LONG_MAX +#endif + +#else +#define MP_NO_MP_WORD 1 +#endif +#endif /* !defined(MP_NO_MP_WORD) */ + +#if !defined(MP_WORD_MAX) && defined(MP_DEFINE_SMALL_WORD) +typedef unsigned int mp_word; +typedef int mp_sword; +#define MP_WORD_MAX UINT_MAX +#endif + +#ifndef CHAR_BIT +#define CHAR_BIT 8 +#endif + +#define MP_DIGIT_BIT (CHAR_BIT*sizeof(mp_digit)) +#define MP_WORD_BIT (CHAR_BIT*sizeof(mp_word)) +#define MP_RADIX (1+(mp_word)MP_DIGIT_MAX) + +#define MP_HALF_DIGIT_BIT (MP_DIGIT_BIT/2) +#define MP_HALF_RADIX (1+(mp_digit)MP_HALF_DIGIT_MAX) +/* MP_HALF_RADIX really ought to be called MP_SQRT_RADIX, but it's named +** MP_HALF_RADIX because it's the radix for MP_HALF_DIGITs, and it's +** consistent with the other _HALF_ names. +*/ + + +/* Macros for accessing the mp_int internals */ +#define MP_FLAG(MP) ((MP)->flag) +#define MP_SIGN(MP) ((MP)->sign) +#define MP_USED(MP) ((MP)->used) +#define MP_ALLOC(MP) ((MP)->alloc) +#define MP_DIGITS(MP) ((MP)->dp) +#define MP_DIGIT(MP,N) (MP)->dp[(N)] + +/* This defines the maximum I/O base (minimum is 2) */ +#define MP_MAX_RADIX 64 + +typedef struct { + mp_sign flag; /* KM_SLEEP/KM_NOSLEEP */ + mp_sign sign; /* sign of this quantity */ + mp_size alloc; /* how many digits allocated */ + mp_size used; /* how many digits used */ + mp_digit *dp; /* the digits themselves */ +} mp_int; + +/* Default precision */ +mp_size mp_get_prec(void); +void mp_set_prec(mp_size prec); + +/* Memory management */ +mp_err mp_init(mp_int *mp, int kmflag); +mp_err mp_init_size(mp_int *mp, mp_size prec, int kmflag); +mp_err mp_init_copy(mp_int *mp, const mp_int *from); +mp_err mp_copy(const mp_int *from, mp_int *to); +void mp_exch(mp_int *mp1, mp_int *mp2); +void mp_clear(mp_int *mp); +void mp_zero(mp_int *mp); +void mp_set(mp_int *mp, mp_digit d); +mp_err mp_set_int(mp_int *mp, long z); +#define mp_set_long(mp,z) mp_set_int(mp,z) +mp_err mp_set_ulong(mp_int *mp, unsigned long z); + +/* Single digit arithmetic */ +mp_err mp_add_d(const mp_int *a, mp_digit d, mp_int *b); +mp_err mp_sub_d(const mp_int *a, mp_digit d, mp_int *b); +mp_err mp_mul_d(const mp_int *a, mp_digit d, mp_int *b); +mp_err mp_mul_2(const mp_int *a, mp_int *c); +mp_err mp_div_d(const mp_int *a, mp_digit d, mp_int *q, mp_digit *r); +mp_err mp_div_2(const mp_int *a, mp_int *c); +mp_err mp_expt_d(const mp_int *a, mp_digit d, mp_int *c); + +/* Sign manipulations */ +mp_err mp_abs(const mp_int *a, mp_int *b); +mp_err mp_neg(const mp_int *a, mp_int *b); + +/* Full arithmetic */ +mp_err mp_add(const mp_int *a, const mp_int *b, mp_int *c); +mp_err mp_sub(const mp_int *a, const mp_int *b, mp_int *c); +mp_err mp_mul(const mp_int *a, const mp_int *b, mp_int *c); +#if MP_SQUARE +mp_err mp_sqr(const mp_int *a, mp_int *b); +#else +#define mp_sqr(a, b) mp_mul(a, a, b) +#endif +mp_err mp_div(const mp_int *a, const mp_int *b, mp_int *q, mp_int *r); +mp_err mp_div_2d(const mp_int *a, mp_digit d, mp_int *q, mp_int *r); +mp_err mp_expt(mp_int *a, mp_int *b, mp_int *c); +mp_err mp_2expt(mp_int *a, mp_digit k); +mp_err mp_sqrt(const mp_int *a, mp_int *b); + +/* Modular arithmetic */ +#if MP_MODARITH +mp_err mp_mod(const mp_int *a, const mp_int *m, mp_int *c); +mp_err mp_mod_d(const mp_int *a, mp_digit d, mp_digit *c); +mp_err mp_addmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c); +mp_err mp_submod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c); +mp_err mp_mulmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c); +#if MP_SQUARE +mp_err mp_sqrmod(const mp_int *a, const mp_int *m, mp_int *c); +#else +#define mp_sqrmod(a, m, c) mp_mulmod(a, a, m, c) +#endif +mp_err mp_exptmod(const mp_int *a, const mp_int *b, const mp_int *m, mp_int *c); +mp_err mp_exptmod_d(const mp_int *a, mp_digit d, const mp_int *m, mp_int *c); +#endif /* MP_MODARITH */ + +/* Comparisons */ +int mp_cmp_z(const mp_int *a); +int mp_cmp_d(const mp_int *a, mp_digit d); +int mp_cmp(const mp_int *a, const mp_int *b); +int mp_cmp_mag(mp_int *a, mp_int *b); +int mp_cmp_int(const mp_int *a, long z, int kmflag); +int mp_isodd(const mp_int *a); +int mp_iseven(const mp_int *a); + +/* Number theoretic */ +#if MP_NUMTH +mp_err mp_gcd(mp_int *a, mp_int *b, mp_int *c); +mp_err mp_lcm(mp_int *a, mp_int *b, mp_int *c); +mp_err mp_xgcd(const mp_int *a, const mp_int *b, mp_int *g, mp_int *x, mp_int *y); +mp_err mp_invmod(const mp_int *a, const mp_int *m, mp_int *c); +mp_err mp_invmod_xgcd(const mp_int *a, const mp_int *m, mp_int *c); +#endif /* end MP_NUMTH */ + +/* Input and output */ +#if MP_IOFUNC +void mp_print(mp_int *mp, FILE *ofp); +#endif /* end MP_IOFUNC */ + +/* Base conversion */ +mp_err mp_read_raw(mp_int *mp, char *str, int len); +int mp_raw_size(mp_int *mp); +mp_err mp_toraw(mp_int *mp, char *str); +mp_err mp_read_radix(mp_int *mp, const char *str, int radix); +mp_err mp_read_variable_radix(mp_int *a, const char * str, int default_radix); +int mp_radix_size(mp_int *mp, int radix); +mp_err mp_toradix(mp_int *mp, char *str, int radix); +int mp_tovalue(char ch, int r); + +#define mp_tobinary(M, S) mp_toradix((M), (S), 2) +#define mp_tooctal(M, S) mp_toradix((M), (S), 8) +#define mp_todecimal(M, S) mp_toradix((M), (S), 10) +#define mp_tohex(M, S) mp_toradix((M), (S), 16) + +/* Error strings */ +const char *mp_strerror(mp_err ec); + +/* Octet string conversion functions */ +mp_err mp_read_unsigned_octets(mp_int *mp, const unsigned char *str, mp_size len); +int mp_unsigned_octet_size(const mp_int *mp); +mp_err mp_to_unsigned_octets(const mp_int *mp, unsigned char *str, mp_size maxlen); +mp_err mp_to_signed_octets(const mp_int *mp, unsigned char *str, mp_size maxlen); +mp_err mp_to_fixlen_octets(const mp_int *mp, unsigned char *str, mp_size len); + +/* Miscellaneous */ +mp_size mp_trailing_zeros(const mp_int *mp); + +#define MP_CHECKOK(x) if (MP_OKAY > (res = (x))) goto CLEANUP +#define MP_CHECKERR(x) if (MP_OKAY > (res = (x))) goto CLEANUP + +#if defined(MP_API_COMPATIBLE) +#define NEG MP_NEG +#define ZPOS MP_ZPOS +#define DIGIT_MAX MP_DIGIT_MAX +#define DIGIT_BIT MP_DIGIT_BIT +#define DIGIT_FMT MP_DIGIT_FMT +#define RADIX MP_RADIX +#define MAX_RADIX MP_MAX_RADIX +#define FLAG(MP) MP_FLAG(MP) +#define SIGN(MP) MP_SIGN(MP) +#define USED(MP) MP_USED(MP) +#define ALLOC(MP) MP_ALLOC(MP) +#define DIGITS(MP) MP_DIGITS(MP) +#define DIGIT(MP,N) MP_DIGIT(MP,N) + +#if MP_ARGCHK == 1 +#define ARGCHK(X,Y) {if(!(X)){return (Y);}} +#elif MP_ARGCHK == 2 +#ifdef _KERNEL +#define ARGCHK(X,Y) ASSERT(X) +#else +#include +#define ARGCHK(X,Y) assert(X) +#endif +#else +#define ARGCHK(X,Y) /* */ +#endif +#endif /* defined MP_API_COMPATIBLE */ + +#endif /* _MPI_H */ diff --git a/src/share/native/sun/security/ec/impl/mplogic.c b/src/share/native/sun/security/ec/impl/mplogic.c new file mode 100644 index 0000000000000000000000000000000000000000..6a5f00a1c36e525908cd793c55aa63f9eb78d051 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mplogic.c @@ -0,0 +1,242 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * + * Bitwise logical operations on MPI values + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mplogic.c,v 1.15 2004/04/27 23:04:36 gerv%gerv.net Exp $ */ + +#include "mpi-priv.h" +#include "mplogic.h" + +/* {{{ Lookup table for population count */ + +static unsigned char bitc[] = { + 0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, + 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8 +}; + +/* }}} */ + +/* + mpl_rsh(a, b, d) - b = a >> d + mpl_lsh(a, b, d) - b = a << d + */ + +/* {{{ mpl_rsh(a, b, d) */ + +mp_err mpl_rsh(const mp_int *a, mp_int *b, mp_digit d) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if((res = mp_copy(a, b)) != MP_OKAY) + return res; + + s_mp_div_2d(b, d); + + return MP_OKAY; + +} /* end mpl_rsh() */ + +/* }}} */ + +/* {{{ mpl_lsh(a, b, d) */ + +mp_err mpl_lsh(const mp_int *a, mp_int *b, mp_digit d) +{ + mp_err res; + + ARGCHK(a != NULL && b != NULL, MP_BADARG); + + if((res = mp_copy(a, b)) != MP_OKAY) + return res; + + return s_mp_mul_2d(b, d); + +} /* end mpl_lsh() */ + +/* }}} */ + +/*------------------------------------------------------------------------*/ +/* + mpl_set_bit + + Returns MP_OKAY or some error code. + Grows a if needed to set a bit to 1. + */ +mp_err mpl_set_bit(mp_int *a, mp_size bitNum, mp_size value) +{ + mp_size ix; + mp_err rv; + mp_digit mask; + + ARGCHK(a != NULL, MP_BADARG); + + ix = bitNum / MP_DIGIT_BIT; + if (ix + 1 > MP_USED(a)) { + rv = s_mp_pad(a, ix + 1); + if (rv != MP_OKAY) + return rv; + } + + bitNum = bitNum % MP_DIGIT_BIT; + mask = (mp_digit)1 << bitNum; + if (value) + MP_DIGIT(a,ix) |= mask; + else + MP_DIGIT(a,ix) &= ~mask; + s_mp_clamp(a); + return MP_OKAY; +} + +/* + mpl_get_bit + + returns 0 or 1 or some (negative) error code. + */ +mp_err mpl_get_bit(const mp_int *a, mp_size bitNum) +{ + mp_size bit, ix; + mp_err rv; + + ARGCHK(a != NULL, MP_BADARG); + + ix = bitNum / MP_DIGIT_BIT; + ARGCHK(ix <= MP_USED(a) - 1, MP_RANGE); + + bit = bitNum % MP_DIGIT_BIT; + rv = (mp_err)(MP_DIGIT(a, ix) >> bit) & 1; + return rv; +} + +/* + mpl_get_bits + - Extracts numBits bits from a, where the least significant extracted bit + is bit lsbNum. Returns a negative value if error occurs. + - Because sign bit is used to indicate error, maximum number of bits to + be returned is the lesser of (a) the number of bits in an mp_digit, or + (b) one less than the number of bits in an mp_err. + - lsbNum + numbits can be greater than the number of significant bits in + integer a, as long as bit lsbNum is in the high order digit of a. + */ +mp_err mpl_get_bits(const mp_int *a, mp_size lsbNum, mp_size numBits) +{ + mp_size rshift = (lsbNum % MP_DIGIT_BIT); + mp_size lsWndx = (lsbNum / MP_DIGIT_BIT); + mp_digit * digit = MP_DIGITS(a) + lsWndx; + mp_digit mask = ((1 << numBits) - 1); + + ARGCHK(numBits < CHAR_BIT * sizeof mask, MP_BADARG); + ARGCHK(MP_HOWMANY(lsbNum, MP_DIGIT_BIT) <= MP_USED(a), MP_RANGE); + + if ((numBits + lsbNum % MP_DIGIT_BIT <= MP_DIGIT_BIT) || + (lsWndx + 1 >= MP_USED(a))) { + mask &= (digit[0] >> rshift); + } else { + mask &= ((digit[0] >> rshift) | (digit[1] << (MP_DIGIT_BIT - rshift))); + } + return (mp_err)mask; +} + +/* + mpl_significant_bits + returns number of significnant bits in abs(a). + returns 1 if value is zero. + */ +mp_err mpl_significant_bits(const mp_int *a) +{ + mp_err bits = 0; + int ix; + + ARGCHK(a != NULL, MP_BADARG); + + ix = MP_USED(a); + for (ix = MP_USED(a); ix > 0; ) { + mp_digit d; + d = MP_DIGIT(a, --ix); + if (d) { + while (d) { + ++bits; + d >>= 1; + } + break; + } + } + bits += ix * MP_DIGIT_BIT; + if (!bits) + bits = 1; + return bits; +} + +/*------------------------------------------------------------------------*/ +/* HERE THERE BE DRAGONS */ diff --git a/src/share/native/sun/security/ec/impl/mplogic.h b/src/share/native/sun/security/ec/impl/mplogic.h new file mode 100644 index 0000000000000000000000000000000000000000..97ddb49c7ea8d73be860690a455e2bcc346f6e94 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mplogic.h @@ -0,0 +1,105 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * + * Bitwise logical operations on MPI values + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1998 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MPLOGIC_H +#define _MPLOGIC_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mplogic.h,v 1.7 2004/04/27 23:04:36 gerv%gerv.net Exp $ */ + +#include "mpi.h" + +/* + The logical operations treat an mp_int as if it were a bit vector, + without regard to its sign (an mp_int is represented in a signed + magnitude format). Values are treated as if they had an infinite + string of zeros left of the most-significant bit. + */ + +/* Parity results */ + +#define MP_EVEN MP_YES +#define MP_ODD MP_NO + +/* Bitwise functions */ + +mp_err mpl_not(mp_int *a, mp_int *b); /* one's complement */ +mp_err mpl_and(mp_int *a, mp_int *b, mp_int *c); /* bitwise AND */ +mp_err mpl_or(mp_int *a, mp_int *b, mp_int *c); /* bitwise OR */ +mp_err mpl_xor(mp_int *a, mp_int *b, mp_int *c); /* bitwise XOR */ + +/* Shift functions */ + +mp_err mpl_rsh(const mp_int *a, mp_int *b, mp_digit d); /* right shift */ +mp_err mpl_lsh(const mp_int *a, mp_int *b, mp_digit d); /* left shift */ + +/* Bit count and parity */ + +mp_err mpl_num_set(mp_int *a, int *num); /* count set bits */ +mp_err mpl_num_clear(mp_int *a, int *num); /* count clear bits */ +mp_err mpl_parity(mp_int *a); /* determine parity */ + +/* Get & Set the value of a bit */ + +mp_err mpl_set_bit(mp_int *a, mp_size bitNum, mp_size value); +mp_err mpl_get_bit(const mp_int *a, mp_size bitNum); +mp_err mpl_get_bits(const mp_int *a, mp_size lsbNum, mp_size numBits); +mp_err mpl_significant_bits(const mp_int *a); + +#endif /* _MPLOGIC_H */ diff --git a/src/share/native/sun/security/ec/impl/mpmontg.c b/src/share/native/sun/security/ec/impl/mpmontg.c new file mode 100644 index 0000000000000000000000000000000000000000..df17f42732163e24f2ac984ebde9e0894c774be9 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mpmontg.c @@ -0,0 +1,199 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Sheueling Chang Shantz , + * Stephen Fung , and + * Douglas Stebila of Sun Laboratories. + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* $Id: mpmontg.c,v 1.20 2006/08/29 02:41:38 nelson%bolyard.com Exp $ */ + +/* This file implements moduluar exponentiation using Montgomery's + * method for modular reduction. This file implements the method + * described as "Improvement 1" in the paper "A Cryptogrpahic Library for + * the Motorola DSP56000" by Stephen R. Dusse' and Burton S. Kaliski Jr. + * published in "Advances in Cryptology: Proceedings of EUROCRYPT '90" + * "Lecture Notes in Computer Science" volume 473, 1991, pg 230-244, + * published by Springer Verlag. + */ + +#define MP_USING_CACHE_SAFE_MOD_EXP 1 +#ifndef _KERNEL +#include +#include /* ptrdiff_t */ +#endif +#include "mpi-priv.h" +#include "mplogic.h" +#include "mpprime.h" +#ifdef MP_USING_MONT_MULF +#include "montmulf.h" +#endif + +/* if MP_CHAR_STORE_SLOW is defined, we */ +/* need to know endianness of this platform. */ +#ifdef MP_CHAR_STORE_SLOW +#if !defined(MP_IS_BIG_ENDIAN) && !defined(MP_IS_LITTLE_ENDIAN) +#error "You must define MP_IS_BIG_ENDIAN or MP_IS_LITTLE_ENDIAN\n" \ + " if you define MP_CHAR_STORE_SLOW." +#endif +#endif + +#ifndef STATIC +#define STATIC +#endif + +#define MAX_ODD_INTS 32 /* 2 ** (WINDOW_BITS - 1) */ + +#ifndef _KERNEL +#if defined(_WIN32_WCE) +#define ABORT res = MP_UNDEF; goto CLEANUP +#else +#define ABORT abort() +#endif +#else +#define ABORT res = MP_UNDEF; goto CLEANUP +#endif /* _KERNEL */ + +/* computes T = REDC(T), 2^b == R */ +mp_err s_mp_redc(mp_int *T, mp_mont_modulus *mmm) +{ + mp_err res; + mp_size i; + + i = MP_USED(T) + MP_USED(&mmm->N) + 2; + MP_CHECKOK( s_mp_pad(T, i) ); + for (i = 0; i < MP_USED(&mmm->N); ++i ) { + mp_digit m_i = MP_DIGIT(T, i) * mmm->n0prime; + /* T += N * m_i * (MP_RADIX ** i); */ + MP_CHECKOK( s_mp_mul_d_add_offset(&mmm->N, m_i, T, i) ); + } + s_mp_clamp(T); + + /* T /= R */ + s_mp_div_2d(T, mmm->b); + + if ((res = s_mp_cmp(T, &mmm->N)) >= 0) { + /* T = T - N */ + MP_CHECKOK( s_mp_sub(T, &mmm->N) ); +#ifdef DEBUG + if ((res = mp_cmp(T, &mmm->N)) >= 0) { + res = MP_UNDEF; + goto CLEANUP; + } +#endif + } + res = MP_OKAY; +CLEANUP: + return res; +} + +#if !defined(MP_ASSEMBLY_MUL_MONT) && !defined(MP_MONT_USE_MP_MUL) +mp_err s_mp_mul_mont(const mp_int *a, const mp_int *b, mp_int *c, + mp_mont_modulus *mmm) +{ + mp_digit *pb; + mp_digit m_i; + mp_err res; + mp_size ib; + mp_size useda, usedb; + + ARGCHK(a != NULL && b != NULL && c != NULL, MP_BADARG); + + if (MP_USED(a) < MP_USED(b)) { + const mp_int *xch = b; /* switch a and b, to do fewer outer loops */ + b = a; + a = xch; + } + + MP_USED(c) = 1; MP_DIGIT(c, 0) = 0; + ib = MP_USED(a) + MP_MAX(MP_USED(b), MP_USED(&mmm->N)) + 2; + if((res = s_mp_pad(c, ib)) != MP_OKAY) + goto CLEANUP; + + useda = MP_USED(a); + pb = MP_DIGITS(b); + s_mpv_mul_d(MP_DIGITS(a), useda, *pb++, MP_DIGITS(c)); + s_mp_setz(MP_DIGITS(c) + useda + 1, ib - (useda + 1)); + m_i = MP_DIGIT(c, 0) * mmm->n0prime; + s_mp_mul_d_add_offset(&mmm->N, m_i, c, 0); + + /* Outer loop: Digits of b */ + usedb = MP_USED(b); + for (ib = 1; ib < usedb; ib++) { + mp_digit b_i = *pb++; + + /* Inner product: Digits of a */ + if (b_i) + s_mpv_mul_d_add_prop(MP_DIGITS(a), useda, b_i, MP_DIGITS(c) + ib); + m_i = MP_DIGIT(c, ib) * mmm->n0prime; + s_mp_mul_d_add_offset(&mmm->N, m_i, c, ib); + } + if (usedb < MP_USED(&mmm->N)) { + for (usedb = MP_USED(&mmm->N); ib < usedb; ++ib ) { + m_i = MP_DIGIT(c, ib) * mmm->n0prime; + s_mp_mul_d_add_offset(&mmm->N, m_i, c, ib); + } + } + s_mp_clamp(c); + s_mp_div_2d(c, mmm->b); + if (s_mp_cmp(c, &mmm->N) >= 0) { + MP_CHECKOK( s_mp_sub(c, &mmm->N) ); + } + res = MP_OKAY; + +CLEANUP: + return res; +} +#endif diff --git a/src/share/native/sun/security/ec/impl/mpprime.h b/src/share/native/sun/security/ec/impl/mpprime.h new file mode 100644 index 0000000000000000000000000000000000000000..78bcb18352ab42a78811360216d2961ac02b686a --- /dev/null +++ b/src/share/native/sun/security/ec/impl/mpprime.h @@ -0,0 +1,89 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * + * Utilities for finding and working with prime and pseudo-prime + * integers + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the MPI Arbitrary Precision Integer Arithmetic library. + * + * The Initial Developer of the Original Code is + * Michael J. Fromberger. + * Portions created by the Initial Developer are Copyright (C) 1997 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _MP_PRIME_H +#define _MP_PRIME_H + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include "mpi.h" + +extern const int prime_tab_size; /* number of primes available */ +extern const mp_digit prime_tab[]; + +/* Tests for divisibility */ +mp_err mpp_divis(mp_int *a, mp_int *b); +mp_err mpp_divis_d(mp_int *a, mp_digit d); + +/* Random selection */ +mp_err mpp_random(mp_int *a); +mp_err mpp_random_size(mp_int *a, mp_size prec); + +/* Pseudo-primality testing */ +mp_err mpp_divis_vector(mp_int *a, const mp_digit *vec, int size, int *which); +mp_err mpp_divis_primes(mp_int *a, mp_digit *np); +mp_err mpp_fermat(mp_int *a, mp_digit w); +mp_err mpp_fermat_list(mp_int *a, const mp_digit *primes, mp_size nPrimes); +mp_err mpp_pprime(mp_int *a, int nt); +mp_err mpp_sieve(mp_int *trial, const mp_digit *primes, mp_size nPrimes, + unsigned char *sieve, mp_size nSieve); +mp_err mpp_make_prime(mp_int *start, mp_size nBits, mp_size strong, + unsigned long * nTries); + +#endif /* _MP_PRIME_H */ diff --git a/src/share/native/sun/security/ec/impl/oid.c b/src/share/native/sun/security/ec/impl/oid.c new file mode 100644 index 0000000000000000000000000000000000000000..f3ced99bcb529472e9b751f40b6b69082a523d63 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/oid.c @@ -0,0 +1,473 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1994-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Dr Vipul Gupta , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +#include + +#ifndef _WIN32 +#ifndef __linux__ +#include +#endif /* __linux__ */ +#include +#endif /* _WIN32 */ + +#ifdef _KERNEL +#include +#else +#include +#endif +#include "ec.h" +#include "ecl-curve.h" +#include "ecc_impl.h" +#include "secoidt.h" + +#define CERTICOM_OID 0x2b, 0x81, 0x04 +#define SECG_OID CERTICOM_OID, 0x00 + +#define ANSI_X962_OID 0x2a, 0x86, 0x48, 0xce, 0x3d +#define ANSI_X962_CURVE_OID ANSI_X962_OID, 0x03 +#define ANSI_X962_GF2m_OID ANSI_X962_CURVE_OID, 0x00 +#define ANSI_X962_GFp_OID ANSI_X962_CURVE_OID, 0x01 + +#define CONST_OID static const unsigned char + +/* ANSI X9.62 prime curve OIDs */ +/* NOTE: prime192v1 is the same as secp192r1, prime256v1 is the + * same as secp256r1 + */ +CONST_OID ansiX962prime192v1[] = { ANSI_X962_GFp_OID, 0x01 }; +CONST_OID ansiX962prime192v2[] = { ANSI_X962_GFp_OID, 0x02 }; +CONST_OID ansiX962prime192v3[] = { ANSI_X962_GFp_OID, 0x03 }; +CONST_OID ansiX962prime239v1[] = { ANSI_X962_GFp_OID, 0x04 }; +CONST_OID ansiX962prime239v2[] = { ANSI_X962_GFp_OID, 0x05 }; +CONST_OID ansiX962prime239v3[] = { ANSI_X962_GFp_OID, 0x06 }; +CONST_OID ansiX962prime256v1[] = { ANSI_X962_GFp_OID, 0x07 }; + +/* SECG prime curve OIDs */ +CONST_OID secgECsecp112r1[] = { SECG_OID, 0x06 }; +CONST_OID secgECsecp112r2[] = { SECG_OID, 0x07 }; +CONST_OID secgECsecp128r1[] = { SECG_OID, 0x1c }; +CONST_OID secgECsecp128r2[] = { SECG_OID, 0x1d }; +CONST_OID secgECsecp160k1[] = { SECG_OID, 0x09 }; +CONST_OID secgECsecp160r1[] = { SECG_OID, 0x08 }; +CONST_OID secgECsecp160r2[] = { SECG_OID, 0x1e }; +CONST_OID secgECsecp192k1[] = { SECG_OID, 0x1f }; +CONST_OID secgECsecp224k1[] = { SECG_OID, 0x20 }; +CONST_OID secgECsecp224r1[] = { SECG_OID, 0x21 }; +CONST_OID secgECsecp256k1[] = { SECG_OID, 0x0a }; +CONST_OID secgECsecp384r1[] = { SECG_OID, 0x22 }; +CONST_OID secgECsecp521r1[] = { SECG_OID, 0x23 }; + +/* SECG characterisitic two curve OIDs */ +CONST_OID secgECsect113r1[] = {SECG_OID, 0x04 }; +CONST_OID secgECsect113r2[] = {SECG_OID, 0x05 }; +CONST_OID secgECsect131r1[] = {SECG_OID, 0x16 }; +CONST_OID secgECsect131r2[] = {SECG_OID, 0x17 }; +CONST_OID secgECsect163k1[] = {SECG_OID, 0x01 }; +CONST_OID secgECsect163r1[] = {SECG_OID, 0x02 }; +CONST_OID secgECsect163r2[] = {SECG_OID, 0x0f }; +CONST_OID secgECsect193r1[] = {SECG_OID, 0x18 }; +CONST_OID secgECsect193r2[] = {SECG_OID, 0x19 }; +CONST_OID secgECsect233k1[] = {SECG_OID, 0x1a }; +CONST_OID secgECsect233r1[] = {SECG_OID, 0x1b }; +CONST_OID secgECsect239k1[] = {SECG_OID, 0x03 }; +CONST_OID secgECsect283k1[] = {SECG_OID, 0x10 }; +CONST_OID secgECsect283r1[] = {SECG_OID, 0x11 }; +CONST_OID secgECsect409k1[] = {SECG_OID, 0x24 }; +CONST_OID secgECsect409r1[] = {SECG_OID, 0x25 }; +CONST_OID secgECsect571k1[] = {SECG_OID, 0x26 }; +CONST_OID secgECsect571r1[] = {SECG_OID, 0x27 }; + +/* ANSI X9.62 characteristic two curve OIDs */ +CONST_OID ansiX962c2pnb163v1[] = { ANSI_X962_GF2m_OID, 0x01 }; +CONST_OID ansiX962c2pnb163v2[] = { ANSI_X962_GF2m_OID, 0x02 }; +CONST_OID ansiX962c2pnb163v3[] = { ANSI_X962_GF2m_OID, 0x03 }; +CONST_OID ansiX962c2pnb176v1[] = { ANSI_X962_GF2m_OID, 0x04 }; +CONST_OID ansiX962c2tnb191v1[] = { ANSI_X962_GF2m_OID, 0x05 }; +CONST_OID ansiX962c2tnb191v2[] = { ANSI_X962_GF2m_OID, 0x06 }; +CONST_OID ansiX962c2tnb191v3[] = { ANSI_X962_GF2m_OID, 0x07 }; +CONST_OID ansiX962c2onb191v4[] = { ANSI_X962_GF2m_OID, 0x08 }; +CONST_OID ansiX962c2onb191v5[] = { ANSI_X962_GF2m_OID, 0x09 }; +CONST_OID ansiX962c2pnb208w1[] = { ANSI_X962_GF2m_OID, 0x0a }; +CONST_OID ansiX962c2tnb239v1[] = { ANSI_X962_GF2m_OID, 0x0b }; +CONST_OID ansiX962c2tnb239v2[] = { ANSI_X962_GF2m_OID, 0x0c }; +CONST_OID ansiX962c2tnb239v3[] = { ANSI_X962_GF2m_OID, 0x0d }; +CONST_OID ansiX962c2onb239v4[] = { ANSI_X962_GF2m_OID, 0x0e }; +CONST_OID ansiX962c2onb239v5[] = { ANSI_X962_GF2m_OID, 0x0f }; +CONST_OID ansiX962c2pnb272w1[] = { ANSI_X962_GF2m_OID, 0x10 }; +CONST_OID ansiX962c2pnb304w1[] = { ANSI_X962_GF2m_OID, 0x11 }; +CONST_OID ansiX962c2tnb359v1[] = { ANSI_X962_GF2m_OID, 0x12 }; +CONST_OID ansiX962c2pnb368w1[] = { ANSI_X962_GF2m_OID, 0x13 }; +CONST_OID ansiX962c2tnb431r1[] = { ANSI_X962_GF2m_OID, 0x14 }; + +#define OI(x) { siDEROID, (unsigned char *)x, sizeof x } +#ifndef SECOID_NO_STRINGS +#define OD(oid,tag,desc,mech,ext) { OI(oid), tag, desc, mech, ext } +#else +#define OD(oid,tag,desc,mech,ext) { OI(oid), tag, 0, mech, ext } +#endif + +#define CKM_INVALID_MECHANISM 0xffffffffUL + +/* XXX this is incorrect */ +#define INVALID_CERT_EXTENSION 1 + +#define CKM_ECDSA 0x00001041 +#define CKM_ECDSA_SHA1 0x00001042 +#define CKM_ECDH1_DERIVE 0x00001050 + +static SECOidData ANSI_prime_oids[] = { + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + + OD( ansiX962prime192v1, ECCurve_NIST_P192, + "ANSI X9.62 elliptic curve prime192v1 (aka secp192r1, NIST P-192)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962prime192v2, ECCurve_X9_62_PRIME_192V2, + "ANSI X9.62 elliptic curve prime192v2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962prime192v3, ECCurve_X9_62_PRIME_192V3, + "ANSI X9.62 elliptic curve prime192v3", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962prime239v1, ECCurve_X9_62_PRIME_239V1, + "ANSI X9.62 elliptic curve prime239v1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962prime239v2, ECCurve_X9_62_PRIME_239V2, + "ANSI X9.62 elliptic curve prime239v2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962prime239v3, ECCurve_X9_62_PRIME_239V3, + "ANSI X9.62 elliptic curve prime239v3", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962prime256v1, ECCurve_NIST_P256, + "ANSI X9.62 elliptic curve prime256v1 (aka secp256r1, NIST P-256)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ) +}; + +static SECOidData SECG_oids[] = { + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + + OD( secgECsect163k1, ECCurve_NIST_K163, + "SECG elliptic curve sect163k1 (aka NIST K-163)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect163r1, ECCurve_SECG_CHAR2_163R1, + "SECG elliptic curve sect163r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect239k1, ECCurve_SECG_CHAR2_239K1, + "SECG elliptic curve sect239k1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect113r1, ECCurve_SECG_CHAR2_113R1, + "SECG elliptic curve sect113r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect113r2, ECCurve_SECG_CHAR2_113R2, + "SECG elliptic curve sect113r2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp112r1, ECCurve_SECG_PRIME_112R1, + "SECG elliptic curve secp112r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp112r2, ECCurve_SECG_PRIME_112R2, + "SECG elliptic curve secp112r2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp160r1, ECCurve_SECG_PRIME_160R1, + "SECG elliptic curve secp160r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp160k1, ECCurve_SECG_PRIME_160K1, + "SECG elliptic curve secp160k1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp256k1, ECCurve_SECG_PRIME_256K1, + "SECG elliptic curve secp256k1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + OD( secgECsect163r2, ECCurve_NIST_B163, + "SECG elliptic curve sect163r2 (aka NIST B-163)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect283k1, ECCurve_NIST_K283, + "SECG elliptic curve sect283k1 (aka NIST K-283)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect283r1, ECCurve_NIST_B283, + "SECG elliptic curve sect283r1 (aka NIST B-283)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + OD( secgECsect131r1, ECCurve_SECG_CHAR2_131R1, + "SECG elliptic curve sect131r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect131r2, ECCurve_SECG_CHAR2_131R2, + "SECG elliptic curve sect131r2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect193r1, ECCurve_SECG_CHAR2_193R1, + "SECG elliptic curve sect193r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect193r2, ECCurve_SECG_CHAR2_193R2, + "SECG elliptic curve sect193r2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect233k1, ECCurve_NIST_K233, + "SECG elliptic curve sect233k1 (aka NIST K-233)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect233r1, ECCurve_NIST_B233, + "SECG elliptic curve sect233r1 (aka NIST B-233)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp128r1, ECCurve_SECG_PRIME_128R1, + "SECG elliptic curve secp128r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp128r2, ECCurve_SECG_PRIME_128R2, + "SECG elliptic curve secp128r2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp160r2, ECCurve_SECG_PRIME_160R2, + "SECG elliptic curve secp160r2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp192k1, ECCurve_SECG_PRIME_192K1, + "SECG elliptic curve secp192k1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp224k1, ECCurve_SECG_PRIME_224K1, + "SECG elliptic curve secp224k1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp224r1, ECCurve_NIST_P224, + "SECG elliptic curve secp224r1 (aka NIST P-224)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp384r1, ECCurve_NIST_P384, + "SECG elliptic curve secp384r1 (aka NIST P-384)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsecp521r1, ECCurve_NIST_P521, + "SECG elliptic curve secp521r1 (aka NIST P-521)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect409k1, ECCurve_NIST_K409, + "SECG elliptic curve sect409k1 (aka NIST K-409)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect409r1, ECCurve_NIST_B409, + "SECG elliptic curve sect409r1 (aka NIST B-409)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect571k1, ECCurve_NIST_K571, + "SECG elliptic curve sect571k1 (aka NIST K-571)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( secgECsect571r1, ECCurve_NIST_B571, + "SECG elliptic curve sect571r1 (aka NIST B-571)", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ) +}; + +static SECOidData ANSI_oids[] = { + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + + /* ANSI X9.62 named elliptic curves (characteristic two field) */ + OD( ansiX962c2pnb163v1, ECCurve_X9_62_CHAR2_PNB163V1, + "ANSI X9.62 elliptic curve c2pnb163v1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2pnb163v2, ECCurve_X9_62_CHAR2_PNB163V2, + "ANSI X9.62 elliptic curve c2pnb163v2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2pnb163v3, ECCurve_X9_62_CHAR2_PNB163V3, + "ANSI X9.62 elliptic curve c2pnb163v3", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2pnb176v1, ECCurve_X9_62_CHAR2_PNB176V1, + "ANSI X9.62 elliptic curve c2pnb176v1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb191v1, ECCurve_X9_62_CHAR2_TNB191V1, + "ANSI X9.62 elliptic curve c2tnb191v1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb191v2, ECCurve_X9_62_CHAR2_TNB191V2, + "ANSI X9.62 elliptic curve c2tnb191v2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb191v3, ECCurve_X9_62_CHAR2_TNB191V3, + "ANSI X9.62 elliptic curve c2tnb191v3", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + OD( ansiX962c2pnb208w1, ECCurve_X9_62_CHAR2_PNB208W1, + "ANSI X9.62 elliptic curve c2pnb208w1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb239v1, ECCurve_X9_62_CHAR2_TNB239V1, + "ANSI X9.62 elliptic curve c2tnb239v1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb239v2, ECCurve_X9_62_CHAR2_TNB239V2, + "ANSI X9.62 elliptic curve c2tnb239v2", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb239v3, ECCurve_X9_62_CHAR2_TNB239V3, + "ANSI X9.62 elliptic curve c2tnb239v3", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + { { siDEROID, NULL, 0 }, ECCurve_noName, + "Unknown OID", CKM_INVALID_MECHANISM, INVALID_CERT_EXTENSION }, + OD( ansiX962c2pnb272w1, ECCurve_X9_62_CHAR2_PNB272W1, + "ANSI X9.62 elliptic curve c2pnb272w1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2pnb304w1, ECCurve_X9_62_CHAR2_PNB304W1, + "ANSI X9.62 elliptic curve c2pnb304w1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb359v1, ECCurve_X9_62_CHAR2_TNB359V1, + "ANSI X9.62 elliptic curve c2tnb359v1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2pnb368w1, ECCurve_X9_62_CHAR2_PNB368W1, + "ANSI X9.62 elliptic curve c2pnb368w1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ), + OD( ansiX962c2tnb431r1, ECCurve_X9_62_CHAR2_TNB431R1, + "ANSI X9.62 elliptic curve c2tnb431r1", + CKM_INVALID_MECHANISM, + INVALID_CERT_EXTENSION ) +}; + +SECOidData * +SECOID_FindOID(const SECItem *oid) +{ + SECOidData *po; + SECOidData *ret; + int i; + + if (oid->len == 8) { + if (oid->data[6] == 0x00) { + /* XXX bounds check */ + po = &ANSI_oids[oid->data[7]]; + if (memcmp(oid->data, po->oid.data, 8) == 0) + ret = po; + } + if (oid->data[6] == 0x01) { + /* XXX bounds check */ + po = &ANSI_prime_oids[oid->data[7]]; + if (memcmp(oid->data, po->oid.data, 8) == 0) + ret = po; + } + } else if (oid->len == 5) { + /* XXX bounds check */ + po = &SECG_oids[oid->data[4]]; + if (memcmp(oid->data, po->oid.data, 5) == 0) + ret = po; + } else { + ret = NULL; + } + return(ret); +} + +ECCurveName +SECOID_FindOIDTag(const SECItem *oid) +{ + SECOidData *oiddata; + + oiddata = SECOID_FindOID (oid); + if (oiddata == NULL) + return ECCurve_noName; + + return oiddata->offset; +} diff --git a/src/share/native/sun/security/ec/impl/secitem.c b/src/share/native/sun/security/ec/impl/secitem.c new file mode 100644 index 0000000000000000000000000000000000000000..d9daacc8bc412d58a181024eca6e933c130804df --- /dev/null +++ b/src/share/native/sun/security/ec/impl/secitem.c @@ -0,0 +1,199 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1994-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* + * Support routines for SECItem data structure. + * + * $Id: secitem.c,v 1.14 2006/05/22 22:24:34 wtchang%redhat.com Exp $ + */ + +#include + +#ifndef _WIN32 +#ifndef __linux__ +#include +#endif /* __linux__ */ +#include +#endif /* _WIN32 */ + +#ifdef _KERNEL +#include +#else +#include + +#ifndef _WIN32 +#include +#endif /* _WIN32 */ + +#include +#endif +#include "ec.h" +#include "ecl-curve.h" +#include "ecc_impl.h" + +void SECITEM_FreeItem(SECItem *, PRBool); + +SECItem * +SECITEM_AllocItem(PRArenaPool *arena, SECItem *item, unsigned int len, + int kmflag) +{ + SECItem *result = NULL; + void *mark = NULL; + + if (arena != NULL) { + mark = PORT_ArenaMark(arena); + } + + if (item == NULL) { + if (arena != NULL) { + result = PORT_ArenaZAlloc(arena, sizeof(SECItem), kmflag); + } else { + result = PORT_ZAlloc(sizeof(SECItem), kmflag); + } + if (result == NULL) { + goto loser; + } + } else { + PORT_Assert(item->data == NULL); + result = item; + } + + result->len = len; + if (len) { + if (arena != NULL) { + result->data = PORT_ArenaAlloc(arena, len, kmflag); + } else { + result->data = PORT_Alloc(len, kmflag); + } + if (result->data == NULL) { + goto loser; + } + } else { + result->data = NULL; + } + + if (mark) { + PORT_ArenaUnmark(arena, mark); + } + return(result); + +loser: + if ( arena != NULL ) { + if (mark) { + PORT_ArenaRelease(arena, mark); + } + if (item != NULL) { + item->data = NULL; + item->len = 0; + } + } else { + if (result != NULL) { + SECITEM_FreeItem(result, (item == NULL) ? PR_TRUE : PR_FALSE); + } + /* + * If item is not NULL, the above has set item->data and + * item->len to 0. + */ + } + return(NULL); +} + +SECStatus +SECITEM_CopyItem(PRArenaPool *arena, SECItem *to, const SECItem *from, + int kmflag) +{ + to->type = from->type; + if (from->data && from->len) { + if ( arena ) { + to->data = (unsigned char*) PORT_ArenaAlloc(arena, from->len, + kmflag); + } else { + to->data = (unsigned char*) PORT_Alloc(from->len, kmflag); + } + + if (!to->data) { + return SECFailure; + } + PORT_Memcpy(to->data, from->data, from->len); + to->len = from->len; + } else { + to->data = 0; + to->len = 0; + } + return SECSuccess; +} + +void +SECITEM_FreeItem(SECItem *zap, PRBool freeit) +{ + if (zap) { +#ifdef _KERNEL + kmem_free(zap->data, zap->len); +#else + free(zap->data); +#endif + zap->data = 0; + zap->len = 0; + if (freeit) { +#ifdef _KERNEL + kmem_free(zap, sizeof (SECItem)); +#else + free(zap); +#endif + } + } +} diff --git a/src/share/native/sun/security/ec/impl/secoidt.h b/src/share/native/sun/security/ec/impl/secoidt.h new file mode 100644 index 0000000000000000000000000000000000000000..0935388cdb8e1f093fce9cd2dd67e1f6949931d8 --- /dev/null +++ b/src/share/native/sun/security/ec/impl/secoidt.h @@ -0,0 +1,103 @@ +/* ********************************************************************* + * + * Sun elects to have this file available under and governed by the + * Mozilla Public License Version 1.1 ("MPL") (see + * http://www.mozilla.org/MPL/ for full license text). For the avoidance + * of doubt and subject to the following, Sun also elects to allow + * licensees to use this file under the MPL, the GNU General Public + * License version 2 only or the Lesser General Public License version + * 2.1 only. Any references to the "GNU General Public License version 2 + * or later" or "GPL" in the following shall be construed to mean the + * GNU General Public License version 2 only. Any references to the "GNU + * Lesser General Public License version 2.1 or later" or "LGPL" in the + * following shall be construed to mean the GNU Lesser General Public + * License version 2.1 only. However, the following notice accompanied + * the original version of this file: + * + * Version: MPL 1.1/GPL 2.0/LGPL 2.1 + * + * The contents of this file are subject to the Mozilla Public License Version + * 1.1 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * http://www.mozilla.org/MPL/ + * + * Software distributed under the License is distributed on an "AS IS" basis, + * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License + * for the specific language governing rights and limitations under the + * License. + * + * The Original Code is the Netscape security libraries. + * + * The Initial Developer of the Original Code is + * Netscape Communications Corporation. + * Portions created by the Initial Developer are Copyright (C) 1994-2000 + * the Initial Developer. All Rights Reserved. + * + * Contributor(s): + * Dr Vipul Gupta , Sun Microsystems Laboratories + * + * Alternatively, the contents of this file may be used under the terms of + * either the GNU General Public License Version 2 or later (the "GPL"), or + * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), + * in which case the provisions of the GPL or the LGPL are applicable instead + * of those above. If you wish to allow use of your version of this file only + * under the terms of either the GPL or the LGPL, and not to allow others to + * use your version of this file under the terms of the MPL, indicate your + * decision by deleting the provisions above and replace them with the notice + * and other provisions required by the GPL or the LGPL. If you do not delete + * the provisions above, a recipient may use your version of this file under + * the terms of any one of the MPL, the GPL or the LGPL. + * + *********************************************************************** */ +/* + * Copyright 2007 Sun Microsystems, Inc. All rights reserved. + * Use is subject to license terms. + */ + +#ifndef _SECOIDT_H_ +#define _SECOIDT_H_ + +#pragma ident "%Z%%M% %I% %E% SMI" + +/* + * secoidt.h - public data structures for ASN.1 OID functions + * + * $Id: secoidt.h,v 1.23 2007/05/05 22:45:16 nelson%bolyard.com Exp $ + */ + +typedef struct SECOidDataStr SECOidData; +typedef struct SECAlgorithmIDStr SECAlgorithmID; + +/* +** An X.500 algorithm identifier +*/ +struct SECAlgorithmIDStr { + SECItem algorithm; + SECItem parameters; +}; + +#define SEC_OID_SECG_EC_SECP192R1 SEC_OID_ANSIX962_EC_PRIME192V1 +#define SEC_OID_SECG_EC_SECP256R1 SEC_OID_ANSIX962_EC_PRIME256V1 +#define SEC_OID_PKCS12_KEY_USAGE SEC_OID_X509_KEY_USAGE + +/* fake OID for DSS sign/verify */ +#define SEC_OID_SHA SEC_OID_MISS_DSS + +typedef enum { + INVALID_CERT_EXTENSION = 0, + UNSUPPORTED_CERT_EXTENSION = 1, + SUPPORTED_CERT_EXTENSION = 2 +} SECSupportExtenTag; + +struct SECOidDataStr { + SECItem oid; + ECCurveName offset; + const char * desc; + unsigned long mechanism; + SECSupportExtenTag supportedExtension; + /* only used for x.509 v3 extensions, so + that we can print the names of those + extensions that we don't even support */ +}; + +#endif /* _SECOIDT_H_ */ diff --git a/src/share/sample/nio/file/Xdd.java b/src/share/sample/nio/file/Xdd.java index b540b31fd1bbe2dbee8890a0a3c1c73fa6a9e9fa..b5102976077cd89db1406414dd919ed1ea99f532 100644 --- a/src/share/sample/nio/file/Xdd.java +++ b/src/share/sample/nio/file/Xdd.java @@ -57,9 +57,9 @@ public class Xdd { Path file = (args.length == 1) ? Paths.get(args[0]) : Paths.get(args[2]); - // check that user defined attributes are supported by the file system + // check that user defined attributes are supported by the file store FileStore store = file.getFileStore(); - if (!store.supportsFileAttributeView("user")) { + if (!store.supportsFileAttributeView(UserDefinedFileAttributeView.class)) { System.err.format("UserDefinedFileAttributeView not supported on %s\n", store); System.exit(-1); diff --git a/src/share/transport/socket/socketTransport.c b/src/share/transport/socket/socketTransport.c index f960fae2d39a726aaf2494410380e47511a98e81..59ebcc9ad3cdab8d4de07270d354c3d8722effac 100644 --- a/src/share/transport/socket/socketTransport.c +++ b/src/share/transport/socket/socketTransport.c @@ -134,15 +134,16 @@ setOptions(int fd) static jdwpTransportError handshake(int fd, jlong timeout) { - char *hello = "JDWP-Handshake"; + const char *hello = "JDWP-Handshake"; char b[16]; - int rv, received, i; + int rv, helloLen, received; if (timeout > 0) { dbgsysConfigureBlocking(fd, JNI_FALSE); } + helloLen = (int)strlen(hello); received = 0; - while (received < (int)strlen(hello)) { + while (received < helloLen) { int n; char *buf; if (timeout > 0) { @@ -154,7 +155,7 @@ handshake(int fd, jlong timeout) { } buf = b; buf += received; - n = dbgsysRecv(fd, buf, (int)strlen(hello)-received, 0); + n = dbgsysRecv(fd, buf, helloLen-received, 0); if (n == 0) { setLastError(0, "handshake failed - connection prematurally closed"); return JDWPTRANSPORT_ERROR_IO_ERROR; @@ -167,20 +168,19 @@ handshake(int fd, jlong timeout) { if (timeout > 0) { dbgsysConfigureBlocking(fd, JNI_TRUE); } - for (i=0; i<(int)strlen(hello); i++) { - if (b[i] != hello[i]) { - char msg[64]; - strcpy(msg, "handshake failed - received >"); - strncat(msg, b, strlen(hello)); - strcat(msg, "< - excepted >"); - strcat(msg, hello); - strcat(msg, "<"); - setLastError(0, msg); - return JDWPTRANSPORT_ERROR_IO_ERROR; - } + if (strncmp(b, hello, received) != 0) { + char msg[80+2*16]; + b[received] = '\0'; + /* + * We should really use snprintf here but it's not available on Windows. + * We can't use jio_snprintf without linking the transport against the VM. + */ + sprintf(msg, "handshake failed - received >%s< - expected >%s<", b, hello); + setLastError(0, msg); + return JDWPTRANSPORT_ERROR_IO_ERROR; } - if (dbgsysSend(fd, hello, (int)strlen(hello), 0) != (int)strlen(hello)) { + if (dbgsysSend(fd, (char*)hello, helloLen, 0) != helloLen) { RETURN_IO_ERROR("send failed during handshake"); } return JDWPTRANSPORT_ERROR_NONE; diff --git a/src/solaris/bin/java_md.c b/src/solaris/bin/java_md.c index 2e574ec2cec5d4638486054fc006dba71d71e7a0..73efc1090fddb70c1e82ef639f8bcf9cef8ebe76 100644 --- a/src/solaris/bin/java_md.c +++ b/src/solaris/bin/java_md.c @@ -1324,12 +1324,12 @@ FindBootStrapClass(JNIEnv *env, const char* classname) { if (findBootClass == NULL) { findBootClass = (FindClassFromBootLoader_t *)dlsym(RTLD_DEFAULT, - "JVM_FindClassFromClassLoader"); + "JVM_FindClassFromBootLoader"); if (findBootClass == NULL) { JLI_ReportErrorMessage(DLL_ERROR4, - "JVM_FindClassFromClassLoader"); + "JVM_FindClassFromBootLoader"); return NULL; } } - return findBootClass(env, classname, JNI_FALSE, (jobject)NULL, JNI_FALSE); + return findBootClass(env, classname); } diff --git a/src/solaris/classes/sun/awt/X11/XErrorHandler.java b/src/solaris/classes/sun/awt/X11/XErrorHandler.java index 218bb30327050f2a1a0885fbf19c4d0f7f52b866..d28ec9e1b3f084b8ac36f35dea094b841b5adb65 100644 --- a/src/solaris/classes/sun/awt/X11/XErrorHandler.java +++ b/src/solaris/classes/sun/awt/X11/XErrorHandler.java @@ -71,8 +71,8 @@ public abstract class XErrorHandler { return super.handleError(display, err); } // Shared instance - private static IgnoreBadWindowHandler theInstance = new IgnoreBadWindowHandler(); - public static IgnoreBadWindowHandler getInstance() { + private static VerifyChangePropertyHandler theInstance = new VerifyChangePropertyHandler(); + public static VerifyChangePropertyHandler getInstance() { return theInstance; } } diff --git a/src/solaris/classes/sun/awt/X11/XKeysym.java b/src/solaris/classes/sun/awt/X11/XKeysym.java index ea39aeacc94ea4b205e13d1b63f0aee1b6ee8413..83c655f11c84614c332252ae509dcdae5170cd85 100644 --- a/src/solaris/classes/sun/awt/X11/XKeysym.java +++ b/src/solaris/classes/sun/awt/X11/XKeysym.java @@ -354,6 +354,7 @@ public class XKeysym { keysym2UCSHash.put( (long)0xFFB7, (char)0x0037); // XK_KP_7 --> DIGIT SEVEN keysym2UCSHash.put( (long)0xFFB8, (char)0x0038); // XK_KP_8 --> DIGIT EIGHT keysym2UCSHash.put( (long)0xFFB9, (char)0x0039); // XK_KP_9 --> DIGIT NINE + keysym2UCSHash.put( (long)0xFE20, (char)0x0009); // XK_ISO_Left_Tab --> keysym2UCSHash.put( (long)0x1a1, (char)0x0104); // XK_Aogonek --> LATIN CAPITAL LETTER A WITH OGONEK keysym2UCSHash.put( (long)0x1a2, (char)0x02d8); // XK_breve --> BREVE keysym2UCSHash.put( (long)0x1a3, (char)0x0141); // XK_Lstroke --> LATIN CAPITAL LETTER L WITH STROKE diff --git a/src/solaris/classes/sun/awt/X11/XToolkit.java b/src/solaris/classes/sun/awt/X11/XToolkit.java index cba955ad1169467694b369af91c994437bcab6f5..dd72f5e43088b30da9fd8da066e4e10a775f00c1 100644 --- a/src/solaris/classes/sun/awt/X11/XToolkit.java +++ b/src/solaris/classes/sun/awt/X11/XToolkit.java @@ -166,6 +166,9 @@ public final class XToolkit extends UNIXToolkit implements Runnable { } public static void RESTORE_XERROR_HANDLER() { + // wait until all requests are processed by the X server + // and only then uninstall the error handler + XSync(); current_error_handler = null; } diff --git a/src/solaris/classes/sun/awt/X11/keysym2ucs.h b/src/solaris/classes/sun/awt/X11/keysym2ucs.h index e03e2a79c04c11600a0adf3e89876ca5e32f3bf9..e2372ac3c2ef0531d3c3cbb585dc5c0ad035f09c 100644 --- a/src/solaris/classes/sun/awt/X11/keysym2ucs.h +++ b/src/solaris/classes/sun/awt/X11/keysym2ucs.h @@ -649,7 +649,7 @@ SOFTWARE. 0x0000 #define XK_ISO_Last_Group 0xFE0E 0x0000 #define XK_ISO_Last_Group_Lock 0xFE0F -0x0000 #define XK_ISO_Left_Tab 0xFE20 +0x0009 #define XK_ISO_Left_Tab 0xFE20 0x0000 #define XK_ISO_Move_Line_Up 0xFE21 0x0000 #define XK_ISO_Move_Line_Down 0xFE22 0x0000 #define XK_ISO_Partial_Line_Up 0xFE23 diff --git a/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java b/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java index 5abd79ed9ef4b8501ca98f2628798c8b0c0a278d..f1ed83fb70ce7e9d19fc98ca91b07a0bb3a8ade7 100644 --- a/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java +++ b/src/solaris/classes/sun/net/www/protocol/http/NTLMAuthentication.java @@ -25,18 +25,23 @@ package sun.net.www.protocol.http; -import java.util.Arrays; -import java.util.StringTokenizer; -import java.util.Random; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.net.InetAddress; +import java.net.PasswordAuthentication; +import java.net.UnknownHostException; +import java.net.URL; +import java.security.GeneralSecurityException; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import javax.crypto.Cipher; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.DESKeySpec; import sun.net.www.HeaderParser; -import java.io.*; -import javax.crypto.*; -import javax.crypto.spec.*; -import java.security.*; -import java.net.*; - /** * NTLMAuthentication: * @@ -66,8 +71,6 @@ import java.net.*; class NTLMAuthentication extends AuthenticationInfo { private static final long serialVersionUID = -2403849171106437142L; - static char NTLM_AUTH = 'N'; - private byte[] type1; private byte[] type3; @@ -142,7 +145,10 @@ class NTLMAuthentication extends AuthenticationInfo { * from a system property: "http.auth.ntlm.domain". */ public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) { - super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, NTLM_AUTH, url, ""); + super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, + AuthScheme.NTLM, + url, + ""); init (pw); } @@ -166,7 +172,11 @@ class NTLMAuthentication extends AuthenticationInfo { */ public NTLMAuthentication(boolean isProxy, String host, int port, PasswordAuthentication pw) { - super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, NTLM_AUTH,host, port, ""); + super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, + AuthScheme.NTLM, + host, + port, + ""); init (pw); } @@ -234,13 +244,6 @@ class NTLMAuthentication extends AuthenticationInfo { } } - /* This is a no-op for NTLM, because there is no authentication information - * provided by the server to the client - */ - public void checkResponse (String header, String method, URL url) throws IOException { - } - - private void copybytes (byte[] dest, int destpos, String src, String enc) { try { byte[] x = src.getBytes(enc); diff --git a/src/solaris/classes/sun/nio/fs/LinuxFileStore.java b/src/solaris/classes/sun/nio/fs/LinuxFileStore.java index 7eb45bde48177836051420b1c50246a1030dea0f..81132985b75ab07ef9329faa66f8dc85f87d952c 100644 --- a/src/solaris/classes/sun/nio/fs/LinuxFileStore.java +++ b/src/solaris/classes/sun/nio/fs/LinuxFileStore.java @@ -25,6 +25,7 @@ package sun.nio.fs; +import java.nio.file.attribute.*; import java.util.*; import java.io.IOException; @@ -113,10 +114,12 @@ class LinuxFileStore } @Override - public boolean supportsFileAttributeView(String name) { + public boolean supportsFileAttributeView(Class type) { // support DosFileAttributeView and UserDefinedAttributeView if extended // attributes enabled - if (name.equals("dos") || name.equals("user")) { + if (type == DosFileAttributeView.class || + type == UserDefinedFileAttributeView.class) + { // lookup fstypes.properties FeatureStatus status = checkIfFeaturePresent("user_xattr"); if (status == FeatureStatus.PRESENT) @@ -142,7 +145,15 @@ class LinuxFileStore } return xattrEnabled; } + return super.supportsFileAttributeView(type); + } + @Override + public boolean supportsFileAttributeView(String name) { + if (name.equals("dos")) + return supportsFileAttributeView(DosFileAttributeView.class); + if (name.equals("user")) + return supportsFileAttributeView(UserDefinedFileAttributeView.class); return super.supportsFileAttributeView(name); } diff --git a/src/solaris/classes/sun/nio/fs/SolarisFileStore.java b/src/solaris/classes/sun/nio/fs/SolarisFileStore.java index aaa737137d3c31a183dde802d473172b782d4801..8cf2bbe08183fbbae053e1e29294b9a87ebf7cbd 100644 --- a/src/solaris/classes/sun/nio/fs/SolarisFileStore.java +++ b/src/solaris/classes/sun/nio/fs/SolarisFileStore.java @@ -25,6 +25,7 @@ package sun.nio.fs; +import java.nio.file.attribute.*; import java.io.IOException; import static sun.nio.fs.UnixNativeDispatcher.*; @@ -72,27 +73,39 @@ class SolarisFileStore } @Override - public boolean supportsFileAttributeView(String name) { - if (name.equals("acl")) { + public boolean supportsFileAttributeView(Class type) { + if (type == AclFileAttributeView.class) { // lookup fstypes.properties FeatureStatus status = checkIfFeaturePresent("nfsv4acl"); - if (status == FeatureStatus.PRESENT) - return true; - if (status == FeatureStatus.NOT_PRESENT) - return false; - // AclFileAttributeView available on ZFS - return (type().equals("zfs")); + switch (status) { + case PRESENT : return true; + case NOT_PRESENT : return false; + default : + // AclFileAttributeView available on ZFS + return (type().equals("zfs")); + } } - if (name.equals("user")) { + if (type == UserDefinedFileAttributeView.class) { // lookup fstypes.properties FeatureStatus status = checkIfFeaturePresent("xattr"); - if (status == FeatureStatus.PRESENT) - return true; - if (status == FeatureStatus.NOT_PRESENT) - return false; - return xattrEnabled; + switch (status) { + case PRESENT : return true; + case NOT_PRESENT : return false; + default : + // UserDefinedFileAttributeView available if extended + // attributes supported + return xattrEnabled; + } } + return super.supportsFileAttributeView(type); + } + @Override + public boolean supportsFileAttributeView(String name) { + if (name.equals("acl")) + return supportsFileAttributeView(AclFileAttributeView.class); + if (name.equals("user")) + return supportsFileAttributeView(UserDefinedFileAttributeView.class); return super.supportsFileAttributeView(name); } diff --git a/src/solaris/classes/sun/nio/fs/UnixFileStore.java b/src/solaris/classes/sun/nio/fs/UnixFileStore.java index 02397648eae122e43130f9226e9f6f360663ea1d..f19b2f90fe8755de58ea87c83096525ff13daa34 100644 --- a/src/solaris/classes/sun/nio/fs/UnixFileStore.java +++ b/src/solaris/classes/sun/nio/fs/UnixFileStore.java @@ -145,9 +145,8 @@ abstract class UnixFileStore { // lookup fstypes.properties FeatureStatus status = checkIfFeaturePresent("posix"); - if (status == FeatureStatus.NOT_PRESENT) - return false; - return true; + // assume supported if UNKNOWN + return (status != FeatureStatus.NOT_PRESENT); } return false; } diff --git a/src/solaris/native/java/util/TimeZone_md.c b/src/solaris/native/java/util/TimeZone_md.c index a3b9fc74c1e6b9068411ed58408d5bdf3f0a2cd8..4ec6ef4122abdb922f785532b2f5c028f30173e9 100644 --- a/src/solaris/native/java/util/TimeZone_md.c +++ b/src/solaris/native/java/util/TimeZone_md.c @@ -51,9 +51,9 @@ #ifdef __linux__ -static const char *sysconfig_clock_file = "/etc/sysconfig/clock"; -static const char *zoneinfo_dir = "/usr/share/zoneinfo"; -static const char *defailt_zoneinfo_file = "/etc/localtime"; +static const char *ETC_TIMEZONE_FILE = "/etc/timezone"; +static const char *ZONEINFO_DIR = "/usr/share/zoneinfo"; +static const char *DEFAULT_ZONEINFO_FILE = "/etc/localtime"; /* * Returns a point to the zone ID portion of the given zoneinfo file @@ -201,53 +201,22 @@ getPlatformTimeZoneID() size_t size; /* - * First, try the ZONE entry in /etc/sysconfig/clock. However, the - * ZONE entry is not set up after initial Red Hat Linux - * installation. In case that /etc/localtime is set up without - * using timeconfig, there might be inconsistency between - * /etc/localtime and the ZONE entry. The inconsistency between - * timeconfig and linuxconf is reported as a bug in the Red Hat - * web page as of May 1, 2000. + * Try reading the /etc/timezone file for Debian distros. There's + * no spec of the file format available. This parsing assumes that + * there's one line of an Olson tzid followed by a '\n', no + * leading or trailing spaces, no comments. */ - if ((fp = fopen(sysconfig_clock_file, "r")) != NULL) { + if ((fp = fopen(ETC_TIMEZONE_FILE, "r")) != NULL) { char line[256]; - while (fgets(line, sizeof(line), fp) != NULL) { - char *p = line; - char *s; - - SKIP_SPACE(p); - if (*p != 'Z') { - continue; - } - if (strncmp(p, "ZONE=\"", 6) == 0) { - p += 6; - } else { - /* - * In case we need to parse it token by token. - */ - if (strncmp(p, "ZONE", 4) != 0) { - continue; - } - p += 4; - SKIP_SPACE(p); - if (*p++ != '=') { - break; - } - SKIP_SPACE(p); - if (*p++ != '"') { - break; - } + if (fgets(line, sizeof(line), fp) != NULL) { + char *p = strchr(line, '\n'); + if (p != NULL) { + *p = '\0'; } - for (s = p; *s && *s != '"'; s++) - ; - if (*s != '"') { - /* this ZONE entry is broken. */ - break; + if (strlen(line) > 0) { + tz = strdup(line); } - *s = '\0'; - tz = strdup(p); - break; } (void) fclose(fp); if (tz != NULL) { @@ -258,7 +227,7 @@ getPlatformTimeZoneID() /* * Next, try /etc/localtime to find the zone ID. */ - if (lstat(defailt_zoneinfo_file, &statbuf) == -1) { + if (lstat(DEFAULT_ZONEINFO_FILE, &statbuf) == -1) { return NULL; } @@ -273,9 +242,9 @@ getPlatformTimeZoneID() char linkbuf[PATH_MAX+1]; int len; - if ((len = readlink(defailt_zoneinfo_file, linkbuf, sizeof(linkbuf)-1)) == -1) { + if ((len = readlink(DEFAULT_ZONEINFO_FILE, linkbuf, sizeof(linkbuf)-1)) == -1) { jio_fprintf(stderr, (const char *) "can't get a symlink of %s\n", - defailt_zoneinfo_file); + DEFAULT_ZONEINFO_FILE); return NULL; } linkbuf[len] = '\0'; @@ -295,7 +264,7 @@ getPlatformTimeZoneID() if (buf == NULL) { return NULL; } - if ((fd = open(defailt_zoneinfo_file, O_RDONLY)) == -1) { + if ((fd = open(DEFAULT_ZONEINFO_FILE, O_RDONLY)) == -1) { free((void *) buf); return NULL; } @@ -307,7 +276,7 @@ getPlatformTimeZoneID() } (void) close(fd); - tz = findZoneinfoFile(buf, size, zoneinfo_dir); + tz = findZoneinfoFile(buf, size, ZONEINFO_DIR); free((void *) buf); return tz; } diff --git a/src/windows/bin/java_md.c b/src/windows/bin/java_md.c index df5e6988c5e592ea84d83259b0e491f6fa4bb29d..a4fa4ccd63a122dbd85ce15b9c063c573a6e31ec 100644 --- a/src/windows/bin/java_md.c +++ b/src/windows/bin/java_md.c @@ -1093,12 +1093,6 @@ void SetJavaLauncherPlatformProps() {} */ static FindClassFromBootLoader_t *findBootClass = NULL; -#ifdef _M_AMD64 -#define JVM_BCLOADER "JVM_FindClassFromClassLoader" -#else -#define JVM_BCLOADER "_JVM_FindClassFromClassLoader@20" -#endif /* _M_AMD64 */ - jclass FindBootStrapClass(JNIEnv *env, const char *classname) { HMODULE hJvm; @@ -1108,13 +1102,13 @@ jclass FindBootStrapClass(JNIEnv *env, const char *classname) if (hJvm == NULL) return NULL; /* need to use the demangled entry point */ findBootClass = (FindClassFromBootLoader_t *)GetProcAddress(hJvm, - JVM_BCLOADER); + "JVM_FindClassFromBootLoader"); if (findBootClass == NULL) { - JLI_ReportErrorMessage(DLL_ERROR4, JVM_BCLOADER); + JLI_ReportErrorMessage(DLL_ERROR4, "JVM_FindClassFromBootLoader"); return NULL; } } - return findBootClass(env, classname, JNI_FALSE, (jobject)NULL, JNI_FALSE); + return findBootClass(env, classname); } void diff --git a/src/windows/classes/java/util/prefs/WindowsPreferences.java b/src/windows/classes/java/util/prefs/WindowsPreferences.java index b9ee8f49b283bd4e9d278582cb522401cd235d5e..c9034277360e915d36c3e384d006ff32a1ab9a7a 100644 --- a/src/windows/classes/java/util/prefs/WindowsPreferences.java +++ b/src/windows/classes/java/util/prefs/WindowsPreferences.java @@ -29,7 +29,7 @@ import java.util.Map; import java.util.TreeMap; import java.util.StringTokenizer; import java.io.ByteArrayOutputStream; -import java.util.logging.Logger; +import sun.util.logging.PlatformLogger; /** * Windows registry based implementation of Preferences. @@ -48,7 +48,7 @@ class WindowsPreferences extends AbstractPreferences{ /** * Logger for error messages */ - private static Logger logger; + private static PlatformLogger logger; /** * Windows registry path to Preferences's root nodes. @@ -1102,9 +1102,9 @@ class WindowsPreferences extends AbstractPreferences{ // assert false; } - private static synchronized Logger logger() { + private static synchronized PlatformLogger logger() { if (logger == null) { - logger = Logger.getLogger("java.util.prefs"); + logger = PlatformLogger.getLogger("java.util.prefs"); } return logger; } diff --git a/src/windows/classes/sun/awt/windows/fontconfig.properties b/src/windows/classes/sun/awt/windows/fontconfig.properties index a4e8e83ff79ac9e9f2c576cac71ea58d7a134358..b3aef483fd4c3b5385734137450ce9c7ebf90a27 100644 --- a/src/windows/classes/sun/awt/windows/fontconfig.properties +++ b/src/windows/classes/sun/awt/windows/fontconfig.properties @@ -1,6 +1,6 @@ # # -# Copyright 2003-2004 Sun Microsystems, Inc. All Rights Reserved. +# Copyright 2003-2009 Sun Microsystems, Inc. All Rights Reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -31,8 +31,11 @@ version=1 # Component Font Mappings allfonts.chinese-ms936=SimSun +allfonts.chinese-ms936-extb=SimSun-ExtB allfonts.chinese-gb18030=SimSun-18030 +allfonts.chinese-gb18030-extb=SimSun-ExtB allfonts.chinese-hkscs=MingLiU_HKSCS +allfonts.chinese-ms950-extb=MingLiU-ExtB allfonts.devanagari=Mangal allfonts.dingbats=Wingdings allfonts.lucida=Lucida Sans Regular @@ -41,120 +44,140 @@ allfonts.thai=Lucida Sans Regular serif.plain.alphabetic=Times New Roman serif.plain.chinese-ms950=MingLiU +serif.plain.chinese-ms950-extb=MingLiU-ExtB serif.plain.hebrew=David serif.plain.japanese=MS Mincho serif.plain.korean=Batang serif.bold.alphabetic=Times New Roman Bold serif.bold.chinese-ms950=PMingLiU +serif.bold.chinese-ms950-extb=PMingLiU-ExtB serif.bold.hebrew=David Bold serif.bold.japanese=MS Mincho serif.bold.korean=Batang serif.italic.alphabetic=Times New Roman Italic serif.italic.chinese-ms950=PMingLiU +serif.italic.chinese-ms950-extb=PMingLiU-ExtB serif.italic.hebrew=David serif.italic.japanese=MS Mincho serif.italic.korean=Batang serif.bolditalic.alphabetic=Times New Roman Bold Italic serif.bolditalic.chinese-ms950=PMingLiU +serif.bolditalic.chinese-ms950-extb=PMingLiU-ExtB serif.bolditalic.hebrew=David Bold serif.bolditalic.japanese=MS Mincho serif.bolditalic.korean=Batang sansserif.plain.alphabetic=Arial sansserif.plain.chinese-ms950=MingLiU +sansserif.plain.chinese-ms950-extb=MingLiU-ExtB sansserif.plain.hebrew=David sansserif.plain.japanese=MS Gothic sansserif.plain.korean=Gulim sansserif.bold.alphabetic=Arial Bold sansserif.bold.chinese-ms950=PMingLiU +sansserif.bold.chinese-ms950-extb=PMingLiU-ExtB sansserif.bold.hebrew=David Bold sansserif.bold.japanese=MS Gothic sansserif.bold.korean=Gulim sansserif.italic.alphabetic=Arial Italic sansserif.italic.chinese-ms950=PMingLiU +sansserif.italic.chinese-ms950-extb=PMingLiU-ExtB sansserif.italic.hebrew=David sansserif.italic.japanese=MS Gothic sansserif.italic.korean=Gulim sansserif.bolditalic.alphabetic=Arial Bold Italic sansserif.bolditalic.chinese-ms950=PMingLiU +sansserif.bolditalic.chinese-ms950-extb=PMingLiU-ExtB sansserif.bolditalic.hebrew=David Bold sansserif.bolditalic.japanese=MS Gothic sansserif.bolditalic.korean=Gulim monospaced.plain.alphabetic=Courier New monospaced.plain.chinese-ms950=MingLiU +monospaced.plain.chinese-ms950-extb=MingLiU-ExtB monospaced.plain.hebrew=David monospaced.plain.japanese=MS Gothic monospaced.plain.korean=GulimChe monospaced.bold.alphabetic=Courier New Bold monospaced.bold.chinese-ms950=PMingLiU +monospaced.bold.chinese-ms950-extb=PMingLiU-ExtB monospaced.bold.hebrew=David Bold monospaced.bold.japanese=MS Gothic monospaced.bold.korean=GulimChe monospaced.italic.alphabetic=Courier New Italic monospaced.italic.chinese-ms950=PMingLiU +monospaced.italic.chinese-ms950-extb=PMingLiU-ExtB monospaced.italic.hebrew=David monospaced.italic.japanese=MS Gothic monospaced.italic.korean=GulimChe monospaced.bolditalic.alphabetic=Courier New Bold Italic monospaced.bolditalic.chinese-ms950=PMingLiU +monospaced.bolditalic.chinese-ms950-extb=PMingLiU-ExtB monospaced.bolditalic.hebrew=David Bold monospaced.bolditalic.japanese=MS Gothic monospaced.bolditalic.korean=GulimChe dialog.plain.alphabetic=Arial dialog.plain.chinese-ms950=MingLiU +dialog.plain.chinese-ms950-extb=MingLiU-ExtB dialog.plain.hebrew=David dialog.plain.japanese=MS Gothic dialog.plain.korean=Gulim dialog.bold.alphabetic=Arial Bold dialog.bold.chinese-ms950=PMingLiU +dialog.bold.chinese-ms950-extb=PMingLiU-ExtB dialog.bold.hebrew=David Bold dialog.bold.japanese=MS Gothic dialog.bold.korean=Gulim dialog.italic.alphabetic=Arial Italic dialog.italic.chinese-ms950=PMingLiU +dialog.italic.chinese-ms950-extb=PMingLiU-ExtB dialog.italic.hebrew=David dialog.italic.japanese=MS Gothic dialog.italic.korean=Gulim dialog.bolditalic.alphabetic=Arial Bold Italic dialog.bolditalic.chinese-ms950=PMingLiU +dialog.bolditalic.chinese-ms950-extb=PMingLiU-ExtB dialog.bolditalic.hebrew=David Bold dialog.bolditalic.japanese=MS Gothic dialog.bolditalic.korean=Gulim dialoginput.plain.alphabetic=Courier New dialoginput.plain.chinese-ms950=MingLiU +dialoginput.plain.chinese-ms950-extb=MingLiU-ExtB dialoginput.plain.hebrew=David dialoginput.plain.japanese=MS Gothic dialoginput.plain.korean=Gulim dialoginput.bold.alphabetic=Courier New Bold dialoginput.bold.chinese-ms950=PMingLiU +dialoginput.bold.chinese-ms950-extb=PMingLiU-ExtB dialoginput.bold.hebrew=David Bold dialoginput.bold.japanese=MS Gothic dialoginput.bold.korean=Gulim dialoginput.italic.alphabetic=Courier New Italic dialoginput.italic.chinese-ms950=PMingLiU +dialoginput.italic.chinese-ms950-extb=PMingLiU-ExtB dialoginput.italic.hebrew=David dialoginput.italic.japanese=MS Gothic dialoginput.italic.korean=Gulim dialoginput.bolditalic.alphabetic=Courier New Bold Italic dialoginput.bolditalic.chinese-ms950=PMingLiU +dialoginput.bolditalic.chinese-ms950-extb=PMingLiU-ExtB dialoginput.bolditalic.hebrew=David Bold dialoginput.bolditalic.japanese=MS Gothic dialoginput.bolditalic.korean=Gulim @@ -163,31 +186,32 @@ dialoginput.bolditalic.korean=Gulim sequence.allfonts=alphabetic/default,dingbats,symbol -sequence.serif.GBK=alphabetic,chinese-ms936,dingbats,symbol -sequence.sansserif.GBK=alphabetic,chinese-ms936,dingbats,symbol -sequence.monospaced.GBK=chinese-ms936,alphabetic,dingbats,symbol -sequence.dialog.GBK=alphabetic,chinese-ms936,dingbats,symbol -sequence.dialoginput.GBK=alphabetic,chinese-ms936,dingbats,symbol - -sequence.serif.GB18030=alphabetic,chinese-gb18030,dingbats,symbol -sequence.sansserif.GB18030=alphabetic,chinese-gb18030,dingbats,symbol -sequence.monospaced.GB18030=chinese-gb18030,alphabetic,dingbats,symbol -sequence.dialog.GB18030=alphabetic,chinese-gb18030,dingbats,symbol -sequence.dialoginput.GB18030=alphabetic,chinese-gb18030,dingbats,symbol - -sequence.serif.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol -sequence.sansserif.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol -sequence.monospaced.x-windows-950=chinese-ms950,alphabetic,dingbats,symbol -sequence.dialog.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol -sequence.dialoginput.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol - -sequence.serif.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol -sequence.sansserif.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol -sequence.monospaced.x-MS950-HKSCS=chinese-ms950,alphabetic,chinese-hkscs,dingbats,symbol -sequence.dialog.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol -sequence.dialoginput.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol +sequence.serif.GBK=alphabetic,chinese-ms936,dingbats,symbol,chinese-ms936-extb +sequence.sansserif.GBK=alphabetic,chinese-ms936,dingbats,symbol,chinese-ms936-extb +sequence.monospaced.GBK=chinese-ms936,alphabetic,dingbats,symbol,chinese-ms936-extb +sequence.dialog.GBK=alphabetic,chinese-ms936,dingbats,symbol,chinese-ms936-extb +sequence.dialoginput.GBK=alphabetic,chinese-ms936,dingbats,symbol,chinese-ms936-extb + +sequence.serif.GB18030=alphabetic,chinese-gb18030,dingbats,symbol,chinese-gb18030-extb +sequence.sansserif.GB18030=alphabetic,chinese-gb18030,dingbats,symbol,chinese-gb18030-extb +sequence.monospaced.GB18030=chinese-gb18030,alphabetic,dingbats,symbol,chinese-gb18030-extb +sequence.dialog.GB18030=alphabetic,chinese-gb18030,dingbats,symbol,chinese-gb18030-extb +sequence.dialoginput.GB18030=alphabetic,chinese-gb18030,dingbats,symbol,chinese-gb18030-extb + +sequence.serif.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol,chinese-ms950-extb +sequence.sansserif.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol,chinese-ms950-extb +sequence.monospaced.x-windows-950=chinese-ms950,alphabetic,dingbats,symbol,chinese-ms950-extb +sequence.dialog.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol,chinese-ms950-extb +sequence.dialoginput.x-windows-950=alphabetic,chinese-ms950,dingbats,symbol,chinese-ms950-extb + +sequence.serif.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol,chinese-ms950-extb +sequence.sansserif.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol,chinese-ms950-extb +sequence.monospaced.x-MS950-HKSCS=chinese-ms950,alphabetic,chinese-hkscs,dingbats,symbol,chinese-ms950-extb +sequence.dialog.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol,chinese-ms950-extb +sequence.dialoginput.x-MS950-HKSCS=alphabetic,chinese-ms950,chinese-hkscs,dingbats,symbol,chinese-ms950-extb sequence.allfonts.UTF-8.hi=alphabetic/1252,devanagari,dingbats,symbol +sequence.allfonts.UTF-8.ja=alphabetic,japanese,devanagari,dingbats,symbol sequence.allfonts.windows-1255=hebrew,alphabetic/1252,dingbats,symbol @@ -207,7 +231,7 @@ sequence.allfonts.x-windows-874=alphabetic,thai,dingbats,symbol sequence.fallback=lucida,\ chinese-ms950,chinese-hkscs,chinese-ms936,chinese-gb18030,\ - japanese,korean + japanese,korean,chinese-ms950-extb,chinese-ms936-extb # Exclusion Ranges @@ -220,6 +244,7 @@ exclusion.hebrew=0041-005a,0060-007a,007f-00ff,20ac-20ac proportional.MS_Gothic=MS PGothic proportional.MS_Mincho=MS PMincho proportional.MingLiU=PMingLiU +proportional.MingLiU-ExtB=PMingLiU-ExtB # Font File Names @@ -240,9 +265,12 @@ filename.Times_New_Roman_Bold_Italic=TIMESBI.TTF filename.SimSun=SIMSUN.TTC filename.SimSun-18030=SIMSUN18030.TTC +filename.SimSun-ExtB=SIMSUNB.TTF filename.MingLiU=MINGLIU.TTC +filename.MingLiU-ExtB=MINGLIUB.TTC filename.PMingLiU=MINGLIU.TTC +filename.PMingLiU-ExtB=MINGLIUB.TTC filename.MingLiU_HKSCS=hkscsm3u.ttf filename.David=DAVID.TTF diff --git a/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java b/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java index 30f076a4f913545f63fa8832769db2255221e10d..462223e12d3f7157d09fad54a219d7eb68d54c74 100644 --- a/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java +++ b/src/windows/classes/sun/java2d/d3d/D3DGraphicsDevice.java @@ -67,6 +67,9 @@ public class D3DGraphicsDevice extends Win32GraphicsDevice { if (d3dAvailable) { // we don't use pixel formats for the d3d pipeline pfDisabled = true; + sun.misc.PerfCounter.getD3DAvailable().set(1); + } else { + sun.misc.PerfCounter.getD3DAvailable().set(0); } } diff --git a/src/windows/classes/sun/net/www/protocol/http/NTLMAuthentication.java b/src/windows/classes/sun/net/www/protocol/http/NTLMAuthentication.java index 12ffdf402ffbc941ec4b07d23dc520336caa047d..d3be68201619867607dedc5a376628181028b632 100644 --- a/src/windows/classes/sun/net/www/protocol/http/NTLMAuthentication.java +++ b/src/windows/classes/sun/net/www/protocol/http/NTLMAuthentication.java @@ -25,18 +25,13 @@ package sun.net.www.protocol.http; -import java.util.Arrays; -import java.util.StringTokenizer; -import java.util.Random; - +import java.io.IOException; +import java.net.InetAddress; +import java.net.PasswordAuthentication; +import java.net.UnknownHostException; +import java.net.URL; import sun.net.www.HeaderParser; -import java.io.*; -import javax.crypto.*; -import javax.crypto.spec.*; -import java.security.*; -import java.net.*; - /** * NTLMAuthentication: * @@ -47,7 +42,6 @@ class NTLMAuthentication extends AuthenticationInfo { private static final long serialVersionUID = 100L; - static final char NTLM_AUTH = 'N'; private String hostname; private static String defaultDomain; /* Domain to use if not specified by user */ @@ -88,7 +82,10 @@ class NTLMAuthentication extends AuthenticationInfo { * from a system property: "http.auth.ntlm.domain". */ public NTLMAuthentication(boolean isProxy, URL url, PasswordAuthentication pw) { - super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, NTLM_AUTH, url, ""); + super(isProxy ? PROXY_AUTHENTICATION : SERVER_AUTHENTICATION, + AuthScheme.NTLM, + url, + ""); init (pw); } @@ -119,7 +116,11 @@ class NTLMAuthentication extends AuthenticationInfo { */ public NTLMAuthentication(boolean isProxy, String host, int port, PasswordAuthentication pw) { - super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, NTLM_AUTH,host, port, ""); + super(isProxy?PROXY_AUTHENTICATION:SERVER_AUTHENTICATION, + AuthScheme.NTLM, + host, + port, + ""); init (pw); } @@ -191,9 +192,4 @@ class NTLMAuthentication extends AuthenticationInfo { } } - /* This is a no-op for NTLM, because there is no authentication information - * provided by the server to the client - */ - public void checkResponse (String header, String method, URL url) throws IOException { - } } diff --git a/src/windows/classes/sun/nio/fs/WindowsFileStore.java b/src/windows/classes/sun/nio/fs/WindowsFileStore.java index a906b54e0de39c2dd68d55916d5c3ae1bcdfa7f2..5af14f1673fca1baa001c3207cf73004d9f07f23 100644 --- a/src/windows/classes/sun/nio/fs/WindowsFileStore.java +++ b/src/windows/classes/sun/nio/fs/WindowsFileStore.java @@ -153,7 +153,7 @@ class WindowsFileStore public boolean supportsFileAttributeView(Class type) { if (type == null) throw new NullPointerException(); - if (type == BasicFileAttributeView.class) + if (type == BasicFileAttributeView.class || type == DosFileAttributeView.class) return true; if (type == AclFileAttributeView.class || type == FileOwnerAttributeView.class) return ((volInfo.flags() & FILE_PERSISTENT_ACLS) != 0); diff --git a/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java b/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java index cb4ded6e668df105aab4371cb16ed63832f4e218..44dee2c86c5f4f3a714e39752fa7fcd3a8e362f8 100644 --- a/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java +++ b/src/windows/classes/sun/security/krb5/internal/tools/Kinit.java @@ -1,5 +1,5 @@ /* - * Portions Copyright 2000-2007 Sun Microsystems, Inc. All Rights Reserved. + * Portions Copyright 2000-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -252,15 +252,15 @@ public class Kinit { } KRBError error = ke.getError(); int etype = error.getEType(); - byte[] salt = error.getSalt(); + String salt = error.getSalt(); byte[] s2kparams = error.getParams(); if (useKeytab) { - as_req = new KrbAsReq(skeys, true, etype, salt, s2kparams, - opt, principal, sname, + as_req = new KrbAsReq(skeys, true, etype, salt, + s2kparams, opt, principal, sname, null, null, null, null, addresses, null); } else { - as_req = new KrbAsReq(psswd, true, etype, salt, s2kparams, - opt, principal, sname, + as_req = new KrbAsReq(psswd, true, etype, salt, + s2kparams, opt, principal, sname, null, null, null, null, addresses, null); } as_rep = sendASRequest(as_req, useKeytab, realm, psswd, skeys); diff --git a/src/windows/classes/sun/security/krb5/internal/tools/Klist.java b/src/windows/classes/sun/security/krb5/internal/tools/Klist.java index 5cb919b9d527d0f9c1e4b5849bee51b589472e6c..40f2942e3a98e82db27ed156d415cfcc7329ffe3 100644 --- a/src/windows/classes/sun/security/krb5/internal/tools/Klist.java +++ b/src/windows/classes/sun/security/krb5/internal/tools/Klist.java @@ -30,17 +30,12 @@ package sun.security.krb5.internal.tools; +import java.net.InetAddress; import sun.security.krb5.*; import sun.security.krb5.internal.*; import sun.security.krb5.internal.ccache.*; import sun.security.krb5.internal.ktab.*; import sun.security.krb5.internal.crypto.EType; -import sun.security.krb5.KrbCryptoException; -import java.lang.RuntimeException; -import java.io.IOException; -import java.io.BufferedReader; -import java.io.InputStreamReader; -import java.io.File; /** * This class can execute as a command-line tool to list entries in @@ -51,9 +46,9 @@ import java.io.File; */ public class Klist { Object target; - // for credentials cache, options are 'f' and 'e'; + // for credentials cache, options are 'f', 'e', 'a' and 'n'; // for keytab, optionsare 't' and 'K' and 'e' - char[] options = new char[3]; + char[] options = new char[4]; String name; // the name of credentials cache and keytable. char action; // actions would be 'c' for credentials cache // and 'k' for keytable. @@ -62,7 +57,7 @@ public class Klist { /** * The main program that can be invoked at command line. *
    Usage: klist - * [[-c] [-f] [-e]] [-k [-t] [-K]] [name] + * [[-c] [-f] [-e] [-a [-n]]] [-k [-t] [-K]] [name] * -c specifes that credential cache is to be listed * -k specifies that key tab is to be listed * name name of the credentials cache or keytab @@ -70,6 +65,8 @@ public class Klist { *
      *
    • -f shows credentials flags *
    • -e shows the encryption type + *
    • -a shows addresses + *
    • -n do not reverse-resolve addresses *
    * available options for keytabs: *
  • -t shows keytab entry timestamps @@ -141,6 +138,12 @@ public class Klist { case 'k': action = 'k'; break; + case 'a': + options[2] = 'a'; + break; + case 'n': + options[3] = 'n'; + break; case 'f': options[1] = 'f'; break; @@ -202,7 +205,7 @@ public class Klist { } if (options[2] == 't') { System.out.println("\t Time stamp: " + - reformat(entries[i].getTimeStamp().toDate().toString())); + reformat(entries[i].getTimeStamp().toDate().toString())); } } } @@ -249,12 +252,33 @@ public class Klist { System.out.println(" Expires: " + endtime); if (options[0] == 'e') { etype = EType.toString(creds[i].getEType()); - System.out.println("\t Encryption type: " + etype); + System.out.println(" Encryption type: " + etype); } if (options[1] == 'f') { - System.out.println("\t Flags: " + + System.out.println(" Flags: " + creds[i].getTicketFlags().toString()); } + if (options[2] == 'a') { + boolean first = true; + InetAddress[] caddr + = creds[i].setKrbCreds().getClientAddresses(); + if (caddr != null) { + for (InetAddress ia: caddr) { + String out; + if (options[3] == 'n') { + out = ia.getHostAddress(); + } else { + out = ia.getCanonicalHostName(); + } + System.out.println(" " + + (first?"Addresses:":" ") + + " " + out); + first = false; + } + } else { + System.out.println(" [No host addresses info]"); + } + } } catch (RealmException e) { System.out.println("Error reading principal from "+ "the entry."); @@ -295,7 +319,7 @@ public class Klist { */ void printHelp() { System.out.println("\nUsage: klist " + - "[[-c] [-f] [-e]] [-k [-t] [-K]] [name]"); + "[[-c] [-f] [-e] [-a [-n]]] [-k [-t] [-K]] [name]"); System.out.println(" name\t name of credentials cache or " + " keytab with the prefix. File-based cache or " + "keytab's prefix is FILE:."); @@ -305,6 +329,8 @@ public class Klist { System.out.println(" options for credentials caches:"); System.out.println("\t-f \t shows credentials flags"); System.out.println("\t-e \t shows the encryption type"); + System.out.println("\t-a \t shows addresses"); + System.out.println("\t -n \t do not reverse-resolve addresses"); System.out.println(" options for keytabs:"); System.out.println("\t-t \t shows keytab entry timestamps"); System.out.println("\t-K \t shows keytab entry key value"); diff --git a/src/windows/lib/tzmappings b/src/windows/lib/tzmappings index a45200b75961a5bd7e22bf5793a9a5aa041ea5a9..ec2732f64fbc6e0aa7ea0eb359f933a9dfe8a77d 100644 --- a/src/windows/lib/tzmappings +++ b/src/windows/lib/tzmappings @@ -82,8 +82,8 @@ GMT:0,1::Europe/London: GMT Standard Time:0,1::Europe/London: Ekaterinburg:10,11::Asia/Yekaterinburg: Ekaterinburg Standard Time:10,11::Asia/Yekaterinburg: -West Asia:10,11::Asia/Karachi: -West Asia Standard Time:10,11::Asia/Karachi: +West Asia:10,11:UZ:Asia/Tashkent: +West Asia Standard Time:10,11:UZ:Asia/Tashkent: Central Asia:12,13::Asia/Dhaka: Central Asia Standard Time:12,13::Asia/Dhaka: N. Central Asia Standard Time:12,13::Asia/Novosibirsk: @@ -146,8 +146,8 @@ South Africa:4,69::Africa/Harare: South Africa Standard Time:4,69::Africa/Harare: Atlantic:40,41::America/Halifax: Atlantic Standard Time:40,41::America/Halifax: -SA Eastern:42,43::America/Buenos_Aires: -SA Eastern Standard Time:42,43::America/Buenos_Aires: +SA Eastern:42,43:GF:America/Cayenne: +SA Eastern Standard Time:42,43:GF:America/Cayenne: Mid-Atlantic:44,45::Atlantic/South_Georgia: Mid-Atlantic Standard Time:44,45::Atlantic/South_Georgia: Azores:46,47::Atlantic/Azores: @@ -160,21 +160,28 @@ New Zealand Standard Time:78,79::Pacific/Auckland: Tonga Standard Time:78,79::Pacific/Tongatapu: Arabian:8,9::Asia/Muscat: Arabian Standard Time:8,9::Asia/Muscat: -Caucasus:8,9::GMT+0400: -Caucasus Standard Time:8,9::GMT+0400: +Caucasus:8,9:AM:Asia/Yerevan: +Caucasus Standard Time:8,9:AM:Asia/Yerevan: GMT Standard Time:88,89::GMT: Greenwich:88,89::GMT: Greenwich Standard Time:88,89::GMT: -Central Brazilian Standard Time:900,900:BR:America/Manaus: -Central Standard Time (Mexico):901,901::America/Mexico_City: -Georgian Standard Time:902,902:GE:Asia/Tbilisi: -Mountain Standard Time (Mexico):903,903:MX:America/Chihuahua: -Namibia Standard Time:904,904:NA:Africa/Windhoek: -Pacific Standard Time (Mexico):905,905:MX:America/Tijuana: -Western Brazilian Standard Time:906,906:BR:America/Rio_Branco: -Azerbaijan Standard Time:907,907:AZ:Asia/Baku: -Jordan Standard Time:908,908:JO:Asia/Amman: -Middle East Standard Time:909,909:LB:Asia/Beirut: -Armenian Standard Time:910,910:AM:Asia/Yerevan: -Montevideo Standard Time:911,911:UY:America/Montevideo: -Venezuela Standard Time:912,912::America/Caracas: +Argentina Standard Time:900,900::America/Buenos_Aires: +Azerbaijan Standard Time:901,901:AZ:Asia/Baku: +Central Brazilian Standard Time:902,902:BR:America/Manaus: +Central Standard Time (Mexico):903,903::America/Mexico_City: +Georgian Standard Time:904,904:GE:Asia/Tbilisi: +Jordan Standard Time:905,905:JO:Asia/Amman: +Mauritius Standard Time:906,906:MU:Indian/Mauritius: +Middle East Standard Time:907,907:LB:Asia/Beirut: +Montevideo Standard Time:908,908:UY:America/Montevideo: +Morocco Standard Time:909,909:MA:Africa/Casablanca: +Mountain Standard Time (Mexico):910,910:MX:America/Chihuahua: +Namibia Standard Time:911,911:NA:Africa/Windhoek: +Pacific Standard Time (Mexico):912,912:MX:America/Tijuana: +Pakistan Standard Time:913,913::Asia/Karachi: +UTC:914,914::UTC: +Venezuela Standard Time:915,915::America/Caracas: +Kamchatka Standard Time:916,916:RU:Asia/Kamchatka: +Paraguay Standard Time:917,917:PY:America/Asuncion: +Western Brazilian Standard Time:918,918:BR:America/Rio_Branco: +Armenian Standard Time:919,919:AM:Asia/Yerevan: diff --git a/src/windows/native/sun/windows/awt_Dialog.cpp b/src/windows/native/sun/windows/awt_Dialog.cpp index 147bcf711ebdc7b7a3c278967e681047abd3f586..c0637237da4333d0f81e67dbfdb52b60eef502b0 100644 --- a/src/windows/native/sun/windows/awt_Dialog.cpp +++ b/src/windows/native/sun/windows/awt_Dialog.cpp @@ -364,6 +364,7 @@ void AwtDialog::Show() if (locationByPlatform) { moveToDefaultLocation(); } + EnableTranslucency(TRUE); if (IsFocusableWindow() && (IsAutoRequestFocus() || IsFocusedWindowModalBlocker())) { ::ShowWindow(GetHWnd(), SW_SHOW); } else { diff --git a/src/windows/native/sun/windows/awt_Frame.cpp b/src/windows/native/sun/windows/awt_Frame.cpp index 6e2ec9c0ff7d1ea65bb82bbe06b3a841e2db18f6..7d48921bab89810aadb8466d5559be3ea7e657fd 100644 --- a/src/windows/native/sun/windows/awt_Frame.cpp +++ b/src/windows/native/sun/windows/awt_Frame.cpp @@ -690,6 +690,8 @@ AwtFrame::Show() if (locationByPlatform) { moveToDefaultLocation(); } + EnableTranslucency(TRUE); + BOOL autoRequestFocus = IsAutoRequestFocus(); if (m_iconic) { diff --git a/src/windows/native/sun/windows/awt_Window.cpp b/src/windows/native/sun/windows/awt_Window.cpp index f10c9055d15c858d0049e679c582d5ec12268d91..4c902c3fb47b97973d0336c8ac3b739fbc4b3c19 100644 --- a/src/windows/native/sun/windows/awt_Window.cpp +++ b/src/windows/native/sun/windows/awt_Window.cpp @@ -218,12 +218,7 @@ AwtWindow::~AwtWindow() if (warningString != NULL) { delete [] warningString; } - ::EnterCriticalSection(&contentBitmapCS); - if (hContentBitmap != NULL) { - ::DeleteObject(hContentBitmap); - hContentBitmap = NULL; - } - ::LeaveCriticalSection(&contentBitmapCS); + DeleteContentBitmap(); ::DeleteCriticalSection(&contentBitmapCS); } @@ -372,6 +367,10 @@ MsgRouting AwtWindow::WmWindowPosChanged(LPARAM windowPos) { } } + if (wp->flags & SWP_HIDEWINDOW) { + EnableTranslucency(FALSE); + } + return mrDoDefault; } @@ -1130,6 +1129,8 @@ void AwtWindow::Show() moveToDefaultLocation(); } + EnableTranslucency(TRUE); + // The following block exists to support Menu/Tooltip animation for // Swing programs in a way which avoids introducing any new public api into // AWT or Swing. @@ -2494,27 +2495,73 @@ void AwtWindow::RedrawWindow() } } -void AwtWindow::SetTranslucency(BYTE opacity, BOOL opaque) +// Deletes the hContentBitmap if it is non-null +void AwtWindow::DeleteContentBitmap() +{ + ::EnterCriticalSection(&contentBitmapCS); + if (hContentBitmap != NULL) { + ::DeleteObject(hContentBitmap); + hContentBitmap = NULL; + } + ::LeaveCriticalSection(&contentBitmapCS); +} + +// The effects are enabled only upon showing the window. +// See 6780496 for details. +void AwtWindow::EnableTranslucency(BOOL enable) +{ + if (enable) { + SetTranslucency(getOpacity(), isOpaque(), FALSE, TRUE); + } else { + SetTranslucency(0xFF, TRUE, FALSE); + } +} + +/** + * Sets the translucency effects. + * + * This method is used to: + * + * 1. Apply the translucency effects upon showing the window + * (setValues == FALSE, useDefaultForOldValues == TRUE); + * 2. Turn off the effects upon hiding the window + * (setValues == FALSE, useDefaultForOldValues == FALSE); + * 3. Set the effects per user's request + * (setValues == TRUE, useDefaultForOldValues == FALSE); + * + * In case #3 the effects may or may not be applied immediately depending on + * the current visibility status of the window. + * + * The setValues argument indicates if we need to preserve the passed values + * in local fields for further use. + * The useDefaultForOldValues argument indicates whether we should consider + * the window as if it has not any effects applied at the moment. + */ +void AwtWindow::SetTranslucency(BYTE opacity, BOOL opaque, BOOL setValues, + BOOL useDefaultForOldValues) { - BYTE old_opacity = getOpacity(); - BOOL old_opaque = isOpaque(); + BYTE old_opacity = useDefaultForOldValues ? 0xFF : getOpacity(); + BOOL old_opaque = useDefaultForOldValues ? TRUE : isOpaque(); if (opacity == old_opacity && opaque == old_opaque) { return; } - setOpacity(opacity); - setOpaque(opaque); + if (setValues) { + m_opacity = opacity; + m_opaque = opaque; + } + + // If we're invisible and are storing the values, return + // Otherwise, apply the effects immediately + if (!IsVisible() && setValues) { + return; + } HWND hwnd = GetHWnd(); if (opaque != old_opaque) { - ::EnterCriticalSection(&contentBitmapCS); - if (hContentBitmap != NULL) { - ::DeleteObject(hContentBitmap); - hContentBitmap = NULL; - } - ::LeaveCriticalSection(&contentBitmapCS); + DeleteContentBitmap(); } if (opaque && opacity == 0xff) { @@ -2634,9 +2681,7 @@ void AwtWindow::UpdateWindow(JNIEnv* env, jintArray data, int width, int height, } ::EnterCriticalSection(&contentBitmapCS); - if (hContentBitmap != NULL) { - ::DeleteObject(hContentBitmap); - } + DeleteContentBitmap(); hContentBitmap = hBitmap; contentWidth = width; contentHeight = height; diff --git a/src/windows/native/sun/windows/awt_Window.h b/src/windows/native/sun/windows/awt_Window.h index 3edd39ed030ab3e66df454e71e55deac388c3e01..1d238b44dac1df0390039fd167f8f1479c1ac215 100644 --- a/src/windows/native/sun/windows/awt_Window.h +++ b/src/windows/native/sun/windows/awt_Window.h @@ -262,32 +262,29 @@ private: // from its hierarchy when shown. Currently applied to instances of // javax/swing/Popup$HeavyWeightWindow class. + // SetTranslucency() is the setter for the following two fields BYTE m_opacity; // The opacity level. == 0xff by default (when opacity mode is disabled) BOOL m_opaque; // Whether the window uses the perpixel translucency (false), or not (true). inline BYTE getOpacity() { return m_opacity; } - inline void setOpacity(BYTE opacity) { - m_opacity = opacity; - } inline BOOL isOpaque() { return m_opaque; } - inline void setOpaque(BOOL opaque) { - m_opaque = opaque; - } CRITICAL_SECTION contentBitmapCS; HBITMAP hContentBitmap; UINT contentWidth; UINT contentHeight; - void SetTranslucency(BYTE opacity, BOOL opaque); + void SetTranslucency(BYTE opacity, BOOL opaque, BOOL setValues = TRUE, + BOOL useDefaultForOldValues = FALSE); void UpdateWindow(int width, int height, HBITMAP hBitmap); void UpdateWindowImpl(int width, int height, HBITMAP hBitmap); void RedrawWindow(); + void DeleteContentBitmap(); static UINT untrustedWindowsCounter; @@ -352,6 +349,8 @@ protected: UINT currentWmSizeState; + void EnableTranslucency(BOOL enable); + private: int m_screenNum; diff --git a/test/com/sun/java/swing/plaf/windows/Test6824600.java b/test/com/sun/java/swing/plaf/windows/Test6824600.java new file mode 100644 index 0000000000000000000000000000000000000000..183bec947e9daedfa2f62a091a598356691886ca --- /dev/null +++ b/test/com/sun/java/swing/plaf/windows/Test6824600.java @@ -0,0 +1,70 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + @bug 6824600 + @summary OOM occurs when setLookAndFeel() is executed in Windows L&F(XP style) + @author Pavel Porvatov + @run main Test6824600 +*/ + +import com.sun.java.swing.plaf.windows.DesktopProperty; + +import java.awt.*; + +public class Test6824600 { + public static void main(String[] args) throws Exception { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + + HackedDesktopProperty desktopProperty = new HackedDesktopProperty("Button.background", null); + + // Register listener in toolkit + desktopProperty.getValueFromDesktop(); + + int length = toolkit.getPropertyChangeListeners().length; + + // Make several invocations + desktopProperty.getValueFromDesktop(); + desktopProperty.getValueFromDesktop(); + + desktopProperty.invalidate(); + + desktopProperty.getValueFromDesktop(); + desktopProperty.getValueFromDesktop(); + + if (length != toolkit.getPropertyChangeListeners().length) { + throw new RuntimeException("New listeners were added into Toolkit"); + } + } + + public static class HackedDesktopProperty extends DesktopProperty { + public HackedDesktopProperty(String key, Object fallback) { + super(key, fallback); + } + + // Publish the method + public Object getValueFromDesktop() { + return super.getValueFromDesktop(); + } + } +} diff --git a/test/com/sun/jdi/BadHandshakeTest.java b/test/com/sun/jdi/BadHandshakeTest.java index a0fba898f0bfff249f8206c0c2ace022c738d21a..d5ecd0a73b84d7a07c7f94912c6b13c421309043 100644 --- a/test/com/sun/jdi/BadHandshakeTest.java +++ b/test/com/sun/jdi/BadHandshakeTest.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 6306165 + * @bug 6306165 6432567 * @summary Check that a bad handshake doesn't cause a debuggee to abort * * @build VMConnection BadHandshakeTest Exit0 diff --git a/test/com/sun/jdi/BreakpointWithFullGC.sh b/test/com/sun/jdi/BreakpointWithFullGC.sh new file mode 100644 index 0000000000000000000000000000000000000000..74106760c7935e109c8dafabdc13b174cb240cde --- /dev/null +++ b/test/com/sun/jdi/BreakpointWithFullGC.sh @@ -0,0 +1,128 @@ +#!/bin/sh + +# +# Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code 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 +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# @test +# @bug 6862295 +# @summary Verify breakpoints still work after a full GC. +# @author dcubed (based on the test program posted to the following +# Eclipse thread https://bugs.eclipse.org/bugs/show_bug.cgi?id=279137) +# +# @run shell BreakpointWithFullGC.sh + +compileOptions=-g +# Hijacking the mode parameter to make sure we use a small amount +# of memory and can see what GC is doing. +mode="-Xmx32m -verbose:gc" +# Force use of a GC framework collector to see the original failure. +#mode="$mode -XX:+UseSerialGC" + +# Uncomment this to see the JDI trace +#jdbOptions=-dbgtrace + +createJavaFile() +{ + cat < $1.java.1 + +import java.util.ArrayList; +import java.util.List; + +public class $1 { + public static List objList = new ArrayList(); + + private static void init(int numObjs) { + for (int i = 0; i < numObjs; i++) { + objList.add(new Object()); + } + } + + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + System.out.println("top of loop"); // @1 breakpoint + init(1000000); + objList.clear(); + System.out.println("bottom of loop"); // @1 breakpoint + } + System.out.println("end of test"); // @1 breakpoint + } +} + +EOF +} + +# This is called to feed cmds to jdb. +dojdbCmds() +{ + setBkpts @1 + + # get to the first loop breakpoint + runToBkpt + # 19 "cont" commands gets us through all the loop breakpoints. + # Use for-loop instead of while-loop to avoid creating processes + # for '[' and 'expr'. + for ii in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19; do + contToBkpt + done + # get to the last breakpoint + contToBkpt +} + + +mysetup() +{ + if [ -z "$TESTSRC" ] ; then + TESTSRC=. + fi + + for ii in . $TESTSRC $TESTSRC/.. ; do + if [ -r "$ii/ShellScaffold.sh" ] ; then + . $ii/ShellScaffold.sh + break + fi + done +} + +# You could replace this next line with the contents +# of ShellScaffold.sh and this script will run just the same. +mysetup + +runit + +# make sure we hit the first breakpoint at least once +jdbFailIfNotPresent 'System\..*top of loop' + +# make sure we hit the second breakpoint at least once +jdbFailIfNotPresent 'System\..*bottom of loop' + +# make sure we hit the last breakpoint +jdbFailIfNotPresent 'System\..*end of test' + +# make sure we had at least one full GC +debuggeeFailIfNotPresent 'Full GC' + +# check for error message due to thread ID change +debuggeeFailIfPresent \ + 'Exception in thread "event-handler" java.lang.NullPointerException' + +pass diff --git a/test/com/sun/jdi/ShellScaffold.sh b/test/com/sun/jdi/ShellScaffold.sh index a133a8673bb215a3580972ce2a2bf80b3027bcbf..0ca14814e6cc4a6edf42d41c3183e9dbc8a86908 100644 --- a/test/com/sun/jdi/ShellScaffold.sh +++ b/test/com/sun/jdi/ShellScaffold.sh @@ -193,11 +193,17 @@ findPid() { # Return 0 if $1 is the pid of a running process. if [ -z "$isWin98" ] ; then - # Never use plain 'ps', which requires a "controlling terminal" - # and will fail with a "ps: no controlling terminal" error. - # Running under 'rsh' will cause this ps error. - # cygwin ps puts an I in column 1 for some reason. - $psCmd -e | $grep '^I* *'"$1 " > $devnull 2>&1 + if [ "$osname" = SunOS ] ; then + #Solaris and OpenSolaris use pgrep and not ps in psCmd + findPidCmd="$psCmd" + else + # Never use plain 'ps', which requires a "controlling terminal" + # and will fail with a "ps: no controlling terminal" error. + # Running under 'rsh' will cause this ps error. + # cygwin ps puts an I in column 1 for some reason. + findPidCmd="$psCmd -e" + fi + $findPidCmd | $grep '^I* *'"$1 " > $devnull 2>&1 return $? fi @@ -292,7 +298,17 @@ EOF # On linux, core files take a long time, and can leave # zombie processes if [ "$osname" = SunOS ] ; then - psCmd="/usr/ucb/ps -axwww" + #Experiments show Solaris '/usr/ucb/ps -axwww' and + #'/usr/bin/pgrep -f -l' provide the same small amount of the + #argv string (PRARGSZ=80 in /usr/include/sys/procfs.h) + # 1) This seems to have been working OK in ShellScaffold. + # 2) OpenSolaris does not provide /usr/ucb/ps, so use pgrep + # instead + #The alternative would be to use /usr/bin/pargs [pid] to get + #all the args for a process, splice them back into one + #long string, then grep. + UU=`/usr/bin/id -un` + psCmd="pgrep -f -l -U $UU" else ulimit -c 0 # See bug 6238593. diff --git a/test/java/lang/Compare.java b/test/java/lang/Compare.java new file mode 100644 index 0000000000000000000000000000000000000000..ea2fa580653eb53d354f25340daf7c754fb1f837 --- /dev/null +++ b/test/java/lang/Compare.java @@ -0,0 +1,142 @@ +/* + * Copyright 2009 Google, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6582946 + * @summary Test the primitive wrappers compare and compareTo methods + */ + +import java.util.Random; + +public class Compare { + + final Random rnd = new Random(); + + boolean toBoolean(long x) { return x > 0; } + + void compareAll(long x, long y) { + check(Double.compare(x, y) == + Double.valueOf(x).compareTo(Double.valueOf(y))); + check(Float.compare(x, y) == + Float.valueOf(x).compareTo(Float.valueOf(y))); + check(Long.compare(x, y) == + Long.valueOf(x).compareTo(Long.valueOf(y))); + check(Integer.compare((int) x, (int) y) == + Integer.valueOf((int) x).compareTo(Integer.valueOf((int) y))); + check(Short.compare((short) x, (short) y) == + Short.valueOf((short) x).compareTo(Short.valueOf((short) y))); + check(Character.compare((char) x, (char) y) == + Character.valueOf((char) x).compareTo(Character.valueOf((char) y))); + check(Byte.compare((byte) x, (byte) y) == + Byte.valueOf((byte) x).compareTo(Byte.valueOf((byte) y))); + check(Boolean.compare(toBoolean(x), toBoolean(y)) == + Boolean.valueOf(toBoolean(x)).compareTo(Boolean.valueOf(toBoolean(y)))); + + check(Double.compare(x, y) == -Double.compare(y, x)); + check(Float.compare(x, y) == -Float.compare(y, x)); + check(Long.compare(x, y) == -Long.compare(y, x)); + check(Integer.compare((int) x, (int) y) == + -Integer.compare((int) y, (int) x)); + check(Short.compare((short) x, (short) y) == + -Short.compare((short) y, (short) x)); + check(Character.compare((char) x, (char) y) == + -Character.compare((char) y, (char) x)); + check(Byte.compare((byte) x, (byte) y) == + -Byte.compare((byte) y, (byte) x)); + + equal(Long.compare(x, y), + x < y ? -1 : x > y ? 1 : 0); + + { + int a = (int) x, b = (int) y; + equal(Integer.compare(a, b), + a < b ? -1 : a > b ? 1 : 0); + } + + { + short a = (short) x, b = (short) y; + equal(Short.compare(a, b), + a - b); + } + + { + char a = (char) x, b = (char) y; + equal(Character.compare(a, b), + a - b); + } + + { + byte a = (byte) x, b = (byte) y; + equal(Byte.compare(a, b), + a - b); + } + + { + boolean a = toBoolean(x), b = toBoolean(y); + equal(Boolean.compare(a, b), + a == b ? 0 : a ? 1 : -1); + } + } + + void test(String args[]) throws Exception { + long[] longs = { + Long.MIN_VALUE, + Integer.MIN_VALUE, + Short.MIN_VALUE, + Character.MIN_VALUE, + Byte.MIN_VALUE, + -1, 0, 1, + Byte.MAX_VALUE, + Character.MAX_VALUE, + Short.MAX_VALUE, + Integer.MAX_VALUE, + Long.MAX_VALUE, + rnd.nextLong(), + rnd.nextInt(), + }; + + for (long x : longs) { + for (long y : longs) { + compareAll(x, y); + } + } + } + + //--------------------- Infrastructure --------------------------- + volatile int passed = 0, failed = 0; + void pass() {passed++;} + void fail() {failed++; Thread.dumpStack();} + void fail(String msg) {System.err.println(msg); fail();} + void unexpected(Throwable t) {failed++; t.printStackTrace();} + void check(boolean cond) {if (cond) pass(); else fail();} + void equal(Object x, Object y) { + if (x == null ? y == null : x.equals(y)) pass(); + else fail(x + " not equal to " + y);} + public static void main(String[] args) throws Throwable { + new Compare().instanceMain(args);} + public void instanceMain(String[] args) throws Throwable { + try {test(args);} catch (Throwable t) {unexpected(t);} + System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); + if (failed > 0) throw new AssertionError("Some tests failed");} +} diff --git a/test/java/lang/HashCode.java b/test/java/lang/HashCode.java new file mode 100644 index 0000000000000000000000000000000000000000..6d62facea7b66531b35b9f0dbe9ea07fddbba081 --- /dev/null +++ b/test/java/lang/HashCode.java @@ -0,0 +1,80 @@ +/* + * Copyright 2009 Google, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 4245470 + * @summary Test the primitive wrappers hashCode() + */ + +import java.util.Random; + +public class HashCode { + + final Random rnd = new Random(); + + void test(String args[]) throws Exception { + int[] ints = { + Integer.MIN_VALUE, + Short.MIN_VALUE, + Character.MIN_VALUE, + Byte.MIN_VALUE, + -1, 0, 1, + Byte.MAX_VALUE, + Character.MAX_VALUE, + Short.MAX_VALUE, + Integer.MAX_VALUE, + rnd.nextInt(), + }; + + for (int x : ints) { + check( new Long(x).hashCode() == (int)((long)x ^ (long)x>>>32)); + check(Long.valueOf(x).hashCode() == (int)((long)x ^ (long)x>>>32)); + check( new Integer(x).hashCode() == x); + check(Integer.valueOf(x).hashCode() == x); + check( new Short((short)x).hashCode() == (short) x); + check(Short.valueOf((short)x).hashCode() == (short) x); + check( new Character((char) x).hashCode() == (char) x); + check(Character.valueOf((char) x).hashCode() == (char) x); + check( new Byte((byte) x).hashCode() == (byte) x); + check(Byte.valueOf((byte) x).hashCode() == (byte) x); + } + } + + //--------------------- Infrastructure --------------------------- + volatile int passed = 0, failed = 0; + void pass() {passed++;} + void fail() {failed++; Thread.dumpStack();} + void fail(String msg) {System.err.println(msg); fail();} + void unexpected(Throwable t) {failed++; t.printStackTrace();} + void check(boolean cond) {if (cond) pass(); else fail();} + void equal(Object x, Object y) { + if (x == null ? y == null : x.equals(y)) pass(); + else fail(x + " not equal to " + y);} + public static void main(String[] args) throws Throwable { + new HashCode().instanceMain(args);} + public void instanceMain(String[] args) throws Throwable { + try {test(args);} catch (Throwable t) {unexpected(t);} + System.out.printf("%nPassed = %d, failed = %d%n%n", passed, failed); + if (failed > 0) throw new AssertionError("Some tests failed");} +} diff --git a/test/java/lang/ProcessBuilder/Basic.java b/test/java/lang/ProcessBuilder/Basic.java index 745fab468b9d4376a2b5362422900c8a025e089a..afb8ea8210e92b7bb8d6d26f3675ea5ee7a18528 100644 --- a/test/java/lang/ProcessBuilder/Basic.java +++ b/test/java/lang/ProcessBuilder/Basic.java @@ -25,7 +25,7 @@ * @test * @bug 4199068 4738465 4937983 4930681 4926230 4931433 4932663 4986689 * 5026830 5023243 5070673 4052517 4811767 6192449 6397034 6413313 - * 6464154 6523983 6206031 4960438 6631352 6631966 + * 6464154 6523983 6206031 4960438 6631352 6631966 6850957 6850958 * @summary Basic tests for Process and Environment Variable code * @run main/othervm Basic * @author Martin Buchholz @@ -302,6 +302,14 @@ public class Basic { printUTF8(val == null ? "null" : val); } else if (action.equals("System.getenv()")) { printUTF8(getenvAsString(System.getenv())); + } else if (action.equals("ArrayOOME")) { + Object dummy; + switch(new Random().nextInt(3)) { + case 0: dummy = new Integer[Integer.MAX_VALUE]; break; + case 1: dummy = new double[Integer.MAX_VALUE]; break; + case 2: dummy = new byte[Integer.MAX_VALUE][]; break; + default: throw new InternalError(); + } } else if (action.equals("pwd")) { printUTF8(new File(System.getProperty("user.dir")) .getCanonicalPath()); @@ -1472,6 +1480,22 @@ public class Basic { } } catch (Throwable t) { unexpected(t); } + //---------------------------------------------------------------- + // OOME in child allocating maximally sized array + // Test for hotspot/jvmti bug 6850957 + //---------------------------------------------------------------- + try { + List list = new ArrayList(javaChildArgs); + list.add(1, String.format("-XX:OnOutOfMemoryError=%s -version", + javaExe)); + list.add("ArrayOOME"); + ProcessResults r = run(new ProcessBuilder(list)); + check(r.out().contains("java.lang.OutOfMemoryError:")); + check(r.out().contains(javaExe)); + check(r.err().contains(System.getProperty("java.version"))); + equal(r.exitValue(), 1); + } catch (Throwable t) { unexpected(t); } + //---------------------------------------------------------------- // Windows has tricky semi-case-insensitive semantics //---------------------------------------------------------------- diff --git a/test/java/net/Authenticator/B4933582.java b/test/java/net/Authenticator/B4933582.java index 1ea04ae08d37c17e2f3fceeec5a2a0d2aca88e17..aa41ce045ee89e5a5bf8c9c563e142c34ffa380b 100644 --- a/test/java/net/Authenticator/B4933582.java +++ b/test/java/net/Authenticator/B4933582.java @@ -125,9 +125,16 @@ public class B4933582 implements HttpCallback { firstTime = args[0].equals ("first"); MyAuthenticator auth = new MyAuthenticator (); Authenticator.setDefault (auth); - AuthCacheValue.setAuthCache (new CacheImpl()); + CacheImpl cache; try { - server = new HttpServer (new B4933582(), 1, 10, 5009); + if (firstTime) { + server = new HttpServer (new B4933582(), 1, 10, 0); + cache = new CacheImpl (server.getLocalPort()); + } else { + cache = new CacheImpl (); + server = new HttpServer(new B4933582(), 1, 10, cache.getPort()); + } + AuthCacheValue.setAuthCache (cache); System.out.println ("Server: listening on port: " + server.getLocalPort()); client ("http://localhost:"+server.getLocalPort()+"/d1/foo.html"); } catch (Exception e) { @@ -172,8 +179,15 @@ public class B4933582 implements HttpCallback { static class CacheImpl extends AuthCacheImpl { HashMap map; + int port; // need to store the port number the server is using + CacheImpl () throws IOException { + this (-1); + } + + CacheImpl (int port) throws IOException { super(); + this.port = port; File src = new File ("cache.ser"); if (src.exists()) { ObjectInputStream is = new ObjectInputStream ( @@ -181,6 +195,8 @@ public class B4933582 implements HttpCallback { ); try { map = (HashMap)is.readObject (); + this.port = (Integer)is.readObject (); + System.out.println ("read port from file " + port); } catch (ClassNotFoundException e) { assert false; } @@ -192,6 +208,10 @@ public class B4933582 implements HttpCallback { setMap (map); } + int getPort () { + return port; + } + private void writeMap () { try { File dst = new File ("cache.ser"); @@ -203,6 +223,8 @@ public class B4933582 implements HttpCallback { new FileOutputStream (dst) ); os.writeObject(map); + os.writeObject(port); + System.out.println ("wrote port " + port); os.close(); } catch (IOException e) {} } diff --git a/test/java/net/Authenticator/B6870935.java b/test/java/net/Authenticator/B6870935.java new file mode 100644 index 0000000000000000000000000000000000000000..5afaed9d73b3f762da3e73e0220ed75863d4aa13 --- /dev/null +++ b/test/java/net/Authenticator/B6870935.java @@ -0,0 +1,262 @@ +/* + * Copyright 2001-2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/** + * @test + * @bug 6870935 + * @run main/othervm -Dhttp.nonProxyHosts="" -Dhttp.auth.digest.validateProxy=true B6870935 + */ + +import java.io.*; +import java.util.*; +import java.net.*; +import java.security.*; +import sun.net.www.*; + +/* This is one simple test of the RFC2617 digest authentication behavior + * It specifically tests that the client correctly checks the returned + * Authentication-Info header field from the server and throws an exception + * if the password is wrong + */ + +public class B6870935 { + + static char[] passwd = "password".toCharArray(); + static String username = "user"; + static String nonce = "abcdefghijklmnopqrstuvwxyz"; + static String realm = "wallyworld"; + static String uri = "http://www.ibm.com"; + static volatile boolean error = false; + + static class DigestServer extends Thread { + + ServerSocket s; + InputStream is; + OutputStream os; + int port; + + String reply1 = "HTTP/1.1 407 Proxy Authentication Required\r\n"+ + "Proxy-Authenticate: Digest realm=\""+realm+"\" domain=/ "+ + "nonce=\""+nonce+"\" qop=\"auth\"\r\n\r\n"; + + String reply2 = "HTTP/1.1 200 OK\r\n" + + "Date: Mon, 15 Jan 2001 12:18:21 GMT\r\n" + + "Server: Apache/1.3.14 (Unix)\r\n" + + "Content-Type: text/html; charset=iso-8859-1\r\n" + + "Transfer-encoding: chunked\r\n\r\n"+ + "B\r\nHelloWorld1\r\n"+ + "B\r\nHelloWorld2\r\n"+ + "B\r\nHelloWorld3\r\n"+ + "B\r\nHelloWorld4\r\n"+ + "B\r\nHelloWorld5\r\n"+ + "0\r\n"+ + "Proxy-Authentication-Info: "; + + DigestServer (ServerSocket y) { + s = y; + port = s.getLocalPort(); + } + + public void run () { + try { + Socket s1 = s.accept (); + is = s1.getInputStream (); + os = s1.getOutputStream (); + is.read (); + os.write (reply1.getBytes()); + Thread.sleep (2000); + s1.close (); + + s1 = s.accept (); + is = s1.getInputStream (); + os = s1.getOutputStream (); + is.read (); + // need to get the cnonce out of the response + MessageHeader header = new MessageHeader (is); + String raw = header.findValue ("Proxy-Authorization"); + HeaderParser parser = new HeaderParser (raw); + String cnonce = parser.findValue ("cnonce"); + String cnstring = parser.findValue ("nc"); + String clientrsp = parser.findValue ("response"); + String expected = computeDigest( + true, username,passwd,realm, + "GET", uri, nonce, cnonce, cnstring + ); + if (!expected.equals(clientrsp)) { + s1.close (); + s.close (); + error = true; + return; + } + + String reply = reply2 + getAuthorization ( + realm, false, uri, "GET", cnonce, + cnstring, passwd, username + ) +"\r\n"; + os.write (reply.getBytes()); + Thread.sleep (2000); + s1.close (); + } + catch (Exception e) { + System.out.println (e); + e.printStackTrace(); + } + } + + private String getAuthorization (String realm, boolean isRequest, String uri, String method, String cnonce, String cnstring, char[] password, String username) { + String response; + + try { + response = computeDigest(isRequest, username,passwd,realm, + method, uri, nonce, cnonce, cnstring); + } catch (NoSuchAlgorithmException ex) { + return null; + } + + String value = "Digest" + + " qop=\"auth" + + "\", cnonce=\"" + cnonce + + "\", rspauth=\"" + response + + "\", nc=\"" + cnstring + "\""; + return (value+ "\r\n"); + } + + private String computeDigest( + boolean isRequest, String userName, char[] password, + String realm, String connMethod, + String requestURI, String nonceString, + String cnonce, String ncValue + ) throws NoSuchAlgorithmException + { + + String A1, HashA1; + + MessageDigest md = MessageDigest.getInstance("MD5"); + + { + A1 = userName + ":" + realm + ":"; + HashA1 = encode(A1, password, md); + } + + String A2; + if (isRequest) { + A2 = connMethod + ":" + requestURI; + } else { + A2 = ":" + requestURI; + } + String HashA2 = encode(A2, null, md); + String combo, finalHash; + + { /* RRC2617 when qop=auth */ + combo = HashA1+ ":" + nonceString + ":" + ncValue + ":" + + cnonce + ":auth:" +HashA2; + + } + finalHash = encode(combo, null, md); + return finalHash; + } + + private final static char charArray[] = { + '0', '1', '2', '3', '4', '5', '6', '7', + '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' + }; + + private String encode(String src, char[] passwd, MessageDigest md) { + md.update(src.getBytes()); + if (passwd != null) { + byte[] passwdBytes = new byte[passwd.length]; + for (int i=0; i>> 4) & 0xf); + res.append(charArray[hashchar]); + hashchar = (digest[i] & 0xf); + res.append(charArray[hashchar]); + } + return res.toString(); + } + } + + + static class MyAuthenticator extends Authenticator { + public MyAuthenticator () { + super (); + } + + public PasswordAuthentication getPasswordAuthentication () + { + return (new PasswordAuthentication (username, passwd)); + } + } + + + public static void main(String[] args) throws Exception { + int nLoops = 1; + int nSize = 10; + int port, n =0; + byte b[] = new byte[nSize]; + DigestServer server; + ServerSocket sock; + + try { + sock = new ServerSocket (0); + port = sock.getLocalPort (); + } + catch (Exception e) { + System.out.println ("Exception: " + e); + return; + } + + server = new DigestServer(sock); + server.start (); + + try { + + Authenticator.setDefault (new MyAuthenticator ()); + SocketAddress addr = new InetSocketAddress ("127.0.0.1", port); + Proxy proxy = new Proxy (Proxy.Type.HTTP, addr); + String s = "http://www.ibm.com"; + URL url = new URL(s); + java.net.URLConnection conURL = url.openConnection(proxy); + + InputStream in = conURL.getInputStream(); + int c; + while ((c = in.read ()) != -1) { + } + in.close (); + } + catch(IOException e) { + e.printStackTrace(); + error = true; + } + if (error) { + throw new RuntimeException ("Error in test"); + } + } +} diff --git a/test/java/net/MulticastSocket/SetOutgoingIf.java b/test/java/net/MulticastSocket/SetOutgoingIf.java index d24b03c79f3cb3c6d26c10a6bb3c13e23147a633..d793f19621570b14a70a51dba17a83e898a00001 100644 --- a/test/java/net/MulticastSocket/SetOutgoingIf.java +++ b/test/java/net/MulticastSocket/SetOutgoingIf.java @@ -70,7 +70,8 @@ public class SetOutgoingIf { // List nics = new ArrayList(); for (NetworkInterface nic : Collections.list(NetworkInterface.getNetworkInterfaces())) { - if (!nic.isLoopback()) + // we should use only network interfaces with multicast support which are in "up" state + if (!nic.isLoopback() && nic.supportsMulticast() && nic.isUp()) nics.add(nic); } if (nics.size() <= 1) { diff --git a/test/java/net/ProxySelector/B6737819.java b/test/java/net/ProxySelector/B6737819.java new file mode 100644 index 0000000000000000000000000000000000000000..360f1ae4aefe24e0d101ea283a6eeaefe09f5ecd --- /dev/null +++ b/test/java/net/ProxySelector/B6737819.java @@ -0,0 +1,63 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +/* + * @test + * @bug 6737819 + * @summary sun.misc.net.DefaultProxySelector doesn't use proxy setting to localhost + */ + +import java.net.ProxySelector; +import java.net.Proxy; +import java.net.URI; + +public class B6737819 { + private static String[] uris = { + "http://localhost/index.html", + "http://127.0.0.1/index.html", + "http://127.2/index.html", + "http://[::1]/index.html" + }; + public static void main(String[] args) throws Exception { + System.setProperty("http.proxyHost", "myproxy"); + System.setProperty("http.proxyPort", "8080"); + ProxySelector sel = ProxySelector.getDefault(); + java.util.List l; + // Default value for http.nonProxyHots should exclude all this uris + // from going through the HTTP proxy + for (String s : uris) { + l = sel.select(new URI(s)); + if (l.size() == 1 && l.get(0).type() != Proxy.Type.DIRECT) { + throw new RuntimeException("ProxySelector returned the wrong proxy for " + s); + } + } + // Let's override the default nonProxyHosts and make sure we now get a + // HTTP proxy + System.setProperty("http.nonProxyHosts", ""); + for (String s : uris) { + l = sel.select(new URI(s)); + if (l.size() == 1 && l.get(0).type() != Proxy.Type.HTTP) { + throw new RuntimeException("ProxySelector returned the wrong proxy for " + s); + } + } + } +} diff --git a/test/java/nio/channels/Channels/Basic.java b/test/java/nio/channels/Channels/Basic.java index 3a931a3f4c5e61d8cc17531aa219f3e4bc89ce1f..bfa9f0d404e2ef07f35c8639672a4f4e4d6672e9 100644 --- a/test/java/nio/channels/Channels/Basic.java +++ b/test/java/nio/channels/Channels/Basic.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 4417152 4481572 6248930 6725399 + * @bug 4417152 4481572 6248930 6725399 6884800 * @summary Test Channels basic functionality */ @@ -225,8 +225,7 @@ public class Basic { private static void testNewInputStream(File blah) throws Exception { FileInputStream fis = new FileInputStream(blah); FileChannel fc = fis.getChannel(); - ReadableByteChannel rbc = (ReadableByteChannel)fc; - InputStream is = Channels.newInputStream(rbc); + InputStream is = Channels.newInputStream(fc); int messageSize = message.length() * ITERATIONS * 3 + 1; byte bb[] = new byte[messageSize]; @@ -234,8 +233,13 @@ public class Basic { int totalRead = 0; while (bytesRead != -1) { totalRead += bytesRead; + long rem = Math.min(fc.size() - totalRead, (long)Integer.MAX_VALUE); + if (is.available() != (int)rem) + throw new RuntimeException("available not useful or not maximally useful"); bytesRead = is.read(bb, totalRead, messageSize - totalRead); } + if (is.available() != 0) + throw new RuntimeException("available() should return 0 at EOF"); String result = new String(bb, 0, totalRead, encoding); int len = message.length(); diff --git a/test/java/nio/file/FileStore/Basic.java b/test/java/nio/file/FileStore/Basic.java index 604795db43591870b97ec35a27dda563ebd0c4a6..85e6b992a57922348f05c4ed364c8fd54a2a91a4 100644 --- a/test/java/nio/file/FileStore/Basic.java +++ b/test/java/nio/file/FileStore/Basic.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 4313887 + * @bug 4313887 6873621 * @summary Unit test for java.nio.file.FileStore * @library .. */ @@ -67,6 +67,15 @@ public class Basic { * Test: File and FileStore attributes */ assertTrue(store1.supportsFileAttributeView("basic")); + assertTrue(store1.supportsFileAttributeView(BasicFileAttributeView.class)); + assertTrue(store1.supportsFileAttributeView("posix") == + store1.supportsFileAttributeView(PosixFileAttributeView.class)); + assertTrue(store1.supportsFileAttributeView("dos") == + store1.supportsFileAttributeView(DosFileAttributeView.class)); + assertTrue(store1.supportsFileAttributeView("acl") == + store1.supportsFileAttributeView(AclFileAttributeView.class)); + assertTrue(store1.supportsFileAttributeView("user") == + store1.supportsFileAttributeView(UserDefinedFileAttributeView.class)); /** * Test: Enumerate all FileStores diff --git a/test/java/nio/file/Files/WalkWithSecurity.java b/test/java/nio/file/Files/WalkWithSecurity.java new file mode 100644 index 0000000000000000000000000000000000000000..5b2ab56447426f6ba81c3467fe45692540d24f20 --- /dev/null +++ b/test/java/nio/file/Files/WalkWithSecurity.java @@ -0,0 +1,132 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6876541 + * @summary Test Files.walkFileTree in the presence of a security manager + * @build WalkWithSecurity + * @run main/othervm WalkWithSecurity grantAll.policy pass + * @run main/othervm WalkWithSecurity denyAll.policy fail + * @run main/othervm WalkWithSecurity grantTopOnly.policy top_only + */ + +import java.nio.file.*; +import java.nio.file.attribute.BasicFileAttributes; +import java.io.IOException; + +public class WalkWithSecurity { + + public static void main(String[] args) throws IOException { + String policyFile = args[0]; + ExpectedResult expectedResult = ExpectedResult.valueOf(args[1].toUpperCase()); + + String here = System.getProperty("user.dir"); + String testSrc = System.getProperty("test.src"); + if (testSrc == null) + throw new RuntimeException("This test must be run by jtreg"); + Path dir = Paths.get(testSrc); + + // Sanity check the environment + if (Paths.get(here).isSameFile(dir)) + throw new RuntimeException("Working directory cannot be " + dir); + DirectoryStream stream = dir.newDirectoryStream(); + try { + if (!stream.iterator().hasNext()) + throw new RuntimeException(testSrc + " is empty"); + } finally { + stream.close(); + } + + // Install security manager with the given policy file + System.setProperty("java.security.policy", + dir.resolve(policyFile).toString()); + System.setSecurityManager(new SecurityManager()); + + // Walk the source tree + CountingVisitor visitor = new CountingVisitor(); + SecurityException exception = null; + try { + Files.walkFileTree(dir, visitor); + } catch (SecurityException se) { + exception = se; + } + + // Check result + switch (expectedResult) { + case PASS: + if (exception != null) { + exception.printStackTrace(); + throw new RuntimeException("SecurityException not expected"); + } + if (visitor.count() == 0) + throw new RuntimeException("No files visited"); + break; + case FAIL: + if (exception == null) + throw new RuntimeException("SecurityException expected"); + if (visitor.count() > 0) + throw new RuntimeException("Files were visited"); + break; + case TOP_ONLY: + if (exception != null) { + exception.printStackTrace(); + throw new RuntimeException("SecurityException not expected"); + } + if (visitor.count() == 0) + throw new RuntimeException("Starting file not visited"); + if (visitor.count() > 1) + throw new RuntimeException("More than starting file visited"); + break; + default: + throw new RuntimeException("Should not get here"); + } + } + + static enum ExpectedResult { + PASS, + FAIL, + TOP_ONLY; + } + + static class CountingVisitor extends SimpleFileVisitor { + private int count; + + int count() { + return count; + } + + @Override + public FileVisitResult preVisitDirectory(Path dir) { + System.out.println(dir); + count++; + return FileVisitResult.CONTINUE; + } + + @Override + public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) { + System.out.println(file); + count++; + return FileVisitResult.CONTINUE; + } + } +} diff --git a/test/java/nio/file/Files/denyAll.policy b/test/java/nio/file/Files/denyAll.policy new file mode 100644 index 0000000000000000000000000000000000000000..32500947791001ea25267a6f5c54d95ec0075172 --- /dev/null +++ b/test/java/nio/file/Files/denyAll.policy @@ -0,0 +1,3 @@ +// policy file that does not grant any permissions +grant { +}; diff --git a/test/java/nio/file/Files/grantAll.policy b/test/java/nio/file/Files/grantAll.policy new file mode 100644 index 0000000000000000000000000000000000000000..85bc0d0fb51f23eea23c226cb8a1f7f79af92901 --- /dev/null +++ b/test/java/nio/file/Files/grantAll.policy @@ -0,0 +1,5 @@ +// policy file that grants read access to source directory and all descendants +grant { + permission java.io.FilePermission "${test.src}", "read"; + permission java.io.FilePermission "${test.src}${file.separator}-", "read"; +}; diff --git a/test/java/nio/file/Files/grantTopOnly.policy b/test/java/nio/file/Files/grantTopOnly.policy new file mode 100644 index 0000000000000000000000000000000000000000..fca1539416feb5a502dfacbff39fe0bc7e14a763 --- /dev/null +++ b/test/java/nio/file/Files/grantTopOnly.policy @@ -0,0 +1,4 @@ +// policy file that grants read access to source directory +grant { + permission java.io.FilePermission "${test.src}", "read"; +}; diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIDimension.java b/test/java/util/TimeZone/ListTimeZones.java similarity index 67% rename from make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIDimension.java rename to test/java/util/TimeZone/ListTimeZones.java index e611ad6274378d492003d17823836a5e62542df8..88e0e866ce20e5979510c8da719fdc2766678e6d 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/UIDimension.java +++ b/test/java/util/TimeZone/ListTimeZones.java @@ -1,5 +1,5 @@ /* - * Copyright 2005-2006 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,27 +22,24 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.synthdesigner.synthmodel; - -import java.awt.Dimension; /** - * UIDimension - * - * @author Richard Bair - * @author Jasper Potts + * @test + * @bug 6851214 + * @summary Allow 24:00 as a valid end/start DST time stamp + * @run main ListTimeZones */ -public class UIDimension extends UIDefault { - public UIDimension() { - } - public Dimension getDimension() { - return super.getValue(); - } +import java.util.*; - public void setDimension(Dimension d) { - Dimension old = getDimension(); - super.setValue(d); - firePropertyChange("dimension", old, d); +public class ListTimeZones{ + public static void main(String[] args){ + Date date = new Date(); + String TimeZoneIds[] = TimeZone.getAvailableIDs(); + for(int i = 0; i < TimeZoneIds.length; i++){ + TimeZone tz = TimeZone.getTimeZone(TimeZoneIds[i]); + Calendar calendar = new GregorianCalendar(tz); + String calString = calendar.toString(); } + } } diff --git a/test/javax/swing/JFileChooser/6484091/bug6484091.java b/test/javax/swing/JFileChooser/6484091/bug6484091.java new file mode 100644 index 0000000000000000000000000000000000000000..bad995f9da27d4a0e384ba4d4622530a517568a5 --- /dev/null +++ b/test/javax/swing/JFileChooser/6484091/bug6484091.java @@ -0,0 +1,61 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6484091 + * @summary FileSystemView leaks directory info + * @author Pavel Porvatov + @run main bug6484091 + */ + +import javax.swing.filechooser.FileSystemView; +import java.io.File; +import java.security.AccessControlException; + +public class bug6484091 { + public static void main(String[] args) { + File dir = FileSystemView.getFileSystemView().getDefaultDirectory(); + + printDirContent(dir); + + System.setSecurityManager(new SecurityManager()); + + // The next test cases use 'dir' obtained without SecurityManager + + try { + printDirContent(dir); + + throw new RuntimeException("Dir content was derived bypass SecurityManager"); + } catch (AccessControlException e) { + // It's a successful situation + } + } + + private static void printDirContent(File dir) { + System.out.println("Files in " + dir.getAbsolutePath() + ":"); + + for (File file : dir.listFiles()) { + System.out.println(file.getName()); + } + } +} diff --git a/test/javax/swing/JLayer/6824395/bug6824395.java b/test/javax/swing/JLayer/6824395/bug6824395.java new file mode 100644 index 0000000000000000000000000000000000000000..28858c98bf0354cca4e99da576998b3bbdb55b03 --- /dev/null +++ b/test/javax/swing/JLayer/6824395/bug6824395.java @@ -0,0 +1,80 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + + /* + * @test + * @summary Checks that JLayer inside JViewport works is correctly laid out + * @author Alexander Potochkin + * @run main bug6824395 + */ + + +import sun.awt.SunToolkit; + +import javax.swing.*; +import javax.swing.plaf.LayerUI; +import java.awt.*; + +public class bug6824395 { + + static JScrollPane scrollPane; + + public static void main(String[] args) throws Exception { + SunToolkit toolkit = (SunToolkit) Toolkit.getDefaultToolkit(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + JFrame frame = new JFrame("testing"); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + JEditorPane editorPane = new JEditorPane(); + String str = "hello\n"; + for(int i = 0; i<5; i++) { + str += str; + } + + editorPane.setText(str); + + JLayer editorPaneLayer = new JLayer(editorPane); + LayerUI layerUI = new LayerUI(); + editorPaneLayer.setUI(layerUI); + + scrollPane = new JScrollPane(editorPaneLayer); + + scrollPane.setPreferredSize(new Dimension(200, 250)); + frame.add(scrollPane); + + frame.setSize(200, 200); + frame.pack(); + frame.setVisible(true); + } + }); + toolkit.realSync(); + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + if (scrollPane.getViewportBorderBounds().width != scrollPane.getViewport().getView().getWidth()) { + throw new RuntimeException("Wrong component's width!"); + } + } + }); + } +} diff --git a/test/javax/swing/JLayer/6872503/bug6872503.java b/test/javax/swing/JLayer/6872503/bug6872503.java new file mode 100644 index 0000000000000000000000000000000000000000..875ba4fd2d69cdd651c0442a7fe7741f3e9963be --- /dev/null +++ b/test/javax/swing/JLayer/6872503/bug6872503.java @@ -0,0 +1,135 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6872503 + * @summary Checks that JLayer correctly works with its AWTEventListener + * @author Alexander Potochkin + */ + +import javax.swing.*; +import java.awt.*; +import java.awt.event.AWTEventListener; +import java.awt.event.AWTEventListenerProxy; + +public class bug6872503 { + + static JLayer l1; + static JLayer l2; + + private static void createGui() { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + int length = toolkit.getAWTEventListeners().length; + + l1 = new JLayer(); + l1.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.FOCUS_EVENT_MASK); + + l2 = new JLayer(); + l2.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.KEY_EVENT_MASK); + + if (isLayerEventControllerAdded()) { + throw new RuntimeException("Unexpected AWTEventListener was added"); + } + + JFrame frame = new JFrame(); + frame.setLayout(new FlowLayout()); + frame.add(l1); + frame.add(l2); + + if (isLayerEventControllerAdded()) { + throw new RuntimeException("Unexpected AWTEventListener was added"); + } + + frame.pack(); + + if (!isLayerEventControllerAdded()) { + throw new RuntimeException("AWTEventListener was not added"); + } + + if (!layerEventControllerMaskEquals(l1.getLayerEventMask() | l2.getLayerEventMask())) { + throw new RuntimeException("Wrong mask for AWTEventListener"); + } + + frame.dispose(); + + if (isLayerEventControllerAdded()) { + throw new RuntimeException("Unexpected AWTEventListener was added"); + } + } + + static boolean isLayerEventControllerAdded() { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + AWTEventListener layerEventController = null; + for (AWTEventListener listener : toolkit.getAWTEventListeners()) { + if (listener instanceof AWTEventListenerProxy) { + listener = ((AWTEventListenerProxy)listener).getListener(); + + } + if ("LayerEventController".equals(listener.getClass().getSimpleName())) { + if (layerEventController != null) { + throw new RuntimeException("Duplicated LayerEventController"); + } + layerEventController = listener; + } + } + boolean ret = layerEventController != null; + if (ret) { + System.out.println("LayerEventController found"); + } else { + System.out.println("No LayerEventController"); + } + return ret; + } + + static boolean layerEventControllerMaskEquals(long mask) { + Toolkit toolkit = Toolkit.getDefaultToolkit(); + AWTEventListener layerEventController = null; + for (AWTEventListener listener : toolkit.getAWTEventListeners(mask)) { + if (listener instanceof AWTEventListenerProxy) { + listener = ((AWTEventListenerProxy)listener).getListener(); + + } + if ("LayerEventController".equals(listener.getClass().getSimpleName())) { + if (layerEventController != null) { + throw new RuntimeException("Duplicated LayerEventController"); + } + layerEventController = listener; + } + } + boolean ret = layerEventController != null; + if (ret) { + System.out.println("LayerEventController with the correct mask found"); + } else { + System.out.println("No LayerEventController with the correct mask"); + } + return ret; + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6872503.createGui(); + } + }); + } +} diff --git a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/CustomUIDefault.java b/test/javax/swing/JLayer/6875153/bug6875153.java similarity index 59% rename from make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/CustomUIDefault.java rename to test/javax/swing/JLayer/6875153/bug6875153.java index 6d4740b8b2bf842762422de2c08bee8b2fa6171e..8e416acc339a5af48aeb062b99f8a8b448d2a81b 100644 --- a/make/tools/swing-nimbus/classes/org/jdesktop/synthdesigner/synthmodel/CustomUIDefault.java +++ b/test/javax/swing/JLayer/6875153/bug6875153.java @@ -1,12 +1,10 @@ /* - * Copyright 2002-2007 Sun Microsystems, Inc. All Rights Reserved. + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. Sun designates this - * particular file as subject to the "Classpath" exception as provided - * by Sun in the LICENSE file that accompanied this code. + * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or @@ -22,22 +20,28 @@ * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ -package org.jdesktop.synthdesigner.synthmodel; -/** - * CustomUIDefault - * - * @author Richard Bair - * @author Jasper Potts +/* @test + * @bug 6875153 + * @summary JLayer.isOptimizedDrawingEnabled() throws NPE for null glass pane set + * @author Alexander Potochkin */ -public class CustomUIDefault extends UIDefault { - private static int counter = -1; - public CustomUIDefault() { - super("Unnamed" + (++counter == 0 ? "" : counter), null); +import javax.swing.*; + +public class bug6875153 { + + private static void createGui() { + JLayer layer = new JLayer(); + layer.setGlassPane(null); + layer.isOptimizedDrawingEnabled(); } - public void setName(String id) { - super.setName(id); + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + bug6875153.createGui(); + } + }); } } diff --git a/test/javax/swing/JLayer/SerializationTest/SerializationTest.java b/test/javax/swing/JLayer/SerializationTest/SerializationTest.java index 0c18e41491e1f84543bdebf7ddb5373261957b3f..cb6ec60846c1adfeccbaede2f15745fab2043fa1 100644 --- a/test/javax/swing/JLayer/SerializationTest/SerializationTest.java +++ b/test/javax/swing/JLayer/SerializationTest/SerializationTest.java @@ -1,3 +1,26 @@ +/* + * Copyright 2008 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + /* * @test * @summary Makes sure that JLayer is synchronizable @@ -50,4 +73,4 @@ public class SerializationTest { return "TestLayerUI"; } } -} \ No newline at end of file +} diff --git a/test/javax/swing/JSlider/6579827/bug6579827.java b/test/javax/swing/JSlider/6579827/bug6579827.java new file mode 100644 index 0000000000000000000000000000000000000000..78fdb7af0c2e1e541372cbea278c52526f709d93 --- /dev/null +++ b/test/javax/swing/JSlider/6579827/bug6579827.java @@ -0,0 +1,68 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * @bug 6579827 + * @summary vista : JSlider on JColorchooser is not properly render or can't be seen completely + * @author Pavel Porvatov + @run main bug6579827 + */ + +import sun.awt.OSInfo; + +import javax.swing.*; +import java.awt.*; + +public class bug6579827 { + public static void main(String[] args) throws Exception { + if (OSInfo.getOSType() != OSInfo.OSType.WINDOWS || + OSInfo.getWindowsVersion() != OSInfo.WINDOWS_VISTA) { + System.out.println("This test is only for Windows Vista. Skipped."); + + return; + } + + SwingUtilities.invokeLater(new Runnable() { + public void run() { + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception e) { + e.printStackTrace(); + + throw new RuntimeException(e); + } + + JSlider slider = new JSlider(JSlider.VERTICAL, 0, 100, 0); + + Dimension prefferdSize = slider.getPreferredSize(); + + slider.setPaintTrack(false); + slider.putClientProperty("Slider.paintThumbArrowShape", Boolean.TRUE); + + if (prefferdSize.equals(slider.getPreferredSize())) { + throw new RuntimeException(); + } + } + }); + } +} diff --git a/test/javax/swing/SwingUtilities/6797139/bug6797139.java b/test/javax/swing/SwingUtilities/6797139/bug6797139.java new file mode 100644 index 0000000000000000000000000000000000000000..acd9e1299e3a4781259aea89b044040c67a8ec3e --- /dev/null +++ b/test/javax/swing/SwingUtilities/6797139/bug6797139.java @@ -0,0 +1,62 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* @test + * + * @bug 6797139 + * @author Alexander Potochkin + * @summary tests that JButton's text is not incorrectly truncated + */ +import javax.swing.*; +import javax.swing.plaf.basic.BasicButtonUI; +import java.awt.*; +import java.awt.image.BufferedImage; + +public class bug6797139 { + + private static void createGui() { + JButton b = new JButton("Probably"); + b.setUI(new BasicButtonUI() { + protected void paintText(Graphics g, AbstractButton b, Rectangle textRect, String text) { + super.paintText(g, b, textRect, text); + if (text.endsWith("...")) { + throw new RuntimeException("Text is truncated!"); + } + } + }); + b.setSize(b.getPreferredSize()); + BufferedImage image = new BufferedImage(b.getWidth(), b.getHeight(), + BufferedImage.TYPE_INT_ARGB); + Graphics g = image.getGraphics(); + b.paint(g); + g.dispose(); + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + public void run() { + createGui(); + } + }); + } +} diff --git a/test/sun/net/www/httptest/HttpTransaction.java b/test/sun/net/www/httptest/HttpTransaction.java index 37cdf0e0ab85f92375aa8a61f0fd7964e4a4b8b9..81b0d82d49133a22229bdf8f5e793777c8189e66 100644 --- a/test/sun/net/www/httptest/HttpTransaction.java +++ b/test/sun/net/www/httptest/HttpTransaction.java @@ -102,7 +102,8 @@ public class HttpTransaction { if (rspheaders != null) { buf.append (rspheaders.toString()).append("\r\n"); } - buf.append ("Body: ").append (new String(rspbody)).append("\r\n"); + String rbody = rspbody == null? "": new String (rspbody); + buf.append ("Body: ").append (rbody).append("\r\n"); return new String (buf); } diff --git a/test/sun/security/ec/TestEC.java b/test/sun/security/ec/TestEC.java index 12694a03c649fbd2e3ac1a1b2bec8c94cf6abc63..5429e51394a7e8150b4a7afe2cdd9e5bd5197458 100644 --- a/test/sun/security/ec/TestEC.java +++ b/test/sun/security/ec/TestEC.java @@ -27,6 +27,8 @@ * @summary Provide out-of-the-box support for ECC algorithms * @library ../pkcs11 * @library ../pkcs11/ec + * @library ../pkcs11/sslecc + * @compile -XDignore.symbol.file TestEC.java * @run main TestEC */ @@ -35,12 +37,15 @@ import java.security.Provider; /* * Leverage the collection of EC tests used by PKCS11 * - * NOTE: the following files were copied here from the PKCS11 EC Test area + * NOTE: the following 6 files were copied here from the PKCS11 EC Test area * and must be kept in sync with the originals: * * ../pkcs11/ec/p12passwords.txt + * ../pkcs11/ec/certs/sunlabscerts.pem * ../pkcs11/ec/pkcs12/secp256r1server-secp384r1ca.p12 * ../pkcs11/ec/pkcs12/sect193r1server-rsa1024ca.p12 + * ../pkcs11/sslecc/keystore + * ../pkcs11/sslecc/truststore */ public class TestEC { @@ -49,18 +54,23 @@ public class TestEC { Provider p = new sun.security.ec.SunEC(); System.out.println("Running tests with " + p.getName() + " provider...\n"); - long start = System.currentTimeMillis(); + + /* + * The entry point used for each test is its instance method + * called main (not its static method called main). + */ new TestECDH().main(p); new TestECDSA().main(p); new TestCurves().main(p); new TestKeyFactory().main(p); new TestECGenSpec().main(p); new ReadPKCS12().main(p); - //new ReadCertificates().main(p); - long stop = System.currentTimeMillis(); + new ReadCertificates().main(p); + new ClientJSSEServerJSSE().main(p); + long stop = System.currentTimeMillis(); System.out.println("\nCompleted tests with " + p.getName() + - " provider (" + (stop - start) + " ms)."); + " provider (" + ((stop - start) / 1000.0) + " seconds)."); } } diff --git a/test/sun/security/ec/certs/sunlabscerts.pem b/test/sun/security/ec/certs/sunlabscerts.pem new file mode 100644 index 0000000000000000000000000000000000000000..5dfb352408a8d12cface9f80b043cc532b34b443 --- /dev/null +++ b/test/sun/security/ec/certs/sunlabscerts.pem @@ -0,0 +1,1317 @@ +-----BEGIN CERTIFICATE----- +MIIDyDCCAzGgAwIBAgIJAJh6e4zfP9lXMA0GCSqGSIb3DQEBBQUAMIGfMQswCQYD +VQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAk +BgNVBAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMR8wHQYDVQQLDBZU +ZXN0IFNlcnZlciAoUlNBIDEwMjQpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFs +c3R1ZmYuY29tMB4XDTA1MTIwNjIxMjk1OFoXDTEwMDExNDIxMjk1OFowgZ8xCzAJ +BgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEm +MCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHzAdBgNVBAsM +FlRlc3QgU2VydmVyIChSU0EgMTAyNCkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50 +YWxzdHVmZi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAJrKL3D9xOca +b5C5m1yeIFXvwufm5m06RnQdLWaj5Epg9+6tM3uZNn9B0r4k7MKYPbzBqyQO9ZSm +sulV9U3nWLhjChOrrNCIxzAUIR1//11QVKfjv3k8Ts7N5g5kIIiG8GUXh1WCNYhN +SvPo0BpNJ3FFwMMCZu0VpAP0j9krqWjfAgMBAAGjggEIMIIBBDAdBgNVHQ4EFgQU +FrXN7dxlrB1ccI0ZOi+NzYpz6UIwgdQGA1UdIwSBzDCByYAUFrXN7dxlrB1ccI0Z +Oi+NzYpz6UKhgaWkgaIwgZ8xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQG +A1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBM +YWJvcmF0b3JpZXMxHzAdBgNVBAsMFlRlc3QgU2VydmVyIChSU0EgMTAyNCkxIjAg +BgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5jb22CCQCYenuM3z/ZVzAMBgNV +HRMEBTADAQH/MA0GCSqGSIb3DQEBBQUAA4GBAAEQHmeWmoe+s784Qi1oK04eNeI3 +m3Iw06IWjdKH5xatQqj9VjvngLWnmY26PYlF6PK3cAktuempXVA2rZ3Dv5pkgAdQ +f3LXGHBKfAEsSjSSpxIsQA6Q+Yk7zqht5hSPOtUXHcWUx9EMvh7HnjmEEdR80fw/ +txvN4xm8V+flmK/T +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICxjCCAi8CCQCg3U8Mc7XCZzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwNTlaFw0xMDAxMTQyMTMwNTlaMIGuMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMS4wLAYDVQQLDCVUZXN0 +IFNlcnZlciAocnNhMTAyNHNlcnZlci1yc2ExMDI0Y2EpMSIwIAYDVQQDDBlkZXYu +ZXhwZXJpbWVudGFsc3R1ZmYuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB +gQCZCOorl//TxbVdj8X+fb9xhMlApe9sAU/jlHRtrv+7FflqCLMmhcR8s90LTCjq +gcX0mGm7fIusBff4/hjaKlmrto0YLNg8c8Zvev5CD+0HQHtbGUfx3TGOHv7gvG31 +nt88ZOzyIlPe2khcDTmb613zxFZhgJBs3bCsQz0TK3bR/wIDAQABMA0GCSqGSIb3 +DQEBBQUAA4GBABHP8xO3ouLm6SgZefjJnmbURTpjosE7oR15T1Fpf6o0WARaTeYO +07H/GdDFUgV3RTA/zNMimfq6XqJB5r5WBziVkLLuixzS7nNaAci6o5b2UaU7shUc +z3k0O4Dclybb4J1dYeAIwXUGqLAzI1NCgjRoGirFWT+O+02tT1KCiSl3 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDRzCCAi8CCQCg3U8Mc7XCaDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMxMDBaFw0xMDAxMTQyMTMxMDBaMIGuMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMS4wLAYDVQQLDCVUZXN0 +IFNlcnZlciAocnNhMTAyNHNlcnZlci1yc2EyMDQ4Y2EpMSIwIAYDVQQDDBlkZXYu +ZXhwZXJpbWVudGFsc3R1ZmYuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB +gQC5EyeXl7YTi5NPgJiIZHNSrG9qlAVoM5BYKqAVtFwHCbLYB7ZWyN2BuEfUSf8p +KSKkq28DkNTqnyz6Rg57kHzO3+kca0+iHlqFpbcP6uuN4ubOGZCuEDT0Ti7VXRtc +a8hGNrOEzZKA6DCl9csfrN0jHB5VBfJ4qTJCEi8fXNQbzwIDAQABMA0GCSqGSIb3 +DQEBBQUAA4IBAQC05575dPOqJ6Qk2rs7wHu4tGE15OR2jnXSZXXDObRUHetykmfQ +YbUq9/z9f3k4R53GAisgDwbVUb3EUsXofy7eMTUD89A7MiZ99SvebPilDQE3djqM +D0uA9a96LG6fAarc1MdpbMPcFiFFiwwlqJVtx4TNlektFbFQRzrrbMSF/ISLzdWK +fR3XD5qpwiCQbSug9Zm7cornUk8cK/Fs571wErOrdPo47aw1C8NjspLhux/JtHM9 +hNuAqona/4lX5lMVNpnSkWaT+B281+ysm1uEK8lvsDSUuLy+fZvokCrhQPFLoI+h +l5HGNqXdyIu1POCl6yqd6+BKNnfA5Qy+Bp87 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICbDCCAioCCQCg3U8Mc7XCYTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA0OVoXDTEwMDExNDIxMzA0OVowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2ExMDI0c2VydmVyLXNlY3AxNjByMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAyvWS +/5LJKlEJNR+jEWB1VMQVC09227El9V80yZ8WYqL0RdvWvDHN/vN1HKlFni/X5pwK +Def0vpXEDueeUgs9nQd+WDI/HOHTZ6BwUu2x2JParIBm9+dylWiBqhV+9LI/TyIr +4KMKjcnTMlCKZvzrIplIvcf+Gu/OFG46q3PUIFcCAwEAATAJBgcqhkjOPQQBAzEA +MC4CFQCslg/BEN7fygz0CIIWO+1n/yenNwIVAMivW2BhQhk1TEPw5Zs3QgXEw187 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIChDCCAioCCQCg3U8Mc7XCYjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA1MVoXDTEwMDExNDIxMzA1MVowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2ExMDI0c2VydmVyLXNlY3AyNTZyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA5v3h +NBYB07K2o8TMStAW5j5qDfy1XciU6Hx32qeoPwBdsvalmiAP+Scawfi7xPWGCMTK +zBiRSRHVgFU+tsvpFhJ+7mnl0k7zQMdmuzJCH/IV8889TAobQbGsvSdMa5ry+FRo +u+2QoEAaOQik4RFZcZmw+46wbMbeNhesirEkG20CAwEAATAJBgcqhkjOPQQBA0kA +MEYCIQCMTGl7AImRhjsdQuEUaODQKFWGcZSFT0ZVe+ikWQCdcQIhANOPoSjaBDHa +kJVhR6MrTMHvnfAGL+EZpAqHGPMM12JD +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICpDCCAioCCQCg3U8Mc7XCYzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA1MloXDTEwMDExNDIxMzA1MlowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2ExMDI0c2VydmVyLXNlY3AzODRyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArsTW +yLsCTz6nEeBEHW1JvMFPFnFqvXWWJJsEHbJtPDU0FF3xurgfNX4T7BsPW5LNIneh +MJbKqSCRgw0q97zgVLhB1WBE6y5jkfYCTDA5QAuNOlqgTGrBg0WIANgsXjHFZ5kQ +46i98IzFOFHZFOdtj+i0T3GviZWKGCbjKShyWnMCAwEAATAJBgcqhkjOPQQBA2kA +MGYCMQD4L6X8M2oCiwQE0/HqNNI4zCt6gp2o8Uk2HWa5If59QhwlfjXQSdbvVGfW +T2XpnUACMQDJ6Ir8G4H9Mu9ktf64MhnYg6A22hV4nWZ5bpM3AiD+10q+30r+TWV4 +89YQz707Eok= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICyDCCAioCCQCg3U8Mc7XCZDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA1NFoXDTEwMDExNDIxMzA1NFowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2ExMDI0c2VydmVyLXNlY3A1MjFyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEA1Nmx +2TOGk8FQXJIzDM2+x4jVWocD2lRShsFQaMhltST4PWm+TbXBPSxpvS9oFW7eZE3J +50OqxMiZkmH8un44Iet7E6fi0iRhw0bl4uqG2JHtyMzSYR6niSy0yqgHVJVwM24Q +Z/39X17PD0NwCEiPBGFx9Xa5E2JP9KcnCbrj49sCAwEAATAJBgcqhkjOPQQBA4GM +ADCBiAJCAZ4Apzk6L7BLjKoln+NEl5a/I1TmNIPVR0HtcLwbdZQ/y9b0+vhENkkS +XIGTc/2Jx+OV/tc4JyNW7PNM/YPl5FDUAkIByKevbRtsBD0HuCVK6WOf+6uz+QFs +fgxz0XoMyWMuoUIM2ytx+Eq9UY13QgqCQ5FxYWJ6RtDiNhEovr5GMjqjG0Q= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICbDCCAioCCQCg3U8Mc7XCZTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA1NVoXDTEwMDExNDIxMzA1NVowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2ExMDI0c2VydmVyLXNlY3QxNjNyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAy4Vh +Ju/NaZEhiu6wsh4fsKGvwdHwRKvmJwMk8wEk3/Vz92/9kPR5B/Co3XVGBmW4UJwD +0BcdPcMyr1TDHYOL7kS65MJGq0eFcBblA5hr2G3unZwgVwpS9GzMA7n8s3BtDGYN +UpUyt5u5C6mTqQoK39xVWWbke5tM90T3jr6MiN0CAwEAATAJBgcqhkjOPQQBAzEA +MC4CFQOcO1rEZFieKqpNL8E8T1wwchv2FQIVAQ4DEcV2AkLqSXxgt+h03NyWPeEN +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICcjCCAioCCQCg3U8Mc7XCZjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA1N1oXDTEwMDExNDIxMzA1N1owgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2ExMDI0c2VydmVyLXNlY3QxOTNyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAws4d +5PHRj1UOeuc60MnkGhmwJ/RD7Vmaq8NUJwliTHnAscTlZuv5Irv9cYHhAka2p8WJ +mo8xZxlUQMIUxIx/9ocZEYAKrv/vjWo05iaDQowJOUHM77usJnTZbDrVfeuOBqFo +6G2scl6RBGdCUOGUBVdRT6sEWQnYm/wIcTxj9OcCAwEAATAJBgcqhkjOPQQBAzcA +MDQCGHDRiFsRMDB+Y4+Mnjs4jWHHKyjqoOYFlwIYemZsC0uC1/oI/ZFUuERW7TEe +BPpqMQgX +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICyzCCAjQCCQClVpDHKllBjTANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEpMCcGA1UECwwgVGVzdCBT +ZXJ2ZXIgKHJzYTEwMjRzZXJ2ZXItc2VsZikxIjAgBgNVBAMMGWRldi5leHBlcmlt +ZW50YWxzdHVmZi5jb20wHhcNMDUxMjA2MjEzMTAxWhcNMTAwMTE0MjEzMTAxWjCB +qTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBW +aWV3MSYwJAYDVQQKDB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEpMCcG +A1UECwwgVGVzdCBTZXJ2ZXIgKHJzYTEwMjRzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0A +MIGJAoGBALx55L25d1DjV6X6z/rqebCJvhD0IfWqUU6ekiADnDgmOhFT8gutI4Xh +2AlBhIyticLU5IMP/MYud0OPnavaH3dcNRsfkJkfmZRULqIDjWnVmtmBhV8th9TM +KaH7V1TOqxqMfGuzFq9uwL8p5i2f8fLQjZ9sNNj7qeuW5XI05cv1AgMBAAEwDQYJ +KoZIhvcNAQEFBQADgYEAG3UcMUmwpTKUwNA6P0i0073ptjmzhRIeDdpf1d69X99Y +Wrnf2H6xA2boa8gBkVFjCaLBakIq6px5IuGFZNB2+0yJqd8QE22DKk1Ikr5hBsEC +owhd0feRaNjO0u/kPFZU1XAVFyz2AGKdLUOw4OEV8tuSOXAmWoMZHwfoocy1JnQ= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIEzTCCA7WgAwIBAgIJAMkNhmYP6nKsMA0GCSqGSIb3DQEBBQUAMIGfMQswCQYD +VQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAk +BgNVBAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMR8wHQYDVQQLDBZU +ZXN0IFNlcnZlciAoUlNBIDIwNDgpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFs +c3R1ZmYuY29tMB4XDTA1MTIwNjIxMzAwOVoXDTEwMDExNDIxMzAwOVowgZ8xCzAJ +BgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEm +MCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHzAdBgNVBAsM +FlRlc3QgU2VydmVyIChSU0EgMjA0OCkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50 +YWxzdHVmZi5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDO/6vZ +zPZAmeKP/fMAwKTRzCmy30TnoEZJybsk8QDlL9xaYIcEiIhf6eOV0/IYPcSwPakv +Ha5lT9aCTEEdcxACqAQlm2LOFZ79pUc0bGEmeFpHDZoO2w7+/RCYbGLkdWKTfj1D +kKG9PoWX5MelBZqkQuvE3+6eAr70IlQRA8uMA+Aq+Hl7KZys+eTX3eVWcNYZu94U +Z9wOKsRnRT4Yzf1G8aPJq4gIwxW4nBVAHqUc2N8bUzsHVqbTpcytU3KYT1YlcLGG +Ir1LulgjWws3Lncx1rZQuAIT5cyjCmW8wZ/O+GewzmbgV95lFsf8HCd0ZD4j65sS +/l0xB4zHnSBAegntAgMBAAGjggEIMIIBBDAdBgNVHQ4EFgQUS1aD1pb8BOGcjSyh +9IhovqLk1TcwgdQGA1UdIwSBzDCByYAUS1aD1pb8BOGcjSyh9IhovqLk1TehgaWk +gaIwgZ8xCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRh +aW4gVmlldzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMx +HzAdBgNVBAsMFlRlc3QgU2VydmVyIChSU0EgMjA0OCkxIjAgBgNVBAMMGWRldi5l +eHBlcmltZW50YWxzdHVmZi5jb22CCQDJDYZmD+pyrDAMBgNVHRMEBTADAQH/MA0G +CSqGSIb3DQEBBQUAA4IBAQBDl6f5HVzv0r0/DNAMy6vaKHrKXCJYVXLh7AZWLShP +3BfvekDRncLFjldTEqE1vqD4wndxpHVVwyZWWBWHVcw76AAtYnZp36ex5ZP56pHw +Mg308O+tYLgjdm5cDEzGzqNgavUIi/T/lMnWJrls1Zr/qnf7hzbvIAlMGJ4jcZGF +U1Z8T4mpFyroafXSbHEE/awX9DbyZL0ryXXtlTggxgLfzPqmSx4ZXurqv4LFdjlu +pZ/+/b6qU3JAlDMDMReb+iDBIllNGVZj88QTp3cC2CtwnYBYvLLWFtWoQpN2Ppz4 +X5xcdh4VuTICpk5kQSbzrij3GXZl0fDVuX4Z+5J1xodl +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDSjCCArMCCQCg3U8Mc7XCbzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMyMjlaFw0xMDAxMTQyMTMyMjlaMIGuMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMS4wLAYDVQQLDCVUZXN0 +IFNlcnZlciAocnNhMjA0OHNlcnZlci1yc2ExMDI0Y2EpMSIwIAYDVQQDDBlkZXYu +ZXhwZXJpbWVudGFsc3R1ZmYuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEA7I6hIU6+t1DQABGWtaqyhUjieQTzoaN3dZzmzTcUXY62F+IedLuVrxcQ +3YJU8+jcM6rl+/eIa90rNcKpxjrdzx676CqFCHO3/aHF1iCMmQF368ezfs2lDPTF +mobrn6KMNe71SM8bQ8MHFmRxY1wWk7GKIuz8OQnJOHD1nXQisjv1GBZ7HssaEPGd +m8c1rKCvzqrC4Nj/U+cKV0VeWtJod5inIx5RT/5FYW4QdBwuhovoKumPxpImYz6Y +SuFAce2hTMjxmvFXD0V1+VfWsYUe0/TilRgOv5l9iWo4haGBftYFWW8w0iqOB4+q +cPqcKozI7Tjs9r3Rby0zTdjB6vZi9wIDAQABMA0GCSqGSIb3DQEBBQUAA4GBAAUd +cnt8YHDUvIroDiLQQsH+p2mDD+ra10K3C9H0Lsvt6cb3/2jn6PupFVJzwkEEankS +Lo/pOe+bO5uSA4C2FQAymrYZX5Hh1guK/Has+Sf0K+HKPx28QPGg1EoS2KAbUf1t +RBX2jtq8Suz3iS9u77PbpB7aMNAEBihr2jAyfSka +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDyzCCArMCCQCg3U8Mc7XCcDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMyMzVaFw0xMDAxMTQyMTMyMzVaMIGuMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMS4wLAYDVQQLDCVUZXN0 +IFNlcnZlciAocnNhMjA0OHNlcnZlci1yc2EyMDQ4Y2EpMSIwIAYDVQQDDBlkZXYu +ZXhwZXJpbWVudGFsc3R1ZmYuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB +CgKCAQEAxHxrsAwLznaK+dmgQxUzmWTsNLhuKk+yBkpJZQDQDjkdxVrime1DxPAZ +MDi4OL+9YCIDS3ZWG0uLH49Atq08/2TB+aYDm0YBjrq3BRphTBrNNpntezSgP/nz +R2hOBvBgSvFqorTLzRF9THq18CrSJJB/OPFzvl6mYK8dtS4CnOfdUs0Pv8SwdxhJ +X6qsO0NJclrfBYBodGW1PiY62NPX0h2mLcg4OmD3gThfjUvXnsdjLJYV6hZFT+YC +vPJNTxTGebfnJr4sRGdqRUyBrjiqZtXwGpIBCSg/YpnUOfDSxJNA2Wd/WFJJv8Fq +kBh2oDRqlFNC/Z+HjGqKj0gFowTq3QIDAQABMA0GCSqGSIb3DQEBBQUAA4IBAQBp +iFO+5KbnHfRBStgxZdTBrr+HEezeFlxeE04bM7kSWII2SiQbAWSG5Rkb518m5x65 +q23KqUK+YJiy7k0zoKInvG/qLf1D5osFlwaAll7AKBadn/R8x822xSJCydHgD64V +b3u89zBY5Jtl+EzTA+n+UWRsurlLL1K9ockWZrDiZn6gGO5/ucR8OkZ192sxqKRr +iQbN12LWSmUCYPwba8nvDdm1ymAbnFOg1oQJ9HvxmFI3GaGjdmNo9rlaoNS/xQ35 +iTtJyi1MK2d+O2JPD5cS5otGfFnQiTWIngBiuEoOwzw7x8eWsOQaBPVnNSlMdU+z +Zrc6M1OSOUh2+DqvAoBp +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIC8DCCAq4CCQCg3U8Mc7XCaTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzExM1oXDTEwMDExNDIxMzExM1owgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2EyMDQ4c2VydmVyLXNlY3AxNjByMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AMPD0turqL6uNjGfquQy3MTv90+RvDCvCQXGnxdJa6QcOOHnv/4ua9g/TOO2cVuc +UuF3EnMSDg+HIo8qJhdKcOa4nnp1IxAnPsQs1K9vq8eqtuSuFMZUoUKy969ThPqd +UTYyZpOn87XMftm76nz92q2gDPLj7ZxD1QOv0MpMHjXJMSRHWEhsoCpYBdFT5Nl5 +28bK0AWTv4nw2RmQryn+UMblAqnJBNiIWzVHBUa1UNMBt2lnO12w6EpSGmkx9+Op +rv8kcfJgXnUkH/l7krHUADplp4yxO1hIzdH5Xsd+Hxrnl85vGjNJyuNOlFJ1Eh0x +AJTT6m1ypPKAs+zF1nWJaJECAwEAATAJBgcqhkjOPQQBAzEAMC4CFQCsQDzAbX4C +uri94k3X0mUTxCrweAIVAON/UYsS+fYp74XS5ucP8I31tl8n +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDCDCCAq4CCQCg3U8Mc7XCajAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzEyOFoXDTEwMDExNDIxMzEyOFowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2EyMDQ4c2VydmVyLXNlY3AyNTZyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALYeH/U234MovGN9iM3mr3kah93WJY64Dg8kGHg4zaUeKSmZVBgj/IlaCbfsRzXp +0xtsBCXAHGlZosiIInQzfxVNS/XIUOI3B5h+n3wMl61BsC2R/pmHyEg8eFp6Jiwv +1HMW9xKYF4qGgH396HczXPxOov3iJvtHHLElzYXDwCqy+x4D1PzXQLEkaGQzXsY4 +xhqskq1qg4pacNvow1eJair9zk5ebrV9t39icdTMkrtwgNBYAM/RU5DBxjdHDb/p +Ef26uOmpEfgopcRpoZlDY7mpBozK49Ocsx+PCAx74A1kj8M2i7s+edlLMxIl66Co ++ELzqZW7YjwtyrOakPNb1m0CAwEAATAJBgcqhkjOPQQBA0kAMEYCIQCwL9kS1Dza +3G7UiC3Hxo2f/kfp9621l8dLV5Uh+yhxagIhAIj28sZe3blr+MkrJHZjkYsAMY1e +JijPcsnXEr0uGamb +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDJzCCAq4CCQCg3U8Mc7XCazAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzE0NloXDTEwMDExNDIxMzE0NlowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2EyMDQ4c2VydmVyLXNlY3AzODRyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AK0JI2U8gdr/OdkEIeWTRnwnmfXJYyIvTQjsMIK/v2o9jpCh5rRiEJfF/JuypP5O +yHg6F1Qs6P/XafvxC/jsEe6VLbkwvT8THCKKMEvy6WyJuq58U5N5Zy2VEdMi+Q8C +XI4QrL6igOEW2W4wgYHgh6qxUee0kUeqY7DJJwvgTVTTHVTWpub/yrY+5LOAiQis +6eHxgp7xfUKKt64nk7pPdEdXeJ80PuCbau27/lQMhT8mBdE9YPkzX8dpS6ivYWFk +6VCv/qTz0qxQZF9BHHLJeStRgcGIQOV3Udm/EsjRfcTipDwVdxhHxJxpAOQ/xO+m +kJRKFitovc90AV9K2TtlG5UCAwEAATAJBgcqhkjOPQQBA2gAMGUCMHzhiyCuCuN6 +UxwoWA0q0nytE4H9t/2PnFGtAgmrzhnb4aWHw4xs5EJbTjGbqfVgBQIxAOIU5d2o +nnpT/vmlvyijgAHFXAE8qHsKi2XTI7bPy9PDrv2FCS7lLAw8+mNF2mJCug== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDSzCCAq4CCQCg3U8Mc7XCbDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzE1MloXDTEwMDExNDIxMzE1MlowgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2EyMDQ4c2VydmVyLXNlY3A1MjFyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AKB2axKYh2X1jRjtLpQIqhjLeIv55HiqlhF2dElrdTQP/qGN9TAYG9m0hAEzLKE/ +djgYMrsp0M9QfSxlNcLYjOtmYVLz57v1BQnDZI7/DS4jWOKfcnlvJSPbwE7LBoLQ +KKfmXmDWvMwmTBtIEs4nxPph2UuROc5exd1samwS6doAcUm09wqP60aM3lK+9ml3 +/Ukd0coK9824cWa5m4OUcqPtbS8u3LcYJqFb7q7N8q0yYBwuU4kUVpGRlKz5baEv +43qr5l+Fyib/pNEEAO1YhEW+7WjmvOAW4F/GSTI7SHce3Q4+3EoMoORM9nF9t482 +ojDsCe8emGFsGq0eS6MwYY0CAwEAATAJBgcqhkjOPQQBA4GLADCBhwJBdd9GUYv4 +BCF0NKQ583v33GreTlqD2Z0iXnni5du9A+8qJgG1wZlAGAosqXpZCi7i+3q2DVxI +hCU67LcsUi59GJMCQgDTLuJI2gkKvqNufZXIR5vR7/RUd4EddkLw2whv4NMfwLJM +532DeZIH+BtbyfjWYFujjoR/rhhcvtU0+lXsRT4xPQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIC7zCCAq4CCQCg3U8Mc7XCbTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzE1N1oXDTEwMDExNDIxMzE1N1owgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2EyMDQ4c2VydmVyLXNlY3QxNjNyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +AJ/8bNSkM/3fhVhEiFtu2r1fam1CVdbHE1tW1MjF2HOHBt2kz2LwLrJZq8ae9NkF +82qSw7TB7b5EWWa+o7y6we8So8VenTXnk1oxRRh1tJi2AMFgqpx+LVh4EVqnhfAp +r7UrtrnM+eAxOyGUVaTMgJKIkhDcfdIS3zHEL1i4tlbmLYRhWUE+wyogZ56FyWhR +mIpfWv9yV8pMaF1VDEBEN/Yl/6w5f8DG4bQnvkOhL51GVb9GdUBKXI/0bybKTgr3 +Ku/T4q1ppHJSSFohM4Riju4EAgrJ2f3p0ebhX0dtTV7SuCH6vgTpOmSqTIGQ5cHh +sGFV4/9Aoky/grDx9hp9D4sCAwEAATAJBgcqhkjOPQQBAzAAMC0CFA1Rg/uMcGW2 +lXuIUjKOiWxBhox7AhUDz3eNq7ir06Ukk5DxFpjGWA4kx2s= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIC9zCCAq4CCQCg3U8Mc7XCbjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzIxM1oXDTEwMDExNDIxMzIxM1owgbAxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMDAuBgNVBAsMJ1Rlc3QgU2VydmVy +IChyc2EyMDQ4c2VydmVyLXNlY3QxOTNyMWNhKTEiMCAGA1UEAwwZZGV2LmV4cGVy +aW1lbnRhbHN0dWZmLmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB +ALY3OYbAL3fEdoDHiak/3aj7141wmsobDVXPbNR1QFoHDrUqpgdQR3zHGY+BPjDD +qvo0xzzIUE40Hg49R3ya6WyECH8ozl9WJ+JS+lH63RYlHDWOJfzjylF6ihiqixj7 +Twjk1j9ZBPjjiGUA/6RlikxsRhoQTDU/pDD6bSn+yosimpePbOao1BDPfntYFejw +JWPlgC307o++ZKLcGjZH/9IfaKvgiBgl48rVDlQjFNLRkehufk1lviz5CdGph4uF +D8qoO83mIH/wGJ9kWVjv0nvcEOGeGfaM1mDBwsuzVPXqtvUQHOnCfc18B8y8Fw8g +bdoNde6lzDo6IMttKQEa+LMCAwEAATAJBgcqhkjOPQQBAzgAMDUCGQCV2p48seE6 +bqHpTgNOe3WdVuZe9dQYJgECGFG66yqtsjvMSg7snsWmMU/S2a8jvMywLg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIID0DCCArgCCQDHAy9pv/zMBzANBgkqhkiG9w0BAQUFADCBqTELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEpMCcGA1UECwwgVGVzdCBT +ZXJ2ZXIgKHJzYTIwNDhzZXJ2ZXItc2VsZikxIjAgBgNVBAMMGWRldi5leHBlcmlt +ZW50YWxzdHVmZi5jb20wHhcNMDUxMjA2MjEzMjM5WhcNMTAwMTE0MjEzMjM5WjCB +qTELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBW +aWV3MSYwJAYDVQQKDB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEpMCcG +A1UECwwgVGVzdCBTZXJ2ZXIgKHJzYTIwNDhzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IB +DwAwggEKAoIBAQDt8MTCSkfQyPw/EjB/lzT1yHMDVuniAFLkxe8GzJYOUEbZQTRt +3gIZ56kX65DDW4R7VCcrFtDbF+PBVwwuBR3YT5adV0mbI0k2jBkteBe2N7CrQMAn +3m5Mmb3pcxLZOHSSH2HJXJzDGY7YCY4UfdUjNCFro56NeSKylTF1TdVpPkDPzbEm +BliscaJZ56WB9AKujbVx2apEaNcpaEXnJ5XbEmtccC463TPXX6Su8haccdXrfDFV +mLe+kwe1w8B/nQbVGWw/v9lysIdx6i1FmWtsU8lJp+kwzg47RiCeb68cumJxvJHp +/WoZGHFE15CYEp4N7lbF/UuiyWsn1VqHfkqnAgMBAAEwDQYJKoZIhvcNAQEFBQAD +ggEBAF0+NeYI0T+ZiDhR4B9kOMZfeQGYov+m2d/Y3Ly3rV35NJ6PbuGpb/VbYSxP +m0l6PhLB/c0V0pyg7MwgwtumhAxlnR5te0wNyYXzuO2oVBoO/8JmsQT8jnCFoANG +9KNrI+A6ed0V7V1u4Uz3YFbD33FWIDWIR+nfDe07FNl7th/8jzpZAhqudtj372jy +Andyzedx/kI4yePpjkHf8F0/MocI691C3rPW8uhSYloPfmaTftYoGl7+E1Xc85bW +JMvnUqwPptOzIVrd2Ei4/4jQDxmI05gDKxZ8aMZddJFkLPKMIFAMwEzo75fCJCBr +7Qo20ez/vMV+XAWGbHr1qLYhHzU= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDAzCCAsKgAwIBAgIJAIsK5NQHdHWbMAkGByqGSM49BAEwgZwxCzAJBgNVBAYT +AlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UE +CgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3Qg +Q0EgKHNlY3AxNjByMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5j +b20wHhcNMDUxMjA2MjEyOTUzWhcNMTAwMTE0MjEyOTUzWjCBnDELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEcMBoGA1UECwwTVGVzdCBD +QSAoc2VjcDE2MHIxKTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNv +bTA+MBAGByqGSM49AgEGBSuBBAAIAyoABEomOz9/rS0q4OSF2hP23h8Cobi6nftl +PlvgqVcjp+vnica6wXZ8TYOjggEFMIIBATAdBgNVHQ4EFgQUfdItvmVsDmZPpKZD +nEvW2UkF1GEwgdEGA1UdIwSByTCBxoAUfdItvmVsDmZPpKZDnEvW2UkF1GGhgaKk +gZ8wgZwxCzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRh +aW4gVmlldzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMx +HDAaBgNVBAsME1Rlc3QgQ0EgKHNlY3AxNjByMSkxIjAgBgNVBAMMGWRldi5leHBl +cmltZW50YWxzdHVmZi5jb22CCQCLCuTUB3R1mzAMBgNVHRMEBTADAQH/MAkGByqG +SM49BAEDMAAwLQIUGxw8NFGW58flX5kQ+9sTr62kN/UCFQClrPQNlpt7uW9Q5qMB +WRpd1SDyIQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICZjCCAc8CCQCg3U8Mc7XCNzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMTNaFw0xMDAxMTQyMTMwMTNaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDE2MHIxc2VydmVyLXJzYTEwMjRjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wPjAQBgcqhkjOPQIBBgUrgQQACAMqAAT9 +re7ILR102TfjTOu5h9XN7kIs42BEGeVyFHGqc9El4PEOy8Q4h5waMA0GCSqGSIb3 +DQEBBQUAA4GBAG0/n0eT7HK/1cgn4Qa6czMBpms0ca22r/V11Aj+h2mAqJNuz4aU +7q1r+W94hblFrzAlGSZqRIHykFL/yr6/xzStCB3gd9OslvXIjgrGatzuhAttuO8A +mA6VmPYG2aT5Ih9Bdg/HKuWdkSIeZTDJKMZli/CNWdtl/YcjsmyJDPUX +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIC5zCCAc8CCQCg3U8Mc7XCODANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMTRaFw0xMDAxMTQyMTMwMTRaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDE2MHIxc2VydmVyLXJzYTIwNDhjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wPjAQBgcqhkjOPQIBBgUrgQQACAMqAAT+ +gt3/qI+svlfcqv3G+ldM/9cBveia+Z4S+UUurYsZR3joZVEUSm2JMA0GCSqGSIb3 +DQEBBQUAA4IBAQAGZFmNoRJUjpqoVkZWOP7ZDgjAgQqKFYI3Mm0QGNPvIEq1VCcj +LQnx9PY2B1oMKZJQQ/1KsNqnEMm8jlFXq+O25/QuD1/jv37ME2sn8rZe6vsdKLr6 +4SB/GU4mHID4eNDttT4WepT8OfRBO2EY8MWv+97tkUIr9saxjVMYrp4nK0vJ2Yql +LY0Jw3PgZ11y+WDKwkTWQkOx0SaZhKGRKZelbZZ2xcrV5XUtOFj2Ze27RMARRmmG +SEnSPUg95eaKjpFbjMiPvTACcYJfnpRKN+ev/dQ0lJa1mZEnsXkaNqzb3q7F91Fm +/NQ0Qi0OLeNZWeUUo1q3xhA3L2YvRyvz3425 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICDDCCAcoCCQCg3U8Mc7XCMTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxMFoXDTEwMDExNDIxMzAxMFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMTYwcjFzZXJ2ZXItc2VjcDE2MHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMD4wEAYHKoZIzj0CAQYFK4EEAAgDKgAEeIPEikmn +11U+4+r1Q1MikFns3u/81SlifvD9FK7i2eHXsm4pJbz66DAJBgcqhkjOPQQBAzEA +MC4CFQD+m6pQXn1FPgD5NS62SFJwZxTe+QIVAOGRJ9XxBZ8CfPMEDDmNkzEyw5I+ +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICIzCCAcoCCQCg3U8Mc7XCMjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxMFoXDTEwMDExNDIxMzAxMFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMTYwcjFzZXJ2ZXItc2VjcDI1NnIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMD4wEAYHKoZIzj0CAQYFK4EEAAgDKgAEsNpgI810 +hR1H/L88VDCIsDJbvQVU/WBqSi+dTVX0E1lITw4S8oJwSDAJBgcqhkjOPQQBA0gA +MEUCIQDTPITeYMLlsJT8jh2CyDHjEskSGLb62OaM4a0iq7wiPwIgbM9hJwczrPcw +3uCNgCT990nAdET61HPVfWOBwDJi7tU= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICQjCCAcoCCQCg3U8Mc7XCMzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxMVoXDTEwMDExNDIxMzAxMVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMTYwcjFzZXJ2ZXItc2VjcDM4NHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMD4wEAYHKoZIzj0CAQYFK4EEAAgDKgAE/E51tE6b +bbeYQtaomWTWdwqTlW/8UbNDlC/LDHFXhYhNNJJzGdHoLzAJBgcqhkjOPQQBA2cA +MGQCMHjfuIklGYjJgYQYBBDNraRptWiaPe7dsI58LZdeJIwJcQcesTpPjjLDszS9 +jfTUNgIwZiD6FVi1yVTckFvPIGqNwzz46KrpKEO1JWR05DkawDnYoUzOoZjEtDhI +fktezP7a +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICZzCCAcoCCQCg3U8Mc7XCNDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxMVoXDTEwMDExNDIxMzAxMVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMTYwcjFzZXJ2ZXItc2VjcDUyMXIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMD4wEAYHKoZIzj0CAQYFK4EEAAgDKgAExrjEN9Rb +kS59txyKYNnlunaAY8PGDBeWy/t5JItcB8BdYNNaQ6Td1jAJBgcqhkjOPQQBA4GL +ADCBhwJBDPCBtcw+W8IBo9x6F9ajBOlstHeR9lV6dE3sLyJhpV9sn697LHA6fQ6u +s4x0aT8OJLod+62DFwDX40ATPoT3RoACQgHscuDNMVpOCx8mdka2mvD442Tcb76w +Qc5DQSd+d0Rw0c9zAvPwObwSttNaaNmuT4v3DturgBVQGdb02bmQIuDNrA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICDDCCAcoCCQCg3U8Mc7XCNTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxMloXDTEwMDExNDIxMzAxMlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMTYwcjFzZXJ2ZXItc2VjdDE2M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMD4wEAYHKoZIzj0CAQYFK4EEAAgDKgAEuQ9FFr/a +O6E1WAQ0LtG1wH8nczXWLqJc7f+sgDgzrub2NjvOvfcQ5DAJBgcqhkjOPQQBAzEA +MC4CFQGBzvmRQ4HhuGwqOnKztHmUS9viEwIVAKZCrx0tZO03y9nSpGBRXeTB+bb2 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICEzCCAcoCCQCg3U8Mc7XCNjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxM1oXDTEwMDExNDIxMzAxM1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMTYwcjFzZXJ2ZXItc2VjdDE5M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMD4wEAYHKoZIzj0CAQYFK4EEAAgDKgAEp8qqFVSZ +48NmZKnPWpaJXybje/F2E0wDq8rNOX+LC73zfK3ZC7xDvDAJBgcqhkjOPQQBAzgA +MDUCGQCQP6SvfPS/AVHix6tG38uduEl53DG97JACGBWSckcbWsXYXDhKo3LrNy0h +9uBgV9Gs5Q== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICEzCCAdICCQDt+YU/aZ6s4TAJBgcqhkjOPQQBMIGrMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMSswKQYDVQQLDCJUZXN0IFNlcnZl +ciAoc2VjcDE2MHIxc2VydmVyLXNlbGYpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVu +dGFsc3R1ZmYuY29tMB4XDTA1MTIwNjIxMzAxNFoXDTEwMDExNDIxMzAxNFowgasx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmll +dzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxKzApBgNV +BAsMIlRlc3QgU2VydmVyIChzZWNwMTYwcjFzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wPjAQBgcqhkjOPQIBBgUrgQQACAMq +AATr4Hx367/3ldBBiTV/6WfVuaRjVYUrFtcXLqsF04z3yL3dw4TcwSnQMAkGByqG +SM49BAEDMAAwLQIVAICB0ciEiBjudkS5M+TgDRowS9wqAhQxdt3pJoNMch0sBGvy +ZvpPEqW4lA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDNTCCAt2gAwIBAgIJAMWAX1EW46gEMAkGByqGSM49BAEwgZwxCzAJBgNVBAYT +AlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UE +CgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3Qg +Q0EgKHNlY3AyNTZyMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5j +b20wHhcNMDUxMjA2MjEyOTUzWhcNMTAwMTE0MjEyOTUzWjCBnDELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEcMBoGA1UECwwTVGVzdCBD +QSAoc2VjcDI1NnIxKTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNv +bTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABNzAD4317T6bb1oio1J2awuyb2wS +F7okuHwbFhfTuXgvLsQcAWh34Md5SJ711rN7an+sEr0RVyE6h6zgQkD8DUyjggEF +MIIBATAdBgNVHQ4EFgQUSPfZCnqQodFg6YlBySBCsrjQ7hYwgdEGA1UdIwSByTCB +xoAUSPfZCnqQodFg6YlBySBCsrjQ7hahgaKkgZ8wgZwxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3QgQ0EgKHNl +Y3AyNTZyMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5jb22CCQDF +gF9RFuOoBDAMBgNVHRMEBTADAQH/MAkGByqGSM49BAEDRwAwRAIgeXLod9K7A3VG +Rw/3wMXrnxNUA+K4yzfAf1OlCy8923kCIGqu3+9B5lZgHWvHiWBkjpkBqegBp5t1 +7YyV4K1ALxcH +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICgTCCAeoCCQCg3U8Mc7XCPzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMThaFw0xMDAxMTQyMTMwMThaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDI1NnIxc2VydmVyLXJzYTEwMjRjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC +AARnBDetfBY6JJYtJ6BTttMX/edfb+Lc/DCwTneZzjE5lUaM+LzNwNt02H/+XD27 +hhTDJWXP5r26qZzuBkwpi2UJMA0GCSqGSIb3DQEBBQUAA4GBAF1uQyY7WpxJkkht +Ru87ib8WISy/liosB1ijy2bcPHjcpKRSW+LH2+A2+mQYiasfOkLck+9pS7efhFtT +b1A/3BkI9tMGhvMgop8860Khkl6pRETNu/nlVIQ2xzdRdpvJCmFPa67YK25/cn0O +XN6PHMPJF1JVyJhppvjmV/u6TS2N +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDAjCCAeoCCQCg3U8Mc7XCQDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMTlaFw0xMDAxMTQyMTMwMTlaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDI1NnIxc2VydmVyLXJzYTIwNDhjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMBBwNC +AAQmlPt4PtwUBkFqDl1dc+5XqpiPYJ8t0oVklz86WljYLHXNWl20Wd+t+/4akyc+ +3L9Wr2OzkZyXWv4nA4UteyFiMA0GCSqGSIb3DQEBBQUAA4IBAQBWbbxxLkiwz7eo +uN7Jfa+I9xMNFwPhCc7api63Z6Q6P1tcdTxtl6xQefdiFc550H+tOWb+sn3EmBFo +r8XIPAb73dG+41Vp2bSajkY9povAT/UHFYt9rwr9bQfWtJktd939A/hQix4YImzV +7cw8b+SAoEWuWifScDKDlFQvs4zxUAOxFeXbOrb3X1oGDjE93TEx7+x9DBNMDSu3 +hN11j9cyMotJCWB5OFYzCf3ibwwo0usiz768Wu1C3RvauET+xbcE3NkxM6rsQxI1 +lNXM1NNbm7/nOm+zK2lTH7g4Qui8owSgwR0uwEHhmrAHIug0uHC7GbrIn4yibkrq +xkZaaUr3 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICJTCCAeUCCQCg3U8Mc7XCOTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxNVoXDTEwMDExNDIxMzAxNVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMjU2cjFzZXJ2ZXItc2VjcDE2MHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAErJOw +EmmdQcay7oSZTNySdc2m4/iwftH3KfY3wDA5qVusJ85AJUYPbwEvqloKpOTdCZI7 +P4za7x7COTuZAzVFVzAJBgcqhkjOPQQBAy8AMCwCFG5V4voKrcE0UlK1osPuHXZD +N2f5AhQR9TzLTT7D1Ee270xtQ+Bwcq9mBA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICPjCCAeUCCQCg3U8Mc7XCOjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxNVoXDTEwMDExNDIxMzAxNVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMjU2cjFzZXJ2ZXItc2VjcDI1NnIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAERwmM +YUHXpp9LfbDmk33yWOjAf9flz43IHqFq2xa6bczvcht7ZDka7UmSOVQ8A8d2FdjG +BlqAnEKvCHlxqw41SjAJBgcqhkjOPQQBA0gAMEUCIH++MmRaY7IhySci6HGfsACD +otlDDt6kvpJOCTXQS0G8AiEAwNA+4/wVeEvtjendgLX7icNK33L53fK9CqiZovfi +w7o= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICXjCCAeUCCQCg3U8Mc7XCOzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxNloXDTEwMDExNDIxMzAxNlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMjU2cjFzZXJ2ZXItc2VjcDM4NHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEXjcN +bCMqCgsKw4WhdPm6ankP3pHHg/bKWiJXJ6BI4QQYGsNBXPb8YvwP6Q1tFPSyjSJo +VRUVmWGn9X7FzQAGQzAJBgcqhkjOPQQBA2gAMGUCMG4SIhLBYKht8fGzVRte/4lJ +Aj+hMTbCuNa36BMOoez16SskyhCtar46QkFIGnmoQgIxAKIxzKgH4dBAdRGu7fsU +OawK3AvNYm9Xb8bn7js+KjB4pJdYBZw4Q3kHB2cBgX+hvg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICgjCCAeUCCQCg3U8Mc7XCPDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxNloXDTEwMDExNDIxMzAxNlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMjU2cjFzZXJ2ZXItc2VjcDUyMXIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEH/cQ +KncxMblNmy+gpvCcfxdnC96RTzVT5ZdbeTBlmsRLXxWlrORx4+URCmHGpFdFzpmb +Hfc8rPAIQNGiQucuQDAJBgcqhkjOPQQBA4GLADCBhwJCANGrCUSZ/X2XMwFavryU +JGEOQFLMAAsEWVMUYbJifwNyeQVuwNV7cJjE5UGEzFDLbazmdrPVmDeSt4nQYCYN +zy/nAkEhOcJqFzXb2PW1E2MK7qGOswGNr1EifKIF5Tn//nCmpfDSH7G7VXH2IqPC +X6P0wdhzr72Gy3YmjXoj/CTZ/fK6Vg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICJjCCAeUCCQCg3U8Mc7XCPTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxN1oXDTEwMDExNDIxMzAxN1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMjU2cjFzZXJ2ZXItc2VjdDE2M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHEs0 +EFQnApDDnOBH0DZtSu7mDqzv3BEwm43BWfjQbuvWtKZxTzCc6Pv3dxLgdblE3Fl5 +MK/8Gk3ugDZwe563KzAJBgcqhkjOPQQBAzAAMC0CFQD8O8WJ7okGjHRs/J6rWo+n +FNrwCgIUcFcuAK3K1tfYuE3QGm4smu2n8iM= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICLzCCAeUCCQCg3U8Mc7XCPjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAxOFoXDTEwMDExNDIxMzAxOFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMjU2cjFzZXJ2ZXItc2VjdDE5M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE6I/f +uxD+wYynPua+enF00uSb3hHLi105QljhMjfpXRyMt7jW7N0N44AeQLqvUuX/Ou0B +zXDtE8R5tbU5n1p9vjAJBgcqhkjOPQQBAzkAMDYCGQCRU8ROxYXzP4UclxGtca7W +b03WyYZAva8CGQCTE3650WcJy0ka07FL3RuScknp/D4SZh0= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICRTCCAe0CCQCwSXFmzpBH6zAJBgcqhkjOPQQBMIGrMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMSswKQYDVQQLDCJUZXN0IFNlcnZl +ciAoc2VjcDI1NnIxc2VydmVyLXNlbGYpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVu +dGFsc3R1ZmYuY29tMB4XDTA1MTIwNjIxMzAxOVoXDTEwMDExNDIxMzAxOVowgasx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmll +dzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxKzApBgNV +BAsMIlRlc3QgU2VydmVyIChzZWNwMjU2cjFzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wWTATBgcqhkjOPQIBBggqhkjOPQMB +BwNCAAQtDOsv5pQz7RzsMK68LUeAIDtdJddk55oLsrd2+93FHIr1CiqOwr/3sH3V +USapRS4Xlb7VvtkFmCGLMna0TEdiMAkGByqGSM49BAEDRwAwRAIgGqI3kC9COsLQ +nUnZmwVaNp6le9PQwro6m6b0r6MgaOgCIFH1x+AgAV+HvbGkPTjIW+Cp1oUcbMgd +iDnA5kk037nh +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDczCCAvqgAwIBAgIJAMKpQMf1IUoCMAkGByqGSM49BAEwgZwxCzAJBgNVBAYT +AlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UE +CgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3Qg +Q0EgKHNlY3AzODRyMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5j +b20wHhcNMDUxMjA2MjEyOTU0WhcNMTAwMTE0MjEyOTU0WjCBnDELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEcMBoGA1UECwwTVGVzdCBD +QSAoc2VjcDM4NHIxKTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNv +bTB2MBAGByqGSM49AgEGBSuBBAAiA2IABMaXMYyVYpN6QWe+5TpTN8r9jbAPUEO/ +YuR23HOX5Kq1bP0GoF96uXx53X0V0EOncf/navTd9e7oF4BOgkCsHe0bD2p8b82I +IbQ953K3DDT6eIW4TXF7YvS/xF9ByIx/iaOCAQUwggEBMB0GA1UdDgQWBBTqywJZ +V6bCSeOnSQ3riDM0TDfIMTCB0QYDVR0jBIHJMIHGgBTqywJZV6bCSeOnSQ3riDM0 +TDfIMaGBoqSBnzCBnDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQH +DA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQKDB1TdW4gTWljcm9zeXN0ZW1zIExhYm9y +YXRvcmllczEcMBoGA1UECwwTVGVzdCBDQSAoc2VjcDM4NHIxKTEiMCAGA1UEAwwZ +ZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNvbYIJAMKpQMf1IUoCMAwGA1UdEwQFMAMB +Af8wCQYHKoZIzj0EAQNoADBlAjBb8D7U8OiqO8ZU9gUrkMo0Y23AN58o3TSapRge +7qiAuUOVraWioNrrNVpC2z2YI2YCMQC53bKQvlqIQ+GbGMY6C5v+F/zESmVie06v +ba7qe2vIl6OIBiPOP5c5gCj4Nj1g3uI= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICnjCCAgcCCQCg3U8Mc7XCRzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMjVaFw0xMDAxMTQyMTMwMjVaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDM4NHIxc2VydmVyLXJzYTEwMjRjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAAR+ ++z6+8do8BpOuYXtGlnKN6jwDj1MdbcUM9sqJBdvVnBJdHfOCL+nVGSvyTY5BUxJ7 +FT5XG+9H0+juJlC7iUu7guxwXdhkChnOQ28buUqsWYH0yHiKJe5F/Re2ESERPi8w +DQYJKoZIhvcNAQEFBQADgYEAPPio0j09V6vXhN3GYwa3ARjboJIO53kTNa65UGgC +qvdLNufcBRldt2vezR0NKj3CTY+/uD+lNwTp+HdnIGkz0hHA722nv0VZGX2MWdMs +/2/D36kJA89IIPLKkQjzmmjIQ9wNDSAt31j9b/TiUfeodaEZZR/iST5UHDvkSIZE +EHs= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDHzCCAgcCCQCg3U8Mc7XCSDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMjVaFw0xMDAxMTQyMTMwMjVaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDM4NHIxc2VydmVyLXJzYTIwNDhjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAASw +i3q++pOW/2tqHTpGB6X85pKO+oCQa/1KSQhKCjVExJxwfQlClNkHgerFUnMr1Zvu +e468EX7/r4gdnMQn+8FPWcYZ+2PYLHaNa4zmLPZq1YJRq5gjIU96uE9nJLoCJO8w +DQYJKoZIhvcNAQEFBQADggEBAE5R94CP/nqChXrMPmHThRReMGXc65FOXtXrQvNb +YKa26EKHy50fqh0sZkfIMqF8CVYhpMM96f7xJgHBJ1GY20Ayp4Om+nmC1U6in5yk +G+LO1H5uDwn3be9tLXW9Jiif/FSDJvY7GhWMys9W9QpojHrNT1eVGPu5zmZxfvDn +nPlrxOxx2yVSkc04zAfBibKd+iNBLI9x1hEWv9gVILow/nsF+HEceGqCKrKtw3CB +vRek+mUZCUDD6gKsN0LeGnRbEFTjyYp3iqbA7/zaCsXi0C9RowKD/uhQmmsduxFT ++mRBNP2Ni4BGJoFGt6ynkhQMKMcZOgCfG9qu9xFpRa2wn+s= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICRDCCAgICCQCg3U8Mc7XCQTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyMFoXDTEwMDExNDIxMzAyMFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMzg0cjFzZXJ2ZXItc2VjcDE2MHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEeU60tao/ +d69lrHxMAx6xC9aIXgbFzDxSl39sQORDuiv7YgqxSNxusAnCCER5YT7i0WfH2LEh +kSO16D40edXpxFXXctF6uOT9KK84oCT2ciV1QbArI1ROExKum1U/qYd3MAkGByqG +SM49BAEDMQAwLgIVAJNssWK3wbZ17bXdaVCc2oydMEqBAhUApNb51n/19FEejcXt +msPefDlmlWA= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICWzCCAgICCQCg3U8Mc7XCQjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyMVoXDTEwMDExNDIxMzAyMVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMzg0cjFzZXJ2ZXItc2VjcDI1NnIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEUKGBne87 +l7cssaiEtxw1EOATJFv/yHz1811mfKPqCJjpVi5NVLt5q2b7DfWvi4839ywNdD5l +ne3mzh6WT20lH52LkS/sMj2shtx0NAIWQM+SJMi7BrBRtymaXtRZQQxdMAkGByqG +SM49BAEDSAAwRQIgBmcyaM69Ryota/XMkDJzkW8a3zCZahsE5DlTrg+Y+VkCIQD1 +Sp6MuZy6JzwtASW/l/Z313mvQduVpzdtezQtvhXqMw== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICfDCCAgICCQCg3U8Mc7XCQzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyMloXDTEwMDExNDIxMzAyMlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMzg0cjFzZXJ2ZXItc2VjcDM4NHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAELraTwEbQ +rTk40nU76I/MUWvDrX4HEhnNt2Wor50zzHpNtcWlDh64xyDIUO6IgwPumY93PMUR +E2ObEw1zm2jLx+ld32CHZhVD3NFg1eyUzxUWXlnV5YyMQg4kM+Q4RfSoMAkGByqG +SM49BAEDaQAwZgIxAJp22vZKPO/FetlqwLIcghqoy0rueCskFQC53fhU0zAybTiI +zDLzM3AwwwIjHHIvOQIxALyleafaqz+Uh10WWnhenZ4wEcGtnvMq7NOLA26DttBq +Hda4UJnBkRFBo5+N0m+l6Q== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICoDCCAgICCQCg3U8Mc7XCRDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyMloXDTEwMDExNDIxMzAyMlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMzg0cjFzZXJ2ZXItc2VjcDUyMXIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEtyVcUCcJ +RsoFtoxLIFg32suhU2Vsm3HjI5+uMg/04EdQWsSZ20b2aPZ0G9eOI//t4LT9ha7D +Q8XjDRQl4+MMpcQZPz05CPeM3V+51ORa0TsU5H55mkaI6jzyqjBqU1zMMAkGByqG +SM49BAEDgYwAMIGIAkIApq6d1qKZ5OzFIEJQ2eqFa4TRW2BH18BhK/5+LHv4hI5Q +yIFU0wvnWufrlDpPd0sHZs4Rtyv7DXKLalafI0rt8wMCQgF3KIktGZN0ppn42anJ +UgxeryI8lssrz6y7o1t8bgkCSpPUHFOJiaPcAMaCJIy9/pTkNqItAS6vD9OXvLCq +qkTIUg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICQzCCAgICCQCg3U8Mc7XCRTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyM1oXDTEwMDExNDIxMzAyM1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMzg0cjFzZXJ2ZXItc2VjdDE2M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAEkRuBmaS+ +693na8/kbscQtkKYQyhZ1w+fRbK8vSoPey6GxxDsFU01DAZtxhAiFKDh5Eh1s8ur +goSjJFGjIJWSzgzK2NN6zrvlpuNFYeIbM4ALvRsYDAMJ+3tl3Vq30BWhMAkGByqG +SM49BAEDMAAwLQIUDc0O2pwXZTxjX/TO4dmxlMoBUUYCFQL051eCJ9zO3XAww5Rv +n2Obyhhq6w== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICTDCCAgICCQCg3U8Mc7XCRjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyNFoXDTEwMDExNDIxMzAyNFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwMzg0cjFzZXJ2ZXItc2VjdDE5M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMHYwEAYHKoZIzj0CAQYFK4EEACIDYgAENttarKTc +CJ4k1b8Fd14pSbGQprsbAFfxk7QhONku4iyam7bmVM5b9Q0SjfNzKIT8yW2swCdi +cFFOcMlpYFGbGNk9kV3mkMhHi5qgbw4iv6/U3WiT7kxfbJjNzWAcGQOQMAkGByqG +SM49BAEDOQAwNgIZAIDGXPjGWx96qYTgjUzg80VsiRV5TINzjQIZAIoa/jec5ioW +ZAvx7piEzY3fRw/YpRMF1A== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICgjCCAgoCCQCROG+IEgiARDAJBgcqhkjOPQQBMIGrMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMSswKQYDVQQLDCJUZXN0IFNlcnZl +ciAoc2VjcDM4NHIxc2VydmVyLXNlbGYpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVu +dGFsc3R1ZmYuY29tMB4XDTA1MTIwNjIxMzAyNloXDTEwMDExNDIxMzAyNlowgasx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmll +dzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxKzApBgNV +BAsMIlRlc3QgU2VydmVyIChzZWNwMzg0cjFzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNi +AASCHyVEN+D1kiuu8teqNLvuT/r0cNoE7RyKEt9wpkOMB9NdcFEzVClX9A0AmovZ ++OGwM4ltWN40BFkImyHmwzGRwZEJYdgmFtZOwRKJaMWadbqpto5PtuB+SpFhtQmO +dDMwCQYHKoZIzj0EAQNnADBkAjBCpsIVKSYpyYXCWfeYVf5odGJ7ZAgnT7iYstM3 +HZBfdXA6t8zjXICA2ICOqrR1xUoCMDm7poy6GrsHEOMsBoVS5T9U0p3ouMyOhkIm +0EykkGk1wK+9Z6QM/DLP8lLJB0IrDA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDvjCCAyCgAwIBAgIJANErVg+ok6iAMAkGByqGSM49BAEwgZwxCzAJBgNVBAYT +AlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UE +CgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3Qg +Q0EgKHNlY3A1MjFyMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5j +b20wHhcNMDUxMjA2MjEyOTU1WhcNMTAwMTE0MjEyOTU1WjCBnDELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEcMBoGA1UECwwTVGVzdCBD +QSAoc2VjcDUyMXIxKTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNv +bTCBmzAQBgcqhkjOPQIBBgUrgQQAIwOBhgAEADNScfIghIZGN1TI9A6iM8F+LrAg +xrInc7nmKIBtdYYfsFWwT4P6bQqNrOZixrSmTiZXSGWhzaj+gGAdF8vfr81YAVNe +1hkuP3iC/4iaRk9vyMDHNvKDHQeUxFNIL2UTAfSTl0vYmL1C5KkpYU3+qBVFTLpa +7uImk1s3wQIkTTHyFLLMo4IBBTCCAQEwHQYDVR0OBBYEFAwP2eZOjIq6F87PsSjp +qniRzxZpMIHRBgNVHSMEgckwgcaAFAwP2eZOjIq6F87PsSjpqniRzxZpoYGipIGf +MIGcMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWlu +IFZpZXcxJjAkBgNVBAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRww +GgYDVQQLDBNUZXN0IENBIChzZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJp +bWVudGFsc3R1ZmYuY29tggkA0StWD6iTqIAwDAYDVR0TBAUwAwEB/zAJBgcqhkjO +PQQBA4GMADCBiAJCAYD/Rk9FMPk0ZzNrXCHKRdXkjBqfsoB5VYRjFIQnIz8+xEAC +KqHjdmYd4djR6l6NA4olKQn+LUwE2hmtom6res2GAkIBPDlBcwGzoDxU4CQQb/rP +cFEMaA5I4fpGdSNYtIJDkXNluVHAPkv+uK9lrhsjuvpVbh76+mM3B9bg4Tq6+Pxb +KN0= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICxDCCAi0CCQCg3U8Mc7XCTzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMzRaFw0xMDAxMTQyMTMwMzRaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDUyMXIxc2VydmVyLXJzYTEwMjRjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYA +BAB+Wp/To8yXNzzp1Iw12ACR2Zc2s8o19H3E8cgC26eDcDYzlAf67/ldZyQ0WDzI +xUlxeJjmNcdiavR5usOo/2lE2AEK1tWu/xVhZZZHWiNQ0vZdZ43BHtBPcqdHRZKv +RRZWrP1pd9ubq1UDzegZdFQ5JwwQjPXz4jpOfTYO5TrmftxZjzANBgkqhkiG9w0B +AQUFAAOBgQAMYv77n1SJ+MDneFbJ2ssBd6aw+hbVqwBVopd0YC+i1Kt5bDe649d/ +vMAtnEmOF8G9/ugg5XVoB0M+6DINC/a5HYYZEYAW/g3Q44XaZCJWOvEVYhFAeUNb +BigmNP4yGv3vP+1rqwEqhb9quxYF2n1e3BuBbi9HkIf2Gp0sMP3pcA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDRTCCAi0CCQCg3U8Mc7XCUDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwMzVaFw0xMDAxMTQyMTMwMzVaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjcDUyMXIxc2VydmVyLXJzYTIwNDhjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYA +BABjwtNCj8IRxv8e0qyePjKGqOvlcPDzx54bcokXDVHxWOL3OEljqi8qWxJm+Mzg +Xhr888VBZdWjF8iXGgtGPEyNRwF635gdYvpcJoz+I1Jg5XzJYo+kLpf/xt5V44/P +EizJQyx/aJ4thsf2gCfFg/zWpDQbcjrwjz10fzLW7rkt7otbAjANBgkqhkiG9w0B +AQUFAAOCAQEAK88ka6Xlvl/Bg2W9TyAh6zPEtDHU3WPN10LxU4ghbStUGx/YupTr +LSg7nLOQo9CI8LKb+tpTaMPmCSTH5Cfwh+f7Uw20wbvPBg06GiBdQjuK3Dvk64B6 +41s4Y75J0wpXJfgezARRlLe0VLAWwH9ZnZRiqtndF527dPBi8EF3qc8X1sGaQ8tn +EVCd2ifptLgp+eI78QdKsgDFpjDOSJNbLDI1yQcm/0EafyJLKd+xH3EBkaaiw+OV +ctYsD3ebQ6tldDnopgbisTmtwvHGqzVGTG8DDX1El2YhVe4bwZTtLBjcbtJxDg/V +0FLkpRjQ/sDqMbDMb6CUoHRa8Urq13e0Cg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICaDCCAigCCQCg3U8Mc7XCSTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyN1oXDTEwMDExNDIxMzAyN1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwNTIxcjFzZXJ2ZXItc2VjcDE2MHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBQ/O2 +98Fp8ZlEDVNNUHEHYrdrhmofdEsOMsyaabFAWp4cexMjGYgOZaD4/sCYjc1N9sXp +1LqIlBVeAfQ5BCSdqJYAaUQrvL/4evYANvIiymw/peV60y6Vchz/XuKH3M4RVCxa +8d7eeobwzCbM2PjR1loiInAhdFrKJHF2z3M84MPgQJswCQYHKoZIzj0EAQMvADAs +AhQ7SDvm2UNjV6SQf5HoMMrh+K1V4wIUBIIDOf2vtxEmVLXZvaoJGbOf9Vs= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICgTCCAigCCQCg3U8Mc7XCSjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyOFoXDTEwMDExNDIxMzAyOFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwNTIxcjFzZXJ2ZXItc2VjcDI1NnIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAqYn6 +hGbL5dTx1gnWnUBp40JXPKxlrAi4p6ofvM6Kd1HwtQLgeNpIqi1TtxXPc4HkHu9F +gqV5pOJhEUAF9ABqeigBCGHqHtp7eqq8ZKVfIdQKDUTGsHZe1mkQA9JHqBwi35Mo +TOkUlws3aEFtXyfZcjgUd7PYzOM5Ry/m56RiZGdMu+EwCQYHKoZIzj0EAQNIADBF +AiEAzxdUODAqmgqDDM13NLrIREDlN8BlRgFUW4AFxOg87Y4CICW2qf+ioupQuvWE +da8fLQVnCbVbLUKFZlJd02uIsud7 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICojCCAigCCQCg3U8Mc7XCSzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAyOVoXDTEwMDExNDIxMzAyOVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwNTIxcjFzZXJ2ZXItc2VjcDM4NHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAx9bl +XZ1Voix3FACqRqpURu5ZjoPPMIY93jbYEL6wZdDU4FFbXOiTYt2At+aQPi8Rjy8a +DI3CxXQ5PCPrCPip8gwABVTtjfQzwJwbqIlZuE/HZL6ZmRkz1iCOmWhk4qDqGUpw +/k78Wgl4GYPBdsZOxzSa0g+XIQEW3MeLGzpEH86zKY8wCQYHKoZIzj0EAQNpADBm +AjEAv1WKxcvLV9MQWHIu1rWic1soAGPIt30b/7Q8VZB7HnRTBtOQUteQevoHHxjo +DZWaAjEA43j2Sh07TKD1c6lglFFONNNuR7orVCapEgoXNgcMceF8cwIuYyCqW75A +EneclLfr +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICxjCCAigCCQCg3U8Mc7XCTDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzMFoXDTEwMDExNDIxMzAzMFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwNTIxcjFzZXJ2ZXItc2VjcDUyMXIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQAyY+l +SUAwJE5hPEUCwuccerdfzoZMp3c9Hkw/fnvVjQpA0Vvb0piBJ39MRCGYi63RbaRs +QexmUq3XGdbL8mwoV0YB5niOZ9cg6YeqXRAnkcS/GboHNjtYQWysta+D+dfX8S1g +YBuXdNZrbGdAj9UP7+gz/9WrPOctz6gwyeiKLKsvosMwCQYHKoZIzj0EAQOBjAAw +gYgCQgErxOvqzrTt5eHrdH4ZxUn4AM9dBAqX33jKXBKNuRgmyYIxoIO2c2tqkdxC +rXmeudFZmFGEEBor5bg2RMI6pkcoWwJCAe6TIx0KcaF6D1wW9tlmRXZ+888SS6Fq +BdVwn4a8/6TrTxQGmDD6qVTwGco76umjHnam50Kcvg6iBAjfSUmwj/56 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICajCCAigCCQCg3U8Mc7XCTTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzMloXDTEwMDExNDIxMzAzMlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwNTIxcjFzZXJ2ZXItc2VjdDE2M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQB3xU0 +hOYQMnJ7L+TLdSkB7ruVnjWo6iwLe0N2GlpCc5jSmBfhGr0NyoKrNY1Zy+VcnGCu +vYgT/aqN7nOnZ86qoQQAq8o2wpdlTbeyzzE26txGTVi+7IN3sVB7DFmqI/R6ngKK +GdkmE6ZOBBcyipzOc/eXRpqoRaIRA+FP2LAPdBnsuNkwCQYHKoZIzj0EAQMxADAu +AhUBOyoJaoo5E6UZ8ICdSZAsL7FpwcMCFQJ1wcD/KuK0g+2WMgpCAuElR+dZIg== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICcDCCAigCCQCg3U8Mc7XCTjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzM1oXDTEwMDExNDIxMzAzM1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWNwNTIxcjFzZXJ2ZXItc2VjdDE5M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBvNN+ +2syVq0vx/Qj1W5IYpeUdyswTzyBNdz0LveNcNEV07jql3o25dPHNGZcVcCvPFw2H +2zpaWV8t0YHjHETM3mEBxgyxwpbM3dkdCuM0VlKEA+rUY64QU8/f0WYU+1cFPBBi +fMOuMKXfb1JNK93W9A9jzmFSVJJVauXYs6JURy60Z+8wCQYHKoZIzj0EAQM3ADA0 +AhgoBo+CqnLTn7UxFzNYtHabS0zMzBzBhN0CGAaNavBCHkk1eX0xmp+7BIxHnWOl +bbeeYQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICzjCCAjACCQCYUruIqLYp5jAJBgcqhkjOPQQBMIGrMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMSswKQYDVQQLDCJUZXN0IFNlcnZl +ciAoc2VjcDUyMXIxc2VydmVyLXNlbGYpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVu +dGFsc3R1ZmYuY29tMB4XDTA1MTIwNjIxMzAzNloXDTEwMDExNDIxMzAzNlowgasx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmll +dzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxKzApBgNV +BAsMIlRlc3QgU2VydmVyIChzZWNwNTIxcjFzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMD +gYYABAH3WSHvJZH8mqyGfVxtoyF5pCUVJZTnebvRphld+jK1PFKlzglYN22J8yN9 +l7Ca2h2OjuuEVj3fZAwSAInZtZQzxAEHFMZEVAzoHUPjx9qEAJiNjXcVV79cvrvc +Q8SbYBF3vGB0su2Qydig+VEjmkyklGhxFLQE8fo7fEZh+FfwGG3x6TAJBgcqhkjO +PQQBA4GMADCBiAJCAYLsxXVifQfzuyZRMNqzldUcASTgs1L/MMtJcEvYtFpeaGXd +Nn1jIynPkC3rgjbejtLe4OypPymrkVE0Bjn3rKU/AkIB1TtXqfmYkTdOO/AUriRl +GSatOobx7QQ+CyOtziObl1UPe7hDYGX8quZPxWnx6MgtO4I4sSZWA7/0C6N61XSq +NPs= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDBjCCAsSgAwIBAgIJAJUfXqNiGl4gMAkGByqGSM49BAEwgZwxCzAJBgNVBAYT +AlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UE +CgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3Qg +Q0EgKHNlY3QxNjNyMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5j +b20wHhcNMDUxMjA2MjEyOTU2WhcNMTAwMTE0MjEyOTU2WjCBnDELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEcMBoGA1UECwwTVGVzdCBD +QSAoc2VjdDE2M3IxKTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNv +bTBAMBAGByqGSM49AgEGBSuBBAACAywABATc2/gR5Sk1spq3ktZK4UCWH8ILGQJy +xhua4tLSekXuk3joLxw7GVD/K6OCAQUwggEBMB0GA1UdDgQWBBTRQhIcGNnfzY1r +7mAO0j6l4jrt1jCB0QYDVR0jBIHJMIHGgBTRQhIcGNnfzY1r7mAO0j6l4jrt1qGB +oqSBnzCBnDELMAkGA1UEBhMCVVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3Vu +dGFpbiBWaWV3MSYwJAYDVQQKDB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmll +czEcMBoGA1UECwwTVGVzdCBDQSAoc2VjdDE2M3IxKTEiMCAGA1UEAwwZZGV2LmV4 +cGVyaW1lbnRhbHN0dWZmLmNvbYIJAJUfXqNiGl4gMAwGA1UdEwQFMAMBAf8wCQYH +KoZIzj0EAQMxADAuAhUD5UVJP72K01PbvDeANWleHbjxd48CFQN6Qt34E0JeefbC +NVkYG6pXLegBvQ== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICaDCCAdECCQCg3U8Mc7XCVzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwNDBaFw0xMDAxMTQyMTMwNDBaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjdDE2M3Ixc2VydmVyLXJzYTEwMjRjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wQDAQBgcqhkjOPQIBBgUrgQQAAgMsAAQE +/r8twiEWpvxX4VUSmCw1JJNHF9IDvIxktMTtZqcK2/57GElqT5Hmi1swDQYJKoZI +hvcNAQEFBQADgYEAHmeOaUdqT4x1o7UCpXTW8D2+XCTCFMpPENH0plL7ALUj5R2D +av2TvKKSwpbyOJa26Rx5KEMNntGpSN1X4+a+wPHZ87J3wmtU7B6nEaHIkFM/iGRQ +M2Ip+lBhebd1e+itwIRnpFcNt5dD276F30928E6kxwSge2uoQJySFV+Xuho= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIC6TCCAdECCQCg3U8Mc7XCWDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwNDFaFw0xMDAxMTQyMTMwNDFaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjdDE2M3Ixc2VydmVyLXJzYTIwNDhjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wQDAQBgcqhkjOPQIBBgUrgQQAAgMsAAQD +jbQ3J7+yvmgc++WxXN52nfRQWnkFc1DUqspljUJyusmdPI1+8ki7FcMwDQYJKoZI +hvcNAQEFBQADggEBAAF3SF1Wmlk6F/IeQs0hlLHF/ik0xWngsO/Qgqrax6MGLdPW +jjJDE1UY6mjNXo8kuV9nIr4+27RN1q3hlSaVC47BX9kZNOs+nO/8h4mFXSV3osq4 +7RrJ5RJ/seXk6s7QItfmZslv7LR/FrzTF7pDv385WwwRXpfhCIY3X24bSt7dgK4j +CkXf6GV9WTrICmNRBeV8/LJAbETU6XPhBXpIlYO0sasSfbCd/j4voIUhwZgPXdGx +iNVWcwgntcOwx4wXJOoWoiiU/j+eS6YDrsxqgdV3j0+JYWQNUvFhrotI/HjbZ8RU +rUiYpAcbghxkent0pcmkcHbJJcj/8/AzQcp+iYg= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICDTCCAcwCCQCg3U8Mc7XCUTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzN1oXDTEwMDExNDIxMzAzN1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTYzcjFzZXJ2ZXItc2VjcDE2MHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEAwEAYHKoZIzj0CAQYFK4EEAAIDLAAEBW5dGOJD +CIYYqj8GEUDWGalB2d6wAQzBC6qR3h5seNsC212ApAdfYdTUMAkGByqGSM49BAED +MAAwLQIVANtclGRvcbIOV+XiYhSBeiuj/XAZAhQjQSZ21bwoOnKjnybeDYMhqEIG +1w== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICJTCCAcwCCQCg3U8Mc7XCUjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzN1oXDTEwMDExNDIxMzAzN1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTYzcjFzZXJ2ZXItc2VjcDI1NnIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEAwEAYHKoZIzj0CAQYFK4EEAAIDLAAEAEvhHRk9 +YT/OvjnDdKuUpfv4RLbvA+ea8m5+4zH4agPsJFjEgC+Tl2AoMAkGByqGSM49BAED +SAAwRQIgEE8zOqy0HkGCnAqdj0xUdpN43vyhBy08G6wx5tWFYekCIQDk0Rc/a8Mz +id0zWgeo4cFUv75+S86WaSSxnkbgKD/PfA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICRDCCAcwCCQCg3U8Mc7XCUzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzOFoXDTEwMDExNDIxMzAzOFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTYzcjFzZXJ2ZXItc2VjcDM4NHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEAwEAYHKoZIzj0CAQYFK4EEAAIDLAAEBLc5EQ+F +QABNsN7pyoOE60q/aokmAgE6Su1TfwZKvAGjxcAF4+l/I015MAkGByqGSM49BAED +ZwAwZAIwD2i5VWRPgSSx/Q2JgJTN96q/T/rmDW+IzyqEU78KwzVIhf8zUIjQH5Pv +az+KrObIAjBNUjCd2rUJorAOrDcf/s8d7KFBnxoiRjNCRKO6SiPvI8Cc4jaXfja5 +XZJjzk8P/nc= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICajCCAcwCCQCg3U8Mc7XCVDAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwNTIxcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzOFoXDTEwMDExNDIxMzAzOFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTYzcjFzZXJ2ZXItc2VjcDUyMXIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEAwEAYHKoZIzj0CAQYFK4EEAAIDLAAEAcPPApQN +hrXdgu0Rxv5SSy9Exry/Ag78xFNPzTR9mJxS1X8tN1wfiJOBMAkGByqGSM49BAED +gYwAMIGIAkIA1Fm7h0vZAywp1Wf3xNI3wm29lK0BSWOVO6fQyWYmKghKi325Tkbw +MbyO3D9YXC2K1G7zQrG5GXA1Jo82ndhpsKUCQgHK67lXzYtfCndSWDrPftXEqn0T +epSGI3I5vxlJuvx2UW1fvZt098Ku4bR8ixKVgDHo8TuEEsJJg+johh0oZHQj7Q== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICDTCCAcwCCQCg3U8Mc7XCVTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzOVoXDTEwMDExNDIxMzAzOVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTYzcjFzZXJ2ZXItc2VjdDE2M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEAwEAYHKoZIzj0CAQYFK4EEAAIDLAAEBd4sp9FM +F2RQWVjZqhqKPRhVhcOrB20Iqn3MfUIXpKnZWBugJZYgQVIvMAkGByqGSM49BAED +MAAwLQIUAwzB/r2hCllysJwxwC4VKKF90igCFQCO0ik9fYlw5RInDzDH/f7xjOOS +gw== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICFTCCAcwCCQCg3U8Mc7XCVjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzAzOVoXDTEwMDExNDIxMzAzOVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTYzcjFzZXJ2ZXItc2VjdDE5M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEAwEAYHKoZIzj0CAQYFK4EEAAIDLAAEAgD1SibB +UQJtSvkK42sdggot73fzBk2J+aj3WSvDHwMXsYslaPQG71lYMAkGByqGSM49BAED +OAAwNQIZANBEfel7WcTKFV0q3UTeod1T3K7ClZQpQgIYZe6dll2Llj3A2S6eRB1G +qjDJaejrFGxR +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICFjCCAdQCCQCKZ9MLoj/3JDAJBgcqhkjOPQQBMIGrMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMSswKQYDVQQLDCJUZXN0IFNlcnZl +ciAoc2VjdDE2M3Ixc2VydmVyLXNlbGYpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVu +dGFsc3R1ZmYuY29tMB4XDTA1MTIwNjIxMzA0MVoXDTEwMDExNDIxMzA0MVowgasx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmll +dzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxKzApBgNV +BAsMIlRlc3QgU2VydmVyIChzZWN0MTYzcjFzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wQDAQBgcqhkjOPQIBBgUrgQQAAgMs +AAQAbsGEXvpTlsxcf5b1S0Uv+CW6aDIAD1SB5MwpErkmq6eCFPVF2c3iIZ4wCQYH +KoZIzj0EAQMxADAuAhUAhh4DeqrebKZ7IoIO+gYcs1tT4IsCFQD51UVBnZrYhqHT +tKfswmapHLXMzA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIDFTCCAsygAwIBAgIJAI4aIMim8fazMAkGByqGSM49BAEwgZwxCzAJBgNVBAYT +AlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UE +CgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxHDAaBgNVBAsME1Rlc3Qg +Q0EgKHNlY3QxOTNyMSkxIjAgBgNVBAMMGWRldi5leHBlcmltZW50YWxzdHVmZi5j +b20wHhcNMDUxMjA2MjEyOTU2WhcNMTAwMTE0MjEyOTU2WjCBnDELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEcMBoGA1UECwwTVGVzdCBD +QSAoc2VjdDE5M3IxKTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZmLmNv +bTBIMBAGByqGSM49AgEGBSuBBAAYAzQABADC/YtwwrsyHusPx05mHRMV3Rjw5dcw +LLUAIh3jrWVGFFLWZl0QCs2xBnGF6KfjKnOdo4IBBTCCAQEwHQYDVR0OBBYEFHVx +jVCVss3ZetdFkR0auNgmLXljMIHRBgNVHSMEgckwgcaAFHVxjVCVss3ZetdFkR0a +uNgmLXljoYGipIGfMIGcMQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExFjAUBgNV +BAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1biBNaWNyb3N5c3RlbXMgTGFi +b3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChzZWN0MTkzcjEpMSIwIAYDVQQD +DBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tggkAjhogyKbx9rMwDAYDVR0TBAUw +AwEB/zAJBgcqhkjOPQQBAzgAMDUCGFVX2d9M0NbxeusbaUjMcWwviXPQpNEHvwIZ +AOPKXDtDGAwkb42kO7ms7rzN7R4LN788MA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICcDCCAdkCCQCg3U8Mc7XCXzANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAxMDI0KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwNDVaFw0xMDAxMTQyMTMwNDVaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjdDE5M3Ixc2VydmVyLXJzYTEwMjRjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wSDAQBgcqhkjOPQIBBgUrgQQAGAM0AAQA +vZA91W5lNk3Ru3pALBexkJpZ9K0WjZrLASMO9wZGvbukocKAPYTfDYdcSwdwqHuU +RzANBgkqhkiG9w0BAQUFAAOBgQB/Gcwd09VVyOWJq9cIA5tga/ZBYwgXv+T3eAUU +Ert7tGQgD/eysWYvTB+Vu9zUvGyWWtUfzoFMP1R2MeuxnDMiXyhhQ+7UKl3P7AQy +P060oo1DP7RWK8D8oz8IFeP6ttaiRgetE3hnHUwbxnO30bdiN61EdWBT0Dp+0LuP +Yg6Ndw== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIIC8TCCAdkCCQCg3U8Mc7XCYDANBgkqhkiG9w0BAQUFADCBnzELMAkGA1UEBhMC +VVMxCzAJBgNVBAgMAkNBMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MSYwJAYDVQQK +DB1TdW4gTWljcm9zeXN0ZW1zIExhYm9yYXRvcmllczEfMB0GA1UECwwWVGVzdCBT +ZXJ2ZXIgKFJTQSAyMDQ4KTEiMCAGA1UEAwwZZGV2LmV4cGVyaW1lbnRhbHN0dWZm +LmNvbTAeFw0wNTEyMDYyMTMwNDZaFw0xMDAxMTQyMTMwNDZaMIGwMQswCQYDVQQG +EwJVUzELMAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNV +BAoMHVN1biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMTAwLgYDVQQLDCdUZXN0 +IFNlcnZlciAoc2VjdDE5M3Ixc2VydmVyLXJzYTIwNDhjYSkxIjAgBgNVBAMMGWRl +di5leHBlcmltZW50YWxzdHVmZi5jb20wSDAQBgcqhkjOPQIBBgUrgQQAGAM0AAQA +qMKb0SJmrWoWnZxXZh5jhRZnF9vRyljvARAR7/z2+gU/qkOTcxuE9RYxgqHtDVRE +fjANBgkqhkiG9w0BAQUFAAOCAQEAScWVdynbg9B9VCtF4Ct8sXMRRYuwCLUt5Yp/ +rtLXmhUuZR0qCvuCMoDo2+HdQNcwEZr7teH2jZ9gYcfq1GWouwA36rafR8e4GQ4P +egySyKLYkZ7sKhrKacN4k1XItlxHsWWtVRs79smAVgpVIu5IA2Pm5BZEuIUPCIAF +3gSHM6Y0UHWGazxaToUEiPh7jVh5eUA8wAdhKFhiLtrIlZo9u2BCXmPiwBj71fSY +iyEArag7u/n5pfoBYzwiiAFLddQiuwaxe8jPt0+RJI5Dhs0IzX6L/Xzu06qkKPjF +9AX5PkBWj5GAjPCU/8t3O2wrMBvCw7G7epMXNXjTqJf6no5sig== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICFTCCAdQCCQCg3U8Mc7XCWTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMTYwcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA0MloXDTEwMDExNDIxMzA0MlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTkzcjFzZXJ2ZXItc2VjcDE2MHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEgwEAYHKoZIzj0CAQYFK4EEABgDNAAEANui7TQR +XIBnrqvvP9zgztIKdqeIwISmzQBKKwC3FMR/Ma/MJCuBuXANUV3Xbi/rwwswCQYH +KoZIzj0EAQMwADAtAhUAhNmGbEAG/eht1YE9KUUf7v/k9ywCFDO9YqZLm7mvDe2Q +Vp2EWIS8AFw0 +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICLjCCAdQCCQCg3U8Mc7XCWjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMjU2cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA0MloXDTEwMDExNDIxMzA0MlowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTkzcjFzZXJ2ZXItc2VjcDI1NnIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEgwEAYHKoZIzj0CAQYFK4EEABgDNAAEAE/bjnPS +yBqy8ageF1ZpfzHTAoEzcV5UywAlrF6AsP5UDVbbxWzEYENodBbIAyu5gmswCQYH +KoZIzj0EAQNJADBGAiEAyOvzEV5o/+YRAkIQY/+Le1n3wzUvr9QMwVlOg/yZMvsC +IQCFFD9AOt0tQTxWsDgGzCoVbz9MnnWzptIsGx4HXUm4YA== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICTTCCAdQCCQCg3U8Mc7XCWzAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWNwMzg0cjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA0M1oXDTEwMDExNDIxMzA0M1owgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTkzcjFzZXJ2ZXItc2VjcDM4NHIxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEgwEAYHKoZIzj0CAQYFK4EEABgDNAAEASNBKWzJ ++B+4G2UTsTqBM0cjsdS6C5cmHwC1oYKyagdGeWkSzI3wsNJri29OBB3wg1YwCQYH +KoZIzj0EAQNoADBlAjEAvCF43f3XJZHJ43dChTwVcMxrvrkEg33BCdkpab3ZzQGc +4z8YLxgXwNgQtoWakxepAjAT9zi78gOcvIOLt+cONUWX1Q3dwsqz7ELfB51+H9EC +njcMe07enAwPTGZhifhBqfQ= +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICFjCCAdQCCQCg3U8Mc7XCXTAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTYzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA0NFoXDTEwMDExNDIxMzA0NFowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTkzcjFzZXJ2ZXItc2VjdDE2M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEgwEAYHKoZIzj0CAQYFK4EEABgDNAAEAInznYj4 +XfwSdi2XrqLF6uQ1/sJoFEveBQCqz+XoSsXKgRmMCO2iMHVGctNbcz8RptMwCQYH +KoZIzj0EAQMxADAuAhUBfBAH/3ROR9VsZKAhW0fR6i/ud9gCFQCdjuAk1NhSTtAD +AcZ+gSnBmESa1g== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICHDCCAdQCCQCg3U8Mc7XCXjAJBgcqhkjOPQQBMIGcMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMRwwGgYDVQQLDBNUZXN0IENBIChz +ZWN0MTkzcjEpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVudGFsc3R1ZmYuY29tMB4X +DTA1MTIwNjIxMzA0NVoXDTEwMDExNDIxMzA0NVowgbIxCzAJBgNVBAYTAlVTMQsw +CQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEmMCQGA1UECgwdU3Vu +IE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxMjAwBgNVBAsMKVRlc3QgU2VydmVy +IChzZWN0MTkzcjFzZXJ2ZXItc2VjdDE5M3IxY2EpMSIwIAYDVQQDDBlkZXYuZXhw +ZXJpbWVudGFsc3R1ZmYuY29tMEgwEAYHKoZIzj0CAQYFK4EEABgDNAAEAGJbRZVS +qbKx8P+C60EaCmnuolgSDf7fqwE0oMSo8dtSmq1vSmqXjbQHWaze3zev50swCQYH +KoZIzj0EAQM3ADA0AhhsmuN8sbGYzItLtNqk/kXRvBSk+gOeKaECGBAT5pnVqKan +q4wuATzeJEv5LeT9H3GU1A== +-----END CERTIFICATE----- +-----BEGIN CERTIFICATE----- +MIICJDCCAdwCCQCzW7zGCDpEhzAJBgcqhkjOPQQBMIGrMQswCQYDVQQGEwJVUzEL +MAkGA1UECAwCQ0ExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxJjAkBgNVBAoMHVN1 +biBNaWNyb3N5c3RlbXMgTGFib3JhdG9yaWVzMSswKQYDVQQLDCJUZXN0IFNlcnZl +ciAoc2VjdDE5M3Ixc2VydmVyLXNlbGYpMSIwIAYDVQQDDBlkZXYuZXhwZXJpbWVu +dGFsc3R1ZmYuY29tMB4XDTA1MTIwNjIxMzA0N1oXDTEwMDExNDIxMzA0N1owgasx +CzAJBgNVBAYTAlVTMQswCQYDVQQIDAJDQTEWMBQGA1UEBwwNTW91bnRhaW4gVmll +dzEmMCQGA1UECgwdU3VuIE1pY3Jvc3lzdGVtcyBMYWJvcmF0b3JpZXMxKzApBgNV +BAsMIlRlc3QgU2VydmVyIChzZWN0MTkzcjFzZXJ2ZXItc2VsZikxIjAgBgNVBAMM +GWRldi5leHBlcmltZW50YWxzdHVmZi5jb20wSDAQBgcqhkjOPQIBBgUrgQQAGAM0 +AAQAjhf42KmZLPPrcBCdsOJpU9uDCZDh7CD7Af3pMkj8friWXyIZBoKwChbkPOnT +wq4XMTAJBgcqhkjOPQQBAzcAMDQCGD0nycV04j9b/1/l1cnRJWtuaHUK2LPmdAIY +fDH6KdS9OQSXMHdiCLnK5mWYTDG0g0em +-----END CERTIFICATE----- diff --git a/test/sun/security/ec/keystore b/test/sun/security/ec/keystore new file mode 100644 index 0000000000000000000000000000000000000000..b59a2ab43c61b99c5d72a943aec13b090f111b62 Binary files /dev/null and b/test/sun/security/ec/keystore differ diff --git a/test/sun/security/ec/truststore b/test/sun/security/ec/truststore new file mode 100644 index 0000000000000000000000000000000000000000..643c7a84dabebc452e1aac303d7eafc206a8229f Binary files /dev/null and b/test/sun/security/ec/truststore differ diff --git a/test/sun/security/krb5/IPv6.java b/test/sun/security/krb5/IPv6.java new file mode 100644 index 0000000000000000000000000000000000000000..768a10f5a1607b6bac8a906365e171ad98ab6cfe --- /dev/null +++ b/test/sun/security/krb5/IPv6.java @@ -0,0 +1,130 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6877357 6885166 + * @summary IPv6 address does not work + */ + +import com.sun.security.auth.module.Krb5LoginModule; +import java.io.*; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.security.auth.Subject; + +public class IPv6 { + + public static void main(String[] args) throws Exception { + + String[][] kdcs = { + {"simple.host", null}, // These are legal settings + {"simple.host", ""}, + {"simple.host", "8080"}, + {"0.0.0.1", null}, + {"0.0.0.1", ""}, + {"0.0.0.1", "8080"}, + {"1::1", null}, + {"[1::1]", null}, + {"[1::1]", ""}, + {"[1::1]", "8080"}, + {"[1::1", null}, // Two illegal settings + {"[1::1]abc", null}, + }; + // Prepares a krb5.conf with every kind of KDC settings + PrintStream out = new PrintStream(new FileOutputStream("ipv6.conf")); + out.println("[libdefaults]"); + out.println("default_realm = V6"); + out.println("kdc_timeout = 1"); + out.println("[realms]"); + out.println("V6 = {"); + for (String[] hp: kdcs) { + if (hp[1] != null) out.println(" kdc = "+hp[0]+":"+hp[1]); + else out.println(" kdc = " + hp[0]); + } + out.println("}"); + out.close(); + + System.setProperty("sun.security.krb5.debug", "true"); + System.setProperty("java.security.krb5.conf", "ipv6.conf"); + + ByteArrayOutputStream bo = new ByteArrayOutputStream(); + PrintStream po = new PrintStream(bo); + PrintStream oldout = System.out; + System.setOut(po); + + try { + Subject subject = new Subject(); + Krb5LoginModule krb5 = new Krb5LoginModule(); + Map map = new HashMap(); + Map shared = new HashMap(); + + map.put("debug", "true"); + map.put("doNotPrompt", "true"); + map.put("useTicketCache", "false"); + map.put("useFirstPass", "true"); + shared.put("javax.security.auth.login.name", "any"); + shared.put("javax.security.auth.login.password", "any".toCharArray()); + krb5.initialize(subject, null, shared, map); + krb5.login(); + } catch (Exception e) { + // Ignore + } + + po.flush(); + + System.setOut(oldout); + BufferedReader br = new BufferedReader(new StringReader( + new String(bo.toByteArray()))); + int cc = 0; + Pattern r = Pattern.compile(".*KrbKdcReq send: kdc=(.*) UDP:(\\d+),.*"); + String line; + while ((line = br.readLine()) != null) { + Matcher m = r.matcher(line.subSequence(0, line.length())); + if (m.matches()) { + System.out.println("------------------"); + System.out.println(line); + String h = m.group(1), p = m.group(2); + String eh = kdcs[cc][0], ep = kdcs[cc][1]; + if (eh.charAt(0) == '[') { + eh = eh.substring(1, eh.length()-1); + } + System.out.println("Expected: " + eh + " : " + ep); + System.out.println("Actual: " + h + " : " + p); + if (!eh.equals(h) || + (ep == null || ep.length() == 0) && !p.equals("88") || + (ep != null && ep.length() > 0) && !p.equals(ep)) { + throw new Exception("Mismatch"); + } + cc++; + } + } + if (cc != kdcs.length - 2) { // 2 illegal settings at the end + throw new Exception("Not traversed"); + } + } +} + + diff --git a/test/sun/security/krb5/RFC396xTest.java b/test/sun/security/krb5/RFC396xTest.java new file mode 100644 index 0000000000000000000000000000000000000000..6ab9255d4f54559f9103c89aab74e03f70b1dec3 --- /dev/null +++ b/test/sun/security/krb5/RFC396xTest.java @@ -0,0 +1,248 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ +/* + * @test + * @bug 6862679 + * @summary ESC: AD Authentication with user with umlauts fails + */ + +import java.lang.reflect.Array; +import java.lang.reflect.Method; +import sun.security.krb5.EncryptedData; +import sun.security.krb5.internal.crypto.Des; +import sun.security.krb5.internal.crypto.EType; +import sun.security.krb5.internal.crypto.crc32; +import sun.security.krb5.internal.crypto.dk.AesDkCrypto; +import sun.security.krb5.internal.crypto.dk.Des3DkCrypto; +import sun.security.krb5.internal.crypto.dk.DkCrypto; +import java.nio.*; +import javax.crypto.*; +import javax.crypto.spec.*; + +public class RFC396xTest { + + static final String gclef = new String(Character.toChars(0x1d11e)); + + /** Creates a new instance of NewClass */ + public static void main(String[] args) throws Exception { + System.setProperty("sun.security.krb5.msinterop.des.s2kcharset", + "utf-8"); + test(); + } + + static void test() throws Exception { + // RFC 3961 + // A.1 + Method nfold = DkCrypto.class.getDeclaredMethod("nfold", byte[].class, Integer.TYPE); + nfold.setAccessible(true); + assertStringEquals(hex((byte[])nfold.invoke(null, "012345".getBytes("UTF-8"), 64)), "be072631276b1955"); + assertStringEquals(hex((byte[])nfold.invoke(null, "password".getBytes("UTF-8"), 56)), "78a07b6caf85fa"); + assertStringEquals(hex((byte[])nfold.invoke(null, "Rough Consensus, and Running Code".getBytes("UTF-8"), 64)), "bb6ed30870b7f0e0"); + assertStringEquals(hex((byte[])nfold.invoke(null, "password".getBytes("UTF-8"), 168)), "59e4a8ca7c0385c3c37b3f6d2000247cb6e6bd5b3e"); + assertStringEquals(hex((byte[])nfold.invoke(null, "MASSACHVSETTS INSTITVTE OF TECHNOLOGY".getBytes("UTF-8"), 192)), "db3b0d8f0b061e603282b308a50841229ad798fab9540c1b"); + assertStringEquals(hex((byte[])nfold.invoke(null, "Q".getBytes("UTF-8"), 168)), "518a54a215a8452a518a54a215a8452a518a54a215"); + assertStringEquals(hex((byte[])nfold.invoke(null, "ba".getBytes("UTF-8"), 168)), "fb25d531ae8974499f52fd92ea9857c4ba24cf297e"); + assertStringEquals(hex((byte[])nfold.invoke(null, "kerberos".getBytes("UTF-8"), 64)), "6b65726265726f73"); + assertStringEquals(hex((byte[])nfold.invoke(null, "kerberos".getBytes("UTF-8"), 128)), "6b65726265726f737b9b5b2b93132b93"); + assertStringEquals(hex((byte[])nfold.invoke(null, "kerberos".getBytes("UTF-8"), 168)), "8372c236344e5f1550cd0747e15d62ca7a5a3bcea4"); + assertStringEquals(hex((byte[])nfold.invoke(null, "kerberos".getBytes("UTF-8"), 256)), "6b65726265726f737b9b5b2b93132b935c9bdcdad95c9899c4cae4dee6d6cae4"); + + // A.2 + assertStringEquals(hex(Des.string_to_key_bytes("passwordATHENA.MIT.EDUraeburn".toCharArray())), "cbc22fae235298e3"); + assertStringEquals(hex(Des.string_to_key_bytes("potatoeWHITEHOUSE.GOVdanny".toCharArray())), "df3d32a74fd92a01"); + assertStringEquals(hex(Des.string_to_key_bytes((gclef+"EXAMPLE.COMpianist").toCharArray())), "4ffb26bab0cd9413"); + assertStringEquals(hex(Des.string_to_key_bytes("\u00dfATHENA.MIT.EDUJuri\u0161i\u0107".toCharArray())), "62c81a5232b5e69d"); + // Next 2 won't pass, since there's no real weak key here + //assertStringEquals(hex(Des.string_to_key_bytes("11119999AAAAAAAA".toCharArray())), "984054d0f1a73e31"); + //assertStringEquals(hex(Des.string_to_key_bytes("NNNN6666FFFFAAAA".toCharArray())), "c4bf6b25adf7a4f8"); + + // A.3 + Object o = Des3DkCrypto.class.getConstructor().newInstance(); + Method dr = DkCrypto.class.getDeclaredMethod("dr", byte[].class, byte[].class); + Method randomToKey = DkCrypto.class.getDeclaredMethod("randomToKey", byte[].class); + dr.setAccessible(true); + randomToKey.setAccessible(true); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("dce06b1f64c857a11c3db57c51899b2cc1791008ce973b92"), + xeh("0000000155")))), + "925179d04591a79b5d3192c4a7e9c289b049c71f6ee604cd"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("5e13d31c70ef765746578531cb51c15bf11ca82c97cee9f2"), + xeh("00000001aa")))), + "9e58e5a146d9942a101c469845d67a20e3c4259ed913f207"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("98e6fd8a04a4b6859b75a176540b9752bad3ecd610a252bc"), + xeh("0000000155")))), + "13fef80d763e94ec6d13fd2ca1d085070249dad39808eabf"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("622aec25a2fe2cad7094680b7c64940280084c1a7cec92b5"), + xeh("00000001aa")))), + "f8dfbf04b097e6d9dc0702686bcb3489d91fd9a4516b703e"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("d3f8298ccb166438dcb9b93ee5a7629286a491f838f802fb"), + xeh("6b65726265726f73")))), + "2370da575d2a3da864cebfdc5204d56df779a7df43d9da43"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("c1081649ada74362e6a1459d01dfd30d67c2234c940704da"), + xeh("0000000155")))), + "348057ec98fdc48016161c2a4c7a943e92ae492c989175f7"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("5d154af238f46713155719d55e2f1f790dd661f279a7917c"), + xeh("00000001aa")))), + "a8808ac267dada3dcbe9a7c84626fbc761c294b01315e5c1"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("798562e049852f57dc8c343ba17f2ca1d97394efc8adc443"), + xeh("0000000155")))), + "c813f88a3be3b334f75425ce9175fbe3c8493b89c8703b49"); + assertStringEquals(hex((byte[])randomToKey.invoke(o, (byte[])dr.invoke(o, + xeh("26dce334b545292f2feab9a8701a89a4b99eb9942cecd016"), + xeh("00000001aa")))), + "f48ffd6e83f83e7354e694fd252cf83bfe58f7d5ba37ec5d"); + + // A.4 + assertStringEquals(hex(new Des3DkCrypto().stringToKey("passwordATHENA.MIT.EDUraeburn".toCharArray())), "850bb51358548cd05e86768c313e3bfef7511937dcf72c3e"); + assertStringEquals(hex(new Des3DkCrypto().stringToKey("potatoeWHITEHOUSE.GOVdanny".toCharArray())), "dfcd233dd0a43204ea6dc437fb15e061b02979c1f74f377a"); + assertStringEquals(hex(new Des3DkCrypto().stringToKey("pennyEXAMPLE.COMbuckaroo".toCharArray())), "6d2fcdf2d6fbbc3ddcadb5da5710a23489b0d3b69d5d9d4a"); + assertStringEquals(hex(new Des3DkCrypto().stringToKey("\u00DFATHENA.MIT.EDUJuri\u0161i\u0107".toCharArray())), "16d5a40e1ce3bacb61b9dce00470324c831973a7b952feb0"); + assertStringEquals(hex(new Des3DkCrypto().stringToKey((gclef+"EXAMPLE.COMpianist").toCharArray())), "85763726585dbc1cce6ec43e1f751f07f1c4cbb098f40b19"); + + // A.5 + assertStringEquals(hex(crc32.byte2crc32sum_bytes("foo".getBytes("UTF-8"))), "33bc3273"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes("test0123456789".getBytes("UTF-8"))), "d6883eb8"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes("MASSACHVSETTS INSTITVTE OF TECHNOLOGY".getBytes("UTF-8"))), "f78041e3"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes(new byte[] {(byte)0x80, 0})), "4b98833b"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes(new byte[] {0, 8})), "3288db0e"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes(new byte[] {0, (byte)0x80})), "2083b8ed"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes(new byte[] {(byte)0x80})), "2083b8ed"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes(new byte[] {(byte)0x80, 0, 0, 0})), "3bb659ed"); + assertStringEquals(hex(crc32.byte2crc32sum_bytes(new byte[] {0, 0, 0, 1})), "96300777"); + + // RFC 3962 + AesDkCrypto a1 = new AesDkCrypto(128); + Method pbkdf2 = AesDkCrypto.class.getDeclaredMethod("PBKDF2", char[].class, byte[].class, Integer.TYPE, Integer.TYPE); + Method s2k = AesDkCrypto.class.getDeclaredMethod("stringToKey", char[].class, byte[].class, byte[].class); + pbkdf2.setAccessible(true); + s2k.setAccessible(true); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), "ATHENA.MIT.EDUraeburn".getBytes("UTF-8"), 1, 128)), "cd ed b5 28 1b b2 f8 01 56 5a 11 22 b2 56 35 15"); + assertStringEquals(hex(a1.stringToKey("password".toCharArray(), "ATHENA.MIT.EDUraeburn", i2b(1))), "42 26 3c 6e 89 f4 fc 28 b8 df 68 ee 09 79 9f 15"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), "ATHENA.MIT.EDUraeburn".getBytes("UTF-8"), 1, 256)), "cd ed b5 28 1b b2 f8 01 56 5a 11 22 b2 56 35 15 0a d1 f7 a0 4b b9 f3 a3 33 ec c0 e2 e1 f7 08 37"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), "ATHENA.MIT.EDUraeburn".getBytes("UTF-8"), 2, 128)), "01 db ee 7f 4a 9e 24 3e 98 8b 62 c7 3c da 93 5d"); + assertStringEquals(hex(a1.stringToKey("password".toCharArray(), "ATHENA.MIT.EDUraeburn", i2b(2))), "c6 51 bf 29 e2 30 0a c2 7f a4 69 d6 93 bd da 13"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), "ATHENA.MIT.EDUraeburn".getBytes("UTF-8"), 2, 256)), "01 db ee 7f 4a 9e 24 3e 98 8b 62 c7 3c da 93 5d a0 53 78 b9 32 44 ec 8f 48 a9 9e 61 ad 79 9d 86"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), "ATHENA.MIT.EDUraeburn".getBytes("UTF-8"), 1200, 128)), "5c 08 eb 61 fd f7 1e 4e 4e c3 cf 6b a1 f5 51 2b"); + assertStringEquals(hex(a1.stringToKey("password".toCharArray(), "ATHENA.MIT.EDUraeburn", i2b(1200))), "4c 01 cd 46 d6 32 d0 1e 6d be 23 0a 01 ed 64 2a"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), "ATHENA.MIT.EDUraeburn".getBytes("UTF-8"), 1200, 256)), "5c 08 eb 61 fd f7 1e 4e 4e c3 cf 6b a1 f5 51 2b a7 e5 2d db c5 e5 14 2f 70 8a 31 e2 e6 2b 1e 13"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), xeh("1234567878563412"), 5, 128)), "d1 da a7 86 15 f2 87 e6 a1 c8 b1 20 d7 06 2a 49"); + assertStringEquals(hex((byte[])s2k.invoke(a1, "password".toCharArray(), xeh("1234567878563412"), i2b(5))), "e9 b2 3d 52 27 37 47 dd 5c 35 cb 55 be 61 9d 8e"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "password".toCharArray(), xeh("1234567878563412"), 5, 256)), "d1 da a7 86 15 f2 87 e6 a1 c8 b1 20 d7 06 2a 49 3f 98 d2 03 e6 be 49 a6 ad f4 fa 57 4b 6e 64 ee"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase equals block size".getBytes("UTF-8"), 1200, 128)), "13 9c 30 c0 96 6b c3 2b a5 5f db f2 12 53 0a c9"); + assertStringEquals(hex(a1.stringToKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase equals block size", i2b(1200))), "59 d1 bb 78 9a 82 8b 1a a5 4e f9 c2 88 3f 69 ed"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase equals block size".getBytes("UTF-8"), 1200, 256)), "13 9c 30 c0 96 6b c3 2b a5 5f db f2 12 53 0a c9 c5 ec 59 f1 a4 52 f5 cc 9a d9 40 fe a0 59 8e d1"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase exceeds block size".getBytes("UTF-8"), 1200, 128)), "9c ca d6 d4 68 77 0c d5 1b 10 e6 a6 87 21 be 61"); + assertStringEquals(hex(a1.stringToKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase exceeds block size", i2b(1200))), "cb 80 05 dc 5f 90 17 9a 7f 02 10 4c 00 18 75 1d"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase exceeds block size".getBytes("UTF-8"), 1200, 256)), "9c ca d6 d4 68 77 0c d5 1b 10 e6 a6 87 21 be 61 1a 8b 4d 28 26 01 db 3b 36 be 92 46 91 5e c8 2a"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, gclef.toCharArray(), "EXAMPLE.COMpianist".getBytes("UTF-8"), 50, 128)), "6b 9c f2 6d 45 45 5a 43 a5 b8 bb 27 6a 40 3b 39"); + assertStringEquals(hex(a1.stringToKey(gclef.toCharArray(), "EXAMPLE.COMpianist", i2b(50))), "f1 49 c1 f2 e1 54 a7 34 52 d4 3e 7f e6 2a 56 e5"); + assertStringEquals(hex((byte[])pbkdf2.invoke(null, gclef.toCharArray(), "EXAMPLE.COMpianist".getBytes("UTF-8"), 50, 256)), "6b 9c f2 6d 45 45 5a 43 a5 b8 bb 27 6a 40 3b 39 e7 fe 37 a0 c4 1e 02 c2 81 ff 30 69 e1 e9 4f 52"); + + if (EType.isSupported(EncryptedData.ETYPE_AES256_CTS_HMAC_SHA1_96)) { + AesDkCrypto a2 = new AesDkCrypto(256); + assertStringEquals(hex(a2.stringToKey("password".toCharArray(), "ATHENA.MIT.EDUraeburn", i2b(1))), "fe 69 7b 52 bc 0d 3c e1 44 32 ba 03 6a 92 e6 5b bb 52 28 09 90 a2 fa 27 88 39 98 d7 2a f3 01 61"); + assertStringEquals(hex(a2.stringToKey("password".toCharArray(), "ATHENA.MIT.EDUraeburn", i2b(2))), "a2 e1 6d 16 b3 60 69 c1 35 d5 e9 d2 e2 5f 89 61 02 68 56 18 b9 59 14 b4 67 c6 76 22 22 58 24 ff"); + assertStringEquals(hex(a2.stringToKey("password".toCharArray(), "ATHENA.MIT.EDUraeburn", i2b(1200))), "55 a6 ac 74 0a d1 7b 48 46 94 10 51 e1 e8 b0 a7 54 8d 93 b0 ab 30 a8 bc 3f f1 62 80 38 2b 8c 2a"); + assertStringEquals(hex((byte[])s2k.invoke(a2, "password".toCharArray(), xeh("1234567878563412"), i2b(5))), "97 a4 e7 86 be 20 d8 1a 38 2d 5e bc 96 d5 90 9c ab cd ad c8 7c a4 8f 57 45 04 15 9f 16 c3 6e 31"); + assertStringEquals(hex(a2.stringToKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase equals block size", i2b(1200))), "89 ad ee 36 08 db 8b c7 1f 1b fb fe 45 94 86 b0 56 18 b7 0c ba e2 20 92 53 4e 56 c5 53 ba 4b 34"); + assertStringEquals(hex(a2.stringToKey("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX".toCharArray(), "pass phrase exceeds block size", i2b(1200))), "d7 8c 5c 9c b8 72 a8 c9 da d4 69 7f 0b b5 b2 d2 14 96 c8 2b eb 2c ae da 21 12 fc ee a0 57 40 1b"); + assertStringEquals(hex(a2.stringToKey(gclef.toCharArray(), "EXAMPLE.COMpianist", i2b(50))), "4b 6d 98 39 f8 44 06 df 1f 09 cc 16 6d b4 b8 3c 57 18 48 b7 84 a3 d6 bd c3 46 58 9a 3e 39 3f 9e"); + } + + Cipher cipher = Cipher.getInstance("AES/CTS/NoPadding"); + + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec( + xeh("63 68 69 63 6b 65 6e 20 74 65 72 69 79 61 6b 69"), "AES"), + new IvParameterSpec( + xeh("00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00"), 0, 16)); + assertStringEquals(hex(cipher.doFinal( + xeh("49 20 77 6f 75 6c 64 20 6c 69 6b 65 20 74 68 65 20"))), + "c6 35 35 68 f2 bf 8c b4 d8 a5 80 36 2d a7 ff 7f 97"); + assertStringEquals(hex(cipher.doFinal( + xeh("49 20 77 6f 75 6c 64 20 6c 69 6b 65 20 74 68 65 20 47 65 6e 65 72 61 6c 20 47 61 75 27 73 20"))), + "fc 00 78 3e 0e fd b2 c1 d4 45 d4 c8 ef f7 ed 22 97 68 72 68 d6 ec cc c0 c0 7b 25 e2 5e cf e5"); + assertStringEquals(hex(cipher.doFinal( + xeh("49 20 77 6f 75 6c 64 20 6c 69 6b 65 20 74 68 65 20 47 65 6e 65 72 61 6c 20 47 61 75 27 73 20 43"))), + "39 31 25 23 a7 86 62 d5 be 7f cb cc 98 eb f5 a8 97 68 72 68 d6 ec cc c0 c0 7b 25 e2 5e cf e5 84"); + assertStringEquals(hex(cipher.doFinal( + xeh("49 20 77 6f 75 6c 64 20 6c 69 6b 65 20 74 68 65 20 47 65 6e 65 72 61 6c 20 47 61 75 27 73 20 43 68 69 63 6b 65 6e 2c 20 70 6c 65 61 73 65 2c"))), + "97 68 72 68 d6 ec cc c0 c0 7b 25 e2 5e cf e5 84 b3 ff fd 94 0c 16 a1 8c 1b 55 49 d2 f8 38 02 9e 39 31 25 23 a7 86 62 d5 be 7f cb cc 98 eb f5"); + assertStringEquals(hex(cipher.doFinal( + xeh("49 20 77 6f 75 6c 64 20 6c 69 6b 65 20 74 68 65 20 47 65 6e 65 72 61 6c 20 47 61 75 27 73 20 43 68 69 63 6b 65 6e 2c 20 70 6c 65 61 73 65 2c 20"))), + "97 68 72 68 d6 ec cc c0 c0 7b 25 e2 5e cf e5 84 9d ad 8b bb 96 c4 cd c0 3b c1 03 e1 a1 94 bb d8 39 31 25 23 a7 86 62 d5 be 7f cb cc 98 eb f5 a8"); + assertStringEquals(hex(cipher.doFinal( + xeh("49 20 77 6f 75 6c 64 20 6c 69 6b 65 20 74 68 65 20 47 65 6e 65 72 61 6c 20 47 61 75 27 73 20 43 68 69 63 6b 65 6e 2c 20 70 6c 65 61 73 65 2c 20 61 6e 64 20 77 6f 6e 74 6f 6e 20 73 6f 75 70 2e"))), + "97 68 72 68 d6 ec cc c0 c0 7b 25 e2 5e cf e5 84 39 31 25 23 a7 86 62 d5 be 7f cb cc 98 eb f5 a8 48 07 ef e8 36 ee 89 a5 26 73 0d bc 2f 7b c8 40 9d ad 8b bb 96 c4 cd c0 3b c1 03 e1 a1 94 bb d8"); + } + + static byte[] i2b(int i) { + ByteBuffer bb = ByteBuffer.allocate(4); + byte[] b = new byte[4]; + bb.putInt(i); + bb.flip(); + bb.get(b); + return b; + } + + static String hex(byte[] bs) { + StringBuffer sb = new StringBuffer(bs.length * 2); + for(byte b: bs) { + char c = (char)((b+256)%256); + if (c / 16 < 10) + sb.append((char)(c/16+'0')); + else + sb.append((char)(c/16-10+'a')); + if (c % 16 < 10) + sb.append((char)(c%16+'0')); + else + sb.append((char)(c%16-10+'a')); + } + return new String(sb); + } + + static byte[] xeh(String in) { + in = in.replaceAll(" ", ""); + int len = in.length()/2; + byte[] out = new byte[len]; + for (int i=0; i 0) && args[0].equals("sh")) { + if ((args != null) && (args.length > 0) && args[0].equals("sh")) { relPath = pathToStoresSH; } else { relPath = pathToStores; diff --git a/test/sun/security/ssl/sun/net/www/httpstest/HttpTransaction.java b/test/sun/security/ssl/sun/net/www/httpstest/HttpTransaction.java index 058632abb193fda5ab08fffb7c41a1b068f3ac71..3d011a41db6ff60527916847fc3a665e633732a6 100644 --- a/test/sun/security/ssl/sun/net/www/httpstest/HttpTransaction.java +++ b/test/sun/security/ssl/sun/net/www/httpstest/HttpTransaction.java @@ -102,7 +102,8 @@ public class HttpTransaction { if (rspheaders != null) { buf.append (rspheaders.toString()).append("\r\n"); } - buf.append ("Body: ").append (new String(rspbody)).append("\r\n"); + String rbody = rspbody == null? "": new String (rspbody); + buf.append ("Body: ").append (rbody).append("\r\n"); return new String (buf); } diff --git a/test/sun/security/tools/jarsigner/passtype.sh b/test/sun/security/tools/jarsigner/passtype.sh new file mode 100644 index 0000000000000000000000000000000000000000..7e942350956983d429073a2c83cbcd64e3cf8e79 --- /dev/null +++ b/test/sun/security/tools/jarsigner/passtype.sh @@ -0,0 +1,72 @@ +# +# Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code 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 +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# @test +# @bug 6868579 +# @summary RFE: jarsigner to support reading password from environment variable +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + ;; + * ) + FS="/" + ;; +esac + +KS=pt.jks +JFILE=pt.jar + +KT="$TESTJAVA${FS}bin${FS}keytool -keystore $KS -validity 300" +JAR=$TESTJAVA${FS}bin${FS}jar +JARSIGNER=$TESTJAVA${FS}bin${FS}jarsigner + +rm $KS $JFILE + +$KT -alias a -dname CN=a -keyalg rsa -genkey \ + -storepass test12 -keypass test12 || exit 1 +PASSENV=test12 $KT -alias b -dname CN=b -keyalg rsa -genkey \ + -storepass:env PASSENV -keypass:env PASSENV || exit 2 +echo test12 > passfile +$KT -alias c -dname CN=c -keyalg rsa -genkey \ + -storepass:file passfile -keypass:file passfile || exit 3 + +echo A > A +$JAR cvf $JFILE A + +$JARSIGNER -keystore $KS -storepass test12 $JFILE a || exit 4 +PASSENV=test12 $JARSIGNER -keystore $KS -storepass:env PASSENV $JFILE b || exit 5 +$JARSIGNER -keystore $KS -storepass:file passfile $JFILE b || exit 6 + +$JARSIGNER -keystore $KS -verify -debug -strict $JFILE || exit 7 + +exit 0 + diff --git a/test/sun/security/tools/keytool/newhelp.sh b/test/sun/security/tools/keytool/newhelp.sh new file mode 100644 index 0000000000000000000000000000000000000000..08c7422e545013d457bff7178020f97ebfe13381 --- /dev/null +++ b/test/sun/security/tools/keytool/newhelp.sh @@ -0,0 +1,53 @@ +# +# Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code 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 +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + +# @test +# @bug 6324292 +# @summary keytool -help is unhelpful +# + +if [ "${TESTJAVA}" = "" ] ; then + JAVAC_CMD=`which javac` + TESTJAVA=`dirname $JAVAC_CMD`/.. +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + Windows_* ) + FS="\\" + ;; + * ) + FS="/" + ;; +esac + +LANG=C +$TESTJAVA${FS}bin${FS}keytool -help 2> h1 || exit 1 +$TESTJAVA${FS}bin${FS}keytool -help -list 2> h2 || exit 2 + +grep Commands: h1 || exit 3 +grep Options: h2 || exit 4 + +exit 0 + diff --git a/test/sun/util/logging/PlatformLoggerTest.java b/test/sun/util/logging/PlatformLoggerTest.java new file mode 100644 index 0000000000000000000000000000000000000000..0c5daf0422e9f40e7666821b691667a2c086525e --- /dev/null +++ b/test/sun/util/logging/PlatformLoggerTest.java @@ -0,0 +1,111 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * @test + * @bug 6882376 + * @summary Test if java.util.logging.Logger is created before and after + * logging is enabled. Also validate some basic PlatformLogger + * operations. + * + * @build PlatformLoggerTest + * @run main PlatformLoggerTest + */ + +import java.util.logging.*; +import sun.util.logging.PlatformLogger; + +public class PlatformLoggerTest { + private static final int defaultEffectiveLevel = 0; + public static void main(String[] args) throws Exception { + final String FOO_PLATFORM_LOGGER = "test.platformlogger.foo"; + final String BAR_PLATFORM_LOGGER = "test.platformlogger.bar"; + final String GOO_PLATFORM_LOGGER = "test.platformlogger.goo"; + final String BAR_LOGGER = "test.logger.bar"; + PlatformLogger goo = PlatformLogger.getLogger(GOO_PLATFORM_LOGGER); + + // Create a platform logger using the default + PlatformLogger foo = PlatformLogger.getLogger(FOO_PLATFORM_LOGGER); + checkPlatformLogger(foo, FOO_PLATFORM_LOGGER); + + // create a java.util.logging.Logger + // now java.util.logging.Logger should be created for each platform logger + Logger logger = Logger.getLogger(BAR_LOGGER); + logger.setLevel(Level.WARNING); + + PlatformLogger bar = PlatformLogger.getLogger(BAR_PLATFORM_LOGGER); + checkPlatformLogger(bar, BAR_PLATFORM_LOGGER); + + checkLogger(FOO_PLATFORM_LOGGER, Level.FINER); + checkLogger(BAR_PLATFORM_LOGGER, Level.FINER); + + checkLogger(GOO_PLATFORM_LOGGER, null); + checkLogger(BAR_LOGGER, Level.WARNING); + + foo.setLevel(PlatformLogger.SEVERE); + checkLogger(FOO_PLATFORM_LOGGER, Level.SEVERE); + } + + private static void checkPlatformLogger(PlatformLogger logger, String name) { + if (!logger.getName().equals(name)) { + throw new RuntimeException("Invalid logger's name " + + logger.getName() + " but expected " + name); + } + + if (logger.getLevel() != defaultEffectiveLevel) { + throw new RuntimeException("Invalid default level for logger " + + logger.getName()); + } + + if (logger.isLoggable(PlatformLogger.FINE) != false) { + throw new RuntimeException("isLoggerable(FINE) returns true for logger " + + logger.getName() + " but expected false"); + } + + logger.setLevel(PlatformLogger.FINER); + if (logger.getLevel() != Level.FINER.intValue()) { + throw new RuntimeException("Invalid level for logger " + + logger.getName() + " " + logger.getLevel()); + } + + if (logger.isLoggable(PlatformLogger.FINE) != true) { + throw new RuntimeException("isLoggerable(FINE) returns false for logger " + + logger.getName() + " but expected true"); + } + + logger.info("OK: Testing log message"); + } + + private static void checkLogger(String name, Level level) { + Logger logger = LogManager.getLogManager().getLogger(name); + if (logger == null) { + throw new RuntimeException("Logger " + name + + " does not exist"); + } + + if (logger.getLevel() != level) { + throw new RuntimeException("Invalid level for logger " + + logger.getName() + " " + logger.getLevel()); + } + } +} diff --git a/test/tools/launcher/6842838/CreateBadJar.java b/test/tools/launcher/6842838/CreateBadJar.java new file mode 100644 index 0000000000000000000000000000000000000000..dfdc9163de2962ecd8abef0a6b62466151d75cb5 --- /dev/null +++ b/test/tools/launcher/6842838/CreateBadJar.java @@ -0,0 +1,168 @@ +/* + * Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code 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 + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, + * CA 95054 USA or visit www.sun.com if you need additional information or + * have any questions. + */ + +/* + * Borrowing significantly from Martin Buchholz's CorruptedZipFiles.java + * + * Needed a way of testing the checks for corrupt zip/jar entry in + * inflate_file from file j2se/src/share/bin/parse_manifest.c + * and running them with the 64-bit launcher. e.g. + * sparcv9/bin/java -jar badjar.jar + * + * Run from a script driver Test6842838.sh as we want to specifically run + * bin/sparcv9/java, the 64-bit launcher. + * + * So this program will create a zip file and damage it in the way + * required to tickle this bug. + * + * It will cause a buffer overrun: but that will not always crash. + * Use libumem preloaded by the script driver in order to + * abort quickly when the overrun happens. That makes the test + * Solaris-specific. + */ + +import java.util.*; +import java.util.zip.*; +import java.io.*; +import static java.lang.System.*; +import static java.util.zip.ZipFile.*; + +public class CreateBadJar { + +public static void main(String [] arguments) { + + if (arguments.length != 2) { + throw new RuntimeException("Arguments: jarfilename entryname"); + } + String outFile = arguments[0]; + String entryName = arguments[1]; + + try { + // If the named file doesn't exist, create it. + // If it does, we are expecting it to contain the named entry, for + // alteration. + if (!new File(outFile).exists()) { + System.out.println("Creating file " + outFile); + + // Create the requested zip/jar file. + ZipOutputStream zos = null; + zos = new ZipOutputStream( + new FileOutputStream(outFile)); + + ZipEntry e = new ZipEntry(entryName); + zos.putNextEntry(e); + for (int j=0; j<50000; j++) { + zos.write((int)'a'); + } + zos.closeEntry(); + zos.close(); + zos = null; + } + + // Read it. + int len = (int)(new File(outFile).length()); + byte[] good = new byte[len]; + FileInputStream fis = new FileInputStream(outFile); + fis.read(good); + fis.close(); + fis = null; + + int endpos = len - ENDHDR; + int cenpos = u16(good, endpos+ENDOFF); + if (u32(good, cenpos) != CENSIG) throw new RuntimeException("Where's CENSIG?"); + + byte[] bad; + bad = good.clone(); + + // Corrupt it... + int pos = findInCEN(bad, cenpos, entryName); + + // What bad stuff are we doing to it? + // Store a 32-bit -1 in uncomp size. + bad[pos+0x18]=(byte)0xff; + bad[pos+0x19]=(byte)0xff; + bad[pos+0x1a]=(byte)0xff; + bad[pos+0x1b]=(byte)0xff; + + // Bad work complete, delete the original. + new File(outFile).delete(); + + // Write it. + FileOutputStream fos = new FileOutputStream(outFile); + fos.write(bad); + fos.close(); + fos = null; + + } catch (Exception e) { + e.printStackTrace(); + } + +} + + /* + * Scan Central Directory File Headers looking for the named entry. + */ + + static int findInCEN(byte[] bytes, int cenpos, String entryName) { + int pos = cenpos; + int nextPos = 0; + String filename = null; + do { + if (nextPos != 0) { + pos = nextPos; + } + System.out.println("entry at pos = " + pos); + if (u32(bytes, pos) != CENSIG) throw new RuntimeException ("entry not found in CEN or premature end..."); + + int csize = u32(bytes, pos+0x14); // +0x14 1 dword csize + int uncompsize = u32(bytes, pos+0x18); // +0x18 1 dword uncomp size + int filenameLength = u16(bytes, pos+0x1c); // +0x1c 1 word length of filename + int extraLength = u16(bytes, pos+0x1e); // +0x1e 1 world length of extra field + int commentLength = u16(bytes, pos+0x20); // +0x20 1 world length of file comment + filename = new String(bytes, pos+0x2e, filenameLength); // +0x2e chars of filename + int offset = u32(bytes, pos+0x2a); // +0x2a chars of filename + + System.out.println("filename = " + filename + "\ncsize = " + csize + + " uncomp.size = " + uncompsize +" file offset = " + offset); + nextPos = pos + 0x2e + filenameLength + extraLength + commentLength; + + } while (!filename.equals(entryName)); + + System.out.println("entry found at pos = " + pos); + return pos; + } + + static int u8(byte[] data, int offset) { + return data[offset]&0xff; + } + + static int u16(byte[] data, int offset) { + return u8(data,offset) + (u8(data,offset+1)<<8); + } + + static int u32(byte[] data, int offset) { + return u16(data,offset) + (u16(data,offset+2)<<16); + } + +} + diff --git a/test/tools/launcher/6842838/Test6842838.sh b/test/tools/launcher/6842838/Test6842838.sh new file mode 100644 index 0000000000000000000000000000000000000000..0d0ba756496e91d25062097818688ad0a099807f --- /dev/null +++ b/test/tools/launcher/6842838/Test6842838.sh @@ -0,0 +1,76 @@ +# +# Copyright 2009 Sun Microsystems, Inc. All Rights Reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code 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 +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, +# CA 95054 USA or visit www.sun.com if you need additional information or +# have any questions. +# + + +# @test Test6842838.sh +# @bug 6842838 +# @summary Test 6842838 64-bit launcher failure due to corrupt jar +# @compile CreateBadJar.java +# @run shell Test6842838.sh + +set -x + +if [ "${TESTJAVA}" = "" ]; then + PARENT=`dirname \`which java\`` + TESTJAVA=`dirname ${PARENT}` + printf "TESTJAVA not set. Test cannot execute. Failed.\n" +fi + +if [ "${TESTCLASSES}" = "" ]; then + printf "TESTCLASSES not set. Test cannot execute. Failed.\n" + exit 1 +fi + +# set platform-dependent variables +OS=`uname -s` +case "$OS" in + SunOS ) + NULL=/dev/null + PS=":" + FS="/" + JAVA_EXE=${TESTJAVA}${FS}bin${FS}sparcv9${FS}java + ;; + * ) + printf "Only testing on sparcv9 (use libumem to reliably catch buffer overrun)\n" + exit 0; + ;; +esac + +if [ ! -x ${JAVA_EXE} ]; then + printf "Warning: sparcv9 components not installed - skipping test.\n" + exit 0 +fi + +LIBUMEM=/lib/64/libumem.so +if [ ! -x ${LIBUMEM} ]; then + printf "Warning: libumem not installed - skipping test.\n" + exit 0 +fi + +BADFILE=newbadjar.jar +${JAVA_EXE} -version +${JAVA_EXE} -cp ${TESTCLASSES} CreateBadJar ${BADFILE} "META-INF/MANIFEST.MF" +LD_PRELOAD=${LIBUMEM} ${JAVA_EXE} -jar ${BADFILE} > test.out 2>&1 + +grep "Invalid or corrupt jarfile" test.out +exit $?