1 /* 2 * Copyright (c) 2009, 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.lang.module.*; 29 import java.io.*; 30 import java.net.URI; 31 import java.nio.file.*; 32 import java.nio.file.attribute.BasicFileAttributes; 33 import java.security.*; 34 import java.security.cert.*; 35 import java.util.*; 36 import java.util.jar.*; 37 import java.util.zip.*; 38 39 import static java.nio.file.StandardCopyOption.*; 40 41 /** 42 * A simple module library which stores data directly in the filesystem 43 * 44 * @see Library 45 */ 46 47 // ## TODO: Move remaining parent-searching logic upward into Library class 48 49 // On-disk library layout 50 // 51 // $LIB/%jigsaw-library 52 // com.foo.bar/1.2.3/info (= module-info.class) 53 // index (list of defined classes) 54 // config (resolved configuration, if a root) 55 // classes/com/foo/bar/... 56 // resources/com/foo/bar/... 57 // lib/libbar.so 58 // bin/bar 59 // signer (signer's certchain & timestamp) 60 // 61 // ## Issue: Concurrent access to the module library 62 // ## e.g. a module is being removed while a running application 63 // ## is depending on it 64 65 public final class SimpleLibrary 66 extends Library 67 { 68 69 private static abstract class MetaData { 70 71 protected final int maxMajorVersion; 72 protected final int maxMinorVersion; 73 protected int majorVersion; 74 protected int minorVersion; 75 private final FileConstants.Type type; 76 private final File file; 77 78 protected MetaData(int maxMajor, int maxMinor, 79 FileConstants.Type t, File f) 80 { 81 maxMajorVersion = majorVersion = maxMajor; 82 maxMinorVersion = minorVersion = maxMinor; 83 type = t; 84 file = f; 85 } 86 87 protected abstract void storeRest(DataOutputStream out) 88 throws IOException; 89 90 void store() throws IOException { 91 try (OutputStream fos = new FileOutputStream(file); 92 BufferedOutputStream bos = new BufferedOutputStream(fos); 93 DataOutputStream out = new DataOutputStream(bos)) { 94 out.writeInt(FileConstants.MAGIC); 95 out.writeShort(type.value()); 96 out.writeShort(majorVersion); 97 out.writeShort(minorVersion); 98 storeRest(out); 99 } 100 } 101 102 protected abstract void loadRest(DataInputStream in) 103 throws IOException; 104 105 protected void load() throws IOException { 106 try (InputStream fis = new FileInputStream(file); 107 BufferedInputStream bis = new BufferedInputStream(fis); 108 DataInputStream in = new DataInputStream(bis)) { 109 if (in.readInt() != FileConstants.MAGIC) 110 throw new IOException(file + ": Invalid magic number"); 111 if (in.readShort() != type.value()) 112 throw new IOException(file + ": Invalid file type"); 113 int maj = in.readShort(); 114 int min = in.readShort(); 115 if ( maj > maxMajorVersion 116 || (maj == maxMajorVersion && min > maxMinorVersion)) { 117 throw new IOException(file 118 + ": Futuristic version number"); 119 } 120 majorVersion = maj; 121 minorVersion = min; 122 loadRest(in); 123 } catch (EOFException x) { 124 throw new IOException(file + ": Invalid library metadata", x); 125 } 126 } 127 } 128 129 /** 130 * Defines the storage options that SimpleLibrary supports. 131 */ 132 public static enum StorageOption { 133 DEFLATED, 134 } 135 136 private static final class Header 137 extends MetaData 138 { 139 private static final String FILE 140 = FileConstants.META_PREFIX + "jigsaw-library"; 141 142 private static final int MAJOR_VERSION = 0; 143 private static final int MINOR_VERSION = 1; 144 145 private static final int DEFLATED = 1 << 0; 146 147 private File parent; 148 // location of native libs for this library (may be outside the library) 149 // null:default, to use a per-module 'lib' directory 150 private File natlibs; 151 // location of native cmds for this library (may be outside the library) 152 // null:default, to use a per-module 'bin' directory 153 private File natcmds; 154 // location of config files for this library (may be outside the library) 155 // null:default, to use a per-module 'etc' directory 156 private File configs; 157 private Set<StorageOption> opts; 158 159 public File parent() { return parent; } 160 public File natlibs() { return natlibs; } 161 public File natcmds() { return natcmds; } 162 public File configs() { return configs; } 163 public boolean isDeflated() { 164 return opts.contains(StorageOption.DEFLATED); 165 } 166 167 private Header(File root) { 168 super(MAJOR_VERSION, MINOR_VERSION, 169 FileConstants.Type.LIBRARY_HEADER, 170 new File(root, FILE)); 171 } 172 173 private Header(File root, File parent, File natlibs, File natcmds, 174 File configs, Set<StorageOption> opts) { 175 this(root); 176 this.parent = parent; 177 this.natlibs = natlibs; 178 this.natcmds = natcmds; 179 this.configs = configs; 180 this.opts = new HashSet<>(opts); 181 } 182 183 private void storePath(File p, DataOutputStream out) throws IOException { 184 if (p != null) { 185 out.writeByte(1); 186 out.writeUTF(Files.convertSeparator(p.toString())); 187 } else { 188 out.write(0); 189 } 190 } 191 192 protected void storeRest(DataOutputStream out) throws IOException { 193 int flags = 0; 194 if (isDeflated()) 195 flags |= DEFLATED; 196 out.writeShort(flags); 197 198 storePath(parent, out); 199 storePath(natlibs, out); 200 storePath(natcmds, out); 201 storePath(configs, out); 202 } 203 204 private File loadPath(DataInputStream in) throws IOException { 205 if (in.readByte() != 0) 206 return new File(Files.platformSeparator(in.readUTF())); 207 return null; 208 } 209 210 protected void loadRest(DataInputStream in) throws IOException { 211 opts = new HashSet<StorageOption>(); 212 int flags = in.readShort(); 213 if ((flags & DEFLATED) == DEFLATED) 214 opts.add(StorageOption.DEFLATED); 215 parent = loadPath(in); 216 natlibs = loadPath(in); 217 natcmds = loadPath(in); 218 configs = loadPath(in); 219 } 220 221 private static Header load(File f) throws IOException { 222 Header h = new Header(f); 223 h.load(); 224 return h; 225 } 226 } 227 228 private final File root; 229 private final File canonicalRoot; 230 private final File parentPath; 231 private final File natlibs; 232 private final File natcmds; 233 private final File configs; 234 private final SimpleLibrary parent; 235 private final Header hd; 236 237 public String name() { return root.toString(); } 238 public File root() { return canonicalRoot; } 239 public int majorVersion() { return hd.majorVersion; } 240 public int minorVersion() { return hd.minorVersion; } 241 public SimpleLibrary parent() { return parent; } 242 public File natlibs() { return natlibs; } 243 public File natcmds() { return natcmds; } 244 public File configs() { return configs; } 245 public boolean isDeflated() { return hd.isDeflated(); } 246 247 private URI location = null; 248 public URI location() { 249 if (location == null) 250 location = root().toURI(); 251 return location; 252 } 253 254 @Override 255 public String toString() { 256 return (this.getClass().getName() 257 + "[" + canonicalRoot 258 + ", v" + hd.majorVersion + "." + hd.minorVersion + "]"); 259 } 260 261 262 private static File resolveAndEnsurePath(File path) throws IOException { 263 if (path == null) { return null; } 264 265 File p = path.getCanonicalFile(); 266 if (!p.exists()) { 267 Files.mkdirs(p, p.toString()); 268 } else { 269 Files.ensureIsDirectory(p); 270 Files.ensureWriteable(p); 271 } 272 return p; 273 } 274 275 private File relativize(File path) throws IOException { 276 if (path == null) { return null; } 277 // Return the path relative to the canonical root 278 return (canonicalRoot.toPath().relativize(path.toPath().toRealPath())).toFile(); 279 } 280 281 // Opens an existing library 282 private SimpleLibrary(File path) throws IOException { 283 root = path; 284 canonicalRoot = root.getCanonicalFile(); 285 Files.ensureIsDirectory(root); 286 hd = Header.load(root); 287 288 parentPath = hd.parent(); 289 parent = parentPath != null ? open(parentPath) : null; 290 291 natlibs = hd.natlibs() == null ? null : 292 new File(canonicalRoot, hd.natlibs().toString()).getCanonicalFile(); 293 natcmds = hd.natcmds() == null ? null : 294 new File(canonicalRoot, hd.natcmds().toString()).getCanonicalFile(); 295 configs = hd.configs() == null ? null : 296 new File(canonicalRoot, hd.configs().toString()).getCanonicalFile(); 297 } 298 299 // Creates a new library 300 private SimpleLibrary(File path, File parentPath, File natlibs, File natcmds, 301 File configs, Set<StorageOption> opts) 302 throws IOException 303 { 304 root = path; 305 canonicalRoot = root.getCanonicalFile(); 306 if (root.exists()) { 307 Files.ensureIsDirectory(root); 308 if (root.list().length != 0) 309 throw new IOException(root + ": Already Exists"); 310 Files.ensureWriteable(root); 311 } else 312 Files.mkdirs(root, root.toString()); 313 314 this.parent = parentPath != null ? open(parentPath) : null; 315 this.parentPath = parentPath != null ? this.parent.root() : null; 316 317 this.natlibs = resolveAndEnsurePath(natlibs); 318 this.natcmds = resolveAndEnsurePath(natcmds); 319 this.configs = resolveAndEnsurePath(configs); 320 321 hd = new Header(canonicalRoot, this.parentPath, relativize(this.natlibs), 322 relativize(this.natcmds), relativize(this.configs), opts); 323 hd.store(); 324 } 325 326 public static SimpleLibrary create(File path, File parent, File natlibs, 327 File natcmds, File configs, 328 Set<StorageOption> opts) 329 throws IOException 330 { 331 return new SimpleLibrary(path, parent, natlibs, natcmds, configs, opts); 332 } 333 334 public static SimpleLibrary create(File path, File parent, Set<StorageOption> opts) 335 throws IOException 336 { 337 return new SimpleLibrary(path, parent, null, null, null, opts); 338 } 339 340 public static SimpleLibrary create(File path, File parent) 341 throws IOException 342 { 343 return SimpleLibrary.create(path, parent, Collections.<StorageOption>emptySet()); 344 } 345 346 public static SimpleLibrary create(File path, Set<StorageOption> opts) 347 throws IOException 348 { 349 // ## Should default parent to $JAVA_HOME/lib/modules 350 return SimpleLibrary.create(path, null, opts); 351 } 352 353 public static SimpleLibrary open(File path) 354 throws IOException 355 { 356 return new SimpleLibrary(path); 357 } 358 359 private static final JigsawModuleSystem jms 360 = JigsawModuleSystem.instance(); 361 362 private static final class Index 363 extends MetaData 364 { 365 366 private static String FILE = "index"; 367 368 private static int MAJOR_VERSION = 0; 369 private static int MINOR_VERSION = 1; 370 371 private Set<String> publicClasses; 372 public Set<String> publicClasses() { return publicClasses; } 373 374 private Set<String> otherClasses; 375 public Set<String> otherClasses() { return otherClasses; } 376 377 private Index(File root) { 378 super(MAJOR_VERSION, MINOR_VERSION, 379 FileConstants.Type.LIBRARY_MODULE_INDEX, 380 new File(root, FILE)); 381 // Unsorted on input, because we don't need it sorted 382 publicClasses = new HashSet<String>(); 383 otherClasses = new HashSet<String>(); 384 } 385 386 private void storeSet(Set<String> cnset, DataOutputStream out) 387 throws IOException 388 { 389 // Sorted on output, because we can afford it 390 List<String> cns = new ArrayList<String>(cnset); 391 Collections.sort(cns); 392 out.writeInt(cns.size()); 393 for (String cn : cns) 394 out.writeUTF(cn); 395 } 396 397 protected void storeRest(DataOutputStream out) 398 throws IOException 399 { 400 storeSet(publicClasses, out); 401 storeSet(otherClasses, out); 402 } 403 404 private void loadSet(DataInputStream in, Set<String> cnset) 405 throws IOException 406 { 407 int n = in.readInt(); 408 for (int i = 0; i < n; i++) 409 cnset.add(in.readUTF()); 410 } 411 412 protected void loadRest(DataInputStream in) 413 throws IOException 414 { 415 loadSet(in, publicClasses); 416 loadSet(in, otherClasses); 417 } 418 419 private static Index load(File f) 420 throws IOException 421 { 422 Index ix = new Index(f); 423 ix.load(); 424 return ix; 425 } 426 427 } 428 429 private static final class StoredConfiguration 430 extends MetaData 431 { 432 433 private static String FILE = "config"; 434 435 private static int MAJOR_VERSION = 0; 436 private static int MINOR_VERSION = 1; 437 438 private Configuration<Context> cf; 439 440 private static void delete(File root) { 441 new File(root, FILE).delete(); 442 } 443 444 private StoredConfiguration(File root, Configuration<Context> conf) 445 { 446 super(MAJOR_VERSION, MINOR_VERSION, 447 FileConstants.Type.LIBRARY_MODULE_CONFIG, 448 new File(root, FILE)); 449 cf = conf; 450 } 451 452 protected void storeRest(DataOutputStream out) 453 throws IOException 454 { 455 // Roots 456 out.writeInt(cf.roots().size()); 457 for (ModuleId mid : cf.roots()) { 458 out.writeUTF(mid.toString()); 459 } 460 // Contexts 461 out.writeInt(cf.contexts().size()); 462 for (Context cx : cf.contexts()) { 463 out.writeUTF(cx.name()); 464 // Module ids, and their libraries 465 out.writeInt(cx.modules().size()); 466 for (ModuleId mid : cx.modules()) { 467 out.writeUTF(mid.toString()); 468 File lp = cx.findLibraryPathForModule(mid); 469 if (lp == null) 470 out.writeUTF(""); 471 else 472 out.writeUTF(lp.toString()); 473 474 // Module views 475 out.writeInt(cx.views(mid).size()); 476 for (ModuleId id : cx.views(mid)) { 477 out.writeUTF(id.toString()); 478 } 479 } 480 481 // Local class map 482 out.writeInt(cx.localClasses().size()); 483 for (Map.Entry<String,ModuleId> me 484 : cx.moduleForLocalClassMap().entrySet()) { 485 out.writeUTF(me.getKey()); 486 out.writeUTF(me.getValue().toString()); 487 } 488 489 // Remote package map 490 out.writeInt(cx.contextForRemotePackageMap().size()); 491 for (Map.Entry<String,String> me 492 : cx.contextForRemotePackageMap().entrySet()) { 493 out.writeUTF(me.getKey()); 494 out.writeUTF(me.getValue()); 495 } 496 497 // Suppliers 498 out.writeInt(cx.remoteContexts().size()); 499 for (String cxn : cx.remoteContexts()) { 500 out.writeUTF(cxn); 501 } 502 503 } 504 } 505 506 protected void loadRest(DataInputStream in) 507 throws IOException 508 { 509 // Roots 510 int nRoots = in.readInt(); 511 List<ModuleId> roots = new ArrayList<>(); 512 for (int i = 0; i < nRoots; i++) { 513 String root = in.readUTF(); 514 ModuleId rmid = jms.parseModuleId(root); 515 roots.add(rmid); 516 } 517 cf = new Configuration<Context>(roots); 518 // Contexts 519 int nContexts = in.readInt(); 520 for (int i = 0; i < nContexts; i++) { 521 Context cx = new Context(); 522 String cxn = in.readUTF(); 523 // Module ids 524 int nModules = in.readInt(); 525 for (int j = 0; j < nModules; j++) { 526 ModuleId mid = jms.parseModuleId(in.readUTF()); 527 String lps = in.readUTF(); 528 if (lps.length() > 0) 529 cx.putLibraryPathForModule(mid, new File(lps)); 530 // Module Views 531 int nViews = in.readInt(); 532 Set<ModuleId> views = new HashSet<>(); 533 for (int k = 0; k < nViews; k++) { 534 ModuleId id = jms.parseModuleId(in.readUTF()); 535 views.add(id); 536 cf.put(id.name(), cx); 537 } 538 cx.add(mid, views); 539 } 540 cx.freeze(); 541 assert cx.name().equals(cxn); 542 cf.add(cx); 543 // Local class map 544 int nClasses = in.readInt(); 545 for (int j = 0; j < nClasses; j++) 546 cx.putModuleForLocalClass(in.readUTF(), 547 jms.parseModuleId(in.readUTF())); 548 // Remote package map 549 int nPackages = in.readInt(); 550 for (int j = 0; j < nPackages; j++) 551 cx.putContextForRemotePackage(in.readUTF(), in.readUTF()); 552 553 // Suppliers 554 int nSuppliers = in.readInt(); 555 for (int j = 0; j < nSuppliers; j++) 556 cx.addSupplier(in.readUTF()); 557 } 558 559 } 560 561 private static StoredConfiguration load(File f) 562 throws IOException 563 { 564 StoredConfiguration sp = new StoredConfiguration(f, null); 565 sp.load(); 566 return sp; 567 } 568 569 } 570 571 private static final class Signers 572 extends MetaData { 573 574 private static String FILE = "signer"; 575 private static int MAJOR_VERSION = 0; 576 private static int MINOR_VERSION = 1; 577 578 private CertificateFactory cf = null; 579 private Set<CodeSigner> signers; 580 private Set<CodeSigner> signers() { return signers; } 581 582 private Signers(File root, Set<CodeSigner> signers) { 583 super(MAJOR_VERSION, MINOR_VERSION, 584 FileConstants.Type.LIBRARY_MODULE_SIGNER, 585 new File(root, FILE)); 586 this.signers = signers; 587 } 588 589 protected void storeRest(DataOutputStream out) 590 throws IOException 591 { 592 out.writeInt(signers.size()); 593 for (CodeSigner signer : signers) { 594 try { 595 CertPath signerCertPath = signer.getSignerCertPath(); 596 out.write(signerCertPath.getEncoded("PkiPath")); 597 Timestamp ts = signer.getTimestamp(); 598 out.writeByte((ts != null) ? 1 : 0); 599 if (ts != null) { 600 out.writeLong(ts.getTimestamp().getTime()); 601 out.write(ts.getSignerCertPath().getEncoded("PkiPath")); 602 } 603 } catch (CertificateEncodingException cee) { 604 throw new IOException(cee); 605 } 606 } 607 } 608 609 protected void loadRest(DataInputStream in) 610 throws IOException 611 { 612 int size = in.readInt(); 613 for (int i = 0; i < size; i++) { 614 try { 615 if (cf == null) 616 cf = CertificateFactory.getInstance("X.509"); 617 CertPath signerCertPath = cf.generateCertPath(in, "PkiPath"); 618 int b = in.readByte(); 619 if (b != 0) { 620 Date timestamp = new Date(in.readLong()); 621 CertPath tsaCertPath = cf.generateCertPath(in, "PkiPath"); 622 Timestamp ts = new Timestamp(timestamp, tsaCertPath); 623 signers.add(new CodeSigner(signerCertPath, ts)); 624 } else { 625 signers.add(new CodeSigner(signerCertPath, null)); 626 } 627 } catch (CertificateException ce) { 628 throw new IOException(ce); 629 } 630 } 631 } 632 633 private static Signers load(File f) 634 throws IOException 635 { 636 Signers signers = new Signers(f, new HashSet<CodeSigner>()); 637 signers.load(); 638 return signers; 639 } 640 } 641 642 private void gatherLocalModuleIds(File mnd, Set<ModuleId> mids) 643 throws IOException 644 { 645 if (!mnd.isDirectory()) 646 throw new IOException(mnd + ": Not a directory"); 647 if (!mnd.canRead()) 648 throw new IOException(mnd + ": Not readable"); 649 for (String v : mnd.list()) { 650 mids.add(jms.parseModuleId(mnd.getName(), v)); 651 } 652 } 653 654 private void gatherLocalModuleIds(Set<ModuleId> mids) 655 throws IOException 656 { 657 File[] mnds = root.listFiles(); 658 for (File mnd : mnds) { 659 if (mnd.getName().startsWith(FileConstants.META_PREFIX)) 660 continue; 661 gatherLocalModuleIds(mnd, mids); 662 } 663 } 664 665 protected void gatherLocalModuleIds(String moduleName, 666 Set<ModuleId> mids) 667 throws IOException 668 { 669 if (moduleName == null) { 670 gatherLocalModuleIds(mids); 671 return; 672 } 673 File mnd = new File(root, moduleName); 674 if (mnd.exists()) 675 gatherLocalModuleIds(mnd, mids); 676 } 677 678 private void checkModuleId(ModuleId mid) { 679 Version v = mid.version(); 680 if (v == null) 681 return; 682 if (!(v instanceof JigsawVersion)) 683 throw new IllegalArgumentException(mid + ": Not a Jigsaw module id"); 684 } 685 686 private File moduleDir(File root, ModuleId mid) { 687 Version v = mid.version(); 688 String vs = (v != null) ? v.toString() : "default"; 689 return new File(new File(root, mid.name()), vs); 690 } 691 692 private void checkModuleDir(File md) 693 throws IOException 694 { 695 if (!md.isDirectory()) 696 throw new IOException(md + ": Not a directory"); 697 if (!md.canRead()) 698 throw new IOException(md + ": Not readable"); 699 } 700 701 private File findModuleDir(ModuleId mid) 702 throws IOException 703 { 704 checkModuleId(mid); 705 File md = moduleDir(root, mid); 706 if (!md.exists()) 707 return null; 708 checkModuleDir(md); 709 710 // mid may be a view or alias of a module 711 byte[] mib = Files.load(new File(md, "info")); 712 ModuleInfo mi = jms.parseModuleInfo(mib); 713 if (!mid.equals(mi.id())) { 714 md = moduleDir(root, mi.id()); 715 if (!md.exists()) 716 throw new IOException(mid + ": " + md + " does not exist"); 717 checkModuleDir(md); 718 } 719 return md; 720 } 721 722 private File makeModuleDir(File root, ModuleInfo mi) 723 throws ConfigurationException, IOException 724 { 725 // view name is unique 726 for (ModuleView mv : mi.views()) { 727 File md = moduleDir(root, mv.id()); 728 if (md.exists()) { 729 throw new ConfigurationException("module view " + 730 mv.id() + " already installed"); 731 } 732 if (!md.mkdirs()) { 733 throw new IOException(md + ": Cannot create"); 734 } 735 } 736 737 return moduleDir(root, mi.id()); 738 } 739 740 private void deleteModuleDir(File root, ModuleInfo mi) 741 throws IOException 742 { 743 // delete the default view and the module content 744 ModuleId mid = mi.defaultView().id(); 745 File md = moduleDir(root, mid); 746 if (md.exists()) 747 ModuleFile.Reader.remove(md); 748 // delete all views 749 for (ModuleView mv : mi.views()) { 750 md = moduleDir(root, mv.id()); 751 if (md.exists()) { 752 Files.deleteTree(md); 753 } 754 } 755 } 756 757 private void deleteModuleDir(ModuleId mid) 758 throws IOException 759 { 760 checkModuleId(mid); 761 File md = moduleDir(root, mid); 762 if (!md.exists()) 763 return; 764 checkModuleDir(md); 765 766 // mid may be a view or alias of a module 767 byte[] mib = Files.load(new File(md, "info")); 768 ModuleInfo mi = jms.parseModuleInfo(mib); 769 if (!mid.equals(mi.id())) { 770 throw new IOException(mi.id() + " found in the module directory for " + mid); 771 } 772 deleteModuleDir(root, mi); 773 } 774 775 private void copyModuleInfo(File root, ModuleInfo mi, byte[] mib) 776 throws IOException 777 { 778 for (ModuleView mv : mi.views()) { 779 if (mv.id().equals(mi.id())) { 780 continue; 781 } 782 783 File mvd = moduleDir(root, mv.id()); 784 Files.store(mib, new File(mvd, "info")); 785 } 786 } 787 public byte[] readLocalModuleInfoBytes(ModuleId mid) 788 throws IOException 789 { 790 File md = findModuleDir(mid); 791 if (md == null) 792 return null; 793 return Files.load(new File(md, "info")); 794 } 795 796 public CodeSigner[] readLocalCodeSigners(ModuleId mid) 797 throws IOException 798 { 799 File md = findModuleDir(mid); 800 if (md == null) 801 return null; 802 // Only one signer is currently supported 803 File f = new File(md, "signer"); 804 // ## concurrency issues : what is the expected behavior if file is 805 // ## removed by another thread/process here? 806 if (!f.exists()) 807 return null; 808 return Signers.load(md).signers().toArray(new CodeSigner[0]); 809 } 810 811 // ## Close all zip files when we close this library 812 private Map<ModuleId, Object> contentForModule = new HashMap<>(); 813 private Object NONE = new Object(); 814 815 private Object findContent(ModuleId mid) 816 throws IOException 817 { 818 Object o = contentForModule.get(mid); 819 if (o != null) 820 return o; 821 if (o == NONE) 822 return null; 823 File md = findModuleDir(mid); 824 if (md == null) { 825 contentForModule.put(mid, NONE); 826 return null; 827 } 828 File cf = new File(md, "classes"); 829 if (cf.isFile()) { 830 ZipFile zf = new ZipFile(cf); 831 contentForModule.put(mid, zf); 832 return zf; 833 } 834 if (cf.isDirectory()) { 835 contentForModule.put(mid, cf); 836 return cf; 837 } 838 contentForModule.put(mid, NONE); 839 return null; 840 } 841 842 private byte[] loadContent(ZipFile zf, String path) 843 throws IOException 844 { 845 ZipEntry ze = zf.getEntry(path); 846 if (ze == null) 847 return null; 848 return Files.load(zf.getInputStream(ze), (int)ze.getSize()); 849 } 850 851 private byte[] loadContent(ModuleId mid, String path) 852 throws IOException 853 { 854 Object o = findContent(mid); 855 if (o == null) 856 return null; 857 if (o instanceof ZipFile) { 858 ZipFile zf = (ZipFile)o; 859 ZipEntry ze = zf.getEntry(path); 860 if (ze == null) 861 return null; 862 return Files.load(zf.getInputStream(ze), (int)ze.getSize()); 863 } 864 if (o instanceof File) { 865 File f = new File((File)o, path); 866 if (!f.exists()) 867 return null; 868 return Files.load(f); 869 } 870 assert false; 871 return null; 872 } 873 874 private URI locateContent(ModuleId mid, String path) 875 throws IOException 876 { 877 Object o = findContent(mid); 878 if (o == null) 879 return null; 880 if (o instanceof ZipFile) { 881 ZipFile zf = (ZipFile)o; 882 ZipEntry ze = zf.getEntry(path); 883 if (ze == null) 884 return null; 885 return URI.create("jar:" 886 + new File(zf.getName()).toURI().toString() 887 + "!/" + path); 888 } 889 if (o instanceof File) { 890 File f = new File((File)o, path); 891 if (!f.exists()) 892 return null; 893 return f.toURI(); 894 } 895 return null; 896 } 897 898 public byte[] readLocalClass(ModuleId mid, String className) 899 throws IOException 900 { 901 return loadContent(mid, className.replace('.', '/') + ".class"); 902 } 903 904 public List<String> listLocalClasses(ModuleId mid, boolean all) 905 throws IOException 906 { 907 File md = findModuleDir(mid); 908 if (md == null) 909 return null; 910 Index ix = Index.load(md); 911 int os = all ? ix.otherClasses().size() : 0; 912 ArrayList<String> cns 913 = new ArrayList<String>(ix.publicClasses().size() + os); 914 cns.addAll(ix.publicClasses()); 915 if (all) 916 cns.addAll(ix.otherClasses()); 917 return cns; 918 } 919 920 public Configuration<Context> readConfiguration(ModuleId mid) 921 throws IOException 922 { 923 File md = findModuleDir(mid); 924 if (md == null) { 925 if (parent != null) 926 return parent.readConfiguration(mid); 927 return null; 928 } 929 StoredConfiguration scf = StoredConfiguration.load(md); 930 return scf.cf; 931 } 932 933 private boolean addToIndex(ClassInfo ci, Index ix) 934 throws IOException 935 { 936 if (ci.isModuleInfo()) 937 return false; 938 if (ci.moduleName() != null) { 939 // ## From early Jigsaw development; can probably delete now 940 throw new IOException("Old-style class file with" 941 + " module attribute"); 942 } 943 if (ci.isPublic()) 944 ix.publicClasses().add(ci.name()); 945 else 946 ix.otherClasses().add(ci.name()); 947 return true; 948 } 949 950 private void reIndex(ModuleId mid) 951 throws IOException 952 { 953 954 File md = findModuleDir(mid); 955 if (md == null) 956 throw new IllegalArgumentException(mid + ": No such module"); 957 File cd = new File(md, "classes"); 958 final Index ix = new Index(md); 959 960 if (cd.isDirectory()) { 961 Files.walkTree(cd, new Files.Visitor<File>() { 962 public void accept(File f) throws IOException { 963 if (f.getPath().endsWith(".class")) 964 addToIndex(ClassInfo.read(f), ix); 965 } 966 }); 967 } else if (cd.isFile()) { 968 FileInputStream fis = new FileInputStream(cd); 969 ZipInputStream zis = new ZipInputStream(fis); 970 ZipEntry ze; 971 while ((ze = zis.getNextEntry()) != null) { 972 if (!ze.getName().endsWith(".class")) 973 continue; 974 addToIndex(ClassInfo.read(Files.nonClosingStream(zis), 975 ze.getSize(), 976 mid + ":" + ze.getName()), 977 ix); 978 } 979 } 980 981 ix.store(); 982 } 983 984 /** 985 * Strip the debug attributes from the classes in a given module 986 * directory. 987 */ 988 private void strip(File md) throws IOException { 989 File classes = new File(md, "classes"); 990 if (classes.isFile()) { 991 File pf = new File(md, "classes.pack"); 992 try (JarFile jf = new JarFile(classes); 993 FileOutputStream out = new FileOutputStream(pf)) 994 { 995 Pack200.Packer packer = Pack200.newPacker(); 996 Map<String,String> p = packer.properties(); 997 p.put("com.sun.java.util.jar.pack.strip.debug", Pack200.Packer.TRUE); 998 packer.pack(jf, out); 999 } 1000 1001 try (OutputStream out = new FileOutputStream(classes); 1002 JarOutputStream jos = new JarOutputStream(out)) 1003 { 1004 Pack200.Unpacker unpacker = Pack200.newUnpacker(); 1005 unpacker.unpack(pf, jos); 1006 } finally { 1007 pf.delete(); 1008 } 1009 } 1010 } 1011 1012 private List<Path> listFiles(Path dir) throws IOException { 1013 final List<Path> files = new ArrayList<>(); 1014 java.nio.file.Files.walkFileTree(dir, new SimpleFileVisitor<Path>() { 1015 @Override 1016 public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 1017 throws IOException { 1018 if (!file.endsWith("module-info.class")) { 1019 files.add(file); 1020 } 1021 return FileVisitResult.CONTINUE; 1022 } 1023 }); 1024 return files; 1025 } 1026 1027 private void install(Manifest mf, File dst, boolean strip) 1028 throws IOException 1029 { 1030 if (mf.classes().size() > 1) 1031 throw new IllegalArgumentException("Multiple module-class" 1032 + " directories" 1033 + " not yet supported"); 1034 if (mf.classes().size() < 1) 1035 throw new IllegalArgumentException("At least one module-class" 1036 + " directory required"); 1037 File classes = mf.classes().get(0); 1038 final String mn = mf.module(); 1039 1040 File mif = new File(classes, "module-info.class"); 1041 File src = null; 1042 if (mif.exists()) { 1043 src = classes; 1044 } else { 1045 src = new File(classes, mn); 1046 mif = new File(src, "module-info.class"); 1047 } 1048 byte[] bs = Files.load(mif); 1049 ModuleInfo mi = jms.parseModuleInfo(bs); 1050 if (!mi.id().name().equals(mn)) { 1051 // ## Need a more appropriate throwable here 1052 throw new Error(mif + " is for module " + mi.id().name() 1053 + ", not " + mn); 1054 } 1055 String m = mi.id().name(); 1056 JigsawVersion v = (JigsawVersion)mi.id().version(); 1057 String vs = (v == null) ? "default" : v.toString(); 1058 deleteModuleDir(dst, mi); 1059 1060 // view name is unique 1061 for (ModuleView mv : mi.views()) { 1062 File md = moduleDir(dst, mv.id()); 1063 if (!md.mkdirs()) { 1064 throw new IOException(md + ": Cannot create"); 1065 } 1066 } 1067 1068 File mdst = moduleDir(dst, mi.id()); 1069 Files.store(bs, new File(mdst, "info")); 1070 File cldst = new File(mdst, "classes"); 1071 1072 // Delete the config file, if one exists 1073 StoredConfiguration.delete(mdst); 1074 1075 if (false) { 1076 1077 // ## Retained for now in case we later want to add an option 1078 // ## to install into a tree rather than a zip file 1079 1080 // Copy class files and build index 1081 final Index ix = new Index(mdst); 1082 Files.copyTree(src, cldst, new Files.Filter<File>() { 1083 public boolean accept(File f) throws IOException { 1084 if (f.isDirectory()) 1085 return true; 1086 if (f.getName().endsWith(".class")) { 1087 return addToIndex(ClassInfo.read(f), ix); 1088 } else { 1089 return true; 1090 } 1091 }}); 1092 ix.store(); 1093 } else { 1094 // Copy class/resource files and build index 1095 Index ix = new Index(mdst); 1096 Path srcPath = src.toPath(); 1097 List<Path> files = listFiles(srcPath); 1098 1099 if (!files.isEmpty()) { 1100 try (FileOutputStream fos = new FileOutputStream(new File(mdst, "classes")); 1101 JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(fos))) 1102 { 1103 boolean deflate = isDeflated(); 1104 for (Path path : files) { 1105 File file = path.toFile(); 1106 String jp = Files.convertSeparator(srcPath.relativize(path).toString()); 1107 try (OutputStream out = Files.newOutputStream(jos, deflate, jp)) { 1108 java.nio.file.Files.copy(path, out); 1109 } 1110 if (file.getName().endsWith(".class")) 1111 addToIndex(ClassInfo.read(file), ix); 1112 } 1113 } 1114 } 1115 ix.store(); 1116 copyModuleInfo(dst, mi, bs); 1117 if (strip) 1118 strip(mdst); 1119 } 1120 1121 } 1122 1123 private void install(Collection<Manifest> mfs, File dst, boolean strip) 1124 throws IOException 1125 { 1126 for (Manifest mf : mfs) 1127 install(mf, dst, strip); 1128 } 1129 1130 public void installFromManifests(Collection<Manifest> mfs, boolean strip) 1131 throws ConfigurationException, IOException 1132 { 1133 install(mfs, root, strip); 1134 configure(null); 1135 } 1136 1137 @Override 1138 public void installFromManifests(Collection<Manifest> mfs) 1139 throws ConfigurationException, IOException 1140 { 1141 installFromManifests(mfs, false); 1142 } 1143 1144 private ModuleFileVerifier.Parameters mfvParams; 1145 private ModuleId install(InputStream is, boolean verifySignature, boolean strip) 1146 throws ConfigurationException, IOException, SignatureException 1147 { 1148 BufferedInputStream bin = new BufferedInputStream(is); 1149 DataInputStream in = new DataInputStream(bin); 1150 ModuleInfo mi = null; 1151 try (ModuleFile.Reader mr = new ModuleFile.Reader(in)) { 1152 byte[] mib = mr.readStart(); 1153 mi = jms.parseModuleInfo(mib); 1154 File md = makeModuleDir(root, mi); 1155 if (verifySignature && mr.hasSignature()) { 1156 ModuleFileVerifier mfv = new SignedModule.PKCS7Verifier(mr); 1157 if (mfvParams == null) { 1158 mfvParams = new SignedModule.VerifierParameters(); 1159 } 1160 // Verify the module signature and validate the signer's 1161 // certificate chain 1162 Set<CodeSigner> signers = mfv.verifySignature(mfvParams); 1163 1164 // Verify the module header hash and the module info hash 1165 mfv.verifyHashesStart(mfvParams); 1166 1167 // ## Check policy - is signer trusted and what permissions 1168 // ## should be granted? 1169 1170 // Store signer info 1171 new Signers(md, signers).store(); 1172 1173 // Read and verify the rest of the hashes 1174 mr.readRest(md, isDeflated(), natlibs(), natcmds(), configs()); 1175 mfv.verifyHashesRest(mfvParams); 1176 } else { 1177 mr.readRest(md, isDeflated(), natlibs(), natcmds(), configs()); 1178 } 1179 1180 if (strip) 1181 strip(md); 1182 reIndex(mi.id()); // ## Could do this while reading module file 1183 1184 // copy module-info.class to each view 1185 copyModuleInfo(root, mi, mib); 1186 return mi.id(); 1187 1188 } catch (IOException | SignatureException x) { 1189 if (mi != null) { 1190 try { 1191 deleteModuleDir(root, mi); 1192 } catch (IOException y) { 1193 y.initCause(x); 1194 throw y; 1195 } 1196 } 1197 throw x; 1198 } 1199 } 1200 1201 private ModuleId installFromJarFile(File mf, boolean verifySignature, boolean strip) 1202 throws ConfigurationException, IOException, SignatureException 1203 { 1204 ModuleInfo mi = null; 1205 try (JarFile jf = new JarFile(mf, verifySignature)) { 1206 mi = jf.getModuleInfo(); 1207 if (mi == null) 1208 throw new ConfigurationException(mf + ": not a modular JAR file"); 1209 1210 File md = makeModuleDir(root, mi); 1211 ModuleId mid = mi.id(); 1212 1213 boolean signed = false; 1214 1215 // copy the jar file to the module library 1216 File classesDir = new File(md, "classes"); 1217 try (FileOutputStream fos = new FileOutputStream(classesDir); 1218 BufferedOutputStream bos = new BufferedOutputStream(fos); 1219 JarOutputStream jos = new JarOutputStream(bos)) { 1220 jos.setLevel(0); 1221 1222 Enumeration<JarEntry> entries = jf.entries(); 1223 while (entries.hasMoreElements()) { 1224 JarEntry je = entries.nextElement(); 1225 try (InputStream is = jf.getInputStream(je)) { 1226 if (je.getName().equals(JarFile.MODULEINFO_NAME)) { 1227 java.nio.file.Files.copy(is, md.toPath().resolve("info")); 1228 } else { 1229 writeJarEntry(is, je, jos); 1230 } 1231 } 1232 if (!signed) { 1233 String name = je.getName().toUpperCase(Locale.ENGLISH); 1234 signed = name.startsWith("META-INF/") 1235 && name.endsWith(".SF"); 1236 } 1237 } 1238 } 1239 1240 try { 1241 if (verifySignature && signed) { 1242 // validate the code signers 1243 Set<CodeSigner> signers = getSigners(jf); 1244 SignedModule.validateSigners(signers); 1245 // store the signers 1246 new Signers(md, signers).store(); 1247 } 1248 } catch (CertificateException ce) { 1249 throw new SignatureException(ce); 1250 } 1251 1252 if (strip) 1253 strip(md); 1254 reIndex(mid); 1255 1256 // copy module-info.class to each view 1257 byte[] mib = java.nio.file.Files.readAllBytes(md.toPath().resolve("info")); 1258 copyModuleInfo(root, mi, mib); 1259 return mid; 1260 } catch (IOException | SignatureException x) { 1261 if (mi != null) { 1262 try { 1263 deleteModuleDir(root, mi); 1264 } catch (IOException y) { 1265 y.initCause(x); 1266 throw y; 1267 } 1268 } 1269 throw x; 1270 } 1271 } 1272 1273 /** 1274 * Returns the set of signers of the specified jar file. Each signer 1275 * must have signed all relevant entries. 1276 */ 1277 private static Set<CodeSigner> getSigners(JarFile jf) 1278 throws SignatureException 1279 { 1280 Set<CodeSigner> signers = new HashSet<>(); 1281 Enumeration<JarEntry> entries = jf.entries(); 1282 while (entries.hasMoreElements()) { 1283 JarEntry je = entries.nextElement(); 1284 String name = je.getName().toUpperCase(Locale.ENGLISH); 1285 if (name.endsWith("/") || isSigningRelated(name)) 1286 continue; 1287 1288 // A signed modular jar can be signed by multiple signers. 1289 // However, all entries must be signed by each of these signers. 1290 // Signers that only sign a subset of entries are ignored. 1291 CodeSigner[] jeSigners = je.getCodeSigners(); 1292 if (jeSigners == null || jeSigners.length == 0) 1293 throw new SignatureException("Found unsigned entry in " 1294 + "signed modular JAR"); 1295 1296 Set<CodeSigner> jeSignerSet = 1297 new HashSet<>(Arrays.asList(jeSigners)); 1298 if (signers.isEmpty()) 1299 signers.addAll(jeSignerSet); 1300 else { 1301 if (signers.retainAll(jeSignerSet) && signers.isEmpty()) 1302 throw new SignatureException("No signers in common in " 1303 + "signed modular JAR"); 1304 } 1305 } 1306 return signers; 1307 } 1308 1309 // true if file is part of the signature mechanism itself 1310 private static boolean isSigningRelated(String name) { 1311 if (!name.startsWith("META-INF/")) { 1312 return false; 1313 } 1314 name = name.substring(9); 1315 if (name.indexOf('/') != -1) { 1316 return false; 1317 } 1318 if (name.endsWith(".DSA") || 1319 name.endsWith(".RSA") || 1320 name.endsWith(".SF") || 1321 name.endsWith(".EC") || 1322 name.startsWith("SIG-") || 1323 name.equals("MANIFEST.MF")) { 1324 return true; 1325 } 1326 return false; 1327 } 1328 1329 private void writeJarEntry(InputStream is, JarEntry je, JarOutputStream jos) 1330 throws IOException, SignatureException 1331 { 1332 JarEntry entry = new JarEntry(je.getName()); 1333 entry.setMethod(isDeflated() ? ZipEntry.DEFLATED : ZipEntry.STORED); 1334 entry.setTime(je.getTime()); 1335 try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) { 1336 int size = 0; 1337 byte[] bs = new byte[1024]; 1338 int cc = 0; 1339 // This will throw a SecurityException if a signature is invalid. 1340 while ((cc = is.read(bs)) > 0) { 1341 baos.write(bs, 0, cc); 1342 size += cc; 1343 } 1344 if (!isDeflated()) { 1345 entry.setSize(size); 1346 entry.setCrc(je.getCrc()); 1347 entry.setCompressedSize(size); 1348 } 1349 jos.putNextEntry(entry); 1350 if (baos.size() > 0) 1351 baos.writeTo(jos); 1352 jos.closeEntry(); 1353 } catch (SecurityException se) { 1354 throw new SignatureException(se); 1355 } 1356 } 1357 1358 private ModuleId install(File mf, boolean verifySignature, boolean strip) 1359 throws ConfigurationException, IOException, SignatureException 1360 { 1361 if (mf.getName().endsWith(".jar")) 1362 return installFromJarFile(mf, verifySignature, strip); 1363 else { 1364 // Assume jmod file 1365 try (FileInputStream in = new FileInputStream(mf)) { 1366 return install(in, verifySignature, strip); 1367 } 1368 } 1369 } 1370 1371 public void install(Collection<File> mfs, boolean verifySignature, boolean strip) 1372 throws ConfigurationException, IOException, SignatureException 1373 { 1374 List<ModuleId> mids = new ArrayList<>(); 1375 boolean complete = false; 1376 Throwable ox = null; 1377 try { 1378 for (File mf : mfs) 1379 mids.add(install(mf, verifySignature, strip)); 1380 configure(mids); 1381 complete = true; 1382 } catch (IOException|ConfigurationException x) { 1383 ox = x; 1384 throw x; 1385 } finally { 1386 if (!complete) { 1387 try { 1388 for (ModuleId mid : mids) 1389 deleteModuleDir(mid); 1390 } catch (IOException x) { 1391 if (ox != null) 1392 x.initCause(ox); 1393 throw x; 1394 } 1395 } 1396 } 1397 } 1398 1399 @Override 1400 public void install(Collection<File> mfs, boolean verifySignature) 1401 throws ConfigurationException, IOException, SignatureException 1402 { 1403 install(mfs, verifySignature, false); 1404 } 1405 1406 // Public entry point, since the Resolver itself is package-private 1407 // 1408 public Resolution resolve(Collection<ModuleIdQuery> midqs) 1409 throws ConfigurationException, IOException 1410 { 1411 return Resolver.run(this, midqs); 1412 } 1413 1414 public void install(Resolution res, boolean verifySignature, boolean strip) 1415 throws ConfigurationException, IOException, SignatureException 1416 { 1417 // ## Handle case of installing multiple root modules 1418 assert res.rootQueries.size() == 1; 1419 ModuleIdQuery midq = res.rootQueries.iterator().next(); 1420 ModuleInfo root = null; 1421 for (String mn : res.moduleViewForName.keySet()) { 1422 ModuleView mv = res.moduleViewForName.get(mn); 1423 if (midq.matches(mv.id())) { 1424 root = mv.moduleInfo(); 1425 break; 1426 } 1427 } 1428 assert root != null; 1429 1430 // Download 1431 // 1432 for (ModuleId mid : res.modulesNeeded()) { 1433 URI u = res.locationForName.get(mid.name()); 1434 assert u != null; 1435 RemoteRepository rr = repositoryList().firstRepository(); 1436 assert rr != null; 1437 install(rr.fetch(mid), verifySignature, strip); 1438 res.locationForName.put(mid.name(), location()); 1439 // ## If something goes wrong, delete all our modules 1440 } 1441 1442 // Configure 1443 // 1444 Configuration<Context> cf 1445 = Configurator.configure(this, res); 1446 new StoredConfiguration(findModuleDir(root.id()), cf).store(); 1447 } 1448 1449 @Override 1450 public void install(Resolution res, boolean verifySignature) 1451 throws ConfigurationException, IOException, SignatureException 1452 { 1453 install(res, verifySignature, false); 1454 } 1455 1456 /** 1457 * <p> Pre-install one or more modules to an arbitrary destination 1458 * directory. </p> 1459 * 1460 * <p> A pre-installed module has the same format as within the library 1461 * itself, except that there is never a configuration file. </p> 1462 * 1463 * <p> This method is provided for use by the module-packaging tool. </p> 1464 * 1465 * @param mfs 1466 * The manifest describing the contents of the modules to be 1467 * pre-installed 1468 * 1469 * @param dst 1470 * The destination directory, with one subdirectory per module 1471 * name, each of which contains one subdirectory per version 1472 */ 1473 public void preInstall(Collection<Manifest> mfs, File dst) 1474 throws IOException 1475 { 1476 Files.mkdirs(dst, "module destination"); 1477 install(mfs, dst, false); 1478 } 1479 1480 public void preInstall(Manifest mf, File dst) 1481 throws IOException 1482 { 1483 preInstall(Collections.singleton(mf), dst); 1484 } 1485 1486 /** 1487 * <p> Update the configurations of any root modules affected by the 1488 * copying of the named modules, in pre-installed format, into this 1489 * library. </p> 1490 * 1491 * @param mids 1492 * The module ids of the new or updated modules, or 1493 * {@code null} if the configuration of every root module 1494 * should be (re)computed 1495 */ 1496 public void configure(List<ModuleId> mids) 1497 throws ConfigurationException, IOException 1498 { 1499 // ## mids not used yet 1500 List<ModuleId> roots = new ArrayList<>(); 1501 for (ModuleView mv : listLocalRootModuleViews()) { 1502 // each module can have multiple entry points 1503 // only configure once for each module. 1504 if (!roots.contains(mv.moduleInfo().id())) 1505 roots.add(mv.moduleInfo().id()); 1506 } 1507 1508 for (ModuleId mid : roots) { 1509 // ## We could be a lot more clever about this! 1510 Configuration<Context> cf 1511 = Configurator.configure(this, mid.toQuery()); 1512 new StoredConfiguration(findModuleDir(mid), cf).store(); 1513 } 1514 } 1515 1516 public URI findLocalResource(ModuleId mid, String name) 1517 throws IOException 1518 { 1519 return locateContent(mid, name); 1520 } 1521 1522 public File findLocalNativeLibrary(ModuleId mid, String name) 1523 throws IOException 1524 { 1525 File f = natlibs(); 1526 if (f == null) { 1527 f = findModuleDir(mid); 1528 if (f == null) 1529 return null; 1530 f = new File(f, "lib"); 1531 } 1532 f = new File(f, name); 1533 if (!f.exists()) 1534 return null; 1535 return f; 1536 } 1537 1538 public File classPath(ModuleId mid) 1539 throws IOException 1540 { 1541 File md = findModuleDir(mid); 1542 if (md == null) { 1543 if (parent != null) 1544 return parent.classPath(mid); 1545 return null; 1546 } 1547 // ## Check for other formats here 1548 return new File(md, "classes"); 1549 } 1550 1551 /** 1552 * <p> Re-index the classes of the named previously-installed modules, and 1553 * then update the configurations of any affected root modules. </p> 1554 * 1555 * <p> This method is intended for use during development, when a build 1556 * process may update a previously-installed module in place, adding or 1557 * removing classes. </p> 1558 * 1559 * @param mids 1560 * The module ids of the new or updated modules, or 1561 * {@code null} if the configuration of every root module 1562 * should be (re)computed 1563 */ 1564 public void reIndex(List<ModuleId> mids) 1565 throws ConfigurationException, IOException 1566 { 1567 for (ModuleId mid : mids) 1568 reIndex(mid); 1569 configure(mids); 1570 } 1571 1572 1573 // -- Repositories -- 1574 1575 private static class RepoList 1576 implements RemoteRepositoryList 1577 { 1578 1579 private static final int MINOR_VERSION = 0; 1580 private static final int MAJOR_VERSION = 0; 1581 1582 private final File root; 1583 private final File listFile; 1584 1585 private RepoList(File r) { 1586 root = new File(r, FileConstants.META_PREFIX + "repos"); 1587 listFile = new File(root, FileConstants.META_PREFIX + "list"); 1588 } 1589 1590 private static FileHeader fileHeader() { 1591 return (new FileHeader() 1592 .type(FileConstants.Type.REMOTE_REPO_LIST) 1593 .majorVersion(MAJOR_VERSION) 1594 .minorVersion(MINOR_VERSION)); 1595 } 1596 1597 private List<RemoteRepository> repos = null; 1598 private long nextRepoId = 0; 1599 1600 private File repoDir(long id) { 1601 return new File(root, Long.toHexString(id)); 1602 } 1603 1604 private void load() throws IOException { 1605 1606 repos = new ArrayList<>(); 1607 if (!root.exists() || !listFile.exists()) 1608 return; 1609 FileInputStream fin = new FileInputStream(listFile); 1610 DataInputStream in 1611 = new DataInputStream(new BufferedInputStream(fin)); 1612 try { 1613 1614 FileHeader fh = fileHeader(); 1615 fh.read(in); 1616 nextRepoId = in.readLong(); 1617 int n = in.readInt(); 1618 long[] ids = new long[n]; 1619 for (int i = 0; i < n; i++) 1620 ids[i] = in.readLong(); 1621 RemoteRepository parent = null; 1622 1623 // Load in reverse order so that parents are correct 1624 for (int i = n - 1; i >= 0; i--) { 1625 long id = ids[i]; 1626 RemoteRepository rr 1627 = RemoteRepository.open(repoDir(id), id, parent); 1628 repos.add(rr); 1629 parent = rr; 1630 } 1631 Collections.reverse(repos); 1632 1633 } finally { 1634 in.close(); 1635 } 1636 1637 } 1638 1639 private List<RemoteRepository> roRepos = null; 1640 1641 // Unmodifiable 1642 public List<RemoteRepository> repositories() throws IOException { 1643 if (repos == null) { 1644 load(); 1645 roRepos = Collections.unmodifiableList(repos); 1646 } 1647 return roRepos; 1648 } 1649 1650 public RemoteRepository firstRepository() throws IOException { 1651 repositories(); 1652 return repos.isEmpty() ? null : repos.get(0); 1653 } 1654 1655 private void store() throws IOException { 1656 File newfn = new File(root, "list.new"); 1657 FileOutputStream fout = new FileOutputStream(newfn); 1658 DataOutputStream out 1659 = new DataOutputStream(new BufferedOutputStream(fout)); 1660 try { 1661 try { 1662 fileHeader().write(out); 1663 out.writeLong(nextRepoId); 1664 out.writeInt(repos.size()); 1665 for (RemoteRepository rr : repos) 1666 out.writeLong(rr.id()); 1667 } finally { 1668 out.close(); 1669 } 1670 } catch (IOException x) { 1671 newfn.delete(); 1672 throw x; 1673 } 1674 java.nio.file.Files.move(newfn.toPath(), listFile.toPath(), ATOMIC_MOVE); 1675 } 1676 1677 public RemoteRepository add(URI u, int position) 1678 throws IOException 1679 { 1680 1681 if (repos == null) 1682 load(); 1683 for (RemoteRepository rr : repos) { 1684 if (rr.location().equals(u)) // ## u not canonical 1685 throw new IllegalStateException(u + ": Already in" 1686 + " repository list"); 1687 } 1688 if (!root.exists()) { 1689 if (!root.mkdir()) 1690 throw new IOException(root + ": Cannot create directory"); 1691 } 1692 1693 if (repos.size() == Integer.MAX_VALUE) 1694 throw new IllegalStateException("Too many repositories"); 1695 if (position < 0) 1696 throw new IllegalArgumentException("Invalid index"); 1697 1698 long id = nextRepoId++; 1699 RemoteRepository rr = RemoteRepository.create(repoDir(id), u, id); 1700 try { 1701 rr.updateCatalog(true); 1702 } catch (IOException x) { 1703 repoDir(id).delete(); 1704 throw x; 1705 } 1706 1707 if (position >= repos.size()) { 1708 repos.add(rr); 1709 } else if (position >= 0) { 1710 List<RemoteRepository> prefix 1711 = new ArrayList<>(repos.subList(0, position)); 1712 List<RemoteRepository> suffix 1713 = new ArrayList<>(repos.subList(position, repos.size())); 1714 repos.clear(); 1715 repos.addAll(prefix); 1716 repos.add(rr); 1717 repos.addAll(suffix); 1718 } 1719 store(); 1720 1721 return rr; 1722 1723 } 1724 1725 public boolean remove(RemoteRepository rr) 1726 throws IOException 1727 { 1728 if (!repos.remove(rr)) 1729 return false; 1730 store(); 1731 File rd = repoDir(rr.id()); 1732 for (File f : rd.listFiles()) { 1733 if (!f.delete()) 1734 throw new IOException(f + ": Cannot delete"); 1735 } 1736 if (!rd.delete()) 1737 throw new IOException(rd + ": Cannot delete"); 1738 return true; 1739 } 1740 1741 public boolean areCatalogsStale() throws IOException { 1742 for (RemoteRepository rr : repos) { 1743 if (rr.isCatalogStale()) 1744 return true; 1745 } 1746 return false; 1747 } 1748 1749 public boolean updateCatalogs(boolean force) throws IOException { 1750 boolean updated = false; 1751 for (RemoteRepository rr : repos) { 1752 if (rr.updateCatalog(force)) 1753 updated = true; 1754 } 1755 return updated; 1756 } 1757 1758 } 1759 1760 private RemoteRepositoryList repoList = null; 1761 1762 public RemoteRepositoryList repositoryList() 1763 throws IOException 1764 { 1765 if (repoList == null) 1766 repoList = new RepoList(root); 1767 return repoList; 1768 } 1769 1770 } --- EOF ---