MarshalInputStream.java 11.6 KB
Newer Older
D
duke 已提交
1
/*
S
sjiang 已提交
2
 * Copyright (c) 1996, 2016, 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 51 52 53 54 55
 */

package sun.rmi.server;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;
import java.io.StreamCorruptedException;
import java.util.*;
import java.security.AccessControlException;
import java.security.Permission;
import java.rmi.server.RMIClassLoader;

/**
 * MarshalInputStream is an extension of ObjectInputStream.  When resolving
 * a class, it reads an object from the stream written by a corresponding
 * MarshalOutputStream.  If the class to be resolved is not available
 * locally, from the first class loader on the execution stack, or from the
 * context class loader of the current thread, it will attempt to load the
 * class from the location annotated by the sending MarshalOutputStream.
 * This location object must be a string representing a path of URLs.
 *
 * A new MarshalInputStream should be created to deserialize remote objects or
 * graphs containing remote objects.  Objects are created from the stream
 * using the ObjectInputStream.readObject method.
 *
 * @author      Peter Jones
 */
public class MarshalInputStream extends ObjectInputStream {

    /**
S
smarks 已提交
56
     * Value of "java.rmi.server.useCodebaseOnly" property,
D
duke 已提交
57
     * as cached at class initialization time.
S
smarks 已提交
58 59 60 61 62
     *
     * The default value is true. That is, the value is true
     * if the property is absent or is not equal to "false".
     * The value is only false when the property is present
     * and is equal to "false".
D
duke 已提交
63 64
     */
    private static final boolean useCodebaseOnlyProperty =
S
smarks 已提交
65 66 67 68
        ! java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction(
                "java.rmi.server.useCodebaseOnly", "true"))
            .equalsIgnoreCase("false");
D
duke 已提交
69 70

    /** table to hold sun classes to which access is explicitly permitted */
71
    protected static Map<String, Class<?>> permittedSunClasses
72
        = new HashMap<>(3);
D
duke 已提交
73 74 75 76 77

    /** if true, don't try superclass first in resolveClass() */
    private boolean skipDefaultResolveClass = false;

    /** callbacks to make when done() called: maps Object to Runnable */
78
    private final Map<Object, Runnable> doneCallbacks
79
        = new HashMap<>(3);
D
duke 已提交
80 81 82 83 84 85 86 87 88 89 90 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

    /**
     * if true, load classes (if not available locally) only from the
     * URL specified by the "java.rmi.server.codebase" property.
     */
    private boolean useCodebaseOnly = useCodebaseOnlyProperty;

    /*
     * Fix for 4179055: The remote object services inside the
     * activation daemon use stubs that are in the package
     * sun.rmi.server.  Classes for these stubs should be loaded from
     * the classpath by RMI system code and not by the normal
     * unmarshalling process as applications should not need to have
     * permission to access the sun implementation classes.
     *
     * Note: this fix should be redone when API changes may be
     * integrated
     *
     * During parameter unmarshalling RMI needs to explicitly permit
     * access to three sun.* stub classes
     */
    static {
        try {
            String system =
                "sun.rmi.server.Activation$ActivationSystemImpl_Stub";
            String registry = "sun.rmi.registry.RegistryImpl_Stub";

            permittedSunClasses.put(system, Class.forName(system));
            permittedSunClasses.put(registry, Class.forName(registry));

        } catch (ClassNotFoundException e) {
            throw new NoClassDefFoundError("Missing system class: " +
                                           e.getMessage());
        }
    }

    /**
     * Create a new MarshalInputStream object.
     */
    public MarshalInputStream(InputStream in)
        throws IOException, StreamCorruptedException
    {
        super(in);
S
sjiang 已提交
123
                    }
D
duke 已提交
124 125 126 127 128 129 130

    /**
     * Returns a callback previously registered via the setDoneCallback
     * method with given key, or null if no callback has yet been registered
     * with that key.
     */
    public Runnable getDoneCallback(Object key) {
131
        return doneCallbacks.get(key);                 // not thread-safe
D
duke 已提交
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
    }

    /**
     * Registers a callback to make when this stream's done() method is
     * invoked, along with a key for retrieving the same callback instance
     * subsequently from the getDoneCallback method.
     */
    public void setDoneCallback(Object key, Runnable callback) {
        //assert(!doneCallbacks.contains(key));
        doneCallbacks.put(key, callback);               // not thread-safe
    }

    /**
     * Indicates that the user of this MarshalInputStream is done reading
     * objects from it, so all callbacks registered with the setDoneCallback
     * method should now be (synchronously) executed.  When this method
     * returns, there are no more callbacks registered.
     *
     * This method is implicitly invoked by close() before it delegates to
     * the superclass's close method.
     */
    public void done() {
154
        Iterator<Runnable> iter = doneCallbacks.values().iterator();
D
duke 已提交
155
        while (iter.hasNext()) {                        // not thread-safe
156
            Runnable callback = iter.next();
D
duke 已提交
157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
            callback.run();
        }
        doneCallbacks.clear();
    }

    /**
     * Closes this stream, implicitly invoking done() first.
     */
    public void close() throws IOException {
        done();
        super.close();
    }

    /**
     * resolveClass is extended to acquire (if present) the location
     * from which to load the specified class.
     * It will find, load, and return the class.
     */
175
    protected Class<?> resolveClass(ObjectStreamClass classDesc)
D
duke 已提交
176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236
        throws IOException, ClassNotFoundException
    {
        /*
         * Always read annotation written by MarshalOutputStream
         * describing where to load class from.
         */
        Object annotation = readLocation();

        String className = classDesc.getName();

        /*
         * Unless we were told to skip this consideration, choose the
         * "default loader" to simulate the default ObjectInputStream
         * resolveClass mechanism (that is, choose the first non-null
         * loader on the execution stack) to maximize the likelihood of
         * type compatibility with calling code.  (This consideration
         * is skipped during server parameter unmarshalling using the 1.2
         * stub protocol, because there would never be a non-null class
         * loader on the stack in that situation anyway.)
         */
        ClassLoader defaultLoader =
            skipDefaultResolveClass ? null : latestUserDefinedLoader();

        /*
         * If the "java.rmi.server.useCodebaseOnly" property was true or
         * useCodebaseOnly() was called or the annotation is not a String,
         * load from the local loader using the "java.rmi.server.codebase"
         * URL.  Otherwise, load from a loader using the codebase URL in
         * the annotation.
         */
        String codebase = null;
        if (!useCodebaseOnly && annotation instanceof String) {
            codebase = (String) annotation;
        }

        try {
            return RMIClassLoader.loadClass(codebase, className,
                                            defaultLoader);
        } catch (AccessControlException e) {
            return checkSunClass(className, e);
        } catch (ClassNotFoundException e) {
            /*
             * Fix for 4442373: delegate to ObjectInputStream.resolveClass()
             * to resolve primitive classes.
             */
            try {
                if (Character.isLowerCase(className.charAt(0)) &&
                    className.indexOf('.') == -1)
                {
                    return super.resolveClass(classDesc);
                }
            } catch (ClassNotFoundException e2) {
            }
            throw e;
        }
    }

    /**
     * resolveProxyClass is extended to acquire (if present) the location
     * to determine the class loader to define the proxy class in.
     */
237
    protected Class<?> resolveProxyClass(String[] interfaces)
D
duke 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
        throws IOException, ClassNotFoundException
    {
        /*
         * Always read annotation written by MarshalOutputStream.
         */
        Object annotation = readLocation();

        ClassLoader defaultLoader =
            skipDefaultResolveClass ? null : latestUserDefinedLoader();

        String codebase = null;
        if (!useCodebaseOnly && annotation instanceof String) {
            codebase = (String) annotation;
        }

        return RMIClassLoader.loadProxyClass(codebase, interfaces,
                                             defaultLoader);
    }

    /*
     * Returns the first non-null class loader up the execution stack, or null
     * if only code from the null class loader is on the stack.
     */
261 262 263
    private static ClassLoader latestUserDefinedLoader() {
        return sun.misc.VM.latestUserDefinedLoader();
    }
D
duke 已提交
264 265 266 267 268

    /**
     * Fix for 4179055: Need to assist resolving sun stubs; resolve
     * class locally if it is a "permitted" sun class
     */
269
    private Class<?> checkSunClass(String className, AccessControlException e)
D
duke 已提交
270 271 272 273 274 275 276 277 278
        throws AccessControlException
    {
        // ensure that we are giving out a stub for the correct reason
        Permission perm = e.getPermission();
        String name = null;
        if (perm != null) {
            name = perm.getName();
        }

279
        Class<?> resolvedClass = permittedSunClasses.get(className);
D
duke 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 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

        // if class not permitted, throw the SecurityException
        if ((name == null) ||
            (resolvedClass == null) ||
            ((!name.equals("accessClassInPackage.sun.rmi.server")) &&
            (!name.equals("accessClassInPackage.sun.rmi.registry"))))
        {
            throw e;
        }

        return resolvedClass;
    }

    /**
     * Return the location for the class in the stream.  This method can
     * be overridden by subclasses that store this annotation somewhere
     * else than as the next object in the stream, as is done by this class.
     */
    protected Object readLocation()
        throws IOException, ClassNotFoundException
    {
        return readObject();
    }

    /**
     * Set a flag to indicate that the superclass's default resolveClass()
     * implementation should not be invoked by our resolveClass().
     */
    void skipDefaultResolveClass() {
        skipDefaultResolveClass = true;
    }

    /**
     * Disable code downloading except from the URL specified by the
     * "java.rmi.server.codebase" property.
     */
    void useCodebaseOnly() {
        useCodebaseOnly = true;
    }
}