1 /* 2 * Copyright (c) 2010, 2011, 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 org.openjdk.jigsaw; 27 28 import java.io.*; 29 import java.security.*; 30 import java.util.*; 31 import java.util.jar.*; 32 import java.util.zip.*; 33 34 import static org.openjdk.jigsaw.FileConstants.ModuleFile.*; 35 36 public final class ModuleFile { 37 /** 38 * Return the subdir of a section in an extracted module file. 39 */ 40 public static String getSubdirOfSection(SectionType type) { 41 switch (type) { 42 case MODULE_INFO: 43 case SIGNATURE: 44 return "."; 45 case CLASSES: 46 case RESOURCES: 47 return "classes"; 48 case NATIVE_LIBS: 49 return "lib"; 50 case NATIVE_CMDS: 51 return "bin"; 52 case CONFIG: 53 return "etc"; 54 default: 55 throw new AssertionError(type); 56 } 57 } 58 59 public final static class Reader implements Closeable { 60 61 private DataInputStream stream; 62 private File destination; 63 private boolean deflate; 64 private HashType hashtype; 65 private File natlibs; 66 private File natcmds; 67 private File configs; 68 69 private static class CountingInputStream extends FilterInputStream { 70 int count; 71 public CountingInputStream(InputStream stream, int count) { 72 super(stream); 73 this.count = count; 74 } 75 76 public int available() throws IOException { 77 return count; 78 } 79 80 public boolean markSupported() { 81 return false; 82 } 83 84 public int read() throws IOException { 85 if (count == 0) 86 return -1; 87 int read = super.read(); 88 if (-1 != read) 89 count--; 90 return read; 91 } 92 93 public int read(byte[] b, int off, int len) throws IOException { 94 if (count == 0) 95 return -1; 96 len = Math.min(len, count); 97 int read = super.read(b, off, len); 98 if (-1 != read) 99 count-=read; 100 return read; 101 } 102 103 public void reset() throws IOException { 104 throw new IOException("Can't reset this stream"); 105 } 106 107 public long skip(long n) throws IOException { 108 if (count == 0) 109 return -1; 110 n = Math.min(n, count); 111 long skipped = super.skip(n); 112 if (n > 0) 113 count-=skipped; 114 return skipped; 115 } 116 } 117 118 public Reader(DataInputStream stream) { 119 hashtype = HashType.SHA256; 120 // Ensure that mark/reset is supported 121 if (stream.markSupported()) { 122 this.stream = stream; 123 } else { 124 this.stream = 125 new DataInputStream(new BufferedInputStream(stream)); 126 } 127 } 128 129 private void checkHashMatch(byte[] expected, byte[] computed) 130 throws IOException 131 { 132 if (!MessageDigest.isEqual(expected, computed)) 133 throw new IOException("Expected hash " 134 + hashHexString(expected) 135 + " instead of " 136 + hashHexString(computed)); 137 } 138 139 private ModuleFileHeader fileHeader = null; 140 private MessageDigest fileDigest = null; 141 private MessageDigest sectionDigest = null; 142 private DataInputStream fileIn = null; 143 private byte[] moduleInfoBytes = null; 144 private Integer moduleSignatureType = null; 145 private byte[] moduleSignatureBytes = null; 146 private final int MAX_SECTION_HEADER_LENGTH = 128; 147 private List<byte[]> calculatedHashes = new ArrayList<>(); 148 private boolean extract = true; 149 150 /* 151 * Reads the MODULE_INFO section and the Signature section, if present, 152 * but does not write any files. 153 */ 154 public byte[] readStart() throws IOException { 155 156 try { 157 fileDigest = getHashInstance(hashtype); 158 sectionDigest = getHashInstance(hashtype); 159 DigestInputStream dis = 160 new DigestInputStream(stream, fileDigest); 161 fileHeader = ModuleFileHeader.read(dis); 162 // calculate module header hash 163 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 164 fileHeader.write(new DataOutputStream(baos)); 165 sectionDigest.update(baos.toByteArray()); 166 calculatedHashes.add(sectionDigest.digest()); 167 168 fileIn = new DataInputStream(dis); 169 if (readSection(fileIn) != SectionType.MODULE_INFO) 170 throw new IOException("First module-file section" 171 + " is not MODULE_INFO"); 172 assert moduleInfoBytes != null; 173 174 // Read the Signature Section, if present 175 readSignatureSection(fileIn, dis); 176 177 return moduleInfoBytes.clone(); 178 } catch (IOException x) { 179 close(); 180 throw x; 181 } 182 } 183 184 public void readRest() throws IOException { 185 extract = false; 186 readRest(null, false, null, null, null); 187 } 188 189 public void readRest(File dst, boolean deflate) throws IOException { 190 readRest(dst, deflate, null, null, null); 191 } 192 193 public void readRest(File dst, boolean deflate, File natlibs, 194 File natcmds, File configs) 195 throws IOException 196 { 197 this.deflate = deflate; 198 this.destination = dst != null ? dst.getCanonicalFile() : null; 199 this.natlibs = natlibs != null ? natlibs : new File(destination, "lib"); 200 this.natcmds = natcmds != null ? natcmds : new File(destination, "bin"); 201 this.configs = configs != null ? configs : new File(destination, "etc"); 202 try { 203 if (extract) 204 Files.store(moduleInfoBytes, computeRealPath("info")); 205 // Module-Info and Signature, if present, have been consumed 206 207 // Read rest of file until all sections have been read 208 stream.mark(1); 209 while (-1 != stream.read()) { 210 stream.reset(); 211 readSection(fileIn); 212 stream.mark(1); 213 } 214 215 close(); 216 byte[] fileHeaderHash = fileHeader.getHashNoClone(); 217 checkHashMatch(fileHeaderHash, fileDigest.digest()); 218 calculatedHashes.add(fileHeaderHash); 219 } finally { 220 close(); 221 } 222 } 223 224 public byte[] getHash() throws IOException { 225 if (null == fileHeader) 226 readStart(); 227 return fileHeader.getHash(); 228 } 229 230 public List<byte[]> getCalculatedHashes() { 231 return calculatedHashes; 232 } 233 234 public boolean hasSignature() throws IOException { 235 if (null == fileHeader) 236 readStart(); 237 return moduleSignatureBytes != null; 238 } 239 240 public Integer getSignatureType() throws IOException { 241 if (null == fileHeader) 242 readStart(); 243 return moduleSignatureType; 244 } 245 246 public byte[] getSignature() throws IOException { 247 if (null == fileHeader) 248 readStart(); 249 return moduleSignatureBytes != null 250 ? moduleSignatureBytes.clone() 251 : null; 252 } 253 254 byte[] getSignatureNoClone() { 255 return moduleSignatureBytes; 256 } 257 258 private JarOutputStream contentStream = null; 259 260 private JarOutputStream contentStream() throws IOException { 261 if (contentStream == null) { 262 if (extract) { 263 FileOutputStream fos 264 = new FileOutputStream(computeRealPath("classes")); 265 contentStream 266 = new JarOutputStream(new BufferedOutputStream(fos)); 267 } else { 268 contentStream = new JarOutputStream(new NullOutputStream()); 269 } 270 } 271 return contentStream; 272 } 273 274 public void close() throws IOException { 275 try { 276 try { 277 if (contentStream != null) { 278 contentStream.close(); 279 contentStream = null; 280 } 281 } finally { 282 if (fileIn != null) { 283 fileIn.close(); 284 fileIn = null; 285 } 286 } 287 } finally { 288 if (filesWriter != null) { 289 filesWriter.close(); 290 filesWriter = null; 291 } 292 } 293 } 294 295 public void readModule() throws IOException { 296 extract = false; 297 readStart(); 298 readRest(); 299 } 300 301 public void readModule(File dst) throws IOException { 302 readStart(); 303 readRest(dst, false); 304 } 305 306 private void readSignatureSection(DataInputStream stream, 307 DigestInputStream dis) 308 throws IOException 309 { 310 311 // Turn off digest computation before reading Signature Section 312 dis.on(false); 313 314 // Mark the starting position 315 stream.mark(MAX_SECTION_HEADER_LENGTH); 316 if (stream.read() != -1) { 317 stream.reset(); 318 SectionHeader header = SectionHeader.read(stream); 319 if (header != null && 320 header.getType() == SectionType.SIGNATURE) { 321 readSectionContent(header, stream); 322 } else { 323 // Revert back to the starting position 324 stream.reset(); 325 } 326 } 327 328 // Turn on digest computation again 329 dis.on(true); 330 } 331 332 private SectionType readSection(DataInputStream stream) 333 throws IOException 334 { 335 SectionHeader header = SectionHeader.read(stream); 336 readSectionContent(header, stream); 337 return header.getType(); 338 } 339 340 private void readSectionContent(SectionHeader header, 341 DataInputStream stream) 342 throws IOException 343 { 344 SectionType type = header.getType(); 345 Compressor compressor = header.getCompressor(); 346 int csize = header.getCSize(); 347 short subsections = 348 type.hasFiles() ? header.getSubsections() : 1; 349 350 CountingInputStream cs = new CountingInputStream(stream, csize); 351 sectionDigest.reset(); 352 DigestInputStream dis = new DigestInputStream(cs, sectionDigest); 353 DataInputStream in = new DataInputStream(dis); 354 355 for (int subsection = 0; subsection < subsections; subsection++) 356 readFile(in, compressor, type, csize); 357 358 byte[] headerHash = header.getHashNoClone(); 359 checkHashMatch(headerHash, sectionDigest.digest()); 360 if (header.getType() != SectionType.SIGNATURE) { 361 calculatedHashes.add(headerHash); 362 } 363 } 364 365 public void readFile(DataInputStream in, 366 Compressor compressor, 367 SectionType type, 368 int csize) 369 throws IOException 370 { 371 switch (compressor) { 372 case NONE: 373 if (type == SectionType.MODULE_INFO) { 374 moduleInfoBytes = readModuleInfo(in, csize); 375 376 } else if (type == SectionType.SIGNATURE) { 377 // Examine the Signature header 378 moduleSignatureType = (int)in.readShort(); 379 int length = in.readInt(); 380 moduleSignatureBytes = readModuleSignature(in, csize - 6); 381 if (length != moduleSignatureBytes.length) { 382 throw new IOException("Invalid Signature length"); 383 } 384 } else { 385 readUncompressedFile(in, type, csize); 386 } 387 break; 388 case GZIP: 389 readGZIPCompressedFile(in, type); 390 break; 391 case PACK200_GZIP: 392 readClasses( 393 new DataInputStream(new CountingInputStream(in, csize))); 394 break; 395 default: 396 throw new IOException("Unsupported Compressor for files: " + 397 compressor); 398 } 399 } 400 401 public void readClasses(DataInputStream in) throws IOException { 402 unpack200gzip(in); 403 } 404 405 private File currentPath = null; 406 407 private OutputStream openOutputStream(SectionType type, 408 String path) 409 throws IOException 410 { 411 if (!extract) 412 return new NullOutputStream(); 413 currentPath = null; 414 assert type != SectionType.CLASSES; 415 if (type == SectionType.RESOURCES) 416 return Files.newOutputStream(contentStream(), path); 417 currentPath = computeRealPath(type, path); 418 File parent = currentPath.getParentFile(); 419 if (!parent.exists()) 420 Files.mkdirs(parent, currentPath.getName()); 421 return new BufferedOutputStream(new FileOutputStream(currentPath)); 422 } 423 424 private static class NullOutputStream extends OutputStream { 425 @Override 426 public void write(int b) throws IOException {} 427 @Override 428 public void write(byte[] b) throws IOException {} 429 @Override 430 public void write(byte[] b, int off, int len) throws IOException {} 431 } 432 433 public void readGZIPCompressedFile(DataInputStream in, 434 SectionType type) 435 throws IOException 436 { 437 SubSectionFileHeader header = SubSectionFileHeader.read(in); 438 int csize = header.getCSize(); 439 440 // Splice off the compressed file from input stream 441 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 442 copyStream(new CountingInputStream(in, csize), baos, csize); 443 444 byte[] compressedfile = baos.toByteArray(); 445 ByteArrayInputStream bain 446 = new ByteArrayInputStream(compressedfile); 447 try (GZIPInputStream gin = new GZIPInputStream(bain); 448 OutputStream out = openOutputStream(type, header.getPath())) { 449 copyStream(gin, out); 450 } 451 452 if (extract) 453 postExtract(type, currentPath); 454 } 455 456 public void readUncompressedFile(DataInputStream in, 457 SectionType type, 458 int csize) 459 throws IOException 460 { 461 assert type != SectionType.MODULE_INFO; 462 SubSectionFileHeader header = SubSectionFileHeader.read(in); 463 csize = header.getCSize(); 464 try (OutputStream out = openOutputStream(type, header.getPath())) { 465 CountingInputStream cin = new CountingInputStream(in, csize); 466 byte[] buf = new byte[8192]; 467 int n; 468 while ((n = cin.read(buf)) >= 0) 469 out.write(buf, 0, n); 470 } 471 if (extract) { 472 postExtract(type, currentPath); 473 } 474 } 475 476 public byte[] readModuleInfo(DataInputStream in, int csize) 477 throws IOException 478 { 479 CountingInputStream cin = new CountingInputStream(in, csize); 480 ByteArrayOutputStream out = new ByteArrayOutputStream(); 481 byte[] buf = new byte[8192]; 482 int n; 483 while ((n = cin.read(buf)) >= 0) 484 out.write(buf, 0, n); 485 return out.toByteArray(); 486 } 487 488 public byte[] readModuleSignature(DataInputStream in, int csize) 489 throws IOException 490 { 491 return readModuleInfo(in, csize); // signature has the same format 492 } 493 494 // Track files installed outside the module library. For later removal. 495 // files are relative to the modules directory. 496 private PrintWriter filesWriter; 497 498 private void trackFiles(SectionType type, File file) 499 throws IOException 500 { 501 if (file == null || file.toPath().startsWith(destination.toPath())) 502 return; 503 504 // Lazy construction, not all modules will need this. 505 if (filesWriter == null) 506 filesWriter = new PrintWriter(computeRealPath("files"), "UTF-8"); 507 508 filesWriter.println(Files.convertSeparator(relativize(destination, file))); 509 filesWriter.flush(); 510 } 511 512 List<IOException> remove() { 513 return ModuleFile.Reader.remove(destination); 514 } 515 516 // Removes a module, given its module install directory 517 static List<IOException> remove(File moduleDir) { 518 List<IOException> excs = new ArrayList<>(); 519 // Firstly remove any files installed outside of the module dir 520 File files = new File(moduleDir, "files"); 521 if (files.exists()) { 522 try (FileInputStream fis = new FileInputStream(files); 523 InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 524 BufferedReader in = new BufferedReader(isr)) { 525 String filename; 526 while ((filename = in.readLine()) != null) { 527 IOException x = Files.deleteUnchecked(new File(moduleDir, 528 Files.platformSeparator(filename)).toPath()); 529 if (x != null) 530 excs.add(x); 531 } 532 } catch (IOException x) { 533 excs.add(x); 534 } 535 } 536 537 excs.addAll(Files.deleteAllUnchecked(moduleDir.toPath())); 538 return excs; 539 } 540 541 // Returns the absolute path of the given section type. 542 private File getDirOfSection(SectionType type) { 543 if (type == SectionType.NATIVE_LIBS) 544 return natlibs; 545 else if (type == SectionType.NATIVE_CMDS) 546 return natcmds; 547 else if (type == SectionType.CONFIG) 548 return configs; 549 550 // resolve sub dir section paths against the modules directory 551 return new File(destination, ModuleFile.getSubdirOfSection(type)); 552 } 553 554 private File computeRealPath(String path) throws IOException { 555 return resolveAndNormalize(destination, path); 556 } 557 558 private File computeRealPath(SectionType type, String storedpath) 559 throws IOException 560 { 561 File sectionPath = getDirOfSection(type); 562 File realpath = new File(sectionPath, 563 Files.ensureNonAbsolute(Files.platformSeparator(storedpath))); 564 565 validatePath(sectionPath, realpath); 566 567 // Create the parent directories if necessary 568 File parent = realpath.getParentFile(); 569 if (!parent.exists()) 570 Files.mkdirs(parent, realpath.getName()); 571 572 return realpath; 573 } 574 575 private static void markNativeCodeExecutable(SectionType type, 576 File file) 577 { 578 if (type == SectionType.NATIVE_CMDS 579 || (type == SectionType.NATIVE_LIBS 580 && System.getProperty("os.name").startsWith("Windows"))) 581 { 582 file.setExecutable(true); 583 } 584 } 585 586 private void postExtract(SectionType type, File path) 587 throws IOException 588 { 589 markNativeCodeExecutable(type, path); 590 trackFiles(type, path); 591 } 592 593 private void unpack200gzip(DataInputStream in) throws IOException { 594 GZIPInputStream gis = new GZIPInputStream(in) { 595 public void close() throws IOException {} 596 }; 597 Pack200.Unpacker unpacker = Pack200.newUnpacker(); 598 if (deflate) { 599 Map<String,String> p = unpacker.properties(); 600 p.put(Pack200.Unpacker.DEFLATE_HINT, Pack200.Unpacker.TRUE); 601 } 602 unpacker.unpack(gis, contentStream()); 603 } 604 605 } 606 607 private static void checkCompressor(SectionType type, 608 Compressor compressor) { 609 610 if ((SectionType.MODULE_INFO == type && 611 Compressor.NONE != compressor) 612 || (SectionType.CLASSES == type && 613 Compressor.PACK200_GZIP != compressor)) 614 throw new IllegalArgumentException(type 615 + " may not use compressor " 616 + compressor); 617 } 618 619 private static void checkSubsectionCount(SectionType type, 620 short subsections) { 621 if (!type.hasFiles() && subsections != 0) 622 throw new IllegalArgumentException(type 623 + " subsection count not 0: " 624 + subsections); 625 else if (type.hasFiles() && subsections == 0) 626 throw new IllegalArgumentException(type + " subsection count is 0"); 627 } 628 629 private static void copyStream(InputStream in, DataOutput out) 630 throws IOException 631 { 632 633 byte[] buffer = new byte[1024 * 8]; 634 for (int b_read = in.read(buffer); 635 -1 != b_read; 636 b_read = in.read(buffer)) 637 out.write(buffer, 0, b_read); 638 } 639 640 private static void copyStream(InputStream in, OutputStream out) 641 throws IOException 642 { 643 copyStream(in, (DataOutput) new DataOutputStream(out)); 644 } 645 646 private static void copyStream(InputStream in, DataOutput out, 647 int count) 648 throws IOException 649 { 650 byte[] buffer = new byte[1024 * 8]; 651 652 while(count > 0) { 653 int b_read = in.read(buffer, 0, Math.min(count, buffer.length)); 654 if (-1 == b_read) 655 return; 656 out.write(buffer, 0, b_read); 657 count-=b_read; 658 } 659 } 660 661 private static void copyStream(InputStream in, OutputStream out, 662 int count) 663 throws IOException 664 { 665 copyStream(in, (DataOutput) new DataOutputStream(out), count); 666 } 667 668 private static void ensureNonNegativity(long size, String parameter) { 669 if (size < 0) 670 throw new IllegalArgumentException(parameter + "<0: " + size); 671 } 672 673 private static void ensureNonNull(Object reference, String parameter) { 674 if (null == reference) 675 throw new IllegalArgumentException(parameter + " == null"); 676 } 677 678 private static void ensureMatch(int found, int expected, String field) 679 throws IOException 680 { 681 if (found != expected) 682 throw new IOException(field + " expected : " 683 + Integer.toHexString(expected) + " found: " 684 + Integer.toHexString(found)); 685 } 686 687 private static void ensureShortNativePath(File path, String name) 688 throws IOException 689 { 690 // TODO: check for native code file in a stricter way 691 if (path.canExecute() 692 && name.indexOf('/') != -1) 693 throw new IOException("Native code path too long: " + path); 694 } 695 696 private static void ensureValidFileSize(long size, File path) 697 throws IOException 698 { 699 if (size < 0 || size > Integer.MAX_VALUE) 700 throw new IOException("File " + path + " too large: " + size); 701 } 702 703 static MessageDigest getHashInstance(HashType hashtype) 704 throws IOException 705 { 706 try { 707 switch(hashtype) { 708 case SHA256: 709 return MessageDigest.getInstance("SHA-256"); 710 default: 711 throw new IOException("Unknown hash type: " + hashtype); 712 } 713 } 714 catch (NoSuchAlgorithmException ex) { 715 throw (IOException) (new IOException(hashtype + " not found")) 716 .initCause(ex); 717 } 718 } 719 720 private static short getMUTF8Length(String name) { 721 short size = 2; 722 723 for (int i = name.length()-1; i >= 0; i--) { 724 char ch = name.charAt(i); 725 726 if ('\u0001' <= ch && ch <= '\u007F') 727 size += 1; 728 else if ('\u0000' == ch 729 || '\u0080' <= ch && ch <= '\u07FF') 730 size += 2; 731 else 732 size += 3; 733 } 734 735 return size; 736 } 737 738 private static String hashHexString(byte[] hash) { 739 StringBuilder hex = new StringBuilder("0x"); 740 for (int i = 0; i < hash.length; i++) { 741 int val = (hash[i] & 0xFF); 742 if (val <= 16) 743 hex.append("0"); 744 hex.append(Integer.toHexString(val)); 745 } 746 return hex.toString(); 747 } 748 749 private static File resolveAndNormalize(File directory, String path) 750 throws IOException 751 { 752 File realpath = new File(directory, path); 753 if (directory != null && 754 ! realpath.toPath().startsWith(directory.toPath())) 755 throw new IOException("Bogus relative path: " + path); 756 757 return realpath; 758 } 759 760 761 private static String relativize(File directory, File path) throws IOException { 762 return (directory.toPath().relativize(path.toPath().toRealPath())).toString(); 763 } 764 765 private static void validatePath(File parent, File child) 766 throws IOException 767 { 768 if (!child.toPath().startsWith(parent.toPath()) ) 769 throw new IOException("Bogus relative path: " + child); 770 if (child.exists()) { 771 // conflict, for now just fail 772 throw new IOException("File " + child + " already exists"); 773 } 774 } 775 776 private static short readHashLength(DataInputStream in) throws IOException { 777 final short hashLength = in.readShort(); 778 ensureNonNegativity(hashLength, "hashLength"); 779 780 return hashLength; 781 } 782 783 private static byte[] readHashBytes(DataInputStream in, short hashLength) 784 throws IOException 785 { 786 787 final byte[] hash = new byte[hashLength]; 788 in.readFully(hash); 789 790 return hash; 791 } 792 793 private static byte[] readHash(DataInputStream in) throws IOException { 794 return readHashBytes(in, readHashLength(in)); 795 } 796 797 private static byte[] readFileHash(DigestInputStream dis) 798 throws IOException 799 { 800 801 DataInputStream in = new DataInputStream(dis); 802 803 final short hashLength = readHashLength(in); 804 805 // Turn digest computation off before reading the file hash 806 dis.on(false); 807 byte[] hash = readHashBytes(in, hashLength); 808 // Turn digest computation on again afterwards. 809 dis.on(true); 810 811 return hash; 812 } 813 814 public final static class ModuleFileHeader { 815 public static final int LENGTH_WITHOUT_HASH = 30; 816 public static final int LENGTH = 817 LENGTH_WITHOUT_HASH + HashType.SHA256.length(); 818 819 // Fields are specified as unsigned. Treat signed values as bugs. 820 private final int magic; // MAGIC 821 private final FileConstants.Type type; // Type.MODULE_FILE 822 private final short major; // ModuleFile.MAJOR_VERSION 823 private final short minor; // ModuleFile.MINOR_VERSION 824 private final long csize; // Size of rest of file, compressed 825 private final long usize; // Space required for uncompressed contents 826 // (upper private final ound; need not be exact) 827 private final HashType hashType; // One of ModuleFile.HashType 828 // (applies final o all hashes in this file) 829 private final byte[] hash; // Hash of entire file (except this hash 830 // and the Signature section, if present) 831 832 public byte[] getHash() { 833 return hash.clone(); 834 } 835 836 private byte[] getHashNoClone() { 837 return hash; 838 } 839 840 public ModuleFileHeader(long csize, long usize, 841 HashType hashType, byte[] hash) { 842 ensureNonNegativity(csize, "csize"); 843 ensureNonNegativity(usize, "usize"); 844 845 magic = FileConstants.MAGIC; 846 type = FileConstants.Type.MODULE_FILE; 847 major = MAJOR_VERSION; 848 minor = MINOR_VERSION; 849 850 this.csize = csize; 851 this.usize = usize; 852 this.hashType = hashType; 853 this.hash = hash.clone(); 854 } 855 856 public void write(final DataOutput out) throws IOException { 857 out.writeInt(magic); 858 out.writeShort(type.value()); 859 out.writeShort(major); 860 out.writeShort(minor); 861 out.writeLong(csize); 862 out.writeLong(usize); 863 out.writeShort(hashType.value()); 864 writeHash(out, hash); 865 } 866 867 private static HashType lookupHashType(short value) { 868 for (HashType i : HashType.class.getEnumConstants()) { 869 if (i.value() == value) return i; 870 } 871 872 throw new IllegalArgumentException("No HashType exists with value " 873 + value); 874 } 875 876 public static ModuleFileHeader read(final DigestInputStream dis) 877 throws IOException 878 { 879 DataInputStream in = new DataInputStream(dis); 880 881 final int magic = in.readInt(); 882 ensureMatch(magic, FileConstants.MAGIC, 883 "FileConstants.MAGIC"); 884 885 final short type = in.readShort(); 886 ensureMatch(type, FileConstants.Type.MODULE_FILE.value(), 887 "Type.MODULE_FILE"); 888 889 final short major = in.readShort(); 890 ensureMatch(major, MAJOR_VERSION, 891 "ModuleFile.MAJOR_VERSION"); 892 893 final short minor = in.readShort(); 894 ensureMatch(minor, MINOR_VERSION, 895 "ModuleFile.MINOR_VERSION"); 896 897 final long csize = in.readLong(); 898 final long usize = in.readLong(); 899 final short hashTypeValue = in.readShort(); 900 HashType hashType = lookupHashType(hashTypeValue); 901 final byte[] hash = readFileHash(dis); 902 903 return new ModuleFileHeader(csize, usize, hashType, hash); 904 } 905 906 public String toString() { 907 return "MODULE{csize=" + csize + 908 ", hash=" + hashHexString(hash) + "}"; 909 } 910 } 911 912 public final static class SectionHeader { 913 public static final int LENGTH_WITHOUT_HASH = 12; 914 public static final int LENGTH = 915 LENGTH_WITHOUT_HASH + HashType.SHA256.length(); 916 917 // Fields are specified as unsigned. Treat signed values as bugs. 918 private final SectionType type; 919 private final Compressor compressor; 920 private final int csize; // Size of section content, compressed 921 private final short subsections; // Number of following subsections 922 private final byte[] hash; // Hash of section content 923 924 public SectionHeader(SectionType type, 925 Compressor compressor, 926 int csize, short subsections, byte[] hash) { 927 ensureNonNull(type, "type"); 928 ensureNonNull(compressor, "compressor"); 929 ensureNonNegativity(csize, "csize"); 930 ensureNonNegativity(subsections, "subsections"); 931 ensureNonNull(hash, "hash"); 932 checkSubsectionCount(type, subsections); 933 checkCompressor(type, compressor); 934 935 this.type = type; 936 this.compressor = compressor; 937 this.csize = csize; 938 this.subsections = subsections; 939 this.hash = hash.clone(); 940 } 941 942 public void write(DataOutput out) throws IOException { 943 out.writeShort(type.value()); 944 out.writeShort(compressor.value()); 945 out.writeInt(csize); 946 out.writeShort(subsections); 947 writeHash(out, hash); 948 } 949 950 private static SectionType lookupSectionType(short value) { 951 for (SectionType i : SectionType.class.getEnumConstants()) { 952 if (i.value() == value) return i; 953 } 954 955 throw new 956 IllegalArgumentException("No SectionType exists with value " 957 + value); 958 } 959 960 private static Compressor lookupCompressor(short value) { 961 for (Compressor i : Compressor.class.getEnumConstants()) { 962 if (i.value() == value) return i; 963 } 964 965 throw new 966 IllegalArgumentException("No Compressor exists with value " 967 + value); 968 } 969 970 public static SectionHeader read(DataInputStream in) throws IOException { 971 short tvalue = in.readShort(); 972 final SectionType type = lookupSectionType(tvalue); 973 short cvalue = in.readShort(); 974 final Compressor compressor = lookupCompressor(cvalue); 975 final int csize = in.readInt(); 976 final short sections = in.readShort(); 977 final byte[] hash = readHash(in); 978 979 return new SectionHeader(type, compressor, csize, 980 sections, hash); 981 } 982 983 public SectionType getType() { 984 return type; 985 } 986 987 public Compressor getCompressor() { 988 return compressor; 989 } 990 991 public int getCSize() { 992 return csize; 993 } 994 995 public short getSubsections() { 996 return subsections; 997 } 998 999 public byte[] getHash() { 1000 return hash.clone(); 1001 } 1002 1003 private byte[] getHashNoClone() { 1004 return hash; 1005 } 1006 1007 public String toString() { 1008 return "SectionHeader{type= " + type 1009 + ", compressor=" + compressor 1010 + ", csize=" + csize 1011 + ", subsections=" + subsections 1012 + ", hash=" + hashHexString(hash) + "}"; 1013 } 1014 } 1015 1016 public final static class SubSectionFileHeader { 1017 private final int csize; // Size of file, compressed 1018 private final String path; // Path name, in Java-modified UTF-8 1019 1020 public int getCSize() { 1021 return csize; 1022 } 1023 1024 public String getPath() { 1025 return path; 1026 } 1027 1028 public SubSectionFileHeader(int csize, String path) { 1029 ensureNonNegativity(csize, "csize"); 1030 ensureNonNull(path, "path"); 1031 1032 this.csize = csize; 1033 this.path = path; 1034 } 1035 1036 public void write(DataOutput out) throws IOException { 1037 out.writeShort(SubSectionType.FILE.value()); 1038 out.writeInt(csize); 1039 out.writeUTF(path); 1040 } 1041 1042 public static SubSectionFileHeader read(DataInputStream in) 1043 throws IOException 1044 { 1045 final short type = in.readShort(); 1046 ensureMatch(type, SubSectionType.FILE.value(), 1047 "ModuleFile.SubSectionType.FILE"); 1048 final int csize = in.readInt(); 1049 final String path = in.readUTF(); 1050 1051 return new SubSectionFileHeader(csize, path); 1052 } 1053 } 1054 1055 private static void writeHash(DataOutput out, byte[] hash) 1056 throws IOException 1057 { 1058 out.writeShort(hash.length); 1059 out.write(hash); 1060 } 1061 } --- EOF ---