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 void remove() throws IOException { 513 ModuleFile.Reader.remove(destination); 514 } 515 516 // Removes a module, given its module install directory 517 static void remove(File moduleDir) throws IOException { 518 // Firstly remove any files installed outside of the module dir 519 File files = new File(moduleDir, "files"); 520 if (files.exists()) { 521 try (FileInputStream fis = new FileInputStream(files); 522 InputStreamReader isr = new InputStreamReader(fis, "UTF-8"); 523 BufferedReader in = new BufferedReader(isr)) { 524 String filename; 525 while ((filename = in.readLine()) != null) 526 Files.delete(new File(moduleDir, 527 Files.platformSeparator(filename))); 528 } 529 } 530 531 Files.deleteTree(moduleDir); 532 } 533 534 // Returns the absolute path of the given section type. 535 private File getDirOfSection(SectionType type) { 536 if (type == SectionType.NATIVE_LIBS) 537 return natlibs; 538 else if (type == SectionType.NATIVE_CMDS) 539 return natcmds; 540 else if (type == SectionType.CONFIG) 541 return configs; 542 543 // resolve sub dir section paths against the modules directory 544 return new File(destination, ModuleFile.getSubdirOfSection(type)); 545 } 546 547 private File computeRealPath(String path) throws IOException { 548 return resolveAndNormalize(destination, path); 549 } 550 551 private File computeRealPath(SectionType type, String storedpath) 552 throws IOException 553 { 554 File sectionPath = getDirOfSection(type); 555 File realpath = new File(sectionPath, 556 Files.ensureNonAbsolute(Files.platformSeparator(storedpath))); 557 558 validatePath(sectionPath, realpath); 559 560 // Create the parent directories if necessary 561 File parent = realpath.getParentFile(); 562 if (!parent.exists()) 563 Files.mkdirs(parent, realpath.getName()); 564 565 return realpath; 566 } 567 568 private static void markNativeCodeExecutable(SectionType type, 569 File file) 570 { 571 if (type == SectionType.NATIVE_CMDS 572 || (type == SectionType.NATIVE_LIBS 573 && System.getProperty("os.name").startsWith("Windows"))) 574 { 575 file.setExecutable(true); 576 } 577 } 578 579 private void postExtract(SectionType type, File path) 580 throws IOException 581 { 582 markNativeCodeExecutable(type, path); 583 trackFiles(type, path); 584 } 585 586 private void unpack200gzip(DataInputStream in) throws IOException { 587 GZIPInputStream gis = new GZIPInputStream(in) { 588 public void close() throws IOException {} 589 }; 590 Pack200.Unpacker unpacker = Pack200.newUnpacker(); 591 if (deflate) { 592 Map<String,String> p = unpacker.properties(); 593 p.put(Pack200.Unpacker.DEFLATE_HINT, Pack200.Unpacker.TRUE); 594 } 595 unpacker.unpack(gis, contentStream()); 596 } 597 598 } 599 600 private static void checkCompressor(SectionType type, 601 Compressor compressor) { 602 603 if ((SectionType.MODULE_INFO == type && 604 Compressor.NONE != compressor) 605 || (SectionType.CLASSES == type && 606 Compressor.PACK200_GZIP != compressor)) 607 throw new IllegalArgumentException(type 608 + " may not use compressor " 609 + compressor); 610 } 611 612 private static void checkSubsectionCount(SectionType type, 613 short subsections) { 614 if (!type.hasFiles() && subsections != 0) 615 throw new IllegalArgumentException(type 616 + " subsection count not 0: " 617 + subsections); 618 else if (type.hasFiles() && subsections == 0) 619 throw new IllegalArgumentException(type + " subsection count is 0"); 620 } 621 622 private static void copyStream(InputStream in, DataOutput out) 623 throws IOException 624 { 625 626 byte[] buffer = new byte[1024 * 8]; 627 for (int b_read = in.read(buffer); 628 -1 != b_read; 629 b_read = in.read(buffer)) 630 out.write(buffer, 0, b_read); 631 } 632 633 private static void copyStream(InputStream in, OutputStream out) 634 throws IOException 635 { 636 copyStream(in, (DataOutput) new DataOutputStream(out)); 637 } 638 639 private static void copyStream(InputStream in, DataOutput out, 640 int count) 641 throws IOException 642 { 643 byte[] buffer = new byte[1024 * 8]; 644 645 while(count > 0) { 646 int b_read = in.read(buffer, 0, Math.min(count, buffer.length)); 647 if (-1 == b_read) 648 return; 649 out.write(buffer, 0, b_read); 650 count-=b_read; 651 } 652 } 653 654 private static void copyStream(InputStream in, OutputStream out, 655 int count) 656 throws IOException 657 { 658 copyStream(in, (DataOutput) new DataOutputStream(out), count); 659 } 660 661 private static void ensureNonNegativity(long size, String parameter) { 662 if (size < 0) 663 throw new IllegalArgumentException(parameter + "<0: " + size); 664 } 665 666 private static void ensureNonNull(Object reference, String parameter) { 667 if (null == reference) 668 throw new IllegalArgumentException(parameter + " == null"); 669 } 670 671 private static void ensureMatch(int found, int expected, String field) 672 throws IOException 673 { 674 if (found != expected) 675 throw new IOException(field + " expected : " 676 + Integer.toHexString(expected) + " found: " 677 + Integer.toHexString(found)); 678 } 679 680 private static void ensureShortNativePath(File path, String name) 681 throws IOException 682 { 683 // TODO: check for native code file in a stricter way 684 if (path.canExecute() 685 && name.indexOf('/') != -1) 686 throw new IOException("Native code path too long: " + path); 687 } 688 689 private static void ensureValidFileSize(long size, File path) 690 throws IOException 691 { 692 if (size < 0 || size > Integer.MAX_VALUE) 693 throw new IOException("File " + path + " too large: " + size); 694 } 695 696 static MessageDigest getHashInstance(HashType hashtype) 697 throws IOException 698 { 699 try { 700 switch(hashtype) { 701 case SHA256: 702 return MessageDigest.getInstance("SHA-256"); 703 default: 704 throw new IOException("Unknown hash type: " + hashtype); 705 } 706 } 707 catch (NoSuchAlgorithmException ex) { 708 throw (IOException) (new IOException(hashtype + " not found")) 709 .initCause(ex); 710 } 711 } 712 713 private static short getMUTF8Length(String name) { 714 short size = 2; 715 716 for (int i = name.length()-1; i >= 0; i--) { 717 char ch = name.charAt(i); 718 719 if ('\u0001' <= ch && ch <= '\u007F') 720 size += 1; 721 else if ('\u0000' == ch 722 || '\u0080' <= ch && ch <= '\u07FF') 723 size += 2; 724 else 725 size += 3; 726 } 727 728 return size; 729 } 730 731 private static String hashHexString(byte[] hash) { 732 StringBuilder hex = new StringBuilder("0x"); 733 for (int i = 0; i < hash.length; i++) { 734 int val = (hash[i] & 0xFF); 735 if (val <= 16) 736 hex.append("0"); 737 hex.append(Integer.toHexString(val)); 738 } 739 return hex.toString(); 740 } 741 742 private static File resolveAndNormalize(File directory, String path) 743 throws IOException 744 { 745 File realpath = new File(directory, path); 746 if (directory != null && 747 ! realpath.toPath().startsWith(directory.toPath())) 748 throw new IOException("Bogus relative path: " + path); 749 750 return realpath; 751 } 752 753 754 private static String relativize(File directory, File path) throws IOException { 755 return (directory.toPath().relativize(path.toPath().toRealPath())).toString(); 756 } 757 758 private static void validatePath(File parent, File child) 759 throws IOException 760 { 761 if (!child.toPath().startsWith(parent.toPath()) ) 762 throw new IOException("Bogus relative path: " + child); 763 if (child.exists()) { 764 // conflict, for now just fail 765 throw new IOException("File " + child + " already exists"); 766 } 767 } 768 769 private static short readHashLength(DataInputStream in) throws IOException { 770 final short hashLength = in.readShort(); 771 ensureNonNegativity(hashLength, "hashLength"); 772 773 return hashLength; 774 } 775 776 private static byte[] readHashBytes(DataInputStream in, short hashLength) 777 throws IOException 778 { 779 780 final byte[] hash = new byte[hashLength]; 781 in.readFully(hash); 782 783 return hash; 784 } 785 786 private static byte[] readHash(DataInputStream in) throws IOException { 787 return readHashBytes(in, readHashLength(in)); 788 } 789 790 private static byte[] readFileHash(DigestInputStream dis) 791 throws IOException 792 { 793 794 DataInputStream in = new DataInputStream(dis); 795 796 final short hashLength = readHashLength(in); 797 798 // Turn digest computation off before reading the file hash 799 dis.on(false); 800 byte[] hash = readHashBytes(in, hashLength); 801 // Turn digest computation on again afterwards. 802 dis.on(true); 803 804 return hash; 805 } 806 807 public final static class ModuleFileHeader { 808 public static final int LENGTH_WITHOUT_HASH = 30; 809 public static final int LENGTH = 810 LENGTH_WITHOUT_HASH + HashType.SHA256.length(); 811 812 // Fields are specified as unsigned. Treat signed values as bugs. 813 private final int magic; // MAGIC 814 private final FileConstants.Type type; // Type.MODULE_FILE 815 private final short major; // ModuleFile.MAJOR_VERSION 816 private final short minor; // ModuleFile.MINOR_VERSION 817 private final long csize; // Size of rest of file, compressed 818 private final long usize; // Space required for uncompressed contents 819 // (upper private final ound; need not be exact) 820 private final HashType hashType; // One of ModuleFile.HashType 821 // (applies final o all hashes in this file) 822 private final byte[] hash; // Hash of entire file (except this hash 823 // and the Signature section, if present) 824 825 public byte[] getHash() { 826 return hash.clone(); 827 } 828 829 private byte[] getHashNoClone() { 830 return hash; 831 } 832 833 public ModuleFileHeader(long csize, long usize, 834 HashType hashType, byte[] hash) { 835 ensureNonNegativity(csize, "csize"); 836 ensureNonNegativity(usize, "usize"); 837 838 magic = FileConstants.MAGIC; 839 type = FileConstants.Type.MODULE_FILE; 840 major = MAJOR_VERSION; 841 minor = MINOR_VERSION; 842 843 this.csize = csize; 844 this.usize = usize; 845 this.hashType = hashType; 846 this.hash = hash.clone(); 847 } 848 849 public void write(final DataOutput out) throws IOException { 850 out.writeInt(magic); 851 out.writeShort(type.value()); 852 out.writeShort(major); 853 out.writeShort(minor); 854 out.writeLong(csize); 855 out.writeLong(usize); 856 out.writeShort(hashType.value()); 857 writeHash(out, hash); 858 } 859 860 private static HashType lookupHashType(short value) { 861 for (HashType i : HashType.class.getEnumConstants()) { 862 if (i.value() == value) return i; 863 } 864 865 throw new IllegalArgumentException("No HashType exists with value " 866 + value); 867 } 868 869 public static ModuleFileHeader read(final DigestInputStream dis) 870 throws IOException 871 { 872 DataInputStream in = new DataInputStream(dis); 873 874 final int magic = in.readInt(); 875 ensureMatch(magic, FileConstants.MAGIC, 876 "FileConstants.MAGIC"); 877 878 final short type = in.readShort(); 879 ensureMatch(type, FileConstants.Type.MODULE_FILE.value(), 880 "Type.MODULE_FILE"); 881 882 final short major = in.readShort(); 883 ensureMatch(major, MAJOR_VERSION, 884 "ModuleFile.MAJOR_VERSION"); 885 886 final short minor = in.readShort(); 887 ensureMatch(minor, MINOR_VERSION, 888 "ModuleFile.MINOR_VERSION"); 889 890 final long csize = in.readLong(); 891 final long usize = in.readLong(); 892 final short hashTypeValue = in.readShort(); 893 HashType hashType = lookupHashType(hashTypeValue); 894 final byte[] hash = readFileHash(dis); 895 896 return new ModuleFileHeader(csize, usize, hashType, hash); 897 } 898 899 public String toString() { 900 return "MODULE{csize=" + csize + 901 ", hash=" + hashHexString(hash) + "}"; 902 } 903 } 904 905 public final static class SectionHeader { 906 public static final int LENGTH_WITHOUT_HASH = 12; 907 public static final int LENGTH = 908 LENGTH_WITHOUT_HASH + HashType.SHA256.length(); 909 910 // Fields are specified as unsigned. Treat signed values as bugs. 911 private final SectionType type; 912 private final Compressor compressor; 913 private final int csize; // Size of section content, compressed 914 private final short subsections; // Number of following subsections 915 private final byte[] hash; // Hash of section content 916 917 public SectionHeader(SectionType type, 918 Compressor compressor, 919 int csize, short subsections, byte[] hash) { 920 ensureNonNull(type, "type"); 921 ensureNonNull(compressor, "compressor"); 922 ensureNonNegativity(csize, "csize"); 923 ensureNonNegativity(subsections, "subsections"); 924 ensureNonNull(hash, "hash"); 925 checkSubsectionCount(type, subsections); 926 checkCompressor(type, compressor); 927 928 this.type = type; 929 this.compressor = compressor; 930 this.csize = csize; 931 this.subsections = subsections; 932 this.hash = hash.clone(); 933 } 934 935 public void write(DataOutput out) throws IOException { 936 out.writeShort(type.value()); 937 out.writeShort(compressor.value()); 938 out.writeInt(csize); 939 out.writeShort(subsections); 940 writeHash(out, hash); 941 } 942 943 private static SectionType lookupSectionType(short value) { 944 for (SectionType i : SectionType.class.getEnumConstants()) { 945 if (i.value() == value) return i; 946 } 947 948 throw new 949 IllegalArgumentException("No SectionType exists with value " 950 + value); 951 } 952 953 private static Compressor lookupCompressor(short value) { 954 for (Compressor i : Compressor.class.getEnumConstants()) { 955 if (i.value() == value) return i; 956 } 957 958 throw new 959 IllegalArgumentException("No Compressor exists with value " 960 + value); 961 } 962 963 public static SectionHeader read(DataInputStream in) throws IOException { 964 short tvalue = in.readShort(); 965 final SectionType type = lookupSectionType(tvalue); 966 short cvalue = in.readShort(); 967 final Compressor compressor = lookupCompressor(cvalue); 968 final int csize = in.readInt(); 969 final short sections = in.readShort(); 970 final byte[] hash = readHash(in); 971 972 return new SectionHeader(type, compressor, csize, 973 sections, hash); 974 } 975 976 public SectionType getType() { 977 return type; 978 } 979 980 public Compressor getCompressor() { 981 return compressor; 982 } 983 984 public int getCSize() { 985 return csize; 986 } 987 988 public short getSubsections() { 989 return subsections; 990 } 991 992 public byte[] getHash() { 993 return hash.clone(); 994 } 995 996 private byte[] getHashNoClone() { 997 return hash; 998 } 999 1000 public String toString() { 1001 return "SectionHeader{type= " + type 1002 + ", compressor=" + compressor 1003 + ", csize=" + csize 1004 + ", subsections=" + subsections 1005 + ", hash=" + hashHexString(hash) + "}"; 1006 } 1007 } 1008 1009 public final static class SubSectionFileHeader { 1010 private final int csize; // Size of file, compressed 1011 private final String path; // Path name, in Java-modified UTF-8 1012 1013 public int getCSize() { 1014 return csize; 1015 } 1016 1017 public String getPath() { 1018 return path; 1019 } 1020 1021 public SubSectionFileHeader(int csize, String path) { 1022 ensureNonNegativity(csize, "csize"); 1023 ensureNonNull(path, "path"); 1024 1025 this.csize = csize; 1026 this.path = path; 1027 } 1028 1029 public void write(DataOutput out) throws IOException { 1030 out.writeShort(SubSectionType.FILE.value()); 1031 out.writeInt(csize); 1032 out.writeUTF(path); 1033 } 1034 1035 public static SubSectionFileHeader read(DataInputStream in) 1036 throws IOException 1037 { 1038 final short type = in.readShort(); 1039 ensureMatch(type, SubSectionType.FILE.value(), 1040 "ModuleFile.SubSectionType.FILE"); 1041 final int csize = in.readInt(); 1042 final String path = in.readUTF(); 1043 1044 return new SubSectionFileHeader(csize, path); 1045 } 1046 } 1047 1048 private static void writeHash(DataOutput out, byte[] hash) 1049 throws IOException 1050 { 1051 out.writeShort(hash.length); 1052 out.write(hash); 1053 } 1054 } --- EOF ---