1 /* 2 * Copyright (c) 1997, 2019, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 26 package sun.rmi.server; 27 28 import java.io.ByteArrayOutputStream; 29 import java.io.File; 30 import java.io.FileOutputStream; 31 import java.io.IOException; 32 import java.io.InputStream; 33 import java.io.ObjectInput; 34 import java.io.ObjectInputStream; 35 import java.io.OutputStream; 36 import java.io.PrintStream; 37 import java.io.PrintWriter; 38 import java.io.Serializable; 39 import java.lang.Process; 40 import java.lang.reflect.InvocationTargetException; 41 import java.lang.reflect.Method; 42 import java.net.InetAddress; 43 import java.net.ServerSocket; 44 import java.net.Socket; 45 import java.net.SocketAddress; 46 import java.net.SocketException; 47 import java.nio.file.Files; 48 import java.nio.channels.Channel; 49 import java.nio.channels.ServerSocketChannel; 50 import java.rmi.AccessException; 51 import java.rmi.AlreadyBoundException; 52 import java.rmi.ConnectException; 53 import java.rmi.ConnectIOException; 54 import java.rmi.MarshalledObject; 55 import java.rmi.NoSuchObjectException; 56 import java.rmi.NotBoundException; 57 import java.rmi.Remote; 58 import java.rmi.RemoteException; 59 import java.rmi.activation.ActivationDesc; 60 import java.rmi.activation.ActivationException; 61 import java.rmi.activation.ActivationGroupDesc; 62 import java.rmi.activation.ActivationGroup; 63 import java.rmi.activation.ActivationGroupID; 64 import java.rmi.activation.ActivationID; 65 import java.rmi.activation.ActivationInstantiator; 66 import java.rmi.activation.ActivationMonitor; 67 import java.rmi.activation.ActivationSystem; 68 import java.rmi.activation.Activator; 69 import java.rmi.activation.UnknownGroupException; 70 import java.rmi.activation.UnknownObjectException; 71 import java.rmi.registry.Registry; 72 import java.rmi.server.ObjID; 73 import java.rmi.server.RMIClassLoader; 74 import java.rmi.server.RMIClientSocketFactory; 75 import java.rmi.server.RMIServerSocketFactory; 76 import java.rmi.server.RemoteObject; 77 import java.rmi.server.RemoteServer; 78 import java.rmi.server.UnicastRemoteObject; 79 import java.security.AccessControlException; 80 import java.security.AccessController; 81 import java.security.AllPermission; 82 import java.security.CodeSource; 83 import java.security.Permission; 84 import java.security.PermissionCollection; 85 import java.security.Permissions; 86 import java.security.Policy; 87 import java.security.PrivilegedAction; 88 import java.security.PrivilegedExceptionAction; 89 import java.security.cert.Certificate; 90 import java.text.MessageFormat; 91 import java.util.ArrayList; 92 import java.util.Arrays; 93 import java.util.Date; 94 import java.util.Enumeration; 95 import java.util.HashMap; 96 import java.util.HashSet; 97 import java.util.Iterator; 98 import java.util.List; 99 import java.util.Map; 100 import java.util.MissingResourceException; 101 import java.util.Properties; 102 import java.util.ResourceBundle; 103 import java.util.Set; 104 import java.util.concurrent.ConcurrentHashMap; 105 import sun.rmi.log.LogHandler; 106 import sun.rmi.log.ReliableLog; 107 import sun.rmi.registry.RegistryImpl; 108 import sun.rmi.runtime.NewThreadAction; 109 import sun.rmi.transport.LiveRef; 110 import sun.security.provider.PolicyFile; 111 import com.sun.rmi.rmid.ExecPermission; 112 import com.sun.rmi.rmid.ExecOptionPermission; 113 114 /** 115 * The Activator facilitates remote object activation. A "faulting" 116 * remote reference calls the activator's <code>activate</code> method 117 * to obtain a "live" reference to a activatable remote object. Upon 118 * receiving a request for activation, the activator looks up the 119 * activation descriptor for the activation identifier, id, determines 120 * the group in which the object should be activated and invokes the 121 * activate method on the object's activation group (described by the 122 * remote interface <code>ActivationInstantiator</code>). The 123 * activator initiates the execution of activation groups as 124 * necessary. For example, if an activation group for a specific group 125 * identifier is not already executing, the activator will spawn a 126 * child process for the activation group. <p> 127 * 128 * The activator is responsible for monitoring and detecting when 129 * activation groups fail so that it can remove stale remote references 130 * from its internal tables. <p> 131 * 132 * @author Ann Wollrath 133 * @since 1.2 134 */ 135 public class Activation implements Serializable { 136 137 /** indicate compatibility with JDK 1.2 version of class */ 138 private static final long serialVersionUID = 2921265612698155191L; 139 private static final byte MAJOR_VERSION = 1; 140 private static final byte MINOR_VERSION = 0; 141 142 /** exec policy object */ 143 private static Object execPolicy; 144 private static Method execPolicyMethod; 145 private static boolean debugExec; 146 147 /** maps activation id to its respective group id */ 148 @SuppressWarnings("serial") // Conditionally serializable 149 private Map<ActivationID,ActivationGroupID> idTable = 150 new ConcurrentHashMap<>(); 151 /** maps group id to its GroupEntry groups */ 152 @SuppressWarnings("serial") // Conditionally serializable 153 private Map<ActivationGroupID,GroupEntry> groupTable = 154 new ConcurrentHashMap<>(); 155 156 private byte majorVersion = MAJOR_VERSION; 157 private byte minorVersion = MINOR_VERSION; 158 159 /** number of simultaneous group exec's */ 160 private transient int groupSemaphore; 161 /** counter for numbering groups */ 162 private transient int groupCounter; 163 /** reliable log to hold descriptor table */ 164 private transient ReliableLog log; 165 /** number of updates since last snapshot */ 166 private transient int numUpdates; 167 168 /** the java command */ 169 // accessed by GroupEntry 170 private transient String[] command; 171 /** timeout on wait for child process to be created or destroyed */ 172 private static final long groupTimeout = 173 getInt("sun.rmi.activation.groupTimeout", 60000); 174 /** take snapshot after this many updates */ 175 private static final int snapshotInterval = 176 getInt("sun.rmi.activation.snapshotInterval", 200); 177 /** timeout on wait for child process to be created */ 178 private static final long execTimeout = 179 getInt("sun.rmi.activation.execTimeout", 30000); 180 181 private static final Object initLock = new Object(); 182 private static boolean initDone = false; 183 184 // this should be a *private* method since it is privileged 185 private static int getInt(String name, int def) { 186 return AccessController.doPrivileged( 187 (PrivilegedAction<Integer>) () -> Integer.getInteger(name, def)); 188 } 189 190 private transient Activator activator; 191 private transient Activator activatorStub; 192 private transient ActivationSystem system; 193 private transient ActivationSystem systemStub; 194 private transient ActivationMonitor monitor; 195 private transient Registry registry; 196 private transient volatile boolean shuttingDown = false; 197 private transient volatile Object startupLock; 198 private transient Thread shutdownHook; 199 200 private static ResourceBundle resources = null; 201 202 /** 203 * Create an uninitialized instance of Activation that can be 204 * populated with log data. This is only called when the initial 205 * snapshot is taken during the first incarnation of rmid. 206 */ 207 private Activation() {} 208 209 /** 210 * Recover activation state from the reliable log and initialize 211 * activation services. 212 */ 213 private static void startActivation(int port, 214 RMIServerSocketFactory ssf, 215 String logName, 216 String[] childArgs) 217 throws Exception 218 { 219 ReliableLog log = new ReliableLog(logName, new ActLogHandler()); 220 Activation state = (Activation) log.recover(); 221 state.init(port, ssf, log, childArgs); 222 } 223 224 /** 225 * Initialize the Activation instantiation; start activation 226 * services. 227 */ 228 private void init(int port, 229 RMIServerSocketFactory ssf, 230 ReliableLog log, 231 String[] childArgs) 232 throws Exception 233 { 234 // initialize 235 this.log = log; 236 numUpdates = 0; 237 shutdownHook = new ShutdownHook(); 238 groupSemaphore = getInt("sun.rmi.activation.groupThrottle", 3); 239 groupCounter = 0; 240 Runtime.getRuntime().addShutdownHook(shutdownHook); 241 242 // Use array size of 0, since the value from calling size() 243 // may be out of date by the time toArray() is called. 244 ActivationGroupID[] gids = 245 groupTable.keySet().toArray(new ActivationGroupID[0]); 246 247 synchronized (startupLock = new Object()) { 248 // all the remote methods briefly synchronize on startupLock 249 // (via checkShutdown) to make sure they don't happen in the 250 // middle of this block. This block must not cause any such 251 // incoming remote calls to happen, or deadlock would result! 252 activator = new ActivatorImpl(port, ssf); 253 activatorStub = (Activator) RemoteObject.toStub(activator); 254 system = new ActivationSystemImpl(port, ssf); 255 systemStub = (ActivationSystem) RemoteObject.toStub(system); 256 monitor = new ActivationMonitorImpl(port, ssf); 257 initCommand(childArgs); 258 registry = new SystemRegistryImpl(port, null, ssf, systemStub); 259 260 if (ssf != null) { 261 synchronized (initLock) { 262 initDone = true; 263 initLock.notifyAll(); 264 } 265 } 266 } 267 startupLock = null; 268 269 // restart services 270 for (int i = gids.length; --i >= 0; ) { 271 try { 272 getGroupEntry(gids[i]).restartServices(); 273 } catch (UnknownGroupException e) { 274 System.err.println( 275 getTextResource("rmid.restart.group.warning")); 276 e.printStackTrace(); 277 } 278 } 279 } 280 281 /** 282 * Previous versions used HashMap instead of ConcurrentHashMap. 283 * Replace any HashMaps found during deserialization with 284 * ConcurrentHashMaps. 285 */ 286 private void readObject(ObjectInputStream ois) 287 throws IOException, ClassNotFoundException 288 { 289 ois.defaultReadObject(); 290 if (! (groupTable instanceof ConcurrentHashMap)) { 291 groupTable = new ConcurrentHashMap<>(groupTable); 292 } 293 if (! (idTable instanceof ConcurrentHashMap)) { 294 idTable = new ConcurrentHashMap<>(idTable); 295 } 296 } 297 298 private static class SystemRegistryImpl extends RegistryImpl { 299 300 private static final String NAME = ActivationSystem.class.getName(); 301 private static final long serialVersionUID = 4877330021609408794L; 302 @SuppressWarnings("serial") // Not statically typed as Serializable 303 private ActivationSystem systemStub = null; 304 305 SystemRegistryImpl(int port, 306 RMIClientSocketFactory csf, 307 RMIServerSocketFactory ssf, 308 ActivationSystem systemStub) 309 throws RemoteException 310 { 311 super(port, csf, ssf); 312 assert systemStub != null; 313 synchronized (this) { 314 this.systemStub = systemStub; 315 notifyAll(); 316 } 317 } 318 319 /** 320 * Waits for systemStub to be initialized and returns its 321 * initialized value. Any remote call that uses systemStub must 322 * call this method to get it instead of using direct field 323 * access. This is necessary because the super() call in the 324 * constructor exports this object before systemStub is initialized 325 * (see JDK-8023541), allowing remote calls to come in during this 326 * time. We can't use checkShutdown() like other nested classes 327 * because this is a static class. 328 */ 329 private synchronized ActivationSystem getSystemStub() { 330 boolean interrupted = false; 331 332 while (systemStub == null) { 333 try { 334 wait(); 335 } catch (InterruptedException ie) { 336 interrupted = true; 337 } 338 } 339 340 if (interrupted) { 341 Thread.currentThread().interrupt(); 342 } 343 344 return systemStub; 345 } 346 347 /** 348 * Returns the activation system stub if the specified name 349 * matches the activation system's class name, otherwise 350 * returns the result of invoking super.lookup with the specified 351 * name. 352 */ 353 public Remote lookup(String name) 354 throws RemoteException, NotBoundException 355 { 356 if (name.equals(NAME)) { 357 return getSystemStub(); 358 } else { 359 return super.lookup(name); 360 } 361 } 362 363 public String[] list() throws RemoteException { 364 String[] list1 = super.list(); 365 int length = list1.length; 366 String[] list2 = new String[length + 1]; 367 if (length > 0) { 368 System.arraycopy(list1, 0, list2, 0, length); 369 } 370 list2[length] = NAME; 371 return list2; 372 } 373 374 public void bind(String name, Remote obj) 375 throws RemoteException, AlreadyBoundException, AccessException 376 { 377 if (name.equals(NAME)) { 378 throw new AccessException( 379 "binding ActivationSystem is disallowed"); 380 } else { 381 RegistryImpl.checkAccess("ActivationSystem.bind"); 382 super.bind(name, obj); 383 } 384 } 385 386 public void unbind(String name) 387 throws RemoteException, NotBoundException, AccessException 388 { 389 if (name.equals(NAME)) { 390 throw new AccessException( 391 "unbinding ActivationSystem is disallowed"); 392 } else { 393 RegistryImpl.checkAccess("ActivationSystem.unbind"); 394 super.unbind(name); 395 } 396 } 397 398 399 public void rebind(String name, Remote obj) 400 throws RemoteException, AccessException 401 { 402 if (name.equals(NAME)) { 403 throw new AccessException( 404 "binding ActivationSystem is disallowed"); 405 } else { 406 RegistryImpl.checkAccess("ActivationSystem.rebind"); 407 super.rebind(name, obj); 408 } 409 } 410 } 411 412 413 class ActivatorImpl extends RemoteServer implements Activator { 414 // Because ActivatorImpl has a fixed ObjID, it can be 415 // called by clients holding stale remote references. Each of 416 // its remote methods, then, must check startupLock (calling 417 // checkShutdown() is easiest). 418 419 private static final long serialVersionUID = -3654244726254566136L; 420 421 /** 422 * Construct a new Activator on a specified port. 423 */ 424 ActivatorImpl(int port, RMIServerSocketFactory ssf) 425 throws RemoteException 426 { 427 /* Server ref must be created and assigned before remote object 428 * 'this' can be exported. 429 */ 430 LiveRef lref = 431 new LiveRef(new ObjID(ObjID.ACTIVATOR_ID), port, null, ssf); 432 UnicastServerRef uref = new UnicastServerRef(lref); 433 ref = uref; 434 uref.exportObject(this, null, false); 435 } 436 437 public MarshalledObject<? extends Remote> activate(ActivationID id, 438 boolean force) 439 throws ActivationException, UnknownObjectException, RemoteException 440 { 441 checkShutdown(); 442 return getGroupEntry(id).activate(id, force); 443 } 444 } 445 446 class ActivationMonitorImpl extends UnicastRemoteObject 447 implements ActivationMonitor 448 { 449 private static final long serialVersionUID = -6214940464757948867L; 450 451 ActivationMonitorImpl(int port, RMIServerSocketFactory ssf) 452 throws RemoteException 453 { 454 super(port, null, ssf); 455 } 456 457 public void inactiveObject(ActivationID id) 458 throws UnknownObjectException, RemoteException 459 { 460 try { 461 checkShutdown(); 462 } catch (ActivationException e) { 463 return; 464 } 465 RegistryImpl.checkAccess("Activator.inactiveObject"); 466 getGroupEntry(id).inactiveObject(id); 467 } 468 469 public void activeObject(ActivationID id, 470 MarshalledObject<? extends Remote> mobj) 471 throws UnknownObjectException, RemoteException 472 { 473 try { 474 checkShutdown(); 475 } catch (ActivationException e) { 476 return; 477 } 478 RegistryImpl.checkAccess("ActivationSystem.activeObject"); 479 getGroupEntry(id).activeObject(id, mobj); 480 } 481 482 public void inactiveGroup(ActivationGroupID id, 483 long incarnation) 484 throws UnknownGroupException, RemoteException 485 { 486 try { 487 checkShutdown(); 488 } catch (ActivationException e) { 489 return; 490 } 491 RegistryImpl.checkAccess("ActivationMonitor.inactiveGroup"); 492 getGroupEntry(id).inactiveGroup(incarnation, false); 493 } 494 } 495 496 497 /** 498 * SameHostOnlyServerRef checks that access is from a local client 499 * before the parameters are deserialized. The unmarshalCustomCallData 500 * hook is used to check the network address of the caller 501 * with RegistryImpl.checkAccess(). 502 * The kind of access is retained for an exception if one is thrown. 503 */ 504 @SuppressWarnings("serial") // Externalizable class w/o no-arg c'tor 505 static class SameHostOnlyServerRef extends UnicastServerRef { 506 private static final long serialVersionUID = 1234L; 507 private String accessKind; // an exception message 508 509 /** 510 * Construct a new SameHostOnlyServerRef from a LiveRef. 511 * @param lref a LiveRef 512 */ 513 SameHostOnlyServerRef(LiveRef lref, String accessKind) { 514 super(lref); 515 this.accessKind = accessKind; 516 } 517 518 @Override 519 protected void unmarshalCustomCallData(ObjectInput in) throws IOException, ClassNotFoundException { 520 RegistryImpl.checkAccess(accessKind); 521 super.unmarshalCustomCallData(in); 522 } 523 } 524 525 class ActivationSystemImpl 526 extends RemoteServer 527 implements ActivationSystem 528 { 529 private static final long serialVersionUID = 9100152600327688967L; 530 531 // Because ActivationSystemImpl has a fixed ObjID, it can be 532 // called by clients holding stale remote references. Each of 533 // its remote methods, then, must check startupLock (calling 534 // checkShutdown() is easiest). 535 ActivationSystemImpl(int port, RMIServerSocketFactory ssf) 536 throws RemoteException 537 { 538 /* Server ref must be created and assigned before remote object 539 * 'this' can be exported. 540 */ 541 LiveRef lref = new LiveRef(new ObjID(4), port, null, ssf); 542 UnicastServerRef uref = new SameHostOnlyServerRef(lref, 543 "ActivationSystem.nonLocalAccess"); 544 ref = uref; 545 uref.exportObject(this, null); 546 } 547 548 public ActivationID registerObject(ActivationDesc desc) 549 throws ActivationException, UnknownGroupException, RemoteException 550 { 551 checkShutdown(); 552 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 553 // during unmarshallCustomData and is not applicable to local access. 554 ActivationGroupID groupID = desc.getGroupID(); 555 ActivationID id = new ActivationID(activatorStub); 556 getGroupEntry(groupID).registerObject(id, desc, true); 557 return id; 558 } 559 560 public void unregisterObject(ActivationID id) 561 throws ActivationException, UnknownObjectException, RemoteException 562 { 563 checkShutdown(); 564 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 565 // during unmarshallCustomData and is not applicable to local access. 566 getGroupEntry(id).unregisterObject(id, true); 567 } 568 569 public ActivationGroupID registerGroup(ActivationGroupDesc desc) 570 throws ActivationException, RemoteException 571 { 572 checkShutdown(); 573 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 574 // during unmarshallCustomData and is not applicable to local access. 575 checkArgs(desc, null); 576 577 ActivationGroupID id = new ActivationGroupID(systemStub); 578 GroupEntry entry = new GroupEntry(id, desc); 579 // table insertion must take place before log update 580 groupTable.put(id, entry); 581 addLogRecord(new LogRegisterGroup(id, desc)); 582 return id; 583 } 584 585 public ActivationMonitor activeGroup(ActivationGroupID id, 586 ActivationInstantiator group, 587 long incarnation) 588 throws ActivationException, UnknownGroupException, RemoteException 589 { 590 checkShutdown(); 591 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 592 // during unmarshallCustomData and is not applicable to local access. 593 594 getGroupEntry(id).activeGroup(group, incarnation); 595 return monitor; 596 } 597 598 public void unregisterGroup(ActivationGroupID id) 599 throws ActivationException, UnknownGroupException, RemoteException 600 { 601 checkShutdown(); 602 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 603 // during unmarshallCustomData and is not applicable to local access. 604 605 // remove entry before unregister so state is updated before 606 // logged 607 removeGroupEntry(id).unregisterGroup(true); 608 } 609 610 public ActivationDesc setActivationDesc(ActivationID id, 611 ActivationDesc desc) 612 throws ActivationException, UnknownObjectException, RemoteException 613 { 614 checkShutdown(); 615 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 616 // during unmarshallCustomData and is not applicable to local access. 617 618 if (!getGroupID(id).equals(desc.getGroupID())) { 619 throw new ActivationException( 620 "ActivationDesc contains wrong group"); 621 } 622 return getGroupEntry(id).setActivationDesc(id, desc, true); 623 } 624 625 public ActivationGroupDesc setActivationGroupDesc(ActivationGroupID id, 626 ActivationGroupDesc desc) 627 throws ActivationException, UnknownGroupException, RemoteException 628 { 629 checkShutdown(); 630 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 631 // during unmarshallCustomData and is not applicable to local access. 632 633 checkArgs(desc, null); 634 return getGroupEntry(id).setActivationGroupDesc(id, desc, true); 635 } 636 637 public ActivationDesc getActivationDesc(ActivationID id) 638 throws ActivationException, UnknownObjectException, RemoteException 639 { 640 checkShutdown(); 641 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 642 // during unmarshallCustomData and is not applicable to local access. 643 644 return getGroupEntry(id).getActivationDesc(id); 645 } 646 647 public ActivationGroupDesc getActivationGroupDesc(ActivationGroupID id) 648 throws ActivationException, UnknownGroupException, RemoteException 649 { 650 checkShutdown(); 651 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 652 // during unmarshallCustomData and is not applicable to local access. 653 654 return getGroupEntry(id).desc; 655 } 656 657 /** 658 * Shutdown the activation system. Destroys all groups spawned by 659 * the activation daemon and exits the activation daemon. 660 */ 661 public void shutdown() throws AccessException { 662 // RegistryImpl.checkAccess() is done in the SameHostOnlyServerRef 663 // during unmarshallCustomData and is not applicable to local access. 664 665 Object lock = startupLock; 666 if (lock != null) { 667 synchronized (lock) { 668 // nothing 669 } 670 } 671 672 synchronized (Activation.this) { 673 if (!shuttingDown) { 674 shuttingDown = true; 675 (new Shutdown()).start(); 676 } 677 } 678 } 679 } 680 681 private void checkShutdown() throws ActivationException { 682 // if the startup critical section is running, wait until it 683 // completes/fails before continuing with the remote call. 684 Object lock = startupLock; 685 if (lock != null) { 686 synchronized (lock) { 687 // nothing 688 } 689 } 690 691 if (shuttingDown == true) { 692 throw new ActivationException( 693 "activation system shutting down"); 694 } 695 } 696 697 private static void unexport(Remote obj) { 698 for (;;) { 699 try { 700 if (UnicastRemoteObject.unexportObject(obj, false) == true) { 701 break; 702 } else { 703 Thread.sleep(100); 704 } 705 } catch (Exception e) { 706 continue; 707 } 708 } 709 } 710 711 /** 712 * Thread to shutdown rmid. 713 */ 714 private class Shutdown extends Thread { 715 Shutdown() { 716 super("rmid Shutdown"); 717 } 718 719 public void run() { 720 try { 721 /* 722 * Unexport activation system services 723 */ 724 unexport(activator); 725 unexport(system); 726 727 // destroy all child processes (groups) 728 for (GroupEntry groupEntry : groupTable.values()) { 729 groupEntry.shutdown(); 730 } 731 732 Runtime.getRuntime().removeShutdownHook(shutdownHook); 733 734 /* 735 * Unexport monitor safely since all processes are destroyed. 736 */ 737 unexport(monitor); 738 739 /* 740 * Close log file, fix for 4243264: rmid shutdown thread 741 * interferes with remote calls in progress. Make sure 742 * the log file is only closed when it is impossible for 743 * its closure to interfere with any pending remote calls. 744 * We close the log when all objects in the rmid VM are 745 * unexported. 746 */ 747 try { 748 synchronized (log) { 749 log.close(); 750 } 751 } catch (IOException e) { 752 } 753 754 } finally { 755 /* 756 * Now exit... A System.exit should only be done if 757 * the RMI activation system daemon was started up 758 * by the main method below (in which should always 759 * be the case since the Activation constructor is private). 760 */ 761 System.err.println(getTextResource("rmid.daemon.shutdown")); 762 System.exit(0); 763 } 764 } 765 } 766 767 /** Thread to destroy children in the event of abnormal termination. */ 768 private class ShutdownHook extends Thread { 769 ShutdownHook() { 770 super("rmid ShutdownHook"); 771 } 772 773 public void run() { 774 synchronized (Activation.this) { 775 shuttingDown = true; 776 } 777 778 // destroy all child processes (groups) quickly 779 for (GroupEntry groupEntry : groupTable.values()) { 780 groupEntry.shutdownFast(); 781 } 782 } 783 } 784 785 /** 786 * Returns the groupID for a given id of an object in the group. 787 * Throws UnknownObjectException if the object is not registered. 788 */ 789 private ActivationGroupID getGroupID(ActivationID id) 790 throws UnknownObjectException 791 { 792 ActivationGroupID groupID = idTable.get(id); 793 if (groupID != null) { 794 return groupID; 795 } 796 throw new UnknownObjectException("unknown object: " + id); 797 } 798 799 /** 800 * Returns the group entry for the group id, optionally removing it. 801 * Throws UnknownGroupException if the group is not registered. 802 */ 803 private GroupEntry getGroupEntry(ActivationGroupID id, boolean rm) 804 throws UnknownGroupException 805 { 806 if (id.getClass() == ActivationGroupID.class) { 807 GroupEntry entry; 808 if (rm) { 809 entry = groupTable.remove(id); 810 } else { 811 entry = groupTable.get(id); 812 } 813 if (entry != null && !entry.removed) { 814 return entry; 815 } 816 } 817 throw new UnknownGroupException("group unknown"); 818 } 819 820 /** 821 * Returns the group entry for the group id. Throws 822 * UnknownGroupException if the group is not registered. 823 */ 824 private GroupEntry getGroupEntry(ActivationGroupID id) 825 throws UnknownGroupException 826 { 827 return getGroupEntry(id, false); 828 } 829 830 /** 831 * Removes and returns the group entry for the group id. Throws 832 * UnknownGroupException if the group is not registered. 833 */ 834 private GroupEntry removeGroupEntry(ActivationGroupID id) 835 throws UnknownGroupException 836 { 837 return getGroupEntry(id, true); 838 } 839 840 /** 841 * Returns the group entry for the object's id. Throws 842 * UnknownObjectException if the object is not registered or the 843 * object's group is not registered. 844 */ 845 private GroupEntry getGroupEntry(ActivationID id) 846 throws UnknownObjectException 847 { 848 ActivationGroupID gid = getGroupID(id); 849 GroupEntry entry = groupTable.get(gid); 850 if (entry != null && !entry.removed) { 851 return entry; 852 } 853 throw new UnknownObjectException("object's group removed"); 854 } 855 856 /** 857 * Container for group information: group's descriptor, group's 858 * instantiator, flag to indicate pending group creation, and 859 * table of the objects that are activated in the group. 860 * 861 * WARNING: GroupEntry objects should not be written into log file 862 * updates. GroupEntrys are inner classes of Activation and they 863 * can not be serialized independent of this class. If the 864 * complete Activation system is written out as a log update, the 865 * point of having updates is nullified. 866 */ 867 private class GroupEntry implements Serializable { 868 869 /** indicate compatibility with JDK 1.2 version of class */ 870 private static final long serialVersionUID = 7222464070032993304L; 871 private static final int MAX_TRIES = 2; 872 private static final int NORMAL = 0; 873 private static final int CREATING = 1; 874 private static final int TERMINATE = 2; 875 private static final int TERMINATING = 3; 876 877 ActivationGroupDesc desc = null; 878 ActivationGroupID groupID = null; 879 long incarnation = 0; 880 @SuppressWarnings("serial") // Conditionally serializable 881 Map<ActivationID,ObjectEntry> objects = new HashMap<>(); 882 @SuppressWarnings("serial") // Conditionally serializable 883 Set<ActivationID> restartSet = new HashSet<>(); 884 885 transient ActivationInstantiator group = null; 886 transient int status = NORMAL; 887 transient long waitTime = 0; 888 transient String groupName = null; 889 transient Process child = null; 890 transient boolean removed = false; 891 transient Watchdog watchdog = null; 892 893 GroupEntry(ActivationGroupID groupID, ActivationGroupDesc desc) { 894 this.groupID = groupID; 895 this.desc = desc; 896 } 897 898 void restartServices() { 899 Iterator<ActivationID> iter = null; 900 901 synchronized (this) { 902 if (restartSet.isEmpty()) { 903 return; 904 } 905 906 /* 907 * Clone the restartSet so the set does not have to be locked 908 * during iteration. Locking the restartSet could cause 909 * deadlock if an object we are restarting caused another 910 * object in this group to be activated. 911 */ 912 iter = (new HashSet<ActivationID>(restartSet)).iterator(); 913 } 914 915 while (iter.hasNext()) { 916 ActivationID id = iter.next(); 917 try { 918 activate(id, true); 919 } catch (Exception e) { 920 if (shuttingDown) { 921 return; 922 } 923 System.err.println( 924 getTextResource("rmid.restart.service.warning")); 925 e.printStackTrace(); 926 } 927 } 928 } 929 930 synchronized void activeGroup(ActivationInstantiator inst, 931 long instIncarnation) 932 throws ActivationException, UnknownGroupException 933 { 934 if (incarnation != instIncarnation) { 935 throw new ActivationException("invalid incarnation"); 936 } 937 938 if (group != null) { 939 if (group.equals(inst)) { 940 return; 941 } else { 942 throw new ActivationException("group already active"); 943 } 944 } 945 946 if (child != null && status != CREATING) { 947 throw new ActivationException("group not being created"); 948 } 949 950 group = inst; 951 status = NORMAL; 952 notifyAll(); 953 } 954 955 private void checkRemoved() throws UnknownGroupException { 956 if (removed) { 957 throw new UnknownGroupException("group removed"); 958 } 959 } 960 961 private ObjectEntry getObjectEntry(ActivationID id) 962 throws UnknownObjectException 963 { 964 if (removed) { 965 throw new UnknownObjectException("object's group removed"); 966 } 967 ObjectEntry objEntry = objects.get(id); 968 if (objEntry == null) { 969 throw new UnknownObjectException("object unknown"); 970 } 971 return objEntry; 972 } 973 974 synchronized void registerObject(ActivationID id, 975 ActivationDesc desc, 976 boolean addRecord) 977 throws UnknownGroupException, ActivationException 978 { 979 checkRemoved(); 980 objects.put(id, new ObjectEntry(desc)); 981 if (desc.getRestartMode() == true) { 982 restartSet.add(id); 983 } 984 985 // table insertion must take place before log update 986 idTable.put(id, groupID); 987 988 if (addRecord) { 989 addLogRecord(new LogRegisterObject(id, desc)); 990 } 991 } 992 993 synchronized void unregisterObject(ActivationID id, boolean addRecord) 994 throws UnknownGroupException, ActivationException 995 { 996 ObjectEntry objEntry = getObjectEntry(id); 997 objEntry.removed = true; 998 objects.remove(id); 999 if (objEntry.desc.getRestartMode() == true) { 1000 restartSet.remove(id); 1001 } 1002 1003 // table removal must take place before log update 1004 idTable.remove(id); 1005 if (addRecord) { 1006 addLogRecord(new LogUnregisterObject(id)); 1007 } 1008 } 1009 1010 synchronized void unregisterGroup(boolean addRecord) 1011 throws UnknownGroupException, ActivationException 1012 { 1013 checkRemoved(); 1014 removed = true; 1015 for (Map.Entry<ActivationID,ObjectEntry> entry : 1016 objects.entrySet()) 1017 { 1018 ActivationID id = entry.getKey(); 1019 idTable.remove(id); 1020 ObjectEntry objEntry = entry.getValue(); 1021 objEntry.removed = true; 1022 } 1023 objects.clear(); 1024 restartSet.clear(); 1025 reset(); 1026 childGone(); 1027 1028 // removal should be recorded before log update 1029 if (addRecord) { 1030 addLogRecord(new LogUnregisterGroup(groupID)); 1031 } 1032 } 1033 1034 synchronized ActivationDesc setActivationDesc(ActivationID id, 1035 ActivationDesc desc, 1036 boolean addRecord) 1037 throws UnknownObjectException, UnknownGroupException, 1038 ActivationException 1039 { 1040 ObjectEntry objEntry = getObjectEntry(id); 1041 ActivationDesc oldDesc = objEntry.desc; 1042 objEntry.desc = desc; 1043 if (desc.getRestartMode() == true) { 1044 restartSet.add(id); 1045 } else { 1046 restartSet.remove(id); 1047 } 1048 // restart information should be recorded before log update 1049 if (addRecord) { 1050 addLogRecord(new LogUpdateDesc(id, desc)); 1051 } 1052 1053 return oldDesc; 1054 } 1055 1056 synchronized ActivationDesc getActivationDesc(ActivationID id) 1057 throws UnknownObjectException, UnknownGroupException 1058 { 1059 return getObjectEntry(id).desc; 1060 } 1061 1062 synchronized ActivationGroupDesc setActivationGroupDesc( 1063 ActivationGroupID id, 1064 ActivationGroupDesc desc, 1065 boolean addRecord) 1066 throws UnknownGroupException, ActivationException 1067 { 1068 checkRemoved(); 1069 ActivationGroupDesc oldDesc = this.desc; 1070 this.desc = desc; 1071 // state update should occur before log update 1072 if (addRecord) { 1073 addLogRecord(new LogUpdateGroupDesc(id, desc)); 1074 } 1075 return oldDesc; 1076 } 1077 1078 synchronized void inactiveGroup(long incarnation, boolean failure) 1079 throws UnknownGroupException 1080 { 1081 checkRemoved(); 1082 if (this.incarnation != incarnation) { 1083 throw new UnknownGroupException("invalid incarnation"); 1084 } 1085 1086 reset(); 1087 if (failure) { 1088 terminate(); 1089 } else if (child != null && status == NORMAL) { 1090 status = TERMINATE; 1091 watchdog.noRestart(); 1092 } 1093 } 1094 1095 synchronized void activeObject(ActivationID id, 1096 MarshalledObject<? extends Remote> mobj) 1097 throws UnknownObjectException 1098 { 1099 getObjectEntry(id).stub = mobj; 1100 } 1101 1102 synchronized void inactiveObject(ActivationID id) 1103 throws UnknownObjectException 1104 { 1105 getObjectEntry(id).reset(); 1106 } 1107 1108 private synchronized void reset() { 1109 group = null; 1110 for (ObjectEntry objectEntry : objects.values()) { 1111 objectEntry.reset(); 1112 } 1113 } 1114 1115 private void childGone() { 1116 if (child != null) { 1117 child = null; 1118 watchdog.dispose(); 1119 watchdog = null; 1120 status = NORMAL; 1121 notifyAll(); 1122 } 1123 } 1124 1125 private void terminate() { 1126 if (child != null && status != TERMINATING) { 1127 child.destroy(); 1128 status = TERMINATING; 1129 waitTime = System.currentTimeMillis() + groupTimeout; 1130 notifyAll(); 1131 } 1132 } 1133 1134 /* 1135 * Fallthrough from TERMINATE to TERMINATING 1136 * is intentional 1137 */ 1138 @SuppressWarnings("fallthrough") 1139 private void await() { 1140 while (true) { 1141 switch (status) { 1142 case NORMAL: 1143 return; 1144 case TERMINATE: 1145 terminate(); 1146 case TERMINATING: 1147 try { 1148 child.exitValue(); 1149 } catch (IllegalThreadStateException e) { 1150 long now = System.currentTimeMillis(); 1151 if (waitTime > now) { 1152 try { 1153 wait(waitTime - now); 1154 } catch (InterruptedException ee) { 1155 } 1156 continue; 1157 } 1158 // REMIND: print message that group did not terminate? 1159 } 1160 childGone(); 1161 return; 1162 case CREATING: 1163 try { 1164 wait(); 1165 } catch (InterruptedException e) { 1166 } 1167 } 1168 } 1169 } 1170 1171 // no synchronization to avoid delay wrt getInstantiator 1172 void shutdownFast() { 1173 Process p = child; 1174 if (p != null) { 1175 p.destroy(); 1176 } 1177 } 1178 1179 synchronized void shutdown() { 1180 reset(); 1181 terminate(); 1182 await(); 1183 } 1184 1185 MarshalledObject<? extends Remote> activate(ActivationID id, 1186 boolean force) 1187 throws ActivationException 1188 { 1189 Exception detail = null; 1190 1191 /* 1192 * Attempt to activate object and reattempt (several times) 1193 * if activation fails due to communication problems. 1194 */ 1195 for (int tries = MAX_TRIES; tries > 0; tries--) { 1196 ActivationInstantiator inst; 1197 long currentIncarnation; 1198 1199 // look up object to activate 1200 ObjectEntry objEntry; 1201 synchronized (this) { 1202 objEntry = getObjectEntry(id); 1203 // if not forcing activation, return cached stub 1204 if (!force && objEntry.stub != null) { 1205 return objEntry.stub; 1206 } 1207 inst = getInstantiator(groupID); 1208 currentIncarnation = incarnation; 1209 } 1210 1211 boolean groupInactive = false; 1212 boolean failure = false; 1213 // activate object 1214 try { 1215 return objEntry.activate(id, force, inst); 1216 } catch (NoSuchObjectException e) { 1217 groupInactive = true; 1218 detail = e; 1219 } catch (ConnectException e) { 1220 groupInactive = true; 1221 failure = true; 1222 detail = e; 1223 } catch (ConnectIOException e) { 1224 groupInactive = true; 1225 failure = true; 1226 detail = e; 1227 } catch (InactiveGroupException e) { 1228 groupInactive = true; 1229 detail = e; 1230 } catch (RemoteException e) { 1231 // REMIND: wait some here before continuing? 1232 if (detail == null) { 1233 detail = e; 1234 } 1235 } 1236 1237 if (groupInactive) { 1238 // group has failed or is inactive; mark inactive 1239 try { 1240 System.err.println( 1241 MessageFormat.format( 1242 getTextResource("rmid.group.inactive"), 1243 detail.toString())); 1244 detail.printStackTrace(); 1245 getGroupEntry(groupID). 1246 inactiveGroup(currentIncarnation, failure); 1247 } catch (UnknownGroupException e) { 1248 // not a problem 1249 } 1250 } 1251 } 1252 1253 /** 1254 * signal that group activation failed, nested exception 1255 * specifies what exception occurred when the group did not 1256 * activate 1257 */ 1258 throw new ActivationException("object activation failed after " + 1259 MAX_TRIES + " tries", detail); 1260 } 1261 1262 /** 1263 * Returns the instantiator for the group specified by id and 1264 * entry. If the group is currently inactive, exec some 1265 * bootstrap code to create the group. 1266 */ 1267 private ActivationInstantiator getInstantiator(ActivationGroupID id) 1268 throws ActivationException 1269 { 1270 assert Thread.holdsLock(this); 1271 1272 await(); 1273 if (group != null) { 1274 return group; 1275 } 1276 checkRemoved(); 1277 boolean acquired = false; 1278 1279 try { 1280 groupName = Pstartgroup(); 1281 acquired = true; 1282 String[] argv = activationArgs(desc); 1283 checkArgs(desc, argv); 1284 1285 if (debugExec) { 1286 StringBuilder sb = new StringBuilder(argv[0]); 1287 int j; 1288 for (j = 1; j < argv.length; j++) { 1289 sb.append(' '); 1290 sb.append(argv[j]); 1291 } 1292 System.err.println( 1293 MessageFormat.format( 1294 getTextResource("rmid.exec.command"), 1295 sb.toString())); 1296 } 1297 1298 try { 1299 child = Runtime.getRuntime().exec(argv); 1300 status = CREATING; 1301 ++incarnation; 1302 watchdog = new Watchdog(); 1303 watchdog.start(); 1304 addLogRecord(new LogGroupIncarnation(id, incarnation)); 1305 1306 // handle child I/O streams before writing to child 1307 PipeWriter.plugTogetherPair 1308 (child.getInputStream(), System.out, 1309 child.getErrorStream(), System.err); 1310 try (MarshalOutputStream out = 1311 new MarshalOutputStream(child.getOutputStream())) { 1312 out.writeObject(id); 1313 out.writeObject(desc); 1314 out.writeLong(incarnation); 1315 out.flush(); 1316 } 1317 1318 1319 } catch (IOException e) { 1320 terminate(); 1321 throw new ActivationException( 1322 "unable to create activation group", e); 1323 } 1324 1325 try { 1326 long now = System.currentTimeMillis(); 1327 long stop = now + execTimeout; 1328 do { 1329 wait(stop - now); 1330 if (group != null) { 1331 return group; 1332 } 1333 now = System.currentTimeMillis(); 1334 } while (status == CREATING && now < stop); 1335 } catch (InterruptedException e) { 1336 } 1337 1338 terminate(); 1339 throw new ActivationException( 1340 (removed ? 1341 "activation group unregistered" : 1342 "timeout creating child process")); 1343 } finally { 1344 if (acquired) { 1345 Vstartgroup(); 1346 } 1347 } 1348 } 1349 1350 /** 1351 * Waits for process termination and then restarts services. 1352 */ 1353 private class Watchdog extends Thread { 1354 private final Process groupProcess = child; 1355 private final long groupIncarnation = incarnation; 1356 private boolean canInterrupt = true; 1357 private boolean shouldQuit = false; 1358 private boolean shouldRestart = true; 1359 1360 Watchdog() { 1361 super("WatchDog-" + groupName + "-" + incarnation); 1362 setDaemon(true); 1363 } 1364 1365 public void run() { 1366 1367 if (shouldQuit) { 1368 return; 1369 } 1370 1371 /* 1372 * Wait for the group to crash or exit. 1373 */ 1374 try { 1375 groupProcess.waitFor(); 1376 } catch (InterruptedException exit) { 1377 return; 1378 } 1379 1380 boolean restart = false; 1381 synchronized (GroupEntry.this) { 1382 if (shouldQuit) { 1383 return; 1384 } 1385 canInterrupt = false; 1386 interrupted(); // clear interrupt bit 1387 /* 1388 * Since the group crashed, we should 1389 * reset the entry before activating objects 1390 */ 1391 if (groupIncarnation == incarnation) { 1392 restart = shouldRestart && !shuttingDown; 1393 reset(); 1394 childGone(); 1395 } 1396 } 1397 1398 /* 1399 * Activate those objects that require restarting 1400 * after a crash. 1401 */ 1402 if (restart) { 1403 restartServices(); 1404 } 1405 } 1406 1407 /** 1408 * Marks this thread as one that is no longer needed. 1409 * If the thread is in a state in which it can be interrupted, 1410 * then the thread is interrupted. 1411 */ 1412 void dispose() { 1413 shouldQuit = true; 1414 if (canInterrupt) { 1415 interrupt(); 1416 } 1417 } 1418 1419 /** 1420 * Marks this thread as no longer needing to restart objects. 1421 */ 1422 void noRestart() { 1423 shouldRestart = false; 1424 } 1425 } 1426 } 1427 1428 private String[] activationArgs(ActivationGroupDesc desc) { 1429 ActivationGroupDesc.CommandEnvironment cmdenv; 1430 cmdenv = desc.getCommandEnvironment(); 1431 1432 // argv is the literal command to exec 1433 List<String> argv = new ArrayList<>(); 1434 1435 // Command name/path 1436 argv.add((cmdenv != null && cmdenv.getCommandPath() != null) 1437 ? cmdenv.getCommandPath() 1438 : command[0]); 1439 1440 // Group-specific command options 1441 if (cmdenv != null && cmdenv.getCommandOptions() != null) { 1442 argv.addAll(Arrays.asList(cmdenv.getCommandOptions())); 1443 } 1444 1445 // Properties become -D parameters 1446 Properties props = desc.getPropertyOverrides(); 1447 if (props != null) { 1448 for (Enumeration<?> p = props.propertyNames(); 1449 p.hasMoreElements();) 1450 { 1451 String name = (String) p.nextElement(); 1452 /* Note on quoting: it would be wrong 1453 * here, since argv will be passed to 1454 * Runtime.exec, which should not parse 1455 * arguments or split on whitespace. 1456 */ 1457 argv.add("-D" + name + "=" + props.getProperty(name)); 1458 } 1459 } 1460 1461 /* Finally, rmid-global command options (e.g. -C options) 1462 * and the classname 1463 */ 1464 for (int i = 1; i < command.length; i++) { 1465 argv.add(command[i]); 1466 } 1467 1468 String[] realArgv = new String[argv.size()]; 1469 System.arraycopy(argv.toArray(), 0, realArgv, 0, realArgv.length); 1470 1471 return realArgv; 1472 } 1473 1474 private void checkArgs(ActivationGroupDesc desc, String[] cmd) 1475 throws SecurityException, ActivationException 1476 { 1477 /* 1478 * Check exec command using execPolicy object 1479 */ 1480 if (execPolicyMethod != null) { 1481 if (cmd == null) { 1482 cmd = activationArgs(desc); 1483 } 1484 try { 1485 execPolicyMethod.invoke(execPolicy, desc, cmd); 1486 } catch (InvocationTargetException e) { 1487 Throwable targetException = e.getTargetException(); 1488 if (targetException instanceof SecurityException) { 1489 throw (SecurityException) targetException; 1490 } else { 1491 throw new ActivationException( 1492 execPolicyMethod.getName() + ": unexpected exception", 1493 e); 1494 } 1495 } catch (Exception e) { 1496 throw new ActivationException( 1497 execPolicyMethod.getName() + ": unexpected exception", e); 1498 } 1499 } 1500 } 1501 1502 private static class ObjectEntry implements Serializable { 1503 1504 private static final long serialVersionUID = -5500114225321357856L; 1505 1506 /** descriptor for object */ 1507 ActivationDesc desc; 1508 /** the stub (if active) */ 1509 volatile transient MarshalledObject<? extends Remote> stub = null; 1510 volatile transient boolean removed = false; 1511 1512 ObjectEntry(ActivationDesc desc) { 1513 this.desc = desc; 1514 } 1515 1516 synchronized MarshalledObject<? extends Remote> 1517 activate(ActivationID id, 1518 boolean force, 1519 ActivationInstantiator inst) 1520 throws RemoteException, ActivationException 1521 { 1522 MarshalledObject<? extends Remote> nstub = stub; 1523 if (removed) { 1524 throw new UnknownObjectException("object removed"); 1525 } else if (!force && nstub != null) { 1526 return nstub; 1527 } 1528 1529 nstub = inst.newInstance(id, desc); 1530 stub = nstub; 1531 /* 1532 * stub could be set to null by a group reset, so return 1533 * the newstub here to prevent returning null. 1534 */ 1535 return nstub; 1536 } 1537 1538 void reset() { 1539 stub = null; 1540 } 1541 } 1542 1543 /** 1544 * Add a record to the activation log. If the number of updates 1545 * passes a predetermined threshold, record a snapshot. 1546 */ 1547 private void addLogRecord(LogRecord rec) throws ActivationException { 1548 synchronized (log) { 1549 checkShutdown(); 1550 try { 1551 log.update(rec, true); 1552 } catch (Exception e) { 1553 numUpdates = snapshotInterval; 1554 System.err.println(getTextResource("rmid.log.update.warning")); 1555 e.printStackTrace(); 1556 } 1557 if (++numUpdates < snapshotInterval) { 1558 return; 1559 } 1560 try { 1561 log.snapshot(this); 1562 numUpdates = 0; 1563 } catch (Exception e) { 1564 System.err.println( 1565 getTextResource("rmid.log.snapshot.warning")); 1566 e.printStackTrace(); 1567 try { 1568 // shutdown activation system because snapshot failed 1569 system.shutdown(); 1570 } catch (RemoteException ignore) { 1571 // can't happen 1572 } 1573 // warn the client of the original update problem 1574 throw new ActivationException("log snapshot failed", e); 1575 } 1576 } 1577 } 1578 1579 /** 1580 * Handler for the log that knows how to take the initial snapshot 1581 * and apply an update (a LogRecord) to the current state. 1582 */ 1583 private static class ActLogHandler extends LogHandler { 1584 1585 ActLogHandler() { 1586 } 1587 1588 public Object initialSnapshot() 1589 { 1590 /** 1591 * Return an empty Activation object. Log will update 1592 * this object with recovered state. 1593 */ 1594 return new Activation(); 1595 } 1596 1597 public Object applyUpdate(Object update, Object state) 1598 throws Exception 1599 { 1600 return ((LogRecord) update).apply(state); 1601 } 1602 1603 } 1604 1605 /** 1606 * Abstract class for all log records. The subclass contains 1607 * specific update information and implements the apply method 1608 * that applys the update information contained in the record 1609 * to the current state. 1610 */ 1611 private static abstract class LogRecord implements Serializable { 1612 /** indicate compatibility with JDK 1.2 version of class */ 1613 private static final long serialVersionUID = 8395140512322687529L; 1614 abstract Object apply(Object state) throws Exception; 1615 } 1616 1617 /** 1618 * Log record for registering an object. 1619 */ 1620 private static class LogRegisterObject extends LogRecord { 1621 /** indicate compatibility with JDK 1.2 version of class */ 1622 private static final long serialVersionUID = -6280336276146085143L; 1623 private ActivationID id; 1624 private ActivationDesc desc; 1625 1626 LogRegisterObject(ActivationID id, ActivationDesc desc) { 1627 this.id = id; 1628 this.desc = desc; 1629 } 1630 1631 Object apply(Object state) { 1632 try { 1633 ((Activation) state).getGroupEntry(desc.getGroupID()). 1634 registerObject(id, desc, false); 1635 } catch (Exception ignore) { 1636 System.err.println( 1637 MessageFormat.format( 1638 getTextResource("rmid.log.recover.warning"), 1639 "LogRegisterObject")); 1640 ignore.printStackTrace(); 1641 } 1642 return state; 1643 } 1644 } 1645 1646 /** 1647 * Log record for unregistering an object. 1648 */ 1649 private static class LogUnregisterObject extends LogRecord { 1650 /** indicate compatibility with JDK 1.2 version of class */ 1651 private static final long serialVersionUID = 6269824097396935501L; 1652 private ActivationID id; 1653 1654 LogUnregisterObject(ActivationID id) { 1655 this.id = id; 1656 } 1657 1658 Object apply(Object state) { 1659 try { 1660 ((Activation) state).getGroupEntry(id). 1661 unregisterObject(id, false); 1662 } catch (Exception ignore) { 1663 System.err.println( 1664 MessageFormat.format( 1665 getTextResource("rmid.log.recover.warning"), 1666 "LogUnregisterObject")); 1667 ignore.printStackTrace(); 1668 } 1669 return state; 1670 } 1671 } 1672 1673 /** 1674 * Log record for registering a group. 1675 */ 1676 private static class LogRegisterGroup extends LogRecord { 1677 /** indicate compatibility with JDK 1.2 version of class */ 1678 private static final long serialVersionUID = -1966827458515403625L; 1679 private ActivationGroupID id; 1680 private ActivationGroupDesc desc; 1681 1682 LogRegisterGroup(ActivationGroupID id, ActivationGroupDesc desc) { 1683 this.id = id; 1684 this.desc = desc; 1685 } 1686 1687 Object apply(Object state) { 1688 // modify state directly; cant ask a nonexistent GroupEntry 1689 // to register itself. 1690 ((Activation) state).groupTable.put(id, ((Activation) state).new 1691 GroupEntry(id, desc)); 1692 return state; 1693 } 1694 } 1695 1696 /** 1697 * Log record for udpating an activation desc 1698 */ 1699 private static class LogUpdateDesc extends LogRecord { 1700 /** indicate compatibility with JDK 1.2 version of class */ 1701 private static final long serialVersionUID = 545511539051179885L; 1702 1703 private ActivationID id; 1704 private ActivationDesc desc; 1705 1706 LogUpdateDesc(ActivationID id, ActivationDesc desc) { 1707 this.id = id; 1708 this.desc = desc; 1709 } 1710 1711 Object apply(Object state) { 1712 try { 1713 ((Activation) state).getGroupEntry(id). 1714 setActivationDesc(id, desc, false); 1715 } catch (Exception ignore) { 1716 System.err.println( 1717 MessageFormat.format( 1718 getTextResource("rmid.log.recover.warning"), 1719 "LogUpdateDesc")); 1720 ignore.printStackTrace(); 1721 } 1722 return state; 1723 } 1724 } 1725 1726 /** 1727 * Log record for unregistering a group. 1728 */ 1729 private static class LogUpdateGroupDesc extends LogRecord { 1730 /** indicate compatibility with JDK 1.2 version of class */ 1731 private static final long serialVersionUID = -1271300989218424337L; 1732 private ActivationGroupID id; 1733 private ActivationGroupDesc desc; 1734 1735 LogUpdateGroupDesc(ActivationGroupID id, ActivationGroupDesc desc) { 1736 this.id = id; 1737 this.desc = desc; 1738 } 1739 1740 Object apply(Object state) { 1741 try { 1742 ((Activation) state).getGroupEntry(id). 1743 setActivationGroupDesc(id, desc, false); 1744 } catch (Exception ignore) { 1745 System.err.println( 1746 MessageFormat.format( 1747 getTextResource("rmid.log.recover.warning"), 1748 "LogUpdateGroupDesc")); 1749 ignore.printStackTrace(); 1750 } 1751 return state; 1752 } 1753 } 1754 1755 /** 1756 * Log record for unregistering a group. 1757 */ 1758 private static class LogUnregisterGroup extends LogRecord { 1759 /** indicate compatibility with JDK 1.2 version of class */ 1760 private static final long serialVersionUID = -3356306586522147344L; 1761 private ActivationGroupID id; 1762 1763 LogUnregisterGroup(ActivationGroupID id) { 1764 this.id = id; 1765 } 1766 1767 Object apply(Object state) { 1768 GroupEntry entry = ((Activation) state).groupTable.remove(id); 1769 try { 1770 entry.unregisterGroup(false); 1771 } catch (Exception ignore) { 1772 System.err.println( 1773 MessageFormat.format( 1774 getTextResource("rmid.log.recover.warning"), 1775 "LogUnregisterGroup")); 1776 ignore.printStackTrace(); 1777 } 1778 return state; 1779 } 1780 } 1781 1782 /** 1783 * Log record for an active group incarnation 1784 */ 1785 private static class LogGroupIncarnation extends LogRecord { 1786 /** indicate compatibility with JDK 1.2 version of class */ 1787 private static final long serialVersionUID = 4146872747377631897L; 1788 private ActivationGroupID id; 1789 private long inc; 1790 1791 LogGroupIncarnation(ActivationGroupID id, long inc) { 1792 this.id = id; 1793 this.inc = inc; 1794 } 1795 1796 Object apply(Object state) { 1797 try { 1798 GroupEntry entry = ((Activation) state).getGroupEntry(id); 1799 entry.incarnation = inc; 1800 } catch (Exception ignore) { 1801 System.err.println( 1802 MessageFormat.format( 1803 getTextResource("rmid.log.recover.warning"), 1804 "LogGroupIncarnation")); 1805 ignore.printStackTrace(); 1806 } 1807 return state; 1808 } 1809 } 1810 1811 /** 1812 * Initialize command to exec a default group. 1813 */ 1814 private void initCommand(String[] childArgs) { 1815 command = new String[childArgs.length + 2]; 1816 AccessController.doPrivileged(new PrivilegedAction<Void>() { 1817 public Void run() { 1818 try { 1819 command[0] = System.getProperty("java.home") + 1820 File.separator + "bin" + File.separator + "java"; 1821 } catch (Exception e) { 1822 System.err.println( 1823 getTextResource("rmid.unfound.java.home.property")); 1824 command[0] = "java"; 1825 } 1826 return null; 1827 } 1828 }); 1829 System.arraycopy(childArgs, 0, command, 1, childArgs.length); 1830 command[command.length-1] = "sun.rmi.server.ActivationGroupInit"; 1831 } 1832 1833 private static void bomb(String error) { 1834 System.err.println("rmid: " + error); // $NON-NLS$ 1835 System.err.println(MessageFormat.format(getTextResource("rmid.usage"), 1836 "rmid")); 1837 System.exit(1); 1838 } 1839 1840 /** 1841 * The default policy for checking a command before it is executed 1842 * makes sure the appropriate com.sun.rmi.rmid.ExecPermission and 1843 * set of com.sun.rmi.rmid.ExecOptionPermissions have been granted. 1844 */ 1845 public static class DefaultExecPolicy { 1846 1847 public void checkExecCommand(ActivationGroupDesc desc, String[] cmd) 1848 throws SecurityException 1849 { 1850 PermissionCollection perms = getExecPermissions(); 1851 1852 /* 1853 * Check properties overrides. 1854 */ 1855 Properties props = desc.getPropertyOverrides(); 1856 if (props != null) { 1857 Enumeration<?> p = props.propertyNames(); 1858 while (p.hasMoreElements()) { 1859 String name = (String) p.nextElement(); 1860 String value = props.getProperty(name); 1861 String option = "-D" + name + "=" + value; 1862 try { 1863 checkPermission(perms, 1864 new ExecOptionPermission(option)); 1865 } catch (AccessControlException e) { 1866 if (value.isEmpty()) { 1867 checkPermission(perms, 1868 new ExecOptionPermission("-D" + name)); 1869 } else { 1870 throw e; 1871 } 1872 } 1873 } 1874 } 1875 1876 /* 1877 * Check group class name (allow nothing but the default), 1878 * code location (must be null), and data (must be null). 1879 */ 1880 String groupClassName = desc.getClassName(); 1881 if ((groupClassName != null && 1882 !groupClassName.equals( 1883 ActivationGroupImpl.class.getName())) || 1884 (desc.getLocation() != null) || 1885 (desc.getData() != null)) 1886 { 1887 throw new AccessControlException( 1888 "access denied (custom group implementation not allowed)"); 1889 } 1890 1891 /* 1892 * If group descriptor has a command environment, check 1893 * command and options. 1894 */ 1895 ActivationGroupDesc.CommandEnvironment cmdenv; 1896 cmdenv = desc.getCommandEnvironment(); 1897 if (cmdenv != null) { 1898 String path = cmdenv.getCommandPath(); 1899 if (path != null) { 1900 checkPermission(perms, new ExecPermission(path)); 1901 } 1902 1903 String[] options = cmdenv.getCommandOptions(); 1904 if (options != null) { 1905 for (String option : options) { 1906 checkPermission(perms, 1907 new ExecOptionPermission(option)); 1908 } 1909 } 1910 } 1911 } 1912 1913 /** 1914 * Prints warning message if installed Policy is the default Policy 1915 * implementation and globally granted permissions do not include 1916 * AllPermission or any ExecPermissions/ExecOptionPermissions. 1917 */ 1918 static void checkConfiguration() { 1919 Policy policy = 1920 AccessController.doPrivileged(new PrivilegedAction<Policy>() { 1921 public Policy run() { 1922 return Policy.getPolicy(); 1923 } 1924 }); 1925 if (!(policy instanceof PolicyFile)) { 1926 return; 1927 } 1928 PermissionCollection perms = getExecPermissions(); 1929 for (Enumeration<Permission> e = perms.elements(); 1930 e.hasMoreElements();) 1931 { 1932 Permission p = e.nextElement(); 1933 if (p instanceof AllPermission || 1934 p instanceof ExecPermission || 1935 p instanceof ExecOptionPermission) 1936 { 1937 return; 1938 } 1939 } 1940 System.err.println(getTextResource("rmid.exec.perms.inadequate")); 1941 } 1942 1943 private static PermissionCollection getExecPermissions() { 1944 /* 1945 * The approach used here is taken from the similar method 1946 * getLoaderAccessControlContext() in the class 1947 * sun.rmi.server.LoaderHandler. 1948 */ 1949 1950 // obtain permissions granted to all code in current policy 1951 PermissionCollection perms = AccessController.doPrivileged( 1952 new PrivilegedAction<PermissionCollection>() { 1953 public PermissionCollection run() { 1954 CodeSource codesource = 1955 new CodeSource(null, (Certificate[]) null); 1956 Policy p = Policy.getPolicy(); 1957 if (p != null) { 1958 return p.getPermissions(codesource); 1959 } else { 1960 return new Permissions(); 1961 } 1962 } 1963 }); 1964 1965 return perms; 1966 } 1967 1968 private static void checkPermission(PermissionCollection perms, 1969 Permission p) 1970 throws AccessControlException 1971 { 1972 if (!perms.implies(p)) { 1973 throw new AccessControlException( 1974 "access denied " + p.toString()); 1975 } 1976 } 1977 } 1978 1979 /** 1980 * Main program to start the activation system. <br> 1981 * The usage is as follows: rmid [-port num] [-log dir]. 1982 */ 1983 public static void main(String[] args) { 1984 boolean stop = false; 1985 1986 // Create and install the security manager if one is not installed 1987 // already. 1988 if (System.getSecurityManager() == null) { 1989 System.setSecurityManager(new SecurityManager()); 1990 } 1991 1992 try { 1993 int port = ActivationSystem.SYSTEM_PORT; 1994 RMIServerSocketFactory ssf = null; 1995 1996 /* 1997 * If rmid has an inherited channel (meaning that it was 1998 * launched from inetd), set the server socket factory to 1999 * return the inherited server socket. 2000 **/ 2001 Channel inheritedChannel = AccessController.doPrivileged( 2002 new PrivilegedExceptionAction<Channel>() { 2003 public Channel run() throws IOException { 2004 return System.inheritedChannel(); 2005 } 2006 }); 2007 2008 if (inheritedChannel != null && 2009 inheritedChannel instanceof ServerSocketChannel) 2010 { 2011 /* 2012 * Redirect System.err output to a file. 2013 */ 2014 AccessController.doPrivileged( 2015 new PrivilegedExceptionAction<Void>() { 2016 public Void run() throws IOException { 2017 boolean disable = Boolean.getBoolean( 2018 "sun.rmi.server.activation.disableErrRedirect"); 2019 if (disable) 2020 return null; 2021 2022 File file = 2023 Files.createTempFile("rmid-err", null).toFile(); 2024 PrintStream errStream = 2025 new PrintStream(new FileOutputStream(file)); 2026 System.setErr(errStream); 2027 return null; 2028 } 2029 }); 2030 2031 ServerSocket serverSocket = 2032 ((ServerSocketChannel) inheritedChannel).socket(); 2033 port = serverSocket.getLocalPort(); 2034 ssf = new ActivationServerSocketFactory(serverSocket); 2035 2036 System.err.println(new Date()); 2037 System.err.println(getTextResource( 2038 "rmid.inherited.channel.info") + 2039 ": " + inheritedChannel); 2040 } 2041 2042 String log = null; 2043 List<String> childArgs = new ArrayList<>(); 2044 2045 /* 2046 * Parse arguments 2047 */ 2048 for (int i = 0; i < args.length; i++) { 2049 if (args[i].equals("-port")) { 2050 if (ssf != null) { 2051 bomb(getTextResource("rmid.syntax.port.badarg")); 2052 } 2053 if ((i + 1) < args.length) { 2054 try { 2055 port = Integer.parseInt(args[++i]); 2056 } catch (NumberFormatException nfe) { 2057 bomb(getTextResource("rmid.syntax.port.badnumber")); 2058 } 2059 } else { 2060 bomb(getTextResource("rmid.syntax.port.missing")); 2061 } 2062 2063 } else if (args[i].equals("-log")) { 2064 if ((i + 1) < args.length) { 2065 log = args[++i]; 2066 } else { 2067 bomb(getTextResource("rmid.syntax.log.missing")); 2068 } 2069 2070 } else if (args[i].equals("-stop")) { 2071 stop = true; 2072 2073 } else if (args[i].startsWith("-C")) { 2074 childArgs.add(args[i].substring(2)); 2075 2076 } else { 2077 bomb(MessageFormat.format( 2078 getTextResource("rmid.syntax.illegal.option"), 2079 args[i])); 2080 } 2081 } 2082 2083 if (log == null) { 2084 if (ssf != null) { 2085 bomb(getTextResource("rmid.syntax.log.required")); 2086 } else { 2087 log = "log"; 2088 } 2089 } 2090 2091 debugExec = AccessController.doPrivileged( 2092 (PrivilegedAction<Boolean>) () -> Boolean.getBoolean("sun.rmi.server.activation.debugExec")); 2093 2094 /** 2095 * Determine class name for activation exec policy (if any). 2096 */ 2097 String execPolicyClassName = AccessController.doPrivileged( 2098 (PrivilegedAction<String>) () -> System.getProperty("sun.rmi.activation.execPolicy")); 2099 if (execPolicyClassName == null) { 2100 if (!stop) { 2101 DefaultExecPolicy.checkConfiguration(); 2102 } 2103 execPolicyClassName = "default"; 2104 } 2105 2106 /** 2107 * Initialize method for activation exec policy. 2108 */ 2109 if (!execPolicyClassName.equals("none")) { 2110 if (execPolicyClassName.isEmpty() || 2111 execPolicyClassName.equals("default")) 2112 { 2113 execPolicyClassName = DefaultExecPolicy.class.getName(); 2114 } 2115 2116 try { 2117 Class<?> execPolicyClass = getRMIClass(execPolicyClassName); 2118 @SuppressWarnings("deprecation") 2119 Object tmp = execPolicyClass.newInstance(); 2120 execPolicy = tmp; 2121 execPolicyMethod = 2122 execPolicyClass.getMethod("checkExecCommand", 2123 ActivationGroupDesc.class, 2124 String[].class); 2125 } catch (Exception e) { 2126 if (debugExec) { 2127 System.err.println( 2128 getTextResource("rmid.exec.policy.exception")); 2129 e.printStackTrace(); 2130 } 2131 bomb(getTextResource("rmid.exec.policy.invalid")); 2132 } 2133 } 2134 2135 if (stop == true) { 2136 final int finalPort = port; 2137 AccessController.doPrivileged(new PrivilegedAction<Void>() { 2138 public Void run() { 2139 System.setProperty("java.rmi.activation.port", 2140 Integer.toString(finalPort)); 2141 return null; 2142 } 2143 }); 2144 ActivationSystem system = ActivationGroup.getSystem(); 2145 system.shutdown(); 2146 System.exit(0); 2147 } 2148 2149 /* 2150 * Fix for 4173960: Create and initialize activation using 2151 * a static method, startActivation, which will build the 2152 * Activation state in two ways: if when rmid is run, no 2153 * log file is found, the ActLogHandler.recover(...) 2154 * method will create a new Activation instance. 2155 * Alternatively, if a logfile is available, a serialized 2156 * instance of activation will be read from the log's 2157 * snapshot file. Log updates will be applied to this 2158 * Activation object until rmid's state has been fully 2159 * recovered. In either case, only one instance of 2160 * Activation is created. 2161 */ 2162 startActivation(port, ssf, log, 2163 childArgs.toArray(new String[childArgs.size()])); 2164 2165 // prevent activator from exiting 2166 while (true) { 2167 try { 2168 Thread.sleep(Long.MAX_VALUE); 2169 } catch (InterruptedException e) { 2170 } 2171 } 2172 } catch (Exception e) { 2173 System.err.println( 2174 MessageFormat.format( 2175 getTextResource("rmid.unexpected.exception"), e)); 2176 e.printStackTrace(); 2177 } 2178 System.exit(1); 2179 } 2180 2181 /** 2182 * Retrieves text resources from the locale-specific properties file. 2183 */ 2184 private static String getTextResource(String key) { 2185 if (Activation.resources == null) { 2186 try { 2187 Activation.resources = ResourceBundle.getBundle( 2188 "sun.rmi.server.resources.rmid"); 2189 } catch (MissingResourceException mre) { 2190 } 2191 if (Activation.resources == null) { 2192 // throwing an Error is a bit extreme, methinks 2193 return ("[missing resource file: " + key + "]"); 2194 } 2195 } 2196 2197 String val = null; 2198 try { 2199 val = Activation.resources.getString (key); 2200 } catch (MissingResourceException mre) { 2201 } 2202 2203 if (val == null) { 2204 return ("[missing resource: " + key + "]"); 2205 } else { 2206 return val; 2207 } 2208 } 2209 2210 @SuppressWarnings("deprecation") 2211 private static Class<?> getRMIClass(String execPolicyClassName) throws Exception { 2212 return RMIClassLoader.loadClass(execPolicyClassName); 2213 } 2214 /* 2215 * Dijkstra semaphore operations to limit the number of subprocesses 2216 * rmid attempts to make at once. 2217 */ 2218 /** 2219 * Acquire the group semaphore and return a group name. Each 2220 * Pstartgroup must be followed by a Vstartgroup. The calling thread 2221 * will wait until there are fewer than <code>N</code> other threads 2222 * holding the group semaphore. The calling thread will then acquire 2223 * the semaphore and return. 2224 */ 2225 private synchronized String Pstartgroup() throws ActivationException { 2226 while (true) { 2227 checkShutdown(); 2228 // Wait until positive, then decrement. 2229 if (groupSemaphore > 0) { 2230 groupSemaphore--; 2231 return "Group-" + groupCounter++; 2232 } 2233 2234 try { 2235 wait(); 2236 } catch (InterruptedException e) { 2237 } 2238 } 2239 } 2240 2241 /** 2242 * Release the group semaphore. Every P operation must be 2243 * followed by a V operation. This may cause another thread to 2244 * wake up and return from its P operation. 2245 */ 2246 private synchronized void Vstartgroup() { 2247 // Increment and notify a waiter (not necessarily FIFO). 2248 groupSemaphore++; 2249 notifyAll(); 2250 } 2251 2252 /** 2253 * A server socket factory to use when rmid is launched via 'inetd' 2254 * with 'wait' status. This socket factory's 'createServerSocket' 2255 * method returns the server socket specified during construction that 2256 * is specialized to delay accepting requests until the 2257 * 'initDone' flag is 'true'. The server socket supplied to 2258 * the constructor should be the server socket obtained from the 2259 * ServerSocketChannel returned from the 'System.inheritedChannel' 2260 * method. 2261 **/ 2262 private static class ActivationServerSocketFactory 2263 implements RMIServerSocketFactory 2264 { 2265 private final ServerSocket serverSocket; 2266 2267 /** 2268 * Constructs an 'ActivationServerSocketFactory' with the specified 2269 * 'serverSocket'. 2270 **/ 2271 ActivationServerSocketFactory(ServerSocket serverSocket) { 2272 this.serverSocket = serverSocket; 2273 } 2274 2275 /** 2276 * Returns the server socket specified during construction wrapped 2277 * in a 'DelayedAcceptServerSocket'. 2278 **/ 2279 public ServerSocket createServerSocket(int port) 2280 throws IOException 2281 { 2282 return new DelayedAcceptServerSocket(serverSocket); 2283 } 2284 2285 } 2286 2287 /** 2288 * A server socket that delegates all public methods to the underlying 2289 * server socket specified at construction. The accept method is 2290 * overridden to delay calling accept on the underlying server socket 2291 * until the 'initDone' flag is 'true'. 2292 **/ 2293 private static class DelayedAcceptServerSocket extends ServerSocket { 2294 2295 private final ServerSocket serverSocket; 2296 2297 DelayedAcceptServerSocket(ServerSocket serverSocket) 2298 throws IOException 2299 { 2300 this.serverSocket = serverSocket; 2301 } 2302 2303 public void bind(SocketAddress endpoint) throws IOException { 2304 serverSocket.bind(endpoint); 2305 } 2306 2307 public void bind(SocketAddress endpoint, int backlog) 2308 throws IOException 2309 { 2310 serverSocket.bind(endpoint, backlog); 2311 } 2312 2313 public InetAddress getInetAddress() { 2314 return AccessController.doPrivileged( 2315 new PrivilegedAction<InetAddress>() { 2316 @Override 2317 public InetAddress run() { 2318 return serverSocket.getInetAddress(); 2319 } 2320 }); 2321 } 2322 2323 public int getLocalPort() { 2324 return serverSocket.getLocalPort(); 2325 } 2326 2327 public SocketAddress getLocalSocketAddress() { 2328 return AccessController.doPrivileged( 2329 new PrivilegedAction<SocketAddress>() { 2330 @Override 2331 public SocketAddress run() { 2332 return serverSocket.getLocalSocketAddress(); 2333 } 2334 }); 2335 } 2336 2337 /** 2338 * Delays calling accept on the underlying server socket until the 2339 * remote service is bound in the registry. 2340 **/ 2341 public Socket accept() throws IOException { 2342 synchronized (initLock) { 2343 try { 2344 while (!initDone) { 2345 initLock.wait(); 2346 } 2347 } catch (InterruptedException ignore) { 2348 throw new AssertionError(ignore); 2349 } 2350 } 2351 return serverSocket.accept(); 2352 } 2353 2354 public void close() throws IOException { 2355 serverSocket.close(); 2356 } 2357 2358 public ServerSocketChannel getChannel() { 2359 return serverSocket.getChannel(); 2360 } 2361 2362 public boolean isBound() { 2363 return serverSocket.isBound(); 2364 } 2365 2366 public boolean isClosed() { 2367 return serverSocket.isClosed(); 2368 } 2369 2370 public void setSoTimeout(int timeout) 2371 throws SocketException 2372 { 2373 serverSocket.setSoTimeout(timeout); 2374 } 2375 2376 public int getSoTimeout() throws IOException { 2377 return serverSocket.getSoTimeout(); 2378 } 2379 2380 public void setReuseAddress(boolean on) throws SocketException { 2381 serverSocket.setReuseAddress(on); 2382 } 2383 2384 public boolean getReuseAddress() throws SocketException { 2385 return serverSocket.getReuseAddress(); 2386 } 2387 2388 public String toString() { 2389 return serverSocket.toString(); 2390 } 2391 2392 public void setReceiveBufferSize(int size) 2393 throws SocketException 2394 { 2395 serverSocket.setReceiveBufferSize(size); 2396 } 2397 2398 public int getReceiveBufferSize() 2399 throws SocketException 2400 { 2401 return serverSocket.getReceiveBufferSize(); 2402 } 2403 } 2404 } 2405 2406 /** 2407 * PipeWriter plugs together two pairs of input and output streams by 2408 * providing readers for input streams and writing through to 2409 * appropriate output streams. Both output streams are annotated on a 2410 * per-line basis. 2411 * 2412 * @author Laird Dornin, much code borrowed from Peter Jones, Ken 2413 * Arnold and Ann Wollrath. 2414 */ 2415 class PipeWriter implements Runnable { 2416 2417 /** stream used for buffering lines */ 2418 private ByteArrayOutputStream bufOut; 2419 2420 /** count since last separator */ 2421 private int cLast; 2422 2423 /** current chunk of input being compared to lineSeparator.*/ 2424 private byte[] currSep; 2425 2426 private PrintWriter out; 2427 private InputStream in; 2428 2429 private String pipeString; 2430 private String execString; 2431 2432 private static String lineSeparator; 2433 private static int lineSeparatorLength; 2434 2435 private static int numExecs = 0; 2436 2437 static { 2438 lineSeparator = AccessController.doPrivileged( 2439 (PrivilegedAction<String>) () -> System.getProperty("line.separator")); 2440 lineSeparatorLength = lineSeparator.length(); 2441 } 2442 2443 /** 2444 * Create a new PipeWriter object. All methods of PipeWriter, 2445 * except plugTogetherPair, are only accesible to PipeWriter 2446 * itself. Synchronization is unnecessary on functions that will 2447 * only be used internally in PipeWriter. 2448 * 2449 * @param in input stream from which pipe input flows 2450 * @param out output stream to which log messages will be sent 2451 * @param dest String which tags output stream as 'out' or 'err' 2452 * @param nExecs number of execed processes, Activation groups. 2453 */ 2454 private PipeWriter 2455 (InputStream in, OutputStream out, String tag, int nExecs) { 2456 2457 this.in = in; 2458 this.out = new PrintWriter(out); 2459 2460 bufOut = new ByteArrayOutputStream(); 2461 currSep = new byte[lineSeparatorLength]; 2462 2463 /* set unique pipe/pair annotations */ 2464 execString = ":ExecGroup-" + 2465 Integer.toString(nExecs) + ':' + tag + ':'; 2466 } 2467 2468 /** 2469 * Create a thread to listen and read from input stream, in. buffer 2470 * the data that is read until a marker which equals lineSeparator 2471 * is read. Once such a string has been discovered; write out an 2472 * annotation string followed by the buffered data and a line 2473 * separator. 2474 */ 2475 public void run() { 2476 byte[] buf = new byte[256]; 2477 int count; 2478 2479 try { 2480 /* read bytes till there are no more. */ 2481 while ((count = in.read(buf)) != -1) { 2482 write(buf, 0, count); 2483 } 2484 2485 /* flush internal buffer... may not have ended on a line 2486 * separator, we also need a last annotation if 2487 * something was left. 2488 */ 2489 String lastInBuffer = bufOut.toString(); 2490 bufOut.reset(); 2491 if (lastInBuffer.length() > 0) { 2492 out.println (createAnnotation() + lastInBuffer); 2493 out.flush(); // add a line separator 2494 // to make output nicer 2495 } 2496 2497 } catch (IOException e) { 2498 } 2499 } 2500 2501 /** 2502 * Write a subarray of bytes. Pass each through write byte method. 2503 */ 2504 private void write(byte b[], int off, int len) throws IOException { 2505 2506 if (len < 0) { 2507 throw new ArrayIndexOutOfBoundsException(len); 2508 } 2509 for (int i = 0; i < len; ++ i) { 2510 write(b[off + i]); 2511 } 2512 } 2513 2514 /** 2515 * Write a byte of data to the stream. If we have not matched a 2516 * line separator string, then the byte is appended to the internal 2517 * buffer. If we have matched a line separator, then the currently 2518 * buffered line is sent to the output writer with a prepended 2519 * annotation string. 2520 */ 2521 private void write(byte b) throws IOException { 2522 int i = 0; 2523 2524 /* shift current to the left */ 2525 for (i = 1 ; i < (currSep.length); i ++) { 2526 currSep[i-1] = currSep[i]; 2527 } 2528 currSep[i-1] = b; 2529 bufOut.write(b); 2530 2531 /* enough characters for a separator? */ 2532 if ( (cLast >= (lineSeparatorLength - 1)) && 2533 (lineSeparator.equals(new String(currSep))) ) { 2534 2535 cLast = 0; 2536 2537 /* write prefix through to underlying byte stream */ 2538 out.print(createAnnotation() + bufOut.toString()); 2539 out.flush(); 2540 bufOut.reset(); 2541 2542 if (out.checkError()) { 2543 throw new IOException 2544 ("PipeWriter: IO Exception when"+ 2545 " writing to output stream."); 2546 } 2547 2548 } else { 2549 cLast++; 2550 } 2551 } 2552 2553 /** 2554 * Create an annotation string to be printed out after 2555 * a new line and end of stream. 2556 */ 2557 private String createAnnotation() { 2558 2559 /* construct prefix for log messages: 2560 * date/time stamp... 2561 */ 2562 return ((new Date()).toString() + 2563 /* ... print pair # ... */ 2564 (execString)); 2565 } 2566 2567 /** 2568 * Allow plugging together two pipes at a time, to associate 2569 * output from an execed process. This is the only publicly 2570 * accessible method of this object; this helps ensure that 2571 * synchronization will not be an issue in the annotation 2572 * process. 2573 * 2574 * @param in input stream from which pipe input comes 2575 * @param out output stream to which log messages will be sent 2576 * @param in1 input stream from which pipe input comes 2577 * @param out1 output stream to which log messages will be sent 2578 */ 2579 static void plugTogetherPair(InputStream in, 2580 OutputStream out, 2581 InputStream in1, 2582 OutputStream out1) { 2583 Thread inThread = null; 2584 Thread outThread = null; 2585 2586 int nExecs = getNumExec(); 2587 2588 /* start RMI threads to read output from child process */ 2589 inThread = AccessController.doPrivileged( 2590 new NewThreadAction(new PipeWriter(in, out, "out", nExecs), 2591 "out", true)); 2592 outThread = AccessController.doPrivileged( 2593 new NewThreadAction(new PipeWriter(in1, out1, "err", nExecs), 2594 "err", true)); 2595 inThread.start(); 2596 outThread.start(); 2597 } 2598 2599 private static synchronized int getNumExec() { 2600 return numExecs++; 2601 } 2602 }