blob: fd5780612649100bc5de7ff58c708c6aa28e5ad9 [file] [log] [blame]
Przemyslaw Szczepaniak8a7c1602015-11-03 09:47:56 +00001/*
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17
18package android.util.jar;
19
20import dalvik.system.CloseGuard;
21import java.io.ByteArrayInputStream;
22import java.io.FilterInputStream;
23import java.io.IOException;
24import java.io.InputStream;
25import java.io.RandomAccessFile;
26import java.security.cert.Certificate;
27import java.util.HashMap;
28import java.util.Iterator;
29import java.util.Set;
30import java.util.zip.Inflater;
31import java.util.zip.InflaterInputStream;
32import java.util.zip.ZipEntry;
33import java.util.zip.ZipFile;
34import java.util.jar.JarFile;
35import java.util.jar.Manifest;
36import libcore.io.IoUtils;
37import libcore.io.Streams;
38
39/**
40 * A subset of the JarFile API implemented as a thin wrapper over
41 * system/core/libziparchive.
42 *
43 * @hide for internal use only. Not API compatible (or as forgiving) as
44 * {@link java.util.jar.JarFile}
45 */
46public final class StrictJarFile {
47
48 private final long nativeHandle;
49
50 // NOTE: It's possible to share a file descriptor with the native
51 // code, at the cost of some additional complexity.
52 private final RandomAccessFile raf;
53
54 private final StrictJarManifest manifest;
55 private final StrictJarVerifier verifier;
56
57 private final boolean isSigned;
58
59 private final CloseGuard guard = CloseGuard.get();
60 private boolean closed;
61
62 public StrictJarFile(String fileName) throws IOException, SecurityException {
63 this.nativeHandle = nativeOpenJarFile(fileName);
64 this.raf = new RandomAccessFile(fileName, "r");
65
66 try {
67 // Read the MANIFEST and signature files up front and try to
68 // parse them. We never want to accept a JAR File with broken signatures
69 // or manifests, so it's best to throw as early as possible.
70 HashMap<String, byte[]> metaEntries = getMetaEntries();
71 this.manifest = new StrictJarManifest(metaEntries.get(JarFile.MANIFEST_NAME), true);
72 this.verifier = new StrictJarVerifier(fileName, manifest, metaEntries);
73 Set<String> files = manifest.getEntries().keySet();
74 for (String file : files) {
75 if (findEntry(file) == null) {
76 throw new SecurityException(fileName + ": File " + file + " in manifest does not exist");
77 }
78 }
79
80 isSigned = verifier.readCertificates() && verifier.isSignedJar();
81 } catch (IOException | SecurityException e) {
82 nativeClose(this.nativeHandle);
83 IoUtils.closeQuietly(this.raf);
84 throw e;
85 }
86
87 guard.open("close");
88 }
89
90 public StrictJarManifest getManifest() {
91 return manifest;
92 }
93
94 public Iterator<ZipEntry> iterator() throws IOException {
95 return new EntryIterator(nativeHandle, "");
96 }
97
98 public ZipEntry findEntry(String name) {
99 return nativeFindEntry(nativeHandle, name);
100 }
101
102 /**
103 * Return all certificate chains for a given {@link ZipEntry} belonging to this jar.
104 * This method MUST be called only after fully exhausting the InputStream belonging
105 * to this entry.
106 *
107 * Returns {@code null} if this jar file isn't signed or if this method is
108 * called before the stream is processed.
109 */
110 public Certificate[][] getCertificateChains(ZipEntry ze) {
111 if (isSigned) {
112 return verifier.getCertificateChains(ze.getName());
113 }
114
115 return null;
116 }
117
118 /**
119 * Return all certificates for a given {@link ZipEntry} belonging to this jar.
120 * This method MUST be called only after fully exhausting the InputStream belonging
121 * to this entry.
122 *
123 * Returns {@code null} if this jar file isn't signed or if this method is
124 * called before the stream is processed.
125 *
126 * @deprecated Switch callers to use getCertificateChains instead
127 */
128 @Deprecated
129 public Certificate[] getCertificates(ZipEntry ze) {
130 if (isSigned) {
131 Certificate[][] certChains = verifier.getCertificateChains(ze.getName());
132
133 // Measure number of certs.
134 int count = 0;
135 for (Certificate[] chain : certChains) {
136 count += chain.length;
137 }
138
139 // Create new array and copy all the certs into it.
140 Certificate[] certs = new Certificate[count];
141 int i = 0;
142 for (Certificate[] chain : certChains) {
143 System.arraycopy(chain, 0, certs, i, chain.length);
144 i += chain.length;
145 }
146
147 return certs;
148 }
149
150 return null;
151 }
152
153 public InputStream getInputStream(ZipEntry ze) {
154 final InputStream is = getZipInputStream(ze);
155
156 if (isSigned) {
157 StrictJarVerifier.VerifierEntry entry = verifier.initEntry(ze.getName());
158 if (entry == null) {
159 return is;
160 }
161
162 return new JarFileInputStream(is, ze.getSize(), entry);
163 }
164
165 return is;
166 }
167
168 public void close() throws IOException {
169 if (!closed) {
170 guard.close();
171
172 nativeClose(nativeHandle);
173 IoUtils.closeQuietly(raf);
174 closed = true;
175 }
176 }
177
178 private InputStream getZipInputStream(ZipEntry ze) {
179 if (ze.getMethod() == ZipEntry.STORED) {
180 return new RAFStream(raf, ze.getDataOffset(),
181 ze.getDataOffset() + ze.getSize());
182 } else {
183 final RAFStream wrapped = new RAFStream(
184 raf, ze.getDataOffset(), ze.getDataOffset() + ze.getCompressedSize());
185
186 int bufSize = Math.max(1024, (int) Math.min(ze.getSize(), 65535L));
187 return new ZipInflaterInputStream(wrapped, new Inflater(true), bufSize, ze);
188 }
189 }
190
191 static final class EntryIterator implements Iterator<ZipEntry> {
192 private final long iterationHandle;
193 private ZipEntry nextEntry;
194
195 EntryIterator(long nativeHandle, String prefix) throws IOException {
196 iterationHandle = nativeStartIteration(nativeHandle, prefix);
197 }
198
199 public ZipEntry next() {
200 if (nextEntry != null) {
201 final ZipEntry ze = nextEntry;
202 nextEntry = null;
203 return ze;
204 }
205
206 return nativeNextEntry(iterationHandle);
207 }
208
209 public boolean hasNext() {
210 if (nextEntry != null) {
211 return true;
212 }
213
214 final ZipEntry ze = nativeNextEntry(iterationHandle);
215 if (ze == null) {
216 return false;
217 }
218
219 nextEntry = ze;
220 return true;
221 }
222
223 public void remove() {
224 throw new UnsupportedOperationException();
225 }
226 }
227
228 private HashMap<String, byte[]> getMetaEntries() throws IOException {
229 HashMap<String, byte[]> metaEntries = new HashMap<String, byte[]>();
230
231 Iterator<ZipEntry> entryIterator = new EntryIterator(nativeHandle, "META-INF/");
232 while (entryIterator.hasNext()) {
233 final ZipEntry entry = entryIterator.next();
234 metaEntries.put(entry.getName(), Streams.readFully(getInputStream(entry)));
235 }
236
237 return metaEntries;
238 }
239
240 static final class JarFileInputStream extends FilterInputStream {
241 private final StrictJarVerifier.VerifierEntry entry;
242
243 private long count;
244 private boolean done = false;
245
246 JarFileInputStream(InputStream is, long size, StrictJarVerifier.VerifierEntry e) {
247 super(is);
248 entry = e;
249
250 count = size;
251 }
252
253 @Override
254 public int read() throws IOException {
255 if (done) {
256 return -1;
257 }
258 if (count > 0) {
259 int r = super.read();
260 if (r != -1) {
261 entry.write(r);
262 count--;
263 } else {
264 count = 0;
265 }
266 if (count == 0) {
267 done = true;
268 entry.verify();
269 }
270 return r;
271 } else {
272 done = true;
273 entry.verify();
274 return -1;
275 }
276 }
277
278 @Override
279 public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
280 if (done) {
281 return -1;
282 }
283 if (count > 0) {
284 int r = super.read(buffer, byteOffset, byteCount);
285 if (r != -1) {
286 int size = r;
287 if (count < size) {
288 size = (int) count;
289 }
290 entry.write(buffer, byteOffset, size);
291 count -= size;
292 } else {
293 count = 0;
294 }
295 if (count == 0) {
296 done = true;
297 entry.verify();
298 }
299 return r;
300 } else {
301 done = true;
302 entry.verify();
303 return -1;
304 }
305 }
306
307 @Override
308 public int available() throws IOException {
309 if (done) {
310 return 0;
311 }
312 return super.available();
313 }
314
315 @Override
316 public long skip(long byteCount) throws IOException {
317 return Streams.skipByReading(this, byteCount);
318 }
319 }
320
321 /** @hide */
322 public static class ZipInflaterInputStream extends InflaterInputStream {
323 private final ZipEntry entry;
324 private long bytesRead = 0;
325
326 public ZipInflaterInputStream(InputStream is, Inflater inf, int bsize, ZipEntry entry) {
327 super(is, inf, bsize);
328 this.entry = entry;
329 }
330
331 @Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
332 final int i;
333 try {
334 i = super.read(buffer, byteOffset, byteCount);
335 } catch (IOException e) {
336 throw new IOException("Error reading data for " + entry.getName() + " near offset "
337 + bytesRead, e);
338 }
339 if (i == -1) {
340 if (entry.getSize() != bytesRead) {
341 throw new IOException("Size mismatch on inflated file: " + bytesRead + " vs "
342 + entry.getSize());
343 }
344 } else {
345 bytesRead += i;
346 }
347 return i;
348 }
349
350 @Override public int available() throws IOException {
351 if (closed) {
352 // Our superclass will throw an exception, but there's a jtreg test that
353 // explicitly checks that the InputStream returned from ZipFile.getInputStream
354 // returns 0 even when closed.
355 return 0;
356 }
357 return super.available() == 0 ? 0 : (int) (entry.getSize() - bytesRead);
358 }
359 }
360
361 /**
362 * Wrap a stream around a RandomAccessFile. The RandomAccessFile is shared
363 * among all streams returned by getInputStream(), so we have to synchronize
364 * access to it. (We can optimize this by adding buffering here to reduce
365 * collisions.)
366 *
367 * <p>We could support mark/reset, but we don't currently need them.
368 *
369 * @hide
370 */
371 public static class RAFStream extends InputStream {
372 private final RandomAccessFile sharedRaf;
373 private long endOffset;
374 private long offset;
375
376
377 public RAFStream(RandomAccessFile raf, long initialOffset, long endOffset) {
378 sharedRaf = raf;
379 offset = initialOffset;
380 this.endOffset = endOffset;
381 }
382
383 public RAFStream(RandomAccessFile raf, long initialOffset) throws IOException {
384 this(raf, initialOffset, raf.length());
385 }
386
387 @Override public int available() throws IOException {
388 return (offset < endOffset ? 1 : 0);
389 }
390
391 @Override public int read() throws IOException {
392 return Streams.readSingleByte(this);
393 }
394
395 @Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
396 synchronized (sharedRaf) {
397 final long length = endOffset - offset;
398 if (byteCount > length) {
399 byteCount = (int) length;
400 }
401 sharedRaf.seek(offset);
402 int count = sharedRaf.read(buffer, byteOffset, byteCount);
403 if (count > 0) {
404 offset += count;
405 return count;
406 } else {
407 return -1;
408 }
409 }
410 }
411
412 @Override public long skip(long byteCount) throws IOException {
413 if (byteCount > endOffset - offset) {
414 byteCount = endOffset - offset;
415 }
416 offset += byteCount;
417 return byteCount;
418 }
419 }
420
421
422 private static native long nativeOpenJarFile(String fileName) throws IOException;
423 private static native long nativeStartIteration(long nativeHandle, String prefix);
424 private static native ZipEntry nativeNextEntry(long iterationHandle);
425 private static native ZipEntry nativeFindEntry(long nativeHandle, String entryName);
426 private static native void nativeClose(long nativeHandle);
427}