MarshalInputStream.java 12.8 KB
Newer Older
D
duke 已提交
1
/*
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
 */

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;
37 38
import sun.misc.ObjectStreamClassValidator;
import sun.misc.SharedSecrets;
D
duke 已提交
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55

/**
 * 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 {
56 57 58 59 60
    interface StreamChecker extends ObjectStreamClassValidator {
        void checkProxyInterfaceNames(String[] ifaces);
    }

    private volatile StreamChecker streamChecker = null;
D
duke 已提交
61 62

    /**
S
smarks 已提交
63
     * Value of "java.rmi.server.useCodebaseOnly" property,
D
duke 已提交
64
     * as cached at class initialization time.
S
smarks 已提交
65 66 67 68 69
     *
     * 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 已提交
70 71
     */
    private static final boolean useCodebaseOnlyProperty =
S
smarks 已提交
72 73 74 75
        ! java.security.AccessController.doPrivileged(
            new sun.security.action.GetPropertyAction(
                "java.rmi.server.useCodebaseOnly", "true"))
            .equalsIgnoreCase("false");
D
duke 已提交
76 77

    /** table to hold sun classes to which access is explicitly permitted */
78
    protected static Map<String, Class<?>> permittedSunClasses
79
        = new HashMap<>(3);
D
duke 已提交
80 81 82 83 84

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

    /** callbacks to make when done() called: maps Object to Runnable */
85
    private final Map<Object, Runnable> doneCallbacks
86
        = new HashMap<>(3);
D
duke 已提交
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 123 124 125 126 127 128 129

    /**
     * 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 已提交
130
                    }
D
duke 已提交
131 132 133 134 135 136 137

    /**
     * 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) {
138
        return doneCallbacks.get(key);                 // not thread-safe
D
duke 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
    }

    /**
     * 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() {
161
        Iterator<Runnable> iter = doneCallbacks.values().iterator();
D
duke 已提交
162
        while (iter.hasNext()) {                        // not thread-safe
163
            Runnable callback = iter.next();
D
duke 已提交
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181
            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.
     */
182
    protected Class<?> resolveClass(ObjectStreamClass classDesc)
D
duke 已提交
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 237 238 239 240 241 242 243
        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.
     */
244
    protected Class<?> resolveProxyClass(String[] interfaces)
D
duke 已提交
245 246
        throws IOException, ClassNotFoundException
    {
247 248 249 250 251
        StreamChecker checker = streamChecker;
        if (checker != null) {
            checker.checkProxyInterfaceNames(interfaces);
        }

D
duke 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        /*
         * 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);
    }

    /*
270 271 272 273
     * Returns first non-privileged class loader on the stack (excluding
     * reflection generated frames) or the extension class loader if only
     * class loaded by the boot class loader and extension class loader are
     * found on the stack.
D
duke 已提交
274
     */
275 276 277
    private static ClassLoader latestUserDefinedLoader() {
        return sun.misc.VM.latestUserDefinedLoader();
    }
D
duke 已提交
278 279 280 281 282

    /**
     * Fix for 4179055: Need to assist resolving sun stubs; resolve
     * class locally if it is a "permitted" sun class
     */
283
    private Class<?> checkSunClass(String className, AccessControlException e)
D
duke 已提交
284 285 286 287 288 289 290 291 292
        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();
        }

293
        Class<?> resolvedClass = permittedSunClasses.get(className);
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 323 324 325 326 327 328 329 330 331 332

        // 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;
    }
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

    synchronized void setStreamChecker(StreamChecker checker) {
        streamChecker = checker;
        SharedSecrets.getJavaObjectInputStreamAccess().setValidator(this, checker);
    }
    @Override
    protected ObjectStreamClass readClassDescriptor() throws IOException,
            ClassNotFoundException {
        ObjectStreamClass descriptor = super.readClassDescriptor();

        validateDesc(descriptor);

        return descriptor;
    }

    private void validateDesc(ObjectStreamClass descriptor) {
        StreamChecker checker;
        synchronized (this) {
            checker = streamChecker;
        }
        if (checker != null) {
            checker.validateDescriptor(descriptor);
        }
    }
D
duke 已提交
357
}