summaryrefslogtreecommitdiff
path: root/sandbox/com/sun/star/lib/sandbox/ResourceImpl.java
blob: 9e915b0549744fc49d5a5a51ba223fef78f7e753 (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
/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: ResourceImpl.java,v $
 * $Revision: 1.5 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

package com.sun.star.lib.sandbox;

import java.applet.AudioClip;

import java.awt.image.ImageProducer;

import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import java.net.URL;
import java.net.URLConnection;
import java.net.MalformedURLException;

import java.util.Enumeration;
import java.util.Vector;
import java.security.AccessController;
import java.security.PrivilegedAction;

import sun.awt.image.ByteArrayImageSource;
import sun.awt.image.URLImageSource;

import sun.applet.AppletAudioClip;

class ResourceImpl implements Resource {
    private static int instances;
    private static final boolean DEBUG = false;

    private Object object;
    private byte bytes[];
    private URL url;
    private String type;
    private ProtectionDomain protectionDomain;

    public ResourceImpl(URL url, byte bytes[], ProtectionDomain protectionDomain) {
        if(DEBUG)System.err.println("#### ResourceImpl.<init>:" + url + " " + bytes + " " + protectionDomain);

        instances ++;

        this.protectionDomain = protectionDomain;
        this.url              = url;
        this.bytes            = bytes;
    }

    public void finalize() {
        instances --;
    }

    public ProtectionDomain getProtectionDomain() {
        return protectionDomain;
    }

    public URL getURL() {
        return url;
    }

    public synchronized InputStream getInputStream() throws IOException {
        if(DEBUG) System.err.print("#### ResourceImpl.getInputStream:" + url);
        InputStream inputStream = null;

        if(bytes == null) {
            if(DEBUG)System.err.println(" - from url");
              URLConnection c = url.openConnection();
            c.setAllowUserInteraction(false);
              inputStream = c.getInputStream();
        }
        else {
            if(DEBUG)System.err.println(" - from bytes");
            inputStream = new ByteArrayInputStream(bytes);
        }

        return inputStream;
    }

    public synchronized byte[] getBytes() throws IOException {
        final int chunkSize = 4096;

        if(bytes == null) {
            InputStream inputStream = getInputStream();

            int read = 0;
            int total = 0;
            Vector chunks = new Vector();

            byte chunk[] = new byte[chunkSize];
            read = inputStream.read(chunk, 0, chunkSize);
            while(read != -1) { // until end of file
                if(read < chunkSize) {
                    byte tmpChunk[] = new byte[read];
                    System.arraycopy(chunk, 0, tmpChunk, 0, tmpChunk.length);
                    chunk = tmpChunk;
                }

                chunks.addElement(chunk);
                chunk = new byte[chunkSize];
                total += read;

                read = inputStream.read(chunk, 0, chunkSize);
            }

            inputStream.close();

            byte tmpBytes[] = new byte[total];
            int index = 0;
            for(int i = 0; i < chunks.size(); i++) {
                chunk = (byte [])chunks.elementAt(i);

                System.arraycopy(chunk, 0, tmpBytes, index, chunk.length);
                index += chunk.length;
            }

            bytes = tmpBytes;
        }
        return bytes;
    }

    public synchronized ImageProducer getImageProducer() {
        if(DEBUG) System.err.println("#### Resource.getImageProducer:");

        ImageProducer imageProducer = null;

        if(object != null)
            imageProducer = (ImageProducer)object;
        else {
            // we use a PrivilegedAction here because otherwise the system classloader
            // will call our SecurityManager's checkPackageAccess method which will
            // refuse to access sun.* packages and hence ByteArrayInputStream and
            // URLImageSource
            imageProducer= (ImageProducer)
                AccessController.doPrivileged( new PrivilegedAction() {
                    public Object run() {
                        if(bytes != null)
                            return new ByteArrayImageSource(bytes, 0, bytes.length);
                        else
                            return new URLImageSource(url);
                    }});
            object = imageProducer;
        }

        return imageProducer;
    }

    public synchronized AudioClip getAudioClip() {
        AudioClip audioClip = null;

        if(object != null)
            audioClip = (AudioClip)object;
        else {
            // we use a PrivilegedAction here because otherwise the system classloader
            // will call our SecurityManager's checkPackageAccess method which will
            // refuse to access sun.* packages and hence AppletAudioClip
            audioClip= (AppletAudioClip)
                AccessController.doPrivileged( new PrivilegedAction() {
                    public Object run() {
                        if(bytes != null)
                            return new AppletAudioClip(bytes);
                        else
                            return new AppletAudioClip(url);
                    }
            });
            object = audioClip;
        }

        return audioClip;
    }

    public synchronized void loadJar(URL baseURL) throws IOException {
        if(object == null) {
            Vector jarResourceProxys = new Vector();
            JarInputStream jar = null;
            byte[] rbuf = new byte[4096];

            try {
                jar = new JarInputStream(getInputStream());

                JarEntry jarEntry = jar.getNextJarEntry();
                while(jarEntry != null) {
                    String extension = null;
                    String fileName = jarEntry.getName();
                    int extensionIndex = fileName.lastIndexOf('.');

                    if(extensionIndex != -1) {
                        extension = jarEntry.getName().substring(extensionIndex);
                        fileName = fileName.substring(0, extensionIndex);
                    }
                    //      System.out.println("AEC entry:" + fileName + " " + extension);
                    fileName = fileName.replace('.', '/');

                    if(extension != null)
                        fileName += extension;


                    // Workaround: available funktioniert nicht!!!
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();

                    int nread;
                    while((nread = jar.read(rbuf)) > 0)
                        baos.write(rbuf, 0, nread);

                    byte bytes[] = baos.toByteArray(); //new byte[jar.available()];
                    //      jar.read(bytes);

                    ProtectionDomain tmpProtectionDomain = null;

                    if(protectionDomain != null) {
                        PermissionCollection permissionCollection = protectionDomain.getPermissions();
                        CodeSource codeSource = new CodeSource(baseURL, jarEntry.getIdentities());
                        tmpProtectionDomain = new ProtectionDomain(codeSource, permissionCollection);
                    }

                      jarResourceProxys.addElement(ResourceProxy.create(new URL(baseURL, fileName), bytes, tmpProtectionDomain));
                      jarResourceProxys.addElement(ResourceProxy.create(new URL(baseURL + "/" +  fileName), bytes, tmpProtectionDomain));

                    jarEntry = jar.getNextJarEntry();
                }
            }
            finally {
                if(jar != null)
                    jar.close();
            }

            object = jarResourceProxys;
        }
    }

    private void guessType() {
        /* Parse entries which have special names, like the
           manifest. We invent "mime types" local to this class */
//          if (type == null) {
//              type = guessManifestType(name);
//          }

        if (type == null) {
            /*  REMIND Get this from MANIFEST.MF. This should
            be changed as soon as manifest support is
            fixed.  Because jvs must support mark, and it
            isn't always obvious since it's a
            FilterInputStream and whatever it used to
            build it is what would give it mark. */
            try {
                InputStream tmpStream = new ByteArrayInputStream(getBytes());
                type = URLConnection.guessContentTypeFromStream(tmpStream);
            }
            catch(IOException iOException) {
                if(DEBUG) System.err.println("#### Resource.guessType - exception:" + iOException);
            }
        }

        if (type == null) {
            // REMIND - this canbe cleaned up if we don't mind
            // exporting access to MANIFEST data. - epll
            type = "input-stream/input-stream";
        }

        if(DEBUG) System.err.println("#### Resource.guessType - guessed:" + type);
    }


    public Object getContent() throws IOException {
        Object content = null;

        guessType();

        if (type.startsWith("image")) {
            content = getImageProducer();
        }
        else if (type.startsWith("audio")) {
            content = getAudioClip();
        }
        else if (type.startsWith("application/java-vm") || type.startsWith("application/x-java-vm")) {

        }
        else if (type.equals("manifest/manifest") || type.equals("manifest/signature-bin")) {
            /* We know what it is. It is handled by JarVerifierStream */

        }
        else {
            content = getInputStream();
        }

        if(DEBUG) System.err.println("#### Resource.getContent:" + content);

        return content;
    }
}