aboutsummaryrefslogtreecommitdiff
path: root/src/share/classes/sun/rmi/server/LoaderHandler.java
blob: d4a9183e4a368bd8002b3a86bee9058dde58fdb3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
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
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
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
220
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
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
582
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
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
/*
 * Copyright 1996-2005 Sun Microsystems, Inc.  All Rights Reserved.
 * 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
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * 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.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package sun.rmi.server;

import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.SoftReference;
import java.lang.ref.WeakReference;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.SocketPermission;
import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLConnection;
import java.security.AccessControlContext;
import java.security.CodeSource;
import java.security.Permission;
import java.security.Permissions;
import java.security.PermissionCollection;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.rmi.server.LogStream;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.StringTokenizer;
import java.util.WeakHashMap;
import sun.rmi.runtime.Log;
import sun.security.action.GetPropertyAction;

/**
 * <code>LoaderHandler</code> provides the implementation of the static
 * methods of the <code>java.rmi.server.RMIClassLoader</code> class.
 *
 * @author      Ann Wollrath
 * @author      Peter Jones
 * @author      Laird Dornin
 */
public final class LoaderHandler {

    /** RMI class loader log level */
    static final int logLevel = LogStream.parseLevel(
        (String) java.security.AccessController.doPrivileged(
            new GetPropertyAction("sun.rmi.loader.logLevel")));

    /* loader system log */
    static final Log loaderLog =
        Log.getLog("sun.rmi.loader", "loader", LoaderHandler.logLevel);

    /**
     * value of "java.rmi.server.codebase" property, as cached at class
     * initialization time.  It may contain malformed URLs.
     */
    private static String codebaseProperty = null;
    static {
        String prop = (String) java.security.AccessController.doPrivileged(
            new GetPropertyAction("java.rmi.server.codebase"));
        if (prop != null && prop.trim().length() > 0) {
            codebaseProperty = prop;
        }
    }

    /** list of URLs represented by the codebase property, if valid */
    private static URL[] codebaseURLs = null;

    /** table of class loaders that use codebase property for annotation */
    private static final Map codebaseLoaders =
        Collections.synchronizedMap(new IdentityHashMap(5));
    static {
        for (ClassLoader codebaseLoader = ClassLoader.getSystemClassLoader();
             codebaseLoader != null;
             codebaseLoader = codebaseLoader.getParent())
        {
            codebaseLoaders.put(codebaseLoader, null);
        }
    }

    /**
     * table mapping codebase URL path and context class loader pairs
     * to class loader instances.  Entries hold class loaders with weak
     * references, so this table does not prevent loaders from being
     * garbage collected.
     */
    private static final HashMap loaderTable = new HashMap(5);

    /** reference queue for cleared class loader entries */
    private static final ReferenceQueue refQueue = new ReferenceQueue();

    /*
     * Disallow anyone from creating one of these.
     */
    private LoaderHandler() {}

    /**
     * Returns an array of URLs initialized with the value of the
     * java.rmi.server.codebase property as the URL path.
     */
    private static synchronized URL[] getDefaultCodebaseURLs()
        throws MalformedURLException
    {
        /*
         * If it hasn't already been done, convert the codebase property
         * into an array of URLs; this may throw a MalformedURLException.
         */
        if (codebaseURLs == null) {
            if (codebaseProperty != null) {
                codebaseURLs = pathToURLs(codebaseProperty);
            } else {
                codebaseURLs = new URL[0];
            }
        }
        return codebaseURLs;
    }

    /**
     * Load a class from a network location (one or more URLs),
     * but first try to resolve the named class through the given
     * "default loader".
     */
    public static Class loadClass(String codebase, String name,
                                  ClassLoader defaultLoader)
        throws MalformedURLException, ClassNotFoundException
    {
        if (loaderLog.isLoggable(Log.BRIEF)) {
            loaderLog.log(Log.BRIEF,
                "name = \"" + name + "\", " +
                "codebase = \"" + (codebase != null ? codebase : "") + "\"" +
                (defaultLoader != null ?
                 ", defaultLoader = " + defaultLoader : ""));
        }

        URL[] urls;
        if (codebase != null) {
            urls = pathToURLs(codebase);
        } else {
            urls = getDefaultCodebaseURLs();
        }

        if (defaultLoader != null) {
            try {
                Class c = Class.forName(name, false, defaultLoader);
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    loaderLog.log(Log.VERBOSE,
                        "class \"" + name + "\" found via defaultLoader, " +
                        "defined by " + c.getClassLoader());
                }
                return c;
            } catch (ClassNotFoundException e) {
            }
        }

        return loadClass(urls, name);
    }

    /**
     * Returns the class annotation (representing the location for
     * a class) that RMI will use to annotate the call stream when
     * marshalling objects of the given class.
     */
    public static String getClassAnnotation(Class cl) {
        String name = cl.getName();

        /*
         * Class objects for arrays of primitive types never need an
         * annotation, because they never need to be (or can be) downloaded.
         *
         * REMIND: should we (not) be annotating classes that are in
         * "java.*" packages?
         */
        int nameLength = name.length();
        if (nameLength > 0 && name.charAt(0) == '[') {
            // skip past all '[' characters (see bugid 4211906)
            int i = 1;
            while (nameLength > i && name.charAt(i) == '[') {
                i++;
            }
            if (nameLength > i && name.charAt(i) != 'L') {
                return null;
            }
        }

        /*
         * Get the class's class loader.  If it is null, the system class
         * loader, an ancestor of the base class loader (such as the loader
         * for installed extensions), return the value of the
         * "java.rmi.server.codebase" property.
         */
        ClassLoader loader = cl.getClassLoader();
        if (loader == null || codebaseLoaders.containsKey(loader)) {
            return codebaseProperty;
        }

        /*
         * Get the codebase URL path for the class loader, if it supports
         * such a notion (i.e., if it is a URLClassLoader or subclass).
         */
        String annotation = null;
        if (loader instanceof Loader) {
            /*
             * If the class loader is one of our RMI class loaders, we have
             * already computed the class annotation string, and no
             * permissions are required to know the URLs.
             */
            annotation = ((Loader) loader).getClassAnnotation();

        } else if (loader instanceof URLClassLoader) {
            try {
                URL[] urls = ((URLClassLoader) loader).getURLs();
                if (urls != null) {
                    /*
                     * If the class loader is not one of our RMI class loaders,
                     * we must verify that the current access control context
                     * has permission to know all of these URLs.
                     */
                    SecurityManager sm = System.getSecurityManager();
                    if (sm != null) {
                        Permissions perms = new Permissions();
                        for (int i = 0; i < urls.length; i++) {
                            Permission p =
                                urls[i].openConnection().getPermission();
                            if (p != null) {
                                if (!perms.implies(p)) {
                                    sm.checkPermission(p);
                                    perms.add(p);
                                }
                            }
                        }
                    }

                    annotation = urlsToPath(urls);
                }
            } catch (SecurityException e) {
                /*
                 * If access was denied to the knowledge of the class
                 * loader's URLs, fall back to the default behavior.
                 */
            } catch (IOException e) {
                /*
                 * This shouldn't happen, although it is declared to be
                 * thrown by openConnection() and getPermission().  If it
                 * does happen, forget about this class loader's URLs and
                 * fall back to the default behavior.
                 */
            }
        }

        if (annotation != null) {
            return annotation;
        } else {
            return codebaseProperty;    // REMIND: does this make sense??
        }
    }

    /**
     * Returns a classloader that loads classes from the given codebase URL
     * path.  The parent classloader of the returned classloader is the
     * context class loader.
     */
    public static ClassLoader getClassLoader(String codebase)
        throws MalformedURLException
    {
        ClassLoader parent = getRMIContextClassLoader();

        URL[] urls;
        if (codebase != null) {
            urls = pathToURLs(codebase);
        } else {
            urls = getDefaultCodebaseURLs();
        }

        /*
         * If there is a security manager, the current access control
         * context must have the "getClassLoader" RuntimePermission.
         */
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(new RuntimePermission("getClassLoader"));
        } else {
            /*
             * But if no security manager is set, disable access to
             * RMI class loaders and simply return the parent loader.
             */
            return parent;
        }

        Loader loader = lookupLoader(urls, parent);

        /*
         * Verify that the caller has permission to access this loader.
         */
        if (loader != null) {
            loader.checkPermissions();
        }

        return loader;
    }

    /**
     * Return the security context of the given class loader.
     */
    public static Object getSecurityContext(ClassLoader loader) {
        /*
         * REMIND: This is a bogus JDK1.1-compatible implementation.
         * This method should never be called by application code anyway
         * (hence the deprecation), but should it do something different
         * and perhaps more useful, like return a String or a URL[]?
         */
        if (loader instanceof Loader) {
            URL[] urls = ((Loader) loader).getURLs();
            if (urls.length > 0) {
                return urls[0];
            }
        }
        return null;
    }

    /**
     * Register a class loader as one whose classes should always be
     * annotated with the value of the "java.rmi.server.codebase" property.
     */
    public static void registerCodebaseLoader(ClassLoader loader) {
        codebaseLoaders.put(loader, null);
    }

    /**
     * Load a class from the RMI class loader corresponding to the given
     * codebase URL path in the current execution context.
     */
    private static Class loadClass(URL[] urls, String name)
        throws ClassNotFoundException
    {
        ClassLoader parent = getRMIContextClassLoader();
        if (loaderLog.isLoggable(Log.VERBOSE)) {
            loaderLog.log(Log.VERBOSE,
                "(thread context class loader: " + parent + ")");
        }

        /*
         * If no security manager is set, disable access to RMI class
         * loaders and simply delegate request to the parent loader
         * (see bugid 4140511).
         */
        SecurityManager sm = System.getSecurityManager();
        if (sm == null) {
            try {
                Class c = Class.forName(name, false, parent);
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    loaderLog.log(Log.VERBOSE,
                        "class \"" + name + "\" found via " +
                        "thread context class loader " +
                        "(no security manager: codebase disabled), " +
                        "defined by " + c.getClassLoader());
                }
                return c;
            } catch (ClassNotFoundException e) {
                if (loaderLog.isLoggable(Log.BRIEF)) {
                    loaderLog.log(Log.BRIEF,
                        "class \"" + name + "\" not found via " +
                        "thread context class loader " +
                        "(no security manager: codebase disabled)", e);
                }
                throw new ClassNotFoundException(e.getMessage() +
                    " (no security manager: RMI class loader disabled)",
                    e.getException());
            }
        }

        /*
         * Get or create the RMI class loader for this codebase URL path
         * and parent class loader pair.
         */
        Loader loader = lookupLoader(urls, parent);

        try {
            if (loader != null) {
                /*
                 * Verify that the caller has permission to access this loader.
                 */
                loader.checkPermissions();
            }
        } catch (SecurityException e) {
            /*
             * If the current access control context does not have permission
             * to access all of the URLs in the codebase path, wrap the
             * resulting security exception in a ClassNotFoundException, so
             * the caller can handle this outcome just like any other class
             * loading failure (see bugid 4146529).
             */
            try {
                /*
                 * But first, check to see if the named class could have been
                 * resolved without the security-offending codebase anyway;
                 * if so, return successfully (see bugids 4191926 & 4349670).
                 */
                Class c = Class.forName(name, false, parent);
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    loaderLog.log(Log.VERBOSE,
                        "class \"" + name + "\" found via " +
                        "thread context class loader " +
                        "(access to codebase denied), " +
                        "defined by " + c.getClassLoader());
                }
                return c;
            } catch (ClassNotFoundException unimportant) {
                /*
                 * Presumably the security exception is the more important
                 * exception to report in this case.
                 */
                if (loaderLog.isLoggable(Log.BRIEF)) {
                    loaderLog.log(Log.BRIEF,
                        "class \"" + name + "\" not found via " +
                        "thread context class loader " +
                        "(access to codebase denied)", e);
                }
                throw new ClassNotFoundException(
                    "access to class loader denied", e);
            }
        }

        try {
            Class c = Class.forName(name, false, loader);
            if (loaderLog.isLoggable(Log.VERBOSE)) {
                loaderLog.log(Log.VERBOSE,
                    "class \"" + name + "\" " + "found via codebase, " +
                    "defined by " + c.getClassLoader());
            }
            return c;
        } catch (ClassNotFoundException e) {
            if (loaderLog.isLoggable(Log.BRIEF)) {
                loaderLog.log(Log.BRIEF,
                    "class \"" + name + "\" not found via codebase", e);
            }
            throw e;
        }
    }

    /**
     * Define and return a dynamic proxy class in a class loader with
     * URLs supplied in the given location.  The proxy class will
     * implement interface classes named by the given array of
     * interface names.
     */
    public static Class loadProxyClass(String codebase, String[] interfaces,
                                       ClassLoader defaultLoader)
        throws MalformedURLException, ClassNotFoundException
    {
        if (loaderLog.isLoggable(Log.BRIEF)) {
            loaderLog.log(Log.BRIEF,
                "interfaces = " + Arrays.asList(interfaces) + ", " +
                "codebase = \"" + (codebase != null ? codebase : "") + "\"" +
                (defaultLoader != null ?
                 ", defaultLoader = " + defaultLoader : ""));
        }

        /*
         * This method uses a fairly complex algorithm to load the
         * proxy class and its interface classes in order to maximize
         * the likelihood that the proxy's codebase annotation will be
         * preserved.  The algorithm is (assuming that all of the
         * proxy interface classes are public):
         *
         * If the default loader is not null, try to load the proxy
         * interfaces through that loader. If the interfaces can be
         * loaded in that loader, try to define the proxy class in an
         * RMI class loader (child of the context class loader) before
         * trying to define the proxy in the default loader.  If the
         * attempt to define the proxy class succeeds, the codebase
         * annotation is preserved.  If the attempt fails, try to
         * define the proxy class in the default loader.
         *
         * If the interface classes can not be loaded from the default
         * loader or the default loader is null, try to load them from
         * the RMI class loader.  Then try to define the proxy class
         * in the RMI class loader.
         *
         * Additionally, if any of the proxy interface classes are not
         * public, all of the non-public interfaces must reside in the
         * same class loader or it will be impossible to define the
         * proxy class (an IllegalAccessError will be thrown).  An
         * attempt to load the interfaces from the default loader is
         * made.  If the attempt fails, a second attempt will be made
         * to load the interfaces from the RMI loader. If all of the
         * non-public interfaces classes do reside in the same class
         * loader, then we attempt to define the proxy class in the
         * class loader of the non-public interfaces.  No other
         * attempt to define the proxy class will be made.
         */
        ClassLoader parent = getRMIContextClassLoader();
        if (loaderLog.isLoggable(Log.VERBOSE)) {
            loaderLog.log(Log.VERBOSE,
                "(thread context class loader: " + parent + ")");
        }

        URL[] urls;
        if (codebase != null) {
            urls = pathToURLs(codebase);
        } else {
            urls = getDefaultCodebaseURLs();
        }

        /*
         * If no security manager is set, disable access to RMI class
         * loaders and use the would-de parent instead.
         */
        SecurityManager sm = System.getSecurityManager();
        if (sm == null) {
            try {
                Class c = loadProxyClass(interfaces, defaultLoader, parent,
                                         false);
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    loaderLog.log(Log.VERBOSE,
                        "(no security manager: codebase disabled) " +
                        "proxy class defined by " + c.getClassLoader());
                }
                return c;
            } catch (ClassNotFoundException e) {
                if (loaderLog.isLoggable(Log.BRIEF)) {
                    loaderLog.log(Log.BRIEF,
                        "(no security manager: codebase disabled) " +
                        "proxy class resolution failed", e);
                }
                throw new ClassNotFoundException(e.getMessage() +
                    " (no security manager: RMI class loader disabled)",
                    e.getException());
            }
        }

        /*
         * Get or create the RMI class loader for this codebase URL path
         * and parent class loader pair.
         */
        Loader loader = lookupLoader(urls, parent);

        try {
            if (loader != null) {
                /*
                 * Verify that the caller has permission to access this loader.
                 */
                loader.checkPermissions();
            }
        } catch (SecurityException e) {
            /*
             * If the current access control context does not have permission
             * to access all of the URLs in the codebase path, wrap the
             * resulting security exception in a ClassNotFoundException, so
             * the caller can handle this outcome just like any other class
             * loading failure (see bugid 4146529).
             */
            try {
                /*
                 * But first, check to see if the proxy class could have been
                 * resolved without the security-offending codebase anyway;
                 * if so, return successfully (see bugids 4191926 & 4349670).
                 */
                Class c = loadProxyClass(interfaces, defaultLoader, parent,
                                         false);
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    loaderLog.log(Log.VERBOSE,
                        "(access to codebase denied) " +
                        "proxy class defined by " + c.getClassLoader());
                }
                return c;
            } catch (ClassNotFoundException unimportant) {
                /*
                 * Presumably the security exception is the more important
                 * exception to report in this case.
                 */
                if (loaderLog.isLoggable(Log.BRIEF)) {
                    loaderLog.log(Log.BRIEF,
                        "(access to codebase denied) " +
                        "proxy class resolution failed", e);
                }
                throw new ClassNotFoundException(
                    "access to class loader denied", e);
            }
        }

        try {
            Class c = loadProxyClass(interfaces, defaultLoader, loader, true);
            if (loaderLog.isLoggable(Log.VERBOSE)) {
                loaderLog.log(Log.VERBOSE,
                              "proxy class defined by " + c.getClassLoader());
            }
            return c;
        } catch (ClassNotFoundException e) {
            if (loaderLog.isLoggable(Log.BRIEF)) {
                loaderLog.log(Log.BRIEF,
                              "proxy class resolution failed", e);
            }
            throw e;
        }
    }

    /**
     * Define a proxy class in the default loader if appropriate.
     * Define the class in an RMI class loader otherwise.  The proxy
     * class will implement classes which are named in the supplied
     * interfaceNames.
     */
    private static Class loadProxyClass(String[] interfaceNames,
                                        ClassLoader defaultLoader,
                                        ClassLoader codebaseLoader,
                                        boolean preferCodebase)
        throws ClassNotFoundException
    {
        ClassLoader proxyLoader = null;
        Class[] classObjs = new Class[interfaceNames.length];
        boolean[] nonpublic = { false };

      defaultLoaderCase:
        if (defaultLoader != null) {
            try {
                proxyLoader =
                    loadProxyInterfaces(interfaceNames, defaultLoader,
                                        classObjs, nonpublic);
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    ClassLoader[] definingLoaders =
                        new ClassLoader[classObjs.length];
                    for (int i = 0; i < definingLoaders.length; i++) {
                        definingLoaders[i] = classObjs[i].getClassLoader();
                    }
                    loaderLog.log(Log.VERBOSE,
                        "proxy interfaces found via defaultLoader, " +
                        "defined by " + Arrays.asList(definingLoaders));
                }
            } catch (ClassNotFoundException e) {
                break defaultLoaderCase;
            }
            if (!nonpublic[0]) {
                if (preferCodebase) {
                    try {
                        return Proxy.getProxyClass(codebaseLoader, classObjs);
                    } catch (IllegalArgumentException e) {
                    }
                }
                proxyLoader = defaultLoader;
            }
            return loadProxyClass(proxyLoader, classObjs);
        }

        nonpublic[0] = false;
        proxyLoader = loadProxyInterfaces(interfaceNames, codebaseLoader,
                                          classObjs, nonpublic);
        if (loaderLog.isLoggable(Log.VERBOSE)) {
            ClassLoader[] definingLoaders = new ClassLoader[classObjs.length];
            for (int i = 0; i < definingLoaders.length; i++) {
                definingLoaders[i] = classObjs[i].getClassLoader();
            }
            loaderLog.log(Log.VERBOSE,
                "proxy interfaces found via codebase, " +
                "defined by " + Arrays.asList(definingLoaders));
        }
        if (!nonpublic[0]) {
            proxyLoader = codebaseLoader;
        }
        return loadProxyClass(proxyLoader, classObjs);
    }

    /**
     * Define a proxy class in the given class loader.  The proxy
     * class will implement the given interfaces Classes.
     */
    private static Class loadProxyClass(ClassLoader loader, Class[] interfaces)
        throws ClassNotFoundException
    {
        try {
            return Proxy.getProxyClass(loader, interfaces);
        } catch (IllegalArgumentException e) {
            throw new ClassNotFoundException(
                "error creating dynamic proxy class", e);
        }
    }

    /*
     * Load Class objects for the names in the interfaces array fron
     * the given class loader.
     *
     * We pass classObjs and nonpublic arrays to avoid needing a
     * multi-element return value.  nonpublic is an array to enable
     * the method to take a boolean argument by reference.
     *
     * nonpublic array is needed to signal when the return value of
     * this method should be used as the proxy class loader.  Because
     * null represents a valid class loader, that value is
     * insufficient to signal that the return value should not be used
     * as the proxy class loader.
     */
    private static ClassLoader loadProxyInterfaces(String[] interfaces,
                                                   ClassLoader loader,
                                                   Class[] classObjs,
                                                   boolean[] nonpublic)
        throws ClassNotFoundException
    {
        /* loader of a non-public interface class */
        ClassLoader nonpublicLoader = null;

        for (int i = 0; i < interfaces.length; i++) {
            Class cl =
                (classObjs[i] = Class.forName(interfaces[i], false, loader));

            if (!Modifier.isPublic(cl.getModifiers())) {
                ClassLoader current = cl.getClassLoader();
                if (loaderLog.isLoggable(Log.VERBOSE)) {
                    loaderLog.log(Log.VERBOSE,
                        "non-public interface \"" + interfaces[i] +
                        "\" defined by " + current);
                }
                if (!nonpublic[0]) {
                    nonpublicLoader = current;
                    nonpublic[0] = true;
                } else if (current != nonpublicLoader) {
                    throw new IllegalAccessError(
                        "non-public interfaces defined in different " +
                        "class loaders");
                }
            }
        }
        return nonpublicLoader;
    }

    /**
     * Convert a string containing a space-separated list of URLs into a
     * corresponding array of URL objects, throwing a MalformedURLException
     * if any of the URLs are invalid.
     */
    private static URL[] pathToURLs(String path)
        throws MalformedURLException
    {
        synchronized (pathToURLsCache) {
            Object[] v = (Object[]) pathToURLsCache.get(path);
            if (v != null) {
                return ((URL[])v[0]);
            }
        }
        StringTokenizer st = new StringTokenizer(path); // divide by spaces
        URL[] urls = new URL[st.countTokens()];
        for (int i = 0; st.hasMoreTokens(); i++) {
            urls[i] = new URL(st.nextToken());
        }
        synchronized (pathToURLsCache) {
            pathToURLsCache.put(path,
                                new Object[] {urls, new SoftReference(path)});
        }
        return urls;
    }

    /** map from weak(key=string) to [URL[], soft(key)] */
    private static final Map pathToURLsCache = new WeakHashMap(5);

    /**
     * Convert an array of URL objects into a corresponding string
     * containing a space-separated list of URLs.
     *
     * Note that if the array has zero elements, the return value is
     * null, not the empty string.
     */
    private static String urlsToPath(URL[] urls) {
        if (urls.length == 0) {
            return null;
        } else if (urls.length == 1) {
            return urls[0].toExternalForm();
        } else {
            StringBuffer path = new StringBuffer(urls[0].toExternalForm());
            for (int i = 1; i < urls.length; i++) {
                path.append(' ');
                path.append(urls[i].toExternalForm());
            }
            return path.toString();
        }
    }

    /**
     * Return the class loader to be used as the parent for an RMI class
     * loader used in the current execution context.
     */
    private static ClassLoader getRMIContextClassLoader() {
        /*
         * The current implementation simply uses the current thread's
         * context class loader.
         */
        return Thread.currentThread().getContextClassLoader();
    }

    /**
     * Look up the RMI class loader for the given codebase URL path
     * and the given parent class loader.  A new class loader instance
     * will be created and returned if no match is found.
     */
    private static Loader lookupLoader(final URL[] urls,
                                       final ClassLoader parent)
    {
        /*
         * If the requested codebase URL path is empty, the supplied
         * parent class loader will be sufficient.
         *
         * REMIND: To be conservative, this optimization is commented out
         * for now so that it does not open a security hole in the future
         * by providing untrusted code with direct access to the public
         * loadClass() method of a class loader instance that it cannot
         * get a reference to.  (It's an unlikely optimization anyway.)
         *
         * if (urls.length == 0) {
         *     return parent;
         * }
         */

        LoaderEntry entry;
        Loader loader;

        synchronized (LoaderHandler.class) {
            /*
             * Take this opportunity to remove from the table entries
             * whose weak references have been cleared.
             */
            while ((entry = (LoaderEntry) refQueue.poll()) != null) {
                if (!entry.removed) {   // ignore entries removed below
                    loaderTable.remove(entry.key);
                }
            }

            /*
             * Look up the codebase URL path and parent class loader pair
             * in the table of RMI class loaders.
             */
            LoaderKey key = new LoaderKey(urls, parent);
            entry = (LoaderEntry) loaderTable.get(key);

            if (entry == null || (loader = (Loader) entry.get()) == null) {
                /*
                 * If entry was in table but it's weak reference was cleared,
                 * remove it from the table and mark it as explicitly cleared,
                 * so that new matching entry that we put in the table will
                 * not be erroneously removed when this entry is processed
                 * from the weak reference queue.
                 */
                if (entry != null) {
                    loaderTable.remove(key);
                    entry.removed = true;
                }

                /*
                 * A matching loader was not found, so create a new class
                 * loader instance for the requested codebase URL path and
                 * parent class loader.  The instance is created within an
                 * access control context retricted to the permissions
                 * necessary to load classes from its codebase URL path.
                 */
                AccessControlContext acc = getLoaderAccessControlContext(urls);
                loader = (Loader) java.security.AccessController.doPrivileged(
                    new java.security.PrivilegedAction() {
                        public Object run() {
                            return new Loader(urls, parent);
                        }
                    }, acc);

                /*
                 * Finally, create an entry to hold the new loader with a
                 * weak reference and store it in the table with the key.
                 */
                entry = new LoaderEntry(key, loader);
                loaderTable.put(key, entry);
            }
        }

        return loader;
    }

    /**
     * LoaderKey holds a codebase URL path and parent class loader pair
     * used to look up RMI class loader instances in its class loader cache.
     */
    private static class LoaderKey {

        private URL[] urls;

        private ClassLoader parent;

        private int hashValue;

        public LoaderKey(URL[] urls, ClassLoader parent) {
            this.urls = urls;
            this.parent = parent;

            if (parent != null) {
                hashValue = parent.hashCode();
            }
            for (int i = 0; i < urls.length; i++) {
                hashValue ^= urls[i].hashCode();
            }
        }

        public int hashCode() {
            return hashValue;
        }

        public boolean equals(Object obj) {
            if (obj instanceof LoaderKey) {
                LoaderKey other = (LoaderKey) obj;
                if (parent != other.parent) {
                    return false;
                }
                if (urls == other.urls) {
                    return true;
                }
                if (urls.length != other.urls.length) {
                    return false;
                }
                for (int i = 0; i < urls.length; i++) {
                    if (!urls[i].equals(other.urls[i])) {
                        return false;
                    }
                }
                return true;
            } else {
                return false;
            }
        }
    }

    /**
     * LoaderEntry contains a weak reference to an RMIClassLoader.  The
     * weak reference is registered with the private static "refQueue"
     * queue.  The entry contains the codebase URL path and parent class
     * loader key for the loader so that the mapping can be removed from
     * the table efficiently when the weak reference is cleared.
     */
    private static class LoaderEntry extends WeakReference {

        public LoaderKey key;

        /**
         * set to true if the entry has been removed from the table
         * because it has been replaced, so it should not be attempted
         * to be removed again
         */
        public boolean removed = false;

        public LoaderEntry(LoaderKey key, Loader loader) {
            super(loader, refQueue);
            this.key = key;
        }
    }

    /**
     * Return the access control context that a loader for the given
     * codebase URL path should execute with.
     */
    private static AccessControlContext getLoaderAccessControlContext(
        URL[] urls)
    {
        /*
         * The approach used here is taken from the similar method
         * getAccessControlContext() in the sun.applet.AppletPanel class.
         */
        // begin with permissions granted to all code in current policy
        PermissionCollection perms = (PermissionCollection)
            java.security.AccessController.doPrivileged(
                new java.security.PrivilegedAction() {
                public Object run() {
                    CodeSource codesource = new CodeSource(null,
                        (java.security.cert.Certificate[]) null);
                    Policy p = java.security.Policy.getPolicy();
                    if (p != null) {
                        return p.getPermissions(codesource);
                    } else {
                        return new Permissions();
                    }
                }
            });

        // createClassLoader permission needed to create loader in context
        perms.add(new RuntimePermission("createClassLoader"));

        // add permissions to read any "java.*" property
        perms.add(new java.util.PropertyPermission("java.*","read"));

        // add permissions reuiqred to load from codebase URL path
        addPermissionsForURLs(urls, perms, true);

        /*
         * Create an AccessControlContext that consists of a single
         * protection domain with only the permissions calculated above.
         */
        ProtectionDomain pd = new ProtectionDomain(
            new CodeSource((urls.length > 0 ? urls[0] : null),
                (java.security.cert.Certificate[]) null),
            perms);
        return new AccessControlContext(new ProtectionDomain[] { pd });
    }

    /**
     * Adds to the specified permission collection the permissions
     * necessary to load classes from a loader with the specified URL
     * path; if "forLoader" is true, also adds URL-specific
     * permissions necessary for the security context that such a
     * loader operates within, such as permissions necessary for
     * granting automatic permissions to classes defined by the
     * loader.  A given permission is only added to the collection if
     * it is not already implied by the collection.
     */
    private static void addPermissionsForURLs(URL[] urls,
                                              PermissionCollection perms,
                                              boolean forLoader)
    {
        for (int i = 0; i < urls.length; i++) {
            URL url = urls[i];
            try {
                URLConnection urlConnection = url.openConnection();
                Permission p = urlConnection.getPermission();
                if (p != null) {
                    if (p instanceof FilePermission) {
                        /*
                         * If the codebase is a file, the permission required
                         * to actually read classes from the codebase URL is
                         * the permission to read all files beneath the last
                         * directory in the file path, either because JAR
                         * files can refer to other JAR files in the same
                         * directory, or because permission to read a
                         * directory is not implied by permission to read the
                         * contents of a directory, which all that might be
                         * granted.
                         */
                        String path = p.getName();
                        int endIndex = path.lastIndexOf(File.separatorChar);
                        if (endIndex != -1) {
                            path = path.substring(0, endIndex+1);
                            if (path.endsWith(File.separator)) {
                                path += "-";
                            }
                            Permission p2 = new FilePermission(path, "read");
                            if (!perms.implies(p2)) {
                                perms.add(p2);
                            }
                            perms.add(new FilePermission(path, "read"));
                        } else {
                            /*
                             * No directory separator: use permission to
                             * read the file.
                             */
                            if (!perms.implies(p)) {
                                perms.add(p);
                            }
                        }
                    } else {
                        if (!perms.implies(p)) {
                            perms.add(p);
                        }

                        /*
                         * If the purpose of these permissions is to grant
                         * them to an instance of a URLClassLoader subclass,
                         * we must add permission to connect to and accept
                         * from the host of non-"file:" URLs, otherwise the
                         * getPermissions() method of URLClassLoader will
                         * throw a security exception.
                         */
                        if (forLoader) {
                            // get URL with meaningful host component
                            URL hostURL = url;
                            for (URLConnection conn = urlConnection;
                                 conn instanceof JarURLConnection;)
                            {
                                hostURL =
                                    ((JarURLConnection) conn).getJarFileURL();
                                conn = hostURL.openConnection();
                            }
                            String host = hostURL.getHost();
                            if (host != null &&
                                p.implies(new SocketPermission(host,
                                                               "resolve")))
                            {
                                Permission p2 =
                                    new SocketPermission(host,
                                                         "connect,accept");
                                if (!perms.implies(p2)) {
                                    perms.add(p2);
                                }
                            }
                        }
                    }
                }
            } catch (IOException e) {
                /*
                 * This shouldn't happen, although it is declared to be
                 * thrown by openConnection() and getPermission().  If it
                 * does, don't bother granting or requiring any permissions
                 * for this URL.
                 */
            }
        }
    }

    /**
     * Loader is the actual class of the RMI class loaders created
     * by the RMIClassLoader static methods.
     */
    private static class Loader extends URLClassLoader {

        /** parent class loader, kept here as an optimization */
        private ClassLoader parent;

        /** string form of loader's codebase URL path, also an optimization */
        private String annotation;

        /** permissions required to access loader through public API */
        private Permissions permissions;

        private Loader(URL[] urls, ClassLoader parent) {
            super(urls, parent);
            this.parent = parent;

            /*
             * Precompute the permissions required to access the loader.
             */
            permissions = new Permissions();
            addPermissionsForURLs(urls, permissions, false);

            /*
             * Caching the value of class annotation string here assumes
             * that the protected method addURL() is never called on this
             * class loader.
             */
            annotation = urlsToPath(urls);
        }

        /**
         * Return the string to be annotated with all classes loaded from
         * this class loader.
         */
        public String getClassAnnotation() {
            return annotation;
        }

        /**
         * Check that the current access control context has all of the
         * permissions necessary to load classes from this loader.
         */
        private void checkPermissions() {
            SecurityManager sm = System.getSecurityManager();
            if (sm != null) {           // should never be null?
                Enumeration enum_ = permissions.elements();
                while (enum_.hasMoreElements()) {
                    sm.checkPermission((Permission) enum_.nextElement());
                }
            }
        }

        /**
         * Return the permissions to be granted to code loaded from the
         * given code source.
         */
        protected PermissionCollection getPermissions(CodeSource codesource) {
            PermissionCollection perms = super.getPermissions(codesource);
            /*
             * Grant the same permissions that URLClassLoader would grant.
             */
            return perms;
        }

        /**
         * Return a string representation of this loader (useful for
         * debugging).
         */
        public String toString() {
            return super.toString() + "[\"" + annotation + "\"]";
        }
    }
}