Util.java 18.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * 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
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * 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.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
 */
package sun.rmi.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.DataOutputStream;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Proxy;
import java.lang.reflect.Method;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.StubNotFoundException;
import java.rmi.registry.Registry;
import java.rmi.server.LogStream;
import java.rmi.server.ObjID;
import java.rmi.server.RMIClientSocketFactory;
import java.rmi.server.RemoteObjectInvocationHandler;
import java.rmi.server.RemoteRef;
import java.rmi.server.RemoteStub;
import java.rmi.server.Skeleton;
import java.rmi.server.SkeletonNotFoundException;
import java.security.AccessController;
import java.security.MessageDigest;
import java.security.DigestOutputStream;
import java.security.NoSuchAlgorithmException;
51
import java.security.PrivilegedAction;
D
duke 已提交
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;
import java.util.WeakHashMap;
import sun.rmi.registry.RegistryImpl;
import sun.rmi.runtime.Log;
import sun.rmi.transport.LiveRef;
import sun.rmi.transport.tcp.TCPEndpoint;
import sun.security.action.GetBooleanAction;
import sun.security.action.GetPropertyAction;

/**
 * A utility class with static methods for creating stubs/proxies and
 * skeletons for remote objects.
 */
67
@SuppressWarnings("deprecation")
D
duke 已提交
68 69 70 71
public final class Util {

    /** "server" package log level */
    static final int logLevel = LogStream.parseLevel(
72
        AccessController.doPrivileged(
D
duke 已提交
73 74 75 76 77 78 79 80
            new GetPropertyAction("sun.rmi.server.logLevel")));

    /** server reference log */
    public static final Log serverRefLog =
        Log.getLog("sun.rmi.server.ref", "transport", Util.logLevel);

    /** cached value of property java.rmi.server.ignoreStubClasses */
    private static final boolean ignoreStubClasses =
81 82
        AccessController.doPrivileged(
            new GetBooleanAction("java.rmi.server.ignoreStubClasses")).
D
duke 已提交
83 84 85
            booleanValue();

    /** cache of  impl classes that have no corresponding stub class */
86 87
    private static final Map<Class<?>, Void> withoutStubs =
        Collections.synchronizedMap(new WeakHashMap<Class<?>, Void>(11));
D
duke 已提交
88 89

    /** parameter types for stub constructor */
90
    private static final Class<?>[] stubConsParamTypes = { RemoteRef.class };
D
duke 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123

    private Util() {
    }

    /**
     * Returns a proxy for the specified implClass.
     *
     * If both of the following criteria is satisfied, a dynamic proxy for
     * the specified implClass is returned (otherwise a RemoteStub instance
     * for the specified implClass is returned):
     *
     *    a) either the property java.rmi.server.ignoreStubClasses is true or
     *       a pregenerated stub class does not exist for the impl class, and
     *    b) forceStubUse is false.
     *
     * If the above criteria are satisfied, this method constructs a
     * dynamic proxy instance (that implements the remote interfaces of
     * implClass) constructed with a RemoteObjectInvocationHandler instance
     * constructed with the clientRef.
     *
     * Otherwise, this method loads the pregenerated stub class (which
     * extends RemoteStub and implements the remote interfaces of
     * implClass) and constructs an instance of the pregenerated stub
     * class with the clientRef.
     *
     * @param implClass the class to obtain remote interfaces from
     * @param clientRef the remote ref to use in the invocation handler
     * @param forceStubUse if true, forces creation of a RemoteStub
     * @throws IllegalArgumentException if implClass implements illegal
     * remote interfaces
     * @throws StubNotFoundException if problem locating/creating stub or
     * creating the dynamic proxy instance
     **/
124
    public static Remote createProxy(Class<?> implClass,
D
duke 已提交
125 126 127 128
                                     RemoteRef clientRef,
                                     boolean forceStubUse)
        throws StubNotFoundException
    {
129
        Class<?> remoteClass;
D
duke 已提交
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144

        try {
            remoteClass = getRemoteClass(implClass);
        } catch (ClassNotFoundException ex ) {
            throw new StubNotFoundException(
                "object does not implement a remote interface: " +
                implClass.getName());
        }

        if (forceStubUse ||
            !(ignoreStubClasses || !stubClassExists(remoteClass)))
        {
            return createStub(remoteClass, clientRef);
        }

145
        final ClassLoader loader = implClass.getClassLoader();
146
        final Class<?>[] interfaces = getRemoteInterfaces(implClass);
147
        final InvocationHandler handler =
D
duke 已提交
148 149 150 151 152
            new RemoteObjectInvocationHandler(clientRef);

        /* REMIND: private remote interfaces? */

        try {
153 154 155 156 157 158
            return AccessController.doPrivileged(new PrivilegedAction<Remote>() {
                public Remote run() {
                    return (Remote) Proxy.newProxyInstance(loader,
                                                           interfaces,
                                                           handler);
                }});
D
duke 已提交
159 160 161 162 163 164 165 166 167 168 169
        } catch (IllegalArgumentException e) {
            throw new StubNotFoundException("unable to create proxy", e);
        }
    }

    /**
     * Returns true if a stub class for the given impl class can be loaded,
     * otherwise returns false.
     *
     * @param remoteClass the class to obtain remote interfaces from
     */
170
    private static boolean stubClassExists(Class<?> remoteClass) {
D
duke 已提交
171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189
        if (!withoutStubs.containsKey(remoteClass)) {
            try {
                Class.forName(remoteClass.getName() + "_Stub",
                              false,
                              remoteClass.getClassLoader());
                return true;

            } catch (ClassNotFoundException cnfe) {
                withoutStubs.put(remoteClass, null);
            }
        }
        return false;
    }

    /*
     * Returns the class/superclass that implements the remote interface.
     * @throws ClassNotFoundException if no class is found to have a
     * remote interface
     */
190
    private static Class<?> getRemoteClass(Class<?> cl)
D
duke 已提交
191 192 193
        throws ClassNotFoundException
    {
        while (cl != null) {
194
            Class<?>[] interfaces = cl.getInterfaces();
D
duke 已提交
195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213
            for (int i = interfaces.length -1; i >= 0; i--) {
                if (Remote.class.isAssignableFrom(interfaces[i]))
                    return cl;          // this class implements remote object
            }
            cl = cl.getSuperclass();
        }
        throw new ClassNotFoundException(
                "class does not implement java.rmi.Remote");
    }

    /**
     * Returns an array containing the remote interfaces implemented
     * by the given class.
     *
     * @param   remoteClass the class to obtain remote interfaces from
     * @throws  IllegalArgumentException if remoteClass implements
     *          any illegal remote interfaces
     * @throws  NullPointerException if remoteClass is null
     */
214 215
    private static Class<?>[] getRemoteInterfaces(Class<?> remoteClass) {
        ArrayList<Class<?>> list = new ArrayList<>();
D
duke 已提交
216
        getRemoteInterfaces(list, remoteClass);
217
        return list.toArray(new Class<?>[list.size()]);
D
duke 已提交
218 219 220 221 222 223 224 225 226 227
    }

    /**
     * Fills the given array list with the remote interfaces implemented
     * by the given class.
     *
     * @throws  IllegalArgumentException if the specified class implements
     *          any illegal remote interfaces
     * @throws  NullPointerException if the specified class or list is null
     */
228 229
    private static void getRemoteInterfaces(ArrayList<Class<?>> list, Class<?> cl) {
        Class<?> superclass = cl.getSuperclass();
D
duke 已提交
230 231 232 233
        if (superclass != null) {
            getRemoteInterfaces(list, superclass);
        }

234
        Class<?>[] interfaces = cl.getInterfaces();
D
duke 已提交
235
        for (int i = 0; i < interfaces.length; i++) {
236
            Class<?> intf = interfaces[i];
D
duke 已提交
237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
            /*
             * If it is a remote interface (if it extends from
             * java.rmi.Remote) and is not already in the list,
             * then add the interface to the list.
             */
            if (Remote.class.isAssignableFrom(intf)) {
                if (!(list.contains(intf))) {
                    Method[] methods = intf.getMethods();
                    for (int j = 0; j < methods.length; j++) {
                        checkMethod(methods[j]);
                    }
                    list.add(intf);
                }
            }
        }
    }

    /**
     * Verifies that the supplied method has at least one declared exception
     * type that is RemoteException or one of its superclasses.  If not,
     * then this method throws IllegalArgumentException.
     *
     * @throws IllegalArgumentException if m is an illegal remote method
     */
    private static void checkMethod(Method m) {
262
        Class<?>[] ex = m.getExceptionTypes();
D
duke 已提交
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
        for (int i = 0; i < ex.length; i++) {
            if (ex[i].isAssignableFrom(RemoteException.class))
                return;
        }
        throw new IllegalArgumentException(
            "illegal remote method encountered: " + m);
    }

    /**
     * Creates a RemoteStub instance for the specified class, constructed
     * with the specified RemoteRef.  The supplied class must be the most
     * derived class in the remote object's superclass chain that
     * implements a remote interface.  The stub class name is the name of
     * the specified remoteClass with the suffix "_Stub".  The loading of
     * the stub class is initiated from class loader of the specified class
     * (which may be the bootstrap class loader).
     **/
280
    private static RemoteStub createStub(Class<?> remoteClass, RemoteRef ref)
D
duke 已提交
281 282 283 284 285 286 287 288 289 290
        throws StubNotFoundException
    {
        String stubname = remoteClass.getName() + "_Stub";

        /* Make sure to use the local stub loader for the stub classes.
         * When loaded by the local loader the load path can be
         * propagated to remote clients, by the MarshalOutputStream/InStream
         * pickle methods
         */
        try {
291
            Class<?> stubcl =
D
duke 已提交
292
                Class.forName(stubname, false, remoteClass.getClassLoader());
293
            Constructor<?> cons = stubcl.getConstructor(stubConsParamTypes);
D
duke 已提交
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322
            return (RemoteStub) cons.newInstance(new Object[] { ref });

        } catch (ClassNotFoundException e) {
            throw new StubNotFoundException(
                "Stub class not found: " + stubname, e);
        } catch (NoSuchMethodException e) {
            throw new StubNotFoundException(
                "Stub class missing constructor: " + stubname, e);
        } catch (InstantiationException e) {
            throw new StubNotFoundException(
                "Can't create instance of stub class: " + stubname, e);
        } catch (IllegalAccessException e) {
            throw new StubNotFoundException(
                "Stub class constructor not public: " + stubname, e);
        } catch (InvocationTargetException e) {
            throw new StubNotFoundException(
                "Exception creating instance of stub class: " + stubname, e);
        } catch (ClassCastException e) {
            throw new StubNotFoundException(
                "Stub class not instance of RemoteStub: " + stubname, e);
        }
    }

    /**
     * Locate and return the Skeleton for the specified remote object
     */
    static Skeleton createSkeleton(Remote object)
        throws SkeletonNotFoundException
    {
323
        Class<?> cl;
D
duke 已提交
324 325 326 327 328 329 330 331 332 333 334
        try {
            cl = getRemoteClass(object.getClass());
        } catch (ClassNotFoundException ex ) {
            throw new SkeletonNotFoundException(
                "object does not implement a remote interface: " +
                object.getClass().getName());
        }

        // now try to load the skeleton based ont he name of the class
        String skelname = cl.getName() + "_Skel";
        try {
335
            Class<?> skelcl = Class.forName(skelname, false, cl.getClassLoader());
D
duke 已提交
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398

            return (Skeleton)skelcl.newInstance();
        } catch (ClassNotFoundException ex) {
            throw new SkeletonNotFoundException("Skeleton class not found: " +
                                                skelname, ex);
        } catch (InstantiationException ex) {
            throw new SkeletonNotFoundException("Can't create skeleton: " +
                                                skelname, ex);
        } catch (IllegalAccessException ex) {
            throw new SkeletonNotFoundException("No public constructor: " +
                                                skelname, ex);
        } catch (ClassCastException ex) {
            throw new SkeletonNotFoundException(
                "Skeleton not of correct class: " + skelname, ex);
        }
    }

    /**
     * Compute the "method hash" of a remote method.  The method hash
     * is a long containing the first 64 bits of the SHA digest from
     * the UTF encoded string of the method name and descriptor.
     */
    public static long computeMethodHash(Method m) {
        long hash = 0;
        ByteArrayOutputStream sink = new ByteArrayOutputStream(127);
        try {
            MessageDigest md = MessageDigest.getInstance("SHA");
            DataOutputStream out = new DataOutputStream(
                new DigestOutputStream(sink, md));

            String s = getMethodNameAndDescriptor(m);
            if (serverRefLog.isLoggable(Log.VERBOSE)) {
                serverRefLog.log(Log.VERBOSE,
                    "string used for method hash: \"" + s + "\"");
            }
            out.writeUTF(s);

            // use only the first 64 bits of the digest for the hash
            out.flush();
            byte hasharray[] = md.digest();
            for (int i = 0; i < Math.min(8, hasharray.length); i++) {
                hash += ((long) (hasharray[i] & 0xFF)) << (i * 8);
            }
        } catch (IOException ignore) {
            /* can't happen, but be deterministic anyway. */
            hash = -1;
        } catch (NoSuchAlgorithmException complain) {
            throw new SecurityException(complain.getMessage());
        }
        return hash;
    }

    /**
     * Return a string consisting of the given method's name followed by
     * its "method descriptor", as appropriate for use in the computation
     * of the "method hash".
     *
     * See section 4.3.3 of The Java Virtual Machine Specification for
     * the definition of a "method descriptor".
     */
    private static String getMethodNameAndDescriptor(Method m) {
        StringBuffer desc = new StringBuffer(m.getName());
        desc.append('(');
399
        Class<?>[] paramTypes = m.getParameterTypes();
D
duke 已提交
400 401 402 403
        for (int i = 0; i < paramTypes.length; i++) {
            desc.append(getTypeDescriptor(paramTypes[i]));
        }
        desc.append(')');
404
        Class<?> returnType = m.getReturnType();
D
duke 已提交
405 406 407 408 409 410 411 412 413 414 415 416
        if (returnType == void.class) { // optimization: handle void here
            desc.append('V');
        } else {
            desc.append(getTypeDescriptor(returnType));
        }
        return desc.toString();
    }

    /**
     * Get the descriptor of a particular type, as appropriate for either
     * a parameter or return type in a method descriptor.
     */
417
    private static String getTypeDescriptor(Class<?> type) {
D
duke 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461
        if (type.isPrimitive()) {
            if (type == int.class) {
                return "I";
            } else if (type == boolean.class) {
                return "Z";
            } else if (type == byte.class) {
                return "B";
            } else if (type == char.class) {
                return "C";
            } else if (type == short.class) {
                return "S";
            } else if (type == long.class) {
                return "J";
            } else if (type == float.class) {
                return "F";
            } else if (type == double.class) {
                return "D";
            } else if (type == void.class) {
                return "V";
            } else {
                throw new Error("unrecognized primitive type: " + type);
            }
        } else if (type.isArray()) {
            /*
             * According to JLS 20.3.2, the getName() method on Class does
             * return the VM type descriptor format for array classes (only);
             * using that should be quicker than the otherwise obvious code:
             *
             *     return "[" + getTypeDescriptor(type.getComponentType());
             */
            return type.getName().replace('.', '/');
        } else {
            return "L" + type.getName().replace('.', '/') + ";";
        }
    }

    /**
     * Returns the binary name of the given type without package
     * qualification.  Nested types are treated no differently from
     * top-level types, so for a nested type, the returned name will
     * still be qualified with the simple name of its enclosing
     * top-level type (and perhaps other enclosing types), the
     * separator will be '$', etc.
     **/
462
    public static String getUnqualifiedName(Class<?> c) {
D
duke 已提交
463 464 465 466
        String binaryName = c.getName();
        return binaryName.substring(binaryName.lastIndexOf('.') + 1);
    }
}