UnicastServerRef.java 22.4 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 1996, 2017, 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
 */

package sun.rmi.server;

import java.io.IOException;
import java.io.ObjectInput;
R
rriggs 已提交
30
import java.io.ObjectInputStream;
D
duke 已提交
31 32 33
import java.io.ObjectOutput;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
34
import java.rmi.AccessException;
D
duke 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
import java.rmi.MarshalException;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.ServerError;
import java.rmi.ServerException;
import java.rmi.UnmarshalException;
import java.rmi.server.ExportException;
import java.rmi.server.RemoteCall;
import java.rmi.server.RemoteRef;
import java.rmi.server.RemoteStub;
import java.rmi.server.ServerNotActiveException;
import java.rmi.server.ServerRef;
import java.rmi.server.Skeleton;
import java.rmi.server.SkeletonNotFoundException;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.WeakHashMap;
S
sjiang 已提交
56
import java.util.concurrent.atomic.AtomicInteger;
R
rriggs 已提交
57
import sun.misc.ObjectInputFilter;
D
duke 已提交
58 59
import sun.rmi.runtime.Log;
import sun.rmi.transport.LiveRef;
C
coffeys 已提交
60
import sun.rmi.transport.StreamRemoteCall;
D
duke 已提交
61 62 63 64 65 66 67 68
import sun.rmi.transport.Target;
import sun.rmi.transport.tcp.TCPTransport;
import sun.security.action.GetBooleanAction;

/**
 * UnicastServerRef implements the remote reference layer server-side
 * behavior for remote objects exported with the "UnicastRef" reference
 * type.
R
rriggs 已提交
69 70 71 72
 * If an {@link ObjectInputFilter ObjectInputFilter} is supplied it is
 * invoked during deserialization to filter the arguments,
 * otherwise the default filter of {@link ObjectInputStream ObjectInputStream}
 * applies.
D
duke 已提交
73 74 75 76 77
 *
 * @author  Ann Wollrath
 * @author  Roger Riggs
 * @author  Peter Jones
 */
78
@SuppressWarnings("deprecation")
D
duke 已提交
79 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
public class UnicastServerRef extends UnicastRef
    implements ServerRef, Dispatcher
{
    /** value of server call log property */
    public static final boolean logCalls = AccessController.doPrivileged(
        new GetBooleanAction("java.rmi.server.logCalls"));

    /** server call log */
    public static final Log callLog =
        Log.getLog("sun.rmi.server.call", "RMI", logCalls);

    // use serialVersionUID from JDK 1.2.2 for interoperability
    private static final long serialVersionUID = -7384275867073752268L;

    /** flag to enable writing exceptions to System.err */
    private static final boolean wantExceptionLog =
        AccessController.doPrivileged(
            new GetBooleanAction("sun.rmi.server.exceptionTrace"));

    private boolean forceStubUse = false;

    /**
     * flag to remove server-side stack traces before marshalling
     * exceptions thrown by remote invocations to this VM
     */
    private static final boolean suppressStackTraces =
        AccessController.doPrivileged(
            new GetBooleanAction(
                "sun.rmi.server.suppressStackTraces"));

    /**
     * skeleton to dispatch remote calls through, for 1.1 stub protocol
     * (may be null if stub class only uses 1.2 stub protocol)
     */
    private transient Skeleton skel;

R
rriggs 已提交
115 116 117
    // The ObjectInputFilter for checking the invocation arguments
    private final transient ObjectInputFilter filter;

D
duke 已提交
118 119 120 121 122 123 124 125 126 127 128 129 130 131
    /** maps method hash to Method object for each remote method */
    private transient Map<Long,Method> hashToMethod_Map = null;

    /**
     * A weak hash map, mapping classes to hash maps that map method
     * hashes to method objects.
     **/
    private static final WeakClassHashMap<Map<Long,Method>> hashToMethod_Maps =
        new HashToMethod_Maps();

    /** cache of impl classes that have no corresponding skeleton class */
    private static final Map<Class<?>,?> withoutSkeletons =
        Collections.synchronizedMap(new WeakHashMap<Class<?>,Void>());

S
sjiang 已提交
132 133
    private final AtomicInteger methodCallIDCount = new AtomicInteger(0);

D
duke 已提交
134 135
    /**
     * Create a new (empty) Unicast server remote reference.
R
rriggs 已提交
136
     * The filter is null to defer to the  default ObjectInputStream filter, if any.
D
duke 已提交
137 138
     */
    public UnicastServerRef() {
R
rriggs 已提交
139
        this.filter = null;
D
duke 已提交
140 141 142 143 144
    }

    /**
     * Construct a Unicast server remote reference for a specified
     * liveRef.
R
rriggs 已提交
145
     * The filter is null to defer to the  default ObjectInputStream filter, if any.
D
duke 已提交
146 147 148
     */
    public UnicastServerRef(LiveRef ref) {
        super(ref);
R
rriggs 已提交
149 150 151 152 153 154 155 156 157 158
        this.filter = null;
    }

    /**
     * Construct a Unicast server remote reference for a specified
     * liveRef and filter.
     */
    public UnicastServerRef(LiveRef ref, ObjectInputFilter filter) {
        super(ref);
        this.filter = filter;
D
duke 已提交
159 160 161 162 163 164 165 166
    }

    /**
     * Construct a Unicast server remote reference to be exported
     * on the specified port.
     */
    public UnicastServerRef(int port) {
        super(new LiveRef(port));
R
rriggs 已提交
167
        this.filter = null;
D
duke 已提交
168 169 170 171 172 173 174 175 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
    }

    /**
     * Constructs a UnicastServerRef to be exported on an
     * anonymous port (i.e., 0) and that uses a pregenerated stub class
     * (NOT a dynamic proxy instance) if 'forceStubUse' is 'true'.
     *
     * This constructor is only called by the method
     * UnicastRemoteObject.exportObject(Remote) passing 'true' for
     * 'forceStubUse'.  The UnicastRemoteObject.exportObject(Remote) method
     * returns RemoteStub, so it must ensure that the stub for the
     * exported object is an instance of a pregenerated stub class that
     * extends RemoteStub (instead of an instance of a dynamic proxy class
     * which is not an instance of RemoteStub).
     **/
    public UnicastServerRef(boolean forceStubUse) {
        this(0);
        this.forceStubUse = forceStubUse;
    }

    /**
     * With the addition of support for dynamic proxies as stubs, this
     * method is obsolete because it returns RemoteStub instead of the more
     * general Remote.  It should not be called.  It sets the
     * 'forceStubUse' flag to true so that the stub for the exported object
     * is forced to be an instance of the pregenerated stub class, which
     * extends RemoteStub.
     *
     * Export this object, create the skeleton and stubs for this
     * dispatcher.  Create a stub based on the type of the impl,
     * initialize it with the appropriate remote reference. Create the
     * target defined by the impl, dispatcher (this) and stub.
     * Export that target via the Ref.
     **/
    public RemoteStub exportObject(Remote impl, Object data)
        throws RemoteException
    {
        forceStubUse = true;
        return (RemoteStub) exportObject(impl, data, false);
    }

    /**
     * Export this object, create the skeleton and stubs for this
     * dispatcher.  Create a stub based on the type of the impl,
     * initialize it with the appropriate remote reference. Create the
     * target defined by the impl, dispatcher (this) and stub.
     * Export that target via the Ref.
     */
    public Remote exportObject(Remote impl, Object data,
                               boolean permanent)
        throws RemoteException
    {
220
        Class<?> implClass = impl.getClass();
D
duke 已提交
221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 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 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
        Remote stub;

        try {
            stub = Util.createProxy(implClass, getClientRef(), forceStubUse);
        } catch (IllegalArgumentException e) {
            throw new ExportException(
                "remote object implements illegal remote interface", e);
        }
        if (stub instanceof RemoteStub) {
            setSkeleton(impl);
        }

        Target target =
            new Target(impl, this, stub, ref.getObjID(), permanent);
        ref.exportObject(target);
        hashToMethod_Map = hashToMethod_Maps.get(implClass);
        return stub;
    }

    /**
     * Return the hostname of the current client.  When called from a
     * thread actively handling a remote method invocation the
     * hostname of the client is returned.
     * @exception ServerNotActiveException If called outside of servicing
     * a remote method invocation.
     */
    public String getClientHost() throws ServerNotActiveException {
        return TCPTransport.getClientHost();
    }

    /**
     * Discovers and sets the appropriate skeleton for the impl.
     */
    public void setSkeleton(Remote impl) throws RemoteException {
        if (!withoutSkeletons.containsKey(impl.getClass())) {
            try {
                skel = Util.createSkeleton(impl);
            } catch (SkeletonNotFoundException e) {
                /*
                 * Ignore exception for skeleton class not found, because a
                 * skeleton class is not necessary with the 1.2 stub protocol.
                 * Remember that this impl's class does not have a skeleton
                 * class so we don't waste time searching for it again.
                 */
                withoutSkeletons.put(impl.getClass(), null);
            }
        }
    }

    /**
     * Call to dispatch to the remote object (on the server side).
     * The up-call to the server and the marshalling of return result
     * (or exception) should be handled before returning from this
     * method.
     * @param obj the target remote object for the call
     * @param call the "remote call" from which operation and
     * method arguments can be obtained.
     * @exception IOException If unable to marshal return result or
     * release input or output streams
     */
    public void dispatch(Remote obj, RemoteCall call) throws IOException {
        // positive operation number in 1.1 stubs;
        // negative version number in 1.2 stubs and beyond...
        int num;
        long op;

        try {
            // read remote call header
            ObjectInput in;
            try {
                in = call.getInputStream();
                num = in.readInt();
293 294 295 296 297 298 299 300 301 302 303 304
            } catch (Exception readEx) {
                throw new UnmarshalException("error unmarshalling call header",
                                             readEx);
            }
            if (num >= 0) {
                if (skel != null) {
                    oldDispatch(obj, call, num);
                    return;
                } else {
                    throw new UnmarshalException(
                        "skeleton class not found but required " +
                        "for client version");
D
duke 已提交
305
                }
306 307
            }
            try {
D
duke 已提交
308 309 310
                op = in.readLong();
            } catch (Exception readEx) {
                throw new UnmarshalException("error unmarshalling call header",
311
                        readEx);
D
duke 已提交
312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
            }

            /*
             * Since only system classes (with null class loaders) will be on
             * the execution stack during parameter unmarshalling for the 1.2
             * stub protocol, tell the MarshalInputStream not to bother trying
             * to resolve classes using its superclasses's default method of
             * consulting the first non-null class loader on the stack.
             */
            MarshalInputStream marshalStream = (MarshalInputStream) in;
            marshalStream.skipDefaultResolveClass();

            Method method = hashToMethod_Map.get(op);
            if (method == null) {
                throw new UnmarshalException("unrecognized method hash: " +
                    "method not supported by remote object");
            }

            // if calls are being logged, write out object id and operation
            logCall(obj, method);

            // unmarshal parameters
334 335
            Class<?>[] types = method.getParameterTypes();
            Object[] params = new Object[types.length];
D
duke 已提交
336 337 338

            try {
                unmarshalCustomCallData(in);
339 340 341 342 343
                // Unmarshal the parameters
                for (int i = 0; i < types.length; i++) {
                    params[i] = unmarshalValue(types[i], in);
                }

344 345 346 347 348
            } catch (AccessException aex) {
                // For compatibility, AccessException is not wrapped in UnmarshalException
                // disable saving any refs in the inputStream for GC
                ((StreamRemoteCall) call).discardPendingRefs();
                throw aex;
C
coffeys 已提交
349 350 351
            } catch (java.io.IOException | ClassNotFoundException e) {
                // disable saving any refs in the inputStream for GC
                ((StreamRemoteCall) call).discardPendingRefs();
D
duke 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368
                throw new UnmarshalException(
                    "error unmarshalling arguments", e);
            } finally {
                call.releaseInputStream();
            }

            // make upcall on remote object
            Object result;
            try {
                result = method.invoke(obj, params);
            } catch (InvocationTargetException e) {
                throw e.getTargetException();
            }

            // marshal return value
            try {
                ObjectOutput out = call.getResultStream(true);
369
                Class<?> rtype = method.getReturnType();
D
duke 已提交
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
                if (rtype != void.class) {
                    marshalValue(rtype, result, out);
                }
            } catch (IOException ex) {
                throw new MarshalException("error marshalling return", ex);
                /*
                 * This throw is problematic because when it is caught below,
                 * we attempt to marshal it back to the client, but at this
                 * point, a "normal return" has already been indicated,
                 * so marshalling an exception will corrupt the stream.
                 * This was the case with skeletons as well; there is no
                 * immediately obvious solution without a protocol change.
                 */
            }
        } catch (Throwable e) {
385
            Throwable origEx = e;
D
duke 已提交
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400
            logCallException(e);

            ObjectOutput out = call.getResultStream(false);
            if (e instanceof Error) {
                e = new ServerError(
                    "Error occurred in server thread", (Error) e);
            } else if (e instanceof RemoteException) {
                e = new ServerException(
                    "RemoteException occurred in server thread",
                    (Exception) e);
            }
            if (suppressStackTraces) {
                clearStackTraces(e);
            }
            out.writeObject(e);
401 402 403 404 405 406

            // AccessExceptions should cause Transport.serviceCall
            // to flag the connection as unusable.
            if (origEx instanceof AccessException) {
                throw new IOException("Connection is not reusable", origEx);
            }
D
duke 已提交
407 408 409 410 411 412
        } finally {
            call.releaseInputStream(); // in case skeleton doesn't
            call.releaseOutputStream();
        }
    }

R
rriggs 已提交
413 414 415 416
    /**
     * Sets a filter for invocation arguments, if a filter has been set.
     * Called by dispatch before the arguments are read.
     */
D
duke 已提交
417
    protected void unmarshalCustomCallData(ObjectInput in)
R
rriggs 已提交
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
            throws IOException, ClassNotFoundException {
        if (filter != null &&
                in instanceof ObjectInputStream) {
            // Set the filter on the stream
            ObjectInputStream ois = (ObjectInputStream) in;

            AccessController.doPrivileged(new PrivilegedAction<Void>() {
                @Override
                public Void run() {
                    ObjectInputFilter.Config.setObjectInputFilter(ois, filter);
                    return null;
                }
            });
        }
    }
D
duke 已提交
433 434 435 436 437

    /**
     * Handle server-side dispatch using the RMI 1.1 stub/skeleton
     * protocol, given a non-negative operation number that has
     * already been read from the call stream.
438
     * Exceptions are handled by the caller to be sent to the remote client.
D
duke 已提交
439 440 441 442 443
     *
     * @param obj the target remote object for the call
     * @param call the "remote call" from which operation and
     * method arguments can be obtained.
     * @param op the operation number
444
     * @throws Exception if unable to marshal return result or
D
duke 已提交
445 446
     * release input or output streams
     */
447 448
    private void oldDispatch(Remote obj, RemoteCall call, int op)
        throws Exception
D
duke 已提交
449 450 451
    {
        long hash;              // hash for matching stub with skeleton

452 453 454
        // read remote call header
        ObjectInput in;
        in = call.getInputStream();
D
duke 已提交
455
        try {
456 457 458
            Class<?> clazz = Class.forName("sun.rmi.transport.DGCImpl_Skel");
            if (clazz.isAssignableFrom(skel.getClass())) {
                ((MarshalInputStream)in).useCodebaseOnly();
D
duke 已提交
459
            }
460
        } catch (ClassNotFoundException ignore) { }
D
duke 已提交
461

462 463 464 465
        try {
            hash = in.readLong();
        } catch (Exception ioe) {
            throw new UnmarshalException("error unmarshalling call header", ioe);
D
duke 已提交
466
        }
467 468 469 470 471 472

        // if calls are being logged, write out object id and operation
        logCall(obj, skel.getOperations()[op]);
        unmarshalCustomCallData(in);
        // dispatch to skeleton for remote object
        skel.dispatch(obj, call, op, hash);
D
duke 已提交
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581
    }

    /**
     * Clear the stack trace of the given Throwable by replacing it with
     * an empty StackTraceElement array, and do the same for all of its
     * chained causative exceptions.
     */
    public static void clearStackTraces(Throwable t) {
        StackTraceElement[] empty = new StackTraceElement[0];
        while (t != null) {
            t.setStackTrace(empty);
            t = t.getCause();
        }
    }

    /**
     * Log the details of an incoming call.  The method parameter is either of
     * type java.lang.reflect.Method or java.rmi.server.Operation.
     */
    private void logCall(Remote obj, Object method) {
        if (callLog.isLoggable(Log.VERBOSE)) {
            String clientHost;
            try {
                clientHost = getClientHost();
            } catch (ServerNotActiveException snae) {
                clientHost = "(local)"; // shouldn't happen
            }
            callLog.log(Log.VERBOSE, "[" + clientHost + ": " +
                              obj.getClass().getName() +
                              ref.getObjID().toString() + ": " +
                              method + "]");
        }
    }

    /**
     * Log the exception detail of an incoming call.
     */
    private void logCallException(Throwable e) {
        // if calls are being logged, log them
        if (callLog.isLoggable(Log.BRIEF)) {
            String clientHost = "";
            try {
                clientHost = "[" + getClientHost() + "] ";
            } catch (ServerNotActiveException snae) {
            }
            callLog.log(Log.BRIEF, clientHost + "exception: ", e);
        }

        // write exceptions (only) to System.err if desired
        if (wantExceptionLog) {
            java.io.PrintStream log = System.err;
            synchronized (log) {
                log.println();
                log.println("Exception dispatching call to " +
                            ref.getObjID() + " in thread \"" +
                            Thread.currentThread().getName() +
                            "\" at " + (new Date()) + ":");
                e.printStackTrace(log);
            }
        }
    }

    /**
     * Returns the class of the ref type to be serialized.
     */
    public String getRefClass(ObjectOutput out) {
        return "UnicastServerRef";
    }

    /**
     * Return the client remote reference for this remoteRef.
     * In the case of a client RemoteRef "this" is the answer.
     * For a server remote reference, a client side one will have to
     * found or created.
     */
    protected RemoteRef getClientRef() {
        return new UnicastRef(ref);
    }

    /**
     * Write out external representation for remote ref.
     */
    public void writeExternal(ObjectOutput out) throws IOException {
    }

    /**
     * Read in external representation for remote ref.
     * @exception ClassNotFoundException If the class for an object
     * being restored cannot be found.
     */
    public void readExternal(ObjectInput in)
        throws IOException, ClassNotFoundException
    {
        // object is re-exported elsewhere (e.g., by UnicastRemoteObject)
        ref = null;
        skel = null;
    }


    /**
     * A weak hash map, mapping classes to hash maps that map method
     * hashes to method objects.
     **/
    private static class HashToMethod_Maps
        extends WeakClassHashMap<Map<Long,Method>>
    {
        HashToMethod_Maps() {}

        protected Map<Long,Method> computeValue(Class<?> remoteClass) {
582
            Map<Long,Method> map = new HashMap<>();
D
duke 已提交
583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610
            for (Class<?> cl = remoteClass;
                 cl != null;
                 cl = cl.getSuperclass())
            {
                for (Class<?> intf : cl.getInterfaces()) {
                    if (Remote.class.isAssignableFrom(intf)) {
                        for (Method method : intf.getMethods()) {
                            final Method m = method;
                            /*
                             * Set this Method object to override language
                             * access checks so that the dispatcher can invoke
                             * methods from non-public remote interfaces.
                             */
                            AccessController.doPrivileged(
                                new PrivilegedAction<Void>() {
                                public Void run() {
                                    m.setAccessible(true);
                                    return null;
                                }
                            });
                            map.put(Util.computeMethodHash(m), m);
                        }
                    }
                }
            }
            return map;
        }
    }
S
sjiang 已提交
611

D
duke 已提交
612
}