summaryrefslogtreecommitdiffstats
path: root/khtml/java/org/kde/kjas/server/KJASAppletClassLoader.java
blob: c6defa8487b4bd74807e6c7f58557afa027c6c0d (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
package org.kde.kjas.server;

import java.net.*;
import java.io.*;
import java.util.*;
import java.util.zip.*;
import java.util.jar.*;
import java.security.*;
/**
 * ClassLoader used to download and instantiate Applets.
 * <P>
 * NOTE: The class loader extends Java 1.2 specific class.
 */
public final class KJASAppletClassLoader
    extends URLClassLoader
{
    private static Hashtable loaders = new Hashtable();

    public static synchronized void removeLoaders()
    {
        loaders.clear();
    }

    public static synchronized KJASAppletClassLoader getLoader( String docBase, String codeBase, String archives )
    {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkCreateClassLoader();
        }
        URL docBaseURL;
        KJASAppletClassLoader loader = null;
        try
        {
            docBaseURL = new URL( docBase );
        
            URL codeBaseURL = getCodeBaseURL( docBaseURL, codeBase );
            String key = codeBaseURL.toString();
            if (archives != null)
                key += archives;

            Main.debug( "CL: getLoader: key = " + key );

            loader = (KJASAppletClassLoader) loaders.get( key );
            if( loader == null )
            {
                URL [] urlList = {};
                loader = new KJASAppletClassLoader( urlList, docBaseURL, codeBaseURL);
                loaders.put( key, loader );
            }
            else
            {
                Main.debug( "CL: reusing classloader" );
            }
        } catch( MalformedURLException e ) { Main.kjas_err( "bad DocBase URL", e ); }
        return loader;
    }

    public static URL getCodeBaseURL( URL docBaseURL, String codeBase )
    {
        URL codeBaseURL = null;
        try
        {
            //first determine what the real codeBase is: 3 cases
            //#1. codeBase is absolute URL- use that
            //#2. codeBase is relative to docBase, create url from those
            //#3. last resort, use docBase as the codeBase
            if(codeBase != null)
            {
                //we need to do this since codeBase should be a directory
                if( !codeBase.endsWith("/") )
                    codeBase = codeBase + "/";

                try
                {
                    codeBaseURL = new URL( codeBase );
                } catch( MalformedURLException mue )
                {
                    try
                    {
                        codeBaseURL = new URL( docBaseURL, codeBase );
                    } catch( MalformedURLException mue2 ) {}
                }
            }

            if(codeBaseURL == null)
            {
                //fall back to docBase but fix it up...
                String file = docBaseURL.getFile();
                if( file == null || (file.length() == 0)  )
                    codeBaseURL = docBaseURL;
                else if( file.endsWith( "/" ) )
                    codeBaseURL = docBaseURL;
                else
                {
                    //delete up to the ending '/'
                    String urlString = docBaseURL.toString();
                    int dot_index = urlString.lastIndexOf( '/' );
                    String newfile = urlString.substring( 0, dot_index+1 );
                    codeBaseURL = new URL( newfile );
                }
            }
        }catch( Exception e ) { Main.kjas_err( "CL: exception ", e ); }
        return codeBaseURL;    
    }

    public static KJASAppletClassLoader getLoader( String key )
    {
        SecurityManager security = System.getSecurityManager();
        if (security != null) {
            security.checkCreateClassLoader();
        }
        if( loaders.containsKey( key ) )
            return (KJASAppletClassLoader) loaders.get( key );
        
        return null;
    }

    /*********************************************************************************
     ****************** KJASAppletClassLoader Implementation *************************
     **********************************************************************************/
    private URL docBaseURL;
    private URL codeBaseURL;
    private Vector archives;
    private String dbgID;
    private static int globalId = 0;
    private int myId = 0;
    private Vector statusListeners = new Vector();
    private AccessControlContext acc;
    // a mapping JS referenced Java objects
    private Hashtable jsReferencedObjects = new Hashtable();
    final static RuntimePermission kjas_access = new RuntimePermission("accessClassInPackage.org.kde.kjas.server");
    
    public KJASAppletClassLoader( URL[] urlList, URL _docBaseURL, URL _codeBaseURL)
    {
        super(urlList);
        acc = AccessController.getContext();
        synchronized(KJASAppletClassLoader.class) {
            myId = ++globalId;
        }
        docBaseURL   = _docBaseURL;
        codeBaseURL  = _codeBaseURL;
        archives     = new Vector();
        
        dbgID = "CL-" + myId + "(" + codeBaseURL.toString() + "): ";
    }
    
    protected void addURL(URL url) {
        Main.debug(this + " add URL: " + url);
        super.addURL(url);
    }
    
    public void addStatusListener(StatusListener lsnr) {
        statusListeners.add(lsnr);
    }
    public void removeStatusListener(StatusListener lsnr) {
        statusListeners.remove(lsnr);
    }
    public void showStatus(String msg) {
        Enumeration en = statusListeners.elements();
        while (en.hasMoreElements()) {
            StatusListener lsnr = (StatusListener)en.nextElement();
            lsnr.showStatus(msg);
        }
    }
    
    public void paramsDone() {
        // simply builds up the search path
        // put the archives first because they are 
        // cached.
        for( int i = 0; i < archives.size(); ++i ) {
            String jar = (String)archives.elementAt( i );
            try {
                URL jarURL = new URL(codeBaseURL, jar);
                addURL(jarURL);
                Main.debug("added archive URL \"" + jarURL + "\" to KJASAppletClassLoader");
            } catch (MalformedURLException e) {
                Main.kjas_err("Could not construct URL for jar file: " + codeBaseURL + " + " + jar, e);
            }
        }
        // finally add code base url and docbase url
        addURL(codeBaseURL);

        // the docBaseURL has to be fixed.
        // strip file part from end otherwise this
        // will be interpreted as an archive
        // (should this perhaps be done generally ??)       
        String dbs = docBaseURL.toString();
        int idx = dbs.lastIndexOf("/");
        if (idx > 0) {
            dbs = dbs.substring(0, idx+1);
        }
        URL docDirURL = null; 
        try {
            docDirURL = new URL(dbs);
        } catch (MalformedURLException e) {
            Main.debug("Could not make a new URL from docBaseURL=" + docBaseURL);
        }
        if (docDirURL != null && !codeBaseURL.equals(docDirURL)) {
            addURL(docDirURL);
        }
    }

    void addArchiveName( String jarname )
    {
        if( !archives.contains( jarname ) )
        {
            archives.add( jarname );
        }
    }
    

    public URL getDocBase()
    {
        return docBaseURL;
    }

    public URL getCodeBase()
    {
        return codeBaseURL;
    }

    Hashtable getJSReferencedObjects() {
        return jsReferencedObjects;
    }
    /***************************************************************************
     **** Class Loading Methods
     **************************************************************************/
    public synchronized Class findClass( String name ) throws ClassNotFoundException
    {
        Class rval = null;
        //check the loaded classes 
        rval = findLoadedClass( name );
        if( rval == null ) {
            try {
                rval =  super.findClass(name);
            } catch (ClassFormatError cfe) {
                Main.debug(name + ": Catched " + cfe + ". Trying to repair...");
                rval = loadFixedClass( name );
            } catch (Exception ex) {
                Main.debug("findClass " + name + " " + ex.getMessage());
            }
        }
        if (rval == null) {
            throw new ClassNotFoundException("Class: " + name);
        }
        return rval;
    }
    public Class loadClass(String name) throws ClassNotFoundException {
        if (name.startsWith("org.kde.kjas.server")) {
            SecurityManager sec = System.getSecurityManager();
            if (sec != null)
                sec.checkPermission(kjas_access);
       }
        return super.loadClass(name);
    }
    private Hashtable loadedClasses = new Hashtable();

    private synchronized final Class loadFixedClass(String name) throws ClassNotFoundException {
        final String fileName = name.replace('.', '/') + ".class";
        try {
            // try to get the class as resource
            final URL u = getResource(fileName);
            Main.debug(dbgID + name + ": got URL: " + u);
            if (u == null) {
                throw new ClassNotFoundException(fileName + ": invalid resource URL.");
            }
            java.security.cert.Certificate[] certs = {}; // FIXME
            CodeSource cs = new CodeSource(u, certs);
            InputStream instream = (InputStream)AccessController.doPrivileged(
              new PrivilegedAction() {
                public Object run() {
                    try {
                        return u.openStream();
                    } catch (IOException ioe) {
                        ioe.printStackTrace();
                        return null;
                    }
                }
              }, acc
            );
            if (instream == null) {
                throw new ClassNotFoundException(name + ": could not be loaded.");
            }
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
            int cnt;
            int total = 0;
            int bufSize = 1024;
            byte [] buffer = new byte[bufSize];
            while ((cnt = instream.read(buffer, 0, bufSize)) > 0) {
                 total += cnt;
                 byteStream.write(buffer, 0, cnt);
            }
            Main.debug(dbgID + name + ": " + total + " bytes");
            
            Class cl = fixAndDefineClass(name, byteStream.toByteArray(), 0, total, cs);
            if (cl != null) {
                loadedClasses.put(name, cl);
            }
            return cl;
            
        } catch (Throwable e) {
            e.printStackTrace();
            throw new ClassNotFoundException("triggered by " + e);
        }
    }
    
    public URL findResource( String name)
    {
        Main.debug( dbgID + "findResource, name = " + name );
        String displayName = name;
        try {
            URL u = new URL(name);
            String filename = u.getFile();
            if (filename != null && filename.length() > 0) {
                displayName = filename;
            }
        } catch (Throwable e) {
        }
        showStatus("Loading: " + displayName);
        URL url =  super.findResource( name );
        Main.debug("findResource for " + name + " returns " + url);
        return url;
    }
   
    protected PermissionCollection getPermissions(CodeSource cs) {
        Main.debug(dbgID + " getPermissions(" + cs + ")");
        PermissionCollection permissions = super.getPermissions(cs);
        Enumeration perms_enum = permissions.elements();
        while (perms_enum.hasMoreElements()) {
            Main.debug(this + " Permission: " + perms_enum.nextElement());
        }
        return permissions;
    }
    
   
    /**
    * define the class <b>name</b>. If  <b>name</b> is broken, try to fix it.
    */
    private final Class fixAndDefineClass(
            String name, 
            byte[] b, 
            int off, 
            int len,
            CodeSource cs) throws ClassFormatError
    {
        KJASBrokenClassFixer fixer = new KJASBrokenClassFixer();
        if (fixer.process(b, off, len)) {
            Main.debug(name + " fixed");
        } else {
            Main.info(name + " could not be fixed");
        }
        return defineClass(name, 
                fixer.getProcessedData(), 
                fixer.getProcessedDataOffset(), 
                fixer.getProcessedDataLength(), 
                cs);
    }
    
    
}