提交 8599b62b 编写于 作者: T tbell

Merge

......@@ -165,6 +165,11 @@ else
JAVADOC_CMD = $(JAVA_TOOLS_DIR)/javadoc $(JAVA_TOOLS_FLAGS:%=-J%)
endif
#always use the bootstrap javah until bug-ID 6889255 is fixed. These
#five lines should be removed as part of that fix:
JAVAH_CMD = $(JAVA_TOOLS_DIR)/javah \
$(JAVAHFLAGS)
# Override of what javac to use (see deploy workspace)
ifdef JAVAC
JAVAC_CMD = $(JAVAC)
......
......@@ -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
#
......
/*
* 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 {
......
......@@ -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;
......
......@@ -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);
......
......@@ -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);
}
}
......
......@@ -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);
}
}
......
......@@ -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);
......
......@@ -1580,7 +1580,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;
......@@ -2128,7 +2128,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;
......
......@@ -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
......@@ -1850,11 +1852,10 @@ public class ICC_Profile implements Serializable {
f = new File(fullPath);
if (!f.isFile()) {
//make sure file was installed in the kernel mode
try {
//kernel uses platform independent paths =>
// should not use platform separator char
sun.jkernel.DownloadManager.downloadFile("lib/cmm/"+fileName);
} catch (IOException ioe) {}
BootClassLoaderHook hook = BootClassLoaderHook.getHook();
if (hook.getHook() != null) {
hook.prefetchFile("lib/cmm/"+fileName);
}
}
}
......
......@@ -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:
* <pre>
* Boolean.valueOf(x).compareTo(Boolean.valueOf(y))
* </pre>
*
* @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) {
......
......@@ -201,7 +201,7 @@ public final class Byte extends Number implements Comparable<Byte> {
*/
public static Byte valueOf(String s, int radix)
throws NumberFormatException {
return new Byte(parseByte(s, radix));
return valueOf(parseByte(s, radix));
}
/**
......@@ -277,7 +277,7 @@ public final class Byte extends Number implements Comparable<Byte> {
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return (byte)i;
return valueOf((byte)i);
}
/**
......@@ -374,11 +374,14 @@ public final class Byte extends Number implements Comparable<Byte> {
* base&nbsp;10.
*/
public String toString() {
return String.valueOf((int)value);
return Integer.toString((int)value);
}
/**
* 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<Byte> {
* @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:
* <pre>
* Byte.valueOf(x).compareTo(Byte.valueOf(y))
* </pre>
*
* @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;
}
/**
......
......@@ -2612,8 +2612,10 @@ class Character extends Object implements java.io.Serializable, Comparable<Chara
}
/**
* Returns a hash code for this <code>Character</code>.
* @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<Chara
* @since 1.2
*/
public int compareTo(Character anotherCharacter) {
return this.value - anotherCharacter.value;
return compare(this.value, anotherCharacter.value);
}
/**
* Compares two {@code char} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Character.valueOf(x).compareTo(Character.valueOf(y))
* </pre>
*
* @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;
}
/**
......
......@@ -265,7 +265,7 @@ public final
}
/** Called after security checks have been made. */
private static native Class forName0(String name, boolean initialize,
private static native Class<?> forName0(String name, boolean initialize,
ClassLoader loader)
throws ClassNotFoundException;
......@@ -339,7 +339,7 @@ public final
);
}
try {
Class[] empty = {};
Class<?>[] empty = {};
final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
// Disable accessibility checks on the constructor
// since we have to do the security check here anyway
......@@ -361,7 +361,7 @@ public final
// Security check (same as in java.lang.reflect.Constructor)
int modifiers = tmpConstructor.getModifiers();
if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
Class caller = Reflection.getCallerClass(3);
Class<?> caller = Reflection.getCallerClass(3);
if (newInstanceCallerCache != caller) {
Reflection.ensureMemberAccess(caller, this, null, modifiers);
newInstanceCallerCache = caller;
......@@ -377,7 +377,7 @@ public final
}
}
private volatile transient Constructor<T> cachedConstructor;
private volatile transient Class newInstanceCallerCache;
private volatile transient Class<?> newInstanceCallerCache;
/**
......@@ -638,7 +638,7 @@ public final
if (getGenericSignature() != null)
return (TypeVariable<Class<T>>[])getGenericInfo().getTypeParameters();
else
return (TypeVariable<Class<T>>[])new TypeVariable[0];
return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
}
......@@ -901,7 +901,7 @@ public final
MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
getFactory());
Class returnType = toClass(typeInfo.getReturnType());
Class<?> returnType = toClass(typeInfo.getReturnType());
Type [] parameterTypes = typeInfo.getParameterTypes();
Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
......@@ -996,12 +996,12 @@ public final
}
private static Class toClass(Type o) {
private static Class<?> toClass(Type o) {
if (o instanceof GenericArrayType)
return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
0)
.getClass();
return (Class)o;
return (Class<?>)o;
}
/**
......@@ -1042,7 +1042,7 @@ public final
* Loop over all declared constructors; match number
* of and type of parameters.
*/
for(Constructor c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
for(Constructor<?> c: enclosingInfo.getEnclosingClass().getDeclaredConstructors()) {
Class<?>[] candidateParamClasses = c.getParameterTypes();
if (candidateParamClasses.length == parameterClasses.length) {
boolean matches = true;
......@@ -1304,12 +1304,12 @@ public final
// has already been ok'd by the SecurityManager.
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Class[]>() {
new java.security.PrivilegedAction<Class<?>[]>() {
public Class[] run() {
List<Class> list = new ArrayList<Class>();
Class currentClass = Class.this;
List<Class<?>> list = new ArrayList<Class<?>>();
Class<?> currentClass = Class.this;
while (currentClass != null) {
Class[] members = currentClass.getDeclaredClasses();
Class<?>[] members = currentClass.getDeclaredClasses();
for (int i = 0; i < members.length; i++) {
if (Modifier.isPublic(members[i].getModifiers())) {
list.add(members[i]);
......@@ -2191,7 +2191,7 @@ public final
return name;
}
if (!name.startsWith("/")) {
Class c = this;
Class<?> c = this;
while (c.isArray()) {
c = c.getComponentType();
}
......@@ -2565,12 +2565,12 @@ public final
// out concrete implementations inherited from superclasses at
// the end.
MethodArray inheritedMethods = new MethodArray();
Class[] interfaces = getInterfaces();
Class<?>[] interfaces = getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
inheritedMethods.addAll(interfaces[i].privateGetPublicMethods());
}
if (!isInterface()) {
Class c = getSuperclass();
Class<?> c = getSuperclass();
if (c != null) {
MethodArray supers = new MethodArray();
supers.addAll(c.privateGetPublicMethods());
......@@ -2632,16 +2632,16 @@ public final
return res;
}
// Direct superinterfaces, recursively
Class[] interfaces = getInterfaces();
Class<?>[] interfaces = getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
Class c = interfaces[i];
Class<?> c = interfaces[i];
if ((res = c.getField0(name)) != null) {
return res;
}
}
// Direct superclass, recursively
if (!isInterface()) {
Class c = getSuperclass();
Class<?> c = getSuperclass();
if (c != null) {
if ((res = c.getField0(name)) != null) {
return res;
......@@ -2653,7 +2653,7 @@ public final
private static Method searchMethods(Method[] methods,
String name,
Class[] parameterTypes)
Class<?>[] parameterTypes)
{
Method res = null;
String internedName = name.intern();
......@@ -2670,7 +2670,7 @@ public final
}
private Method getMethod0(String name, Class[] parameterTypes) {
private Method getMethod0(String name, Class<?>[] parameterTypes) {
// Note: the intent is that the search algorithm this routine
// uses be equivalent to the ordering imposed by
// privateGetPublicMethods(). It fetches only the declared
......@@ -2687,7 +2687,7 @@ public final
}
// Search superclass's methods
if (!isInterface()) {
Class c = getSuperclass();
Class<? super T> c = getSuperclass();
if (c != null) {
if ((res = c.getMethod0(name, parameterTypes)) != null) {
return res;
......@@ -2695,9 +2695,9 @@ public final
}
}
// Search superinterfaces' methods
Class[] interfaces = getInterfaces();
Class<?>[] interfaces = getInterfaces();
for (int i = 0; i < interfaces.length; i++) {
Class c = interfaces[i];
Class<?> c = interfaces[i];
if ((res = c.getMethod0(name, parameterTypes)) != null) {
return res;
}
......@@ -2706,7 +2706,7 @@ public final
return null;
}
private Constructor<T> getConstructor0(Class[] parameterTypes,
private Constructor<T> getConstructor0(Class<?>[] parameterTypes,
int which) throws NoSuchMethodException
{
Constructor<T>[] constructors = privateGetDeclaredConstructors((which == Member.PUBLIC));
......@@ -2775,9 +2775,9 @@ public final
private native Field[] getDeclaredFields0(boolean publicOnly);
private native Method[] getDeclaredMethods0(boolean publicOnly);
private native Constructor<T>[] getDeclaredConstructors0(boolean publicOnly);
private native Class[] getDeclaredClasses0();
private native Class<?>[] getDeclaredClasses0();
private static String argumentTypesToString(Class[] argTypes) {
private static String argumentTypesToString(Class<?>[] argTypes) {
StringBuilder buf = new StringBuilder();
buf.append("(");
if (argTypes != null) {
......@@ -2785,7 +2785,7 @@ public final
if (i > 0) {
buf.append(", ");
}
Class c = argTypes[i];
Class<?> c = argTypes[i];
buf.append((c == null) ? "null" : c.getName());
}
}
......@@ -2858,7 +2858,7 @@ public final
}
// Retrieves the desired assertion status of this class from the VM
private static native boolean desiredAssertionStatus0(Class clazz);
private static native boolean desiredAssertionStatus0(Class<?> clazz);
/**
* Returns true if and only if this class was declared as an enum in the
......@@ -2979,7 +2979,7 @@ public final
getName() + " is not an enum type");
Map<String, T> m = new HashMap<String, T>(2 * universe.length);
for (T constant : universe)
m.put(((Enum)constant).name(), constant);
m.put(((Enum<?>)constant).name(), constant);
enumConstantDirectory = m;
}
return enumConstantDirectory;
......@@ -3077,8 +3077,8 @@ public final
}
// Annotations cache
private transient Map<Class, Annotation> annotations;
private transient Map<Class, Annotation> declaredAnnotations;
private transient Map<Class<? extends Annotation>, Annotation> annotations;
private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
private synchronized void initAnnotationsIfNecessary() {
clearCachesOnClassRedefinition();
......@@ -3090,10 +3090,10 @@ public final
if (superClass == null) {
annotations = declaredAnnotations;
} else {
annotations = new HashMap<Class, Annotation>();
annotations = new HashMap<Class<? extends Annotation>, Annotation>();
superClass.initAnnotationsIfNecessary();
for (Map.Entry<Class, Annotation> e : superClass.annotations.entrySet()) {
Class annotationClass = e.getKey();
for (Map.Entry<Class<? extends Annotation>, Annotation> e : superClass.annotations.entrySet()) {
Class<? extends Annotation> annotationClass = e.getKey();
if (AnnotationType.getInstance(annotationClass).isInherited())
annotations.put(annotationClass, e.getValue());
}
......
......@@ -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
......@@ -1300,21 +1300,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;
......@@ -1831,24 +1817,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) {
......
......@@ -629,7 +629,7 @@ public final class Double extends Number implements Comparable<Double> {
* @see java.lang.Double#toString(double)
*/
public String toString() {
return String.valueOf(value);
return toString(value);
}
/**
......
......@@ -551,7 +551,7 @@ public final class Float extends Number implements Comparable<Float> {
* @see java.lang.Float#toString(float)
*/
public String toString() {
return String.valueOf(value);
return Float.toString(value);
}
/**
......
......@@ -746,7 +746,7 @@ public final class Integer extends Number implements Comparable<Integer> {
* base&nbsp;10.
*/
public String toString() {
return String.valueOf(value);
return toString(value);
}
/**
......@@ -1010,9 +1010,25 @@ public final class Integer extends Number implements Comparable<Integer> {
* @since 1.2
*/
public int compareTo(Integer anotherInteger) {
int thisVal = this.value;
int anotherVal = anotherInteger.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
return compare(this.value, anotherInteger.value);
}
/**
* Compares two {@code int} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Integer.valueOf(x).compareTo(Integer.valueOf(y))
* </pre>
*
* @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);
}
......
......@@ -761,7 +761,7 @@ public final class Long extends Number implements Comparable<Long> {
* base&nbsp;10.
*/
public String toString() {
return String.valueOf(value);
return toString(value);
}
/**
......@@ -950,9 +950,25 @@ public final class Long extends Number implements Comparable<Long> {
* @since 1.2
*/
public int compareTo(Long anotherLong) {
long thisVal = this.value;
long anotherVal = anotherLong.value;
return (thisVal<anotherVal ? -1 : (thisVal==anotherVal ? 0 : 1));
return compare(this.value, anotherLong.value);
}
/**
* Compares two {@code long} values numerically.
* The value returned is identical to what would be returned by:
* <pre>
* Long.valueOf(x).compareTo(Long.valueOf(y))
* </pre>
*
* @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);
}
......
......@@ -320,7 +320,7 @@ public class Package implements java.lang.reflect.AnnotatedElement {
* @param class the class to get the package of.
* @return the package of the class. It may be null if no package
* information is available from the archive or codebase. */
static Package getPackage(Class c) {
static Package getPackage(Class<?> c) {
String name = c.getName();
int i = name.lastIndexOf('.');
if (i != -1) {
......
......@@ -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);
}
/*
......
......@@ -170,7 +170,7 @@ public final class Short extends Number implements Comparable<Short> {
*/
public static Short valueOf(String s, int radix)
throws NumberFormatException {
return new Short(parseShort(s, radix));
return valueOf(parseShort(s, radix));
}
/**
......@@ -282,7 +282,7 @@ public final class Short extends Number implements Comparable<Short> {
if (i < MIN_VALUE || i > MAX_VALUE)
throw new NumberFormatException(
"Value " + i + " out of range from input " + nm);
return (short)i;
return valueOf((short)i);
}
/**
......@@ -379,11 +379,14 @@ public final class Short extends Number implements Comparable<Short> {
* base&nbsp;10.
*/
public String toString() {
return String.valueOf((int)value);
return Integer.toString((int)value);
}
/**
* 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<Short> {
* @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:
* <pre>
* Short.valueOf(x).compareTo(Short.valueOf(y))
* </pre>
*
* @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;
}
/**
......
......@@ -2995,7 +2995,7 @@ public final class String
* @see java.lang.Integer#toString(int, int)
*/
public static String valueOf(int i) {
return Integer.toString(i, 10);
return Integer.toString(i);
}
/**
......@@ -3009,7 +3009,7 @@ public final class String
* @see java.lang.Long#toString(long)
*/
public static String valueOf(long l) {
return Long.toString(l, 10);
return Long.toString(l);
}
/**
......
......@@ -131,7 +131,7 @@ public class AccessibleObject implements AnnotatedElement {
throws SecurityException
{
if (obj instanceof Constructor && flag == true) {
Constructor c = (Constructor)obj;
Constructor<?> c = (Constructor<?>)obj;
if (c.getDeclaringClass() == Class.class) {
throw new SecurityException("Can not make a java.lang.Class" +
" constructor accessible");
......
......@@ -64,8 +64,8 @@ public final
private Class<T> clazz;
private int slot;
private Class[] parameterTypes;
private Class[] exceptionTypes;
private Class<?>[] parameterTypes;
private Class<?>[] exceptionTypes;
private int modifiers;
// Generics and annotations support
private transient String signature;
......@@ -80,7 +80,7 @@ public final
// always succeed (it is not affected by the granting or revoking
// of permissions); we speed up the check in the common case by
// remembering the last Class for which the check succeeded.
private volatile Class securityCheckCache;
private volatile Class<?> securityCheckCache;
// Generics infrastructure
// Accessor for factory
......@@ -113,8 +113,8 @@ public final
* package via sun.reflect.LangReflectAccess.
*/
Constructor(Class<T> declaringClass,
Class[] parameterTypes,
Class[] checkedExceptions,
Class<?>[] parameterTypes,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
......@@ -275,10 +275,6 @@ public final
* Returns an array of length 0 if the underlying method declares
* no exceptions in its {@code throws} clause.
*
* <p>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.
*
* <p>If an exception type is a type variable or a parameterized
* type, it is created. Otherwise, it is resolved.
*
......@@ -311,11 +307,11 @@ public final
*/
public boolean equals(Object obj) {
if (obj != null && obj instanceof Constructor) {
Constructor other = (Constructor)obj;
Constructor<?> other = (Constructor<?>)obj;
if (getDeclaringClass() == other.getDeclaringClass()) {
/* Avoid unnecessary cloning */
Class[] params1 = parameterTypes;
Class[] params2 = other.parameterTypes;
Class<?>[] params1 = parameterTypes;
Class<?>[] params2 = other.parameterTypes;
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
......@@ -361,14 +357,14 @@ public final
}
sb.append(Field.getTypeName(getDeclaringClass()));
sb.append("(");
Class[] params = parameterTypes; // avoid clone
Class<?>[] params = parameterTypes; // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(Field.getTypeName(params[j]));
if (j < (params.length - 1))
sb.append(",");
}
sb.append(")");
Class[] exceptions = exceptionTypes; // avoid clone
Class<?>[] exceptions = exceptionTypes; // avoid clone
if (exceptions.length > 0) {
sb.append(" throws ");
for (int k = 0; k < exceptions.length; k++) {
......@@ -456,7 +452,7 @@ public final
sb.append(" throws ");
for (int k = 0; k < exceptions.length; k++) {
sb.append((exceptions[k] instanceof Class)?
((Class)exceptions[k]).getName():
((Class<?>)exceptions[k]).getName():
exceptions[k].toString());
if (k < (exceptions.length - 1))
sb.append(",");
......@@ -522,7 +518,7 @@ public final
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class caller = Reflection.getCallerClass(2);
Class<?> caller = Reflection.getCallerClass(2);
if (securityCheckCache != caller) {
Reflection.ensureMemberAccess(caller, clazz, null, modifiers);
securityCheckCache = caller;
......@@ -629,9 +625,9 @@ public final
return AnnotationParser.toArray(declaredAnnotations());
}
private transient Map<Class, Annotation> declaredAnnotations;
private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
private synchronized Map<Class, Annotation> declaredAnnotations() {
private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
if (declaredAnnotations == null) {
declaredAnnotations = AnnotationParser.parseAnnotations(
annotations, sun.misc.SharedSecrets.getJavaLangAccess().
......
......@@ -58,12 +58,12 @@ import sun.reflect.annotation.AnnotationParser;
public final
class Field extends AccessibleObject implements Member {
private Class clazz;
private Class<?> clazz;
private int slot;
// This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private String name;
private Class type;
private Class<?> type;
private int modifiers;
// Generics and annotations support
private transient String signature;
......@@ -81,8 +81,8 @@ class Field extends AccessibleObject implements Member {
// More complicated security check cache needed here than for
// Class.newInstance() and Constructor.newInstance()
private Class securityCheckCache;
private Class securityCheckTargetClassCache;
private Class<?> securityCheckCache;
private Class<?> securityCheckTargetClassCache;
// Generics infrastructure
......@@ -112,9 +112,9 @@ class Field extends AccessibleObject implements Member {
* instantiation of these objects in Java code from the java.lang
* package via sun.reflect.LangReflectAccess.
*/
Field(Class declaringClass,
Field(Class<?> declaringClass,
String name,
Class type,
Class<?> type,
int modifiers,
int slot,
String signature,
......@@ -964,10 +964,10 @@ class Field extends AccessibleObject implements Member {
private void doSecurityCheck(Object obj) throws IllegalAccessException {
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class caller = Reflection.getCallerClass(4);
Class targetClass = ((obj == null || !Modifier.isProtected(modifiers))
? clazz
: obj.getClass());
Class<?> caller = Reflection.getCallerClass(4);
Class<?> targetClass = ((obj == null || !Modifier.isProtected(modifiers))
? clazz
: obj.getClass());
synchronized (this) {
if ((securityCheckCache == caller)
......@@ -987,10 +987,10 @@ class Field extends AccessibleObject implements Member {
/*
* Utility routine to paper over array type names
*/
static String getTypeName(Class type) {
static String getTypeName(Class<?> type) {
if (type.isArray()) {
try {
Class cl = type;
Class<?> cl = type;
int dimensions = 0;
while (cl.isArray()) {
dimensions++;
......@@ -1025,9 +1025,9 @@ class Field extends AccessibleObject implements Member {
return AnnotationParser.toArray(declaredAnnotations());
}
private transient Map<Class, Annotation> declaredAnnotations;
private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
private synchronized Map<Class, Annotation> declaredAnnotations() {
private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
if (declaredAnnotations == null) {
declaredAnnotations = AnnotationParser.parseAnnotations(
annotations, sun.misc.SharedSecrets.getJavaLangAccess().
......
......@@ -61,14 +61,14 @@ import java.util.Map;
public final
class Method extends AccessibleObject implements GenericDeclaration,
Member {
private Class clazz;
private Class<?> clazz;
private int slot;
// This is guaranteed to be interned by the VM in the 1.4
// reflection implementation
private String name;
private Class returnType;
private Class[] parameterTypes;
private Class[] exceptionTypes;
private Class<?> returnType;
private Class<?>[] parameterTypes;
private Class<?>[] exceptionTypes;
private int modifiers;
// Generics and annotations support
private transient String signature;
......@@ -85,8 +85,8 @@ public final
// More complicated security check cache needed here than for
// Class.newInstance() and Constructor.newInstance()
private Class securityCheckCache;
private Class securityCheckTargetClassCache;
private Class<?> securityCheckCache;
private Class<?> securityCheckTargetClassCache;
// Generics infrastructure
......@@ -114,11 +114,11 @@ public final
* instantiation of these objects in Java code from the java.lang
* package via sun.reflect.LangReflectAccess.
*/
Method(Class declaringClass,
Method(Class<?> declaringClass,
String name,
Class[] parameterTypes,
Class returnType,
Class[] checkedExceptions,
Class<?>[] parameterTypes,
Class<?> returnType,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
......@@ -317,10 +317,6 @@ public final
* Returns an array of length 0 if the underlying method declares
* no exceptions in its {@code throws} clause.
*
* <p>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.
*
* <p>If an exception type is a type variable or a parameterized
* type, it is created. Otherwise, it is resolved.
*
......@@ -359,8 +355,8 @@ public final
if (!returnType.equals(other.getReturnType()))
return false;
/* Avoid unnecessary cloning */
Class[] params1 = parameterTypes;
Class[] params2 = other.parameterTypes;
Class<?>[] params1 = parameterTypes;
Class<?>[] params2 = other.parameterTypes;
if (params1.length == params2.length) {
for (int i = 0; i < params1.length; i++) {
if (params1[i] != params2[i])
......@@ -414,14 +410,14 @@ public final
sb.append(Field.getTypeName(getReturnType()) + " ");
sb.append(Field.getTypeName(getDeclaringClass()) + ".");
sb.append(getName() + "(");
Class[] params = parameterTypes; // avoid clone
Class<?>[] params = parameterTypes; // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(Field.getTypeName(params[j]));
if (j < (params.length - 1))
sb.append(",");
}
sb.append(")");
Class[] exceptions = exceptionTypes; // avoid clone
Class<?>[] exceptions = exceptionTypes; // avoid clone
if (exceptions.length > 0) {
sb.append(" throws ");
for (int k = 0; k < exceptions.length; k++) {
......@@ -594,10 +590,10 @@ public final
{
if (!override) {
if (!Reflection.quickCheckMemberAccess(clazz, modifiers)) {
Class caller = Reflection.getCallerClass(1);
Class targetClass = ((obj == null || !Modifier.isProtected(modifiers))
? clazz
: obj.getClass());
Class<?> caller = Reflection.getCallerClass(1);
Class<?> targetClass = ((obj == null || !Modifier.isProtected(modifiers))
? clazz
: obj.getClass());
boolean cached;
synchronized (this) {
......@@ -706,9 +702,9 @@ public final
return AnnotationParser.toArray(declaredAnnotations());
}
private transient Map<Class, Annotation> declaredAnnotations;
private transient Map<Class<? extends Annotation>, Annotation> declaredAnnotations;
private synchronized Map<Class, Annotation> declaredAnnotations() {
private synchronized Map<Class<? extends Annotation>, Annotation> declaredAnnotations() {
if (declaredAnnotations == null) {
declaredAnnotations = AnnotationParser.parseAnnotations(
annotations, sun.misc.SharedSecrets.getJavaLangAccess().
......@@ -735,7 +731,7 @@ public final
public Object getDefaultValue() {
if (annotationDefault == null)
return null;
Class memberType = AnnotationType.invocationHandlerReturnType(
Class<?> memberType = AnnotationType.invocationHandlerReturnType(
getReturnType());
Object result = AnnotationParser.parseMemberValue(
memberType, ByteBuffer.wrap(annotationDefault),
......
......@@ -350,7 +350,7 @@ public class Proxy implements java.io.Serializable {
throw new IllegalArgumentException("interface limit exceeded");
}
Class proxyClass = null;
Class<?> proxyClass = null;
/* collect interface names to use as key for proxy class cache */
String[] interfaceNames = new String[interfaces.length];
......@@ -364,7 +364,7 @@ public class Proxy implements java.io.Serializable {
* interface to the same Class object.
*/
String interfaceName = interfaces[i].getName();
Class interfaceClass = null;
Class<?> interfaceClass = null;
try {
interfaceClass = Class.forName(interfaceName, false, loader);
} catch (ClassNotFoundException e) {
......
......@@ -33,9 +33,9 @@ import sun.reflect.ConstructorAccessor;
package to instantiate objects in this package. */
class ReflectAccess implements sun.reflect.LangReflectAccess {
public Field newField(Class declaringClass,
public Field newField(Class<?> declaringClass,
String name,
Class type,
Class<?> type,
int modifiers,
int slot,
String signature,
......@@ -50,11 +50,11 @@ class ReflectAccess implements sun.reflect.LangReflectAccess {
annotations);
}
public Method newMethod(Class declaringClass,
public Method newMethod(Class<?> declaringClass,
String name,
Class[] parameterTypes,
Class returnType,
Class[] checkedExceptions,
Class<?>[] parameterTypes,
Class<?> returnType,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
......@@ -76,8 +76,8 @@ class ReflectAccess implements sun.reflect.LangReflectAccess {
}
public <T> Constructor<T> newConstructor(Class<T> declaringClass,
Class[] parameterTypes,
Class[] checkedExceptions,
Class<?>[] parameterTypes,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
......@@ -102,29 +102,29 @@ class ReflectAccess implements sun.reflect.LangReflectAccess {
m.setMethodAccessor(accessor);
}
public ConstructorAccessor getConstructorAccessor(Constructor c) {
public ConstructorAccessor getConstructorAccessor(Constructor<?> c) {
return c.getConstructorAccessor();
}
public void setConstructorAccessor(Constructor c,
public void setConstructorAccessor(Constructor<?> c,
ConstructorAccessor accessor)
{
c.setConstructorAccessor(accessor);
}
public int getConstructorSlot(Constructor c) {
public int getConstructorSlot(Constructor<?> c) {
return c.getSlot();
}
public String getConstructorSignature(Constructor c) {
public String getConstructorSignature(Constructor<?> c) {
return c.getSignature();
}
public byte[] getConstructorAnnotations(Constructor c) {
public byte[] getConstructorAnnotations(Constructor<?> c) {
return c.getRawAnnotations();
}
public byte[] getConstructorParameterAnnotations(Constructor c) {
public byte[] getConstructorParameterAnnotations(Constructor<?> c) {
return c.getRawParameterAnnotations();
}
......
......@@ -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);
}
......
......@@ -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
......
/*
* 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.awt;
import java.awt.AWTPermission;
import sun.security.util.PermissionFactory;
/**
* A factory object for AWTPermission objects.
*/
public class AWTPermissionFactory
implements PermissionFactory<AWTPermission>
{
@Override
public AWTPermission newPermission(String name) {
return new AWTPermission(name);
}
}
......@@ -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 <code>true</code> 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());
......
/*
* 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.getAdditionalBootstrapPaths();
} 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);
}
......@@ -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<additionalBootStrapPaths.length; i++) {
bootstrapClassPath.addURL(
getFileURL(additionalBootStrapPaths[i]));
}
return null;
final File[] additionalBootStrapPaths =
BootClassLoaderHook.getBootstrapPaths();
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
for (int i=0; i<additionalBootStrapPaths.length; i++) {
bootstrapClassPath.addURL(
getFileURL(additionalBootStrapPaths[i]));
}
});
}
return null;
}
});
}
return bootstrapClassPath;
}
......
......@@ -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();
}
......
......@@ -398,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
......
......@@ -178,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
......
......@@ -291,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();
}
......@@ -385,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();
......
......@@ -390,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");
......@@ -1546,10 +1546,14 @@ public class HttpURLConnection extends java.net.HttpURLConnection {
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);
}
......@@ -1765,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);
}
......@@ -2075,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;
}
}
......@@ -2099,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
......@@ -2160,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
......@@ -2204,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();
......
......@@ -214,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
......
/*
* 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) &&
......
......@@ -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();
}
......
......@@ -33,9 +33,9 @@ import java.lang.reflect.*;
public interface LangReflectAccess {
/** Creates a new java.lang.reflect.Field. Access checks as per
java.lang.reflect.AccessibleObject are not overridden. */
public Field newField(Class declaringClass,
public Field newField(Class<?> declaringClass,
String name,
Class type,
Class<?> type,
int modifiers,
int slot,
String signature,
......@@ -43,11 +43,11 @@ public interface LangReflectAccess {
/** Creates a new java.lang.reflect.Method. Access checks as per
java.lang.reflect.AccessibleObject are not overridden. */
public Method newMethod(Class declaringClass,
public Method newMethod(Class<?> declaringClass,
String name,
Class[] parameterTypes,
Class returnType,
Class[] checkedExceptions,
Class<?>[] parameterTypes,
Class<?> returnType,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
......@@ -58,8 +58,8 @@ public interface LangReflectAccess {
/** Creates a new java.lang.reflect.Constructor. Access checks as
per java.lang.reflect.AccessibleObject are not overridden. */
public <T> Constructor<T> newConstructor(Class<T> declaringClass,
Class[] parameterTypes,
Class[] checkedExceptions,
Class<?>[] parameterTypes,
Class<?>[] checkedExceptions,
int modifiers,
int slot,
String signature,
......@@ -74,24 +74,24 @@ public interface LangReflectAccess {
/** Gets the ConstructorAccessor object for a
java.lang.reflect.Constructor */
public ConstructorAccessor getConstructorAccessor(Constructor c);
public ConstructorAccessor getConstructorAccessor(Constructor<?> c);
/** Sets the ConstructorAccessor object for a
java.lang.reflect.Constructor */
public void setConstructorAccessor(Constructor c,
public void setConstructorAccessor(Constructor<?> c,
ConstructorAccessor accessor);
/** Gets the "slot" field from a Constructor (used for serialization) */
public int getConstructorSlot(Constructor c);
public int getConstructorSlot(Constructor<?> c);
/** Gets the "signature" field from a Constructor (used for serialization) */
public String getConstructorSignature(Constructor c);
public String getConstructorSignature(Constructor<?> c);
/** Gets the "annotations" field from a Constructor (used for serialization) */
public byte[] getConstructorAnnotations(Constructor c);
public byte[] getConstructorAnnotations(Constructor<?> c);
/** Gets the "parameterAnnotations" field from a Constructor (used for serialization) */
public byte[] getConstructorParameterAnnotations(Constructor c);
public byte[] getConstructorParameterAnnotations(Constructor<?> c);
//
// Copying routines, needed to quickly fabricate new Field,
......
......@@ -40,17 +40,17 @@ import java.security.PrivilegedAction;
* @since 1.5
*/
class AnnotationInvocationHandler implements InvocationHandler, Serializable {
private final Class type;
private final Class<? extends Annotation> type;
private final Map<String, Object> memberValues;
AnnotationInvocationHandler(Class type, Map<String, Object> memberValues) {
AnnotationInvocationHandler(Class<? extends Annotation> type, Map<String, Object> memberValues) {
this.type = type;
this.memberValues = memberValues;
}
public Object invoke(Object proxy, Method method, Object[] args) {
String member = method.getName();
Class[] paramTypes = method.getParameterTypes();
Class<?>[] paramTypes = method.getParameterTypes();
// Handle Object and Annotation methods
if (member.equals("equals") && paramTypes.length == 1 &&
......@@ -84,7 +84,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
* if Cloneable had a public clone method.
*/
private Object cloneArray(Object array) {
Class type = array.getClass();
Class<?> type = array.getClass();
if (type == byte[].class) {
byte[] byteArray = (byte[])array;
......@@ -151,7 +151,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
* Translates a member value (in "dynamic proxy return form") into a string
*/
private static String memberValueToString(Object value) {
Class type = value.getClass();
Class<?> type = value.getClass();
if (!type.isArray()) // primitive, string, class, enum const,
// or annotation
return value.toString();
......@@ -229,7 +229,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
* two members are identical object references.
*/
private static boolean memberValueEquals(Object v1, Object v2) {
Class type = v1.getClass();
Class<?> type = v1.getClass();
// Check for primitive, string, class, enum const, annotation,
// or ExceptionProxy
......@@ -301,7 +301,7 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
* Computes hashCode of a member value (in "dynamic proxy return form")
*/
private static int memberValueHashCode(Object value) {
Class type = value.getClass();
Class<?> type = value.getClass();
if (!type.isArray()) // primitive, string, class, enum const,
// or annotation
return value.hashCode();
......@@ -340,11 +340,11 @@ class AnnotationInvocationHandler implements InvocationHandler, Serializable {
return;
}
Map<String, Class> memberTypes = annotationType.memberTypes();
Map<String, Class<?>> memberTypes = annotationType.memberTypes();
for (Map.Entry<String, Object> memberValue : memberValues.entrySet()) {
String name = memberValue.getKey();
Class memberType = memberTypes.get(name);
Class<?> memberType = memberTypes.get(name);
if (memberType != null) { // i.e. member still exists
Object value = memberValue.getValue();
if (!(memberType.isInstance(value) ||
......
......@@ -59,10 +59,10 @@ public class AnnotationParser {
* @throws AnnotationFormatError if an annotation is found to be
* malformed.
*/
public static Map<Class, Annotation> parseAnnotations(
public static Map<Class<? extends Annotation>, Annotation> parseAnnotations(
byte[] rawAnnotations,
ConstantPool constPool,
Class container) {
Class<?> container) {
if (rawAnnotations == null)
return Collections.emptyMap();
......@@ -76,17 +76,18 @@ public class AnnotationParser {
}
}
private static Map<Class, Annotation> parseAnnotations2(
private static Map<Class<? extends Annotation>, Annotation> parseAnnotations2(
byte[] rawAnnotations,
ConstantPool constPool,
Class container) {
Map<Class, Annotation> result = new LinkedHashMap<Class, Annotation>();
Class<?> container) {
Map<Class<? extends Annotation>, Annotation> result =
new LinkedHashMap<Class<? extends Annotation>, Annotation>();
ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
int numAnnotations = buf.getShort() & 0xFFFF;
for (int i = 0; i < numAnnotations; i++) {
Annotation a = parseAnnotation(buf, constPool, container, false);
if (a != null) {
Class klass = a.annotationType();
Class<? extends Annotation> klass = a.annotationType();
AnnotationType type = AnnotationType.getInstance(klass);
if (type.retention() == RetentionPolicy.RUNTIME)
if (result.put(klass, a) != null)
......@@ -123,7 +124,7 @@ public class AnnotationParser {
public static Annotation[][] parseParameterAnnotations(
byte[] rawAnnotations,
ConstantPool constPool,
Class container) {
Class<?> container) {
try {
return parseParameterAnnotations2(rawAnnotations, constPool, container);
} catch(BufferUnderflowException e) {
......@@ -138,7 +139,7 @@ public class AnnotationParser {
private static Annotation[][] parseParameterAnnotations2(
byte[] rawAnnotations,
ConstantPool constPool,
Class container) {
Class<?> container) {
ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
int numParameters = buf.get() & 0xFF;
Annotation[][] result = new Annotation[numParameters][];
......@@ -188,15 +189,15 @@ public class AnnotationParser {
*/
private static Annotation parseAnnotation(ByteBuffer buf,
ConstantPool constPool,
Class container,
Class<?> container,
boolean exceptionOnMissingAnnotationClass) {
int typeIndex = buf.getShort() & 0xFFFF;
Class annotationClass = null;
Class<? extends Annotation> annotationClass = null;
String sig = "[unknown]";
try {
try {
sig = constPool.getUTF8At(typeIndex);
annotationClass = parseSig(sig, container);
annotationClass = (Class<? extends Annotation>)parseSig(sig, container);
} catch (IllegalArgumentException ex) {
// support obsolete early jsr175 format class files
annotationClass = constPool.getClassAt(typeIndex);
......@@ -223,7 +224,7 @@ public class AnnotationParser {
return null;
}
Map<String, Class> memberTypes = type.memberTypes();
Map<String, Class<?>> memberTypes = type.memberTypes();
Map<String, Object> memberValues =
new LinkedHashMap<String, Object>(type.memberDefaults());
......@@ -231,7 +232,7 @@ public class AnnotationParser {
for (int i = 0; i < numMembers; i++) {
int memberNameIndex = buf.getShort() & 0xFFFF;
String memberName = constPool.getUTF8At(memberNameIndex);
Class memberType = memberTypes.get(memberName);
Class<?> memberType = memberTypes.get(memberName);
if (memberType == null) {
// Member is no longer present in annotation type; ignore it
......@@ -252,7 +253,7 @@ public class AnnotationParser {
* member -> value map.
*/
public static Annotation annotationForMap(
Class type, Map<String, Object> memberValues)
Class<? extends Annotation> type, Map<String, Object> memberValues)
{
return (Annotation) Proxy.newProxyInstance(
type.getClassLoader(), new Class[] { type },
......@@ -286,14 +287,15 @@ public class AnnotationParser {
* The member must be of the indicated type. If it is not, this
* method returns an AnnotationTypeMismatchExceptionProxy.
*/
public static Object parseMemberValue(Class memberType, ByteBuffer buf,
public static Object parseMemberValue(Class<?> memberType,
ByteBuffer buf,
ConstantPool constPool,
Class container) {
Class<?> container) {
Object result = null;
int tag = buf.get();
switch(tag) {
case 'e':
return parseEnumValue(memberType, buf, constPool, container);
return parseEnumValue((Class<? extends Enum<?>>)memberType, buf, constPool, container);
case 'c':
result = parseClassValue(buf, constPool, container);
break;
......@@ -361,7 +363,7 @@ public class AnnotationParser {
*/
private static Object parseClassValue(ByteBuffer buf,
ConstantPool constPool,
Class container) {
Class<?> container) {
int classIndex = buf.getShort() & 0xFFFF;
try {
try {
......@@ -379,7 +381,7 @@ public class AnnotationParser {
}
}
private static Class<?> parseSig(String sig, Class container) {
private static Class<?> parseSig(String sig, Class<?> container) {
if (sig.equals("V")) return void.class;
SignatureParser parser = SignatureParser.make();
TypeSignature typeSig = parser.parseTypeSig(sig);
......@@ -389,7 +391,7 @@ public class AnnotationParser {
Type result = reify.getResult();
return toClass(result);
}
static Class toClass(Type o) {
static Class<?> toClass(Type o) {
if (o instanceof GenericArrayType)
return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
0)
......@@ -409,9 +411,9 @@ public class AnnotationParser {
* u2 const_name_index;
* } enum_const_value;
*/
private static Object parseEnumValue(Class enumType, ByteBuffer buf,
private static Object parseEnumValue(Class<? extends Enum> enumType, ByteBuffer buf,
ConstantPool constPool,
Class container) {
Class<?> container) {
int typeNameIndex = buf.getShort() & 0xFFFF;
String typeName = constPool.getUTF8At(typeNameIndex);
int constNameIndex = buf.getShort() & 0xFFFF;
......@@ -449,12 +451,12 @@ public class AnnotationParser {
* If the array values do not match arrayType, an
* AnnotationTypeMismatchExceptionProxy will be returned.
*/
private static Object parseArray(Class arrayType,
private static Object parseArray(Class<?> arrayType,
ByteBuffer buf,
ConstantPool constPool,
Class container) {
Class<?> container) {
int length = buf.getShort() & 0xFFFF; // Number of array components
Class componentType = arrayType.getComponentType();
Class<?> componentType = arrayType.getComponentType();
if (componentType == byte.class) {
return parseByteArray(length, buf, constPool);
......@@ -477,11 +479,11 @@ public class AnnotationParser {
} else if (componentType == Class.class) {
return parseClassArray(length, buf, constPool, container);
} else if (componentType.isEnum()) {
return parseEnumArray(length, componentType, buf,
return parseEnumArray(length, (Class<? extends Enum>)componentType, buf,
constPool, container);
} else {
assert componentType.isAnnotation();
return parseAnnotationArray(length, componentType, buf,
return parseAnnotationArray(length, (Class <? extends Annotation>)componentType, buf,
constPool, container);
}
}
......@@ -660,8 +662,8 @@ public class AnnotationParser {
private static Object parseClassArray(int length,
ByteBuffer buf,
ConstantPool constPool,
Class container) {
Object[] result = new Class[length];
Class<?> container) {
Object[] result = new Class<?>[length];
boolean typeMismatch = false;
int tag = 0;
......@@ -677,10 +679,10 @@ public class AnnotationParser {
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseEnumArray(int length, Class enumType,
private static Object parseEnumArray(int length, Class<? extends Enum> enumType,
ByteBuffer buf,
ConstantPool constPool,
Class container) {
Class<?> container) {
Object[] result = (Object[]) Array.newInstance(enumType, length);
boolean typeMismatch = false;
int tag = 0;
......@@ -698,10 +700,10 @@ public class AnnotationParser {
}
private static Object parseAnnotationArray(int length,
Class annotationType,
Class<? extends Annotation> annotationType,
ByteBuffer buf,
ConstantPool constPool,
Class container) {
Class<?> container) {
Object[] result = (Object[]) Array.newInstance(annotationType, length);
boolean typeMismatch = false;
int tag = 0;
......@@ -797,7 +799,7 @@ public class AnnotationParser {
* it is needed.
*/
private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
public static Annotation[] toArray(Map<Class, Annotation> annotations) {
public static Annotation[] toArray(Map<Class<? extends Annotation>, Annotation> annotations) {
return annotations.values().toArray(EMPTY_ANNOTATION_ARRAY);
}
}
......@@ -45,7 +45,7 @@ public class AnnotationType {
* types. This matches the return value that must be used for a
* dynamic proxy, allowing for a simple isInstance test.
*/
private final Map<String, Class> memberTypes = new HashMap<String,Class>();
private final Map<String, Class<?>> memberTypes = new HashMap<String,Class<?>>();
/**
* Member name -> default value mapping.
......@@ -76,12 +76,12 @@ public class AnnotationType {
* does not represent a valid annotation type
*/
public static synchronized AnnotationType getInstance(
Class annotationClass)
Class<? extends Annotation> annotationClass)
{
AnnotationType result = sun.misc.SharedSecrets.getJavaLangAccess().
getAnnotationType(annotationClass);
if (result == null)
result = new AnnotationType((Class<?>) annotationClass);
result = new AnnotationType((Class<? extends Annotation>) annotationClass);
return result;
}
......@@ -93,7 +93,7 @@ public class AnnotationType {
* @throw IllegalArgumentException if the specified class object for
* does not represent a valid annotation type
*/
private AnnotationType(final Class<?> annotationClass) {
private AnnotationType(final Class<? extends Annotation> annotationClass) {
if (!annotationClass.isAnnotation())
throw new IllegalArgumentException("Not an annotation type");
......@@ -110,7 +110,7 @@ public class AnnotationType {
if (method.getParameterTypes().length != 0)
throw new IllegalArgumentException(method + " has params");
String name = method.getName();
Class type = method.getReturnType();
Class<?> type = method.getReturnType();
memberTypes.put(name, invocationHandlerReturnType(type));
members.put(name, method);
......@@ -140,7 +140,7 @@ public class AnnotationType {
* the specified type (which is assumed to be a legal member type
* for an annotation).
*/
public static Class invocationHandlerReturnType(Class type) {
public static Class<?> invocationHandlerReturnType(Class<?> type) {
// Translate primitives to wrappers
if (type == byte.class)
return Byte.class;
......@@ -167,7 +167,7 @@ public class AnnotationType {
* Returns member types for this annotation type
* (member name -> type mapping).
*/
public Map<String, Class> memberTypes() {
public Map<String, Class<?>> memberTypes() {
return memberTypes;
}
......
......@@ -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
......
/*
* 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,
......
......@@ -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);
......
......@@ -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();
}
......
/*
* 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;
}
}
/*
* 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() {
......
/*
* 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) {
......
......@@ -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) {
......
/*
* 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.
*
* <pre>
* KerberosString ::= GeneralString (IA5String)
* </pre>
*
* This definition reflects the Network Working Group RFC 4120
* specification available at
* <a href="http://www.ietf.org/rfc/rfc4120.txt">
* http://www.ietf.org/rfc/rfc4120.txt</a>.
*/
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"));
}
}
......@@ -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);
......
/*
* 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() {
......
/*
* 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<Void>() {
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.
*/
......
......@@ -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
......
/*
* 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.util;
import java.security.Permission;
/**
* A factory object that creates Permission objects.
*/
public interface PermissionFactory<T extends Permission> {
T newPermission(String name);
}
......@@ -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 <flag> needs an argument.", "Command option {0} needs an argument."},
{"Warning: Different store and key passwords not supported for PKCS12 KeyStores. Ignoring user-specified <command> 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, <arg> 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 <alias>] [-sigalg <sigalg>]",
"\t [-alias <alias>] [-sigalg <sigalg>]"},
{"\t [-dname <dname>]", "\t [-dname <dname>]"},
{"\t [-file <csr_file>] [-keypass <keypass>]",
"\t [-file <csr_file>] [-keypass <keypass>]"},
{"\t [-keystore <keystore>] [-storepass <storepass>]",
"\t [-keystore <keystore>] [-storepass <storepass>]"},
{"\t [-storetype <storetype>] [-providername <name>]",
"\t [-storetype <storetype>] [-providername <name>]"},
{"\t [-providerclass <provider_class_name> [-providerarg <arg>]] ...",
"\t [-providerclass <provider_class_name> [-providerarg <arg>]] ..."},
{"\t [-providerpath <pathlist>]",
"\t [-providerpath <pathlist>]"},
{"-delete [-v] [-protected] -alias <alias>",
"-delete [-v] [-protected] -alias <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 <alias>] [-file <cert_file>]",
"\t [-alias <alias>] [-file <cert_file>]"},
/** rest is same as -certreq starting from -keystore **/
//{"-genkey [-v] [-protected]",
// "-genkey [-v] [-protected]"},
{"-genkeypair [-v] [-protected]",
"-genkeypair [-v] [-protected]"},
{"\t [-alias <alias>]", "\t [-alias <alias>]"},
{"\t [-keyalg <keyalg>] [-keysize <keysize>]",
"\t [-keyalg <keyalg>] [-keysize <keysize>]"},
{"\t [-sigalg <sigalg>] [-dname <dname>]",
"\t [-sigalg <sigalg>] [-dname <dname>]"},
{"\t [-startdate <startdate>]",
"\t [-startdate <startdate>]"},
{"\t [-validity <valDays>] [-keypass <keypass>]",
"\t [-validity <valDays>] [-keypass <keypass>]"},
/** rest is same as -certreq starting from -keystore **/
{"-gencert [-v] [-rfc] [-protected]",
"-gencert [-v] [-rfc] [-protected]"},
{"\t [-infile <infile>] [-outfile <outfile>]",
"\t [-infile <infile>] [-outfile <outfile>]"},
{"\t [-sigalg <sigalg>]",
"\t [-sigalg <sigalg>]"},
{"\t [-ext <key>[:critical][=<value>]]...",
"\t [-ext <key>[:critical][=<value>]]..."},
{"-genseckey [-v] [-protected]",
"-genseckey [-v] [-protected]"},
/** rest is same as -certreq starting from -keystore **/
{"-help", "-help"},
//{"-identitydb [-v] [-protected]",
// "-identitydb [-v] [-protected]"},
//{"\t [-file <idb_file>]", "\t [-file <idb_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 <alias>]", "\t [-alias <alias>]"},
{"\t [-alias <alias>] [-keypass <keypass>]",
"\t [-alias <alias>] [-keypass <keypass>]"},
{"\t [-file <cert_file>] [-keypass <keypass>]",
"\t [-file <cert_file>] [-keypass <keypass>]"},
/** rest is same as -certreq starting from -keystore **/
{"-importkeystore [-v] ",
"-importkeystore [-v] "},
{"\t [-srckeystore <srckeystore>] [-destkeystore <destkeystore>]",
"\t [-srckeystore <srckeystore>] [-destkeystore <destkeystore>]"},
{"\t [-srcstoretype <srcstoretype>] [-deststoretype <deststoretype>]",
"\t [-srcstoretype <srcstoretype>] [-deststoretype <deststoretype>]"},
{"\t [-srcprotected] [-destprotected]",
"\t [-srcprotected] [-destprotected]"},
{"\t [-srcstorepass <srcstorepass>] [-deststorepass <deststorepass>]",
"\t [-srcstorepass <srcstorepass>] [-deststorepass <deststorepass>]"},
{"\t [-srcprovidername <srcprovidername>]\n\t [-destprovidername <destprovidername>]", // line too long, split to 2
"\t [-srcprovidername <srcprovidername>]\n\t [-destprovidername <destprovidername>]"},
{"\t [-srcalias <srcalias> [-destalias <destalias>]",
"\t [-srcalias <srcalias> [-destalias <destalias>]"},
{"\t [-srckeypass <srckeypass>] [-destkeypass <destkeypass>]]",
"\t [-srckeypass <srckeypass>] [-destkeypass <destkeypass>]]"},
{"\t [-noprompt]", "\t [-noprompt]"},
/** rest is same as -certreq starting from -keystore **/
{"-changealias [-v] [-protected] -alias <alias> -destalias <destalias>",
"-changealias [-v] [-protected] -alias <alias> -destalias <destalias>"},
{"\t [-keypass <keypass>]", "\t [-keypass <keypass>]"},
//{"-keyclone [-v] [-protected]",
// "-keyclone [-v] [-protected]"},
//{"\t [-alias <alias>] -dest <dest_alias>",
// "\t [-alias <alias>] -dest <dest_alias>"},
//{"\t [-keypass <keypass>] [-new <new_keypass>]",
// "\t [-keypass <keypass>] [-new <new_keypass>]"},
/** rest is same as -certreq starting from -keystore **/
{"-keypasswd [-v] [-alias <alias>]",
"-keypasswd [-v] [-alias <alias>]"},
{"\t [-keypass <old_keypass>] [-new <new_keypass>]",
"\t [-keypass <old_keypass>] [-new <new_keypass>]"},
/** rest is same as -certreq starting from -keystore **/
{"-list [-v | -rfc] [-protected]",
"-list [-v | -rfc] [-protected]"},
{"\t [-alias <alias>]", "\t [-alias <alias>]"},
/** rest is same as -certreq starting from -keystore **/
{"-printcert [-v] [-rfc] [-file <cert_file> | -sslserver <host[:port]>]",
"-printcert [-v] [-rfc] [-file <cert_file> | -sslserver <host[:port]>]"},
{"-printcertreq [-v] [-file <cert_file>]",
"-printcertreq [-v] [-file <cert_file>]"},
{"No certificate from the SSL server",
"No certificate from the SSL server"},
//{"-selfcert [-v] [-protected]",
// "-selfcert [-v] [-protected]"},
{"\t [-alias <alias>]", "\t [-alias <alias>]"},
//{"\t [-dname <dname>] [-validity <valDays>]",
// "\t [-dname <dname>] [-validity <valDays>]"},
//{"\t [-keypass <keypass>] [-sigalg <sigalg>]",
// "\t [-keypass <keypass>] [-sigalg <sigalg>]"},
/** rest is same as -certreq starting from -keystore **/
{"-storepasswd [-v] [-new <new_storepass>]",
"-storepasswd [-v] [-new <new_storepass>]"},
/** 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;
}
}
......@@ -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<FakeAWTPermission>
{
@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<Class<?>>() {
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 =
......
......@@ -338,7 +338,8 @@ static void read_all_code(context_type *context, jclass cb, int num_methods,
int** code_lengths, unsigned char*** code);
static void verify_method(context_type *context, jclass cb, int index,
int code_length, unsigned char* code);
static void free_all_code(int num_methods, int* lengths, unsigned char** code);
static void free_all_code(context_type* context, int num_methods,
unsigned char** code);
static void verify_field(context_type *context, jclass cb, int index);
static void verify_opcode_operands (context_type *, unsigned int inumber, int offset);
......@@ -813,11 +814,11 @@ VerifyClassForMajorVersion(JNIEnv *env, jclass cb, char *buffer, jint len,
/* Look at each method */
for (i = JVM_GetClassFieldsCount(env, cb); --i >= 0;)
verify_field(context, cb, i);
num_methods = JVM_GetClassMethodsCount(env, cb);
read_all_code(context, cb, num_methods, &code_lengths, &code);
for (i = num_methods - 1; i >= 0; --i)
num_methods = JVM_GetClassMethodsCount(env, cb);
read_all_code(context, cb, num_methods, &code_lengths, &code);
for (i = num_methods - 1; i >= 0; --i)
verify_method(context, cb, i, code_lengths[i], code[i]);
free_all_code(num_methods, code_lengths, code);
free_all_code(context, num_methods, code);
result = CC_OK;
} else {
result = context->err_code;
......@@ -836,9 +837,6 @@ VerifyClassForMajorVersion(JNIEnv *env, jclass cb, char *buffer, jint len,
if (context->exceptions)
free(context->exceptions);
if (context->code)
free(context->code);
if (context->constant_types)
free(context->constant_types);
......@@ -895,41 +893,42 @@ static void
read_all_code(context_type* context, jclass cb, int num_methods,
int** lengths_addr, unsigned char*** code_addr)
{
int* lengths = malloc(sizeof(int) * num_methods);
unsigned char** code = malloc(sizeof(unsigned char*) * num_methods);
int* lengths;
unsigned char** code;
int i;
*(lengths_addr) = lengths;
*(code_addr) = code;
lengths = malloc(sizeof(int) * num_methods);
check_and_push(context, lengths, VM_MALLOC_BLK);
code = malloc(sizeof(unsigned char*) * num_methods);
check_and_push(context, code, VM_MALLOC_BLK);
*(lengths_addr) = lengths;
*(code_addr) = code;
if (lengths == 0 || code == 0) {
CCout_of_memory(context);
} else {
int i;
for (i = 0; i < num_methods; ++i) {
lengths[i] = JVM_GetMethodIxByteCodeLength(context->env, cb, i);
if (lengths[i] != 0) {
code[i] = malloc(sizeof(unsigned char) * (lengths[i] + 1));
if (code[i] == NULL) {
CCout_of_memory(context);
lengths[i] = JVM_GetMethodIxByteCodeLength(context->env, cb, i);
if (lengths[i] > 0) {
code[i] = malloc(sizeof(unsigned char) * (lengths[i] + 1));
check_and_push(context, code[i], VM_MALLOC_BLK);
JVM_GetMethodIxByteCode(context->env, cb, i, code[i]);
} else {
JVM_GetMethodIxByteCode(context->env, cb, i, code[i]);
code[i] = NULL;
}
} else {
code[i] = NULL;
}
}
}
}
static void
free_all_code(int num_methods, int* lengths, unsigned char** code)
free_all_code(context_type* context, int num_methods, unsigned char** code)
{
int i;
for (i = 0; i < num_methods; ++i) {
free(code[i]);
if (code[i] != NULL) {
pop_and_free(context);
}
}
free(lengths);
free(code);
pop_and_free(context); /* code */
pop_and_free(context); /* lengths */
}
/* Verify the code of one method */
......
......@@ -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);
}
}
}
}
......@@ -244,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);
......
......@@ -192,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 {
}
}
/*
* 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);
......
......@@ -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.
* <br>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 {
* <ul>
* <li><b>-f</b> shows credentials flags
* <li><b>-e</b> shows the encryption type
* <li><b>-a</b> shows addresses
* <li><b>-n</b> do not reverse-resolve addresses
* </ul>
* available options for keytabs:
* <li><b>-t</b> 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");
......
......@@ -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.
......
/*
* 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");}
}
/*
* 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");}
}
......@@ -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) {}
}
......
/*
* 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<passwd.length; i++)
passwdBytes[i] = (byte)passwd[i];
md.update(passwdBytes);
Arrays.fill(passwdBytes, (byte)0x00);
}
byte[] digest = md.digest();
StringBuffer res = new StringBuffer(digest.length * 2);
for (int i = 0; i < digest.length; i++) {
int hashchar = ((digest[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");
}
}
}
此差异已折叠。
......@@ -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);
}
......
此差异已折叠。
......@@ -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);
}
......
此差异已折叠。
此差异已折叠。
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册