private static synchronized boolean checkSystemFolders() {
    final String configPath = PathManager.getConfigPath();
    if (configPath == null || !new File(configPath).isDirectory()) {
      showError(
          "Invalid config path",
          "Config path '"
              + configPath
              + "' is invalid.\n"
              + "If you have modified the 'idea.config.path' property please make sure it is correct,\n"
              + "otherwise please re-install the IDE.");
      return false;
    }

    final String systemPath = PathManager.getSystemPath();
    if (systemPath == null || !new File(systemPath).isDirectory()) {
      showError(
          "Invalid system path",
          "System path '"
              + systemPath
              + "' is invalid.\n"
              + "If you have modified the 'idea.system.path' property please make sure it is correct,\n"
              + "otherwise please re-install the IDE.");
      return false;
    }

    return true;
  }
  public void removeCoverageSuite(final CoverageSuite suite) {
    final String fileName = suite.getCoverageDataFileName();

    boolean deleteTraces = suite.isTracingEnabled();
    if (!FileUtil.isAncestor(PathManager.getSystemPath(), fileName, false)) {
      String message = "Would you like to delete file \'" + fileName + "\' ";
      if (deleteTraces) {
        message +=
            "and traces directory \'"
                + FileUtil.getNameWithoutExtension(new File(fileName))
                + "\' ";
      }
      message += "on disk?";
      if (Messages.showYesNoDialog(
              myProject, message, CommonBundle.getWarningTitle(), Messages.getWarningIcon())
          == Messages.YES) {
        deleteCachedCoverage(fileName, deleteTraces);
      }
    } else {
      deleteCachedCoverage(fileName, deleteTraces);
    }

    myCoverageSuites.remove(suite);
    if (myCurrentSuitesBundle != null && myCurrentSuitesBundle.contains(suite)) {
      CoverageSuite[] suites = myCurrentSuitesBundle.getSuites();
      suites = ArrayUtil.remove(suites, suite);
      chooseSuitesBundle(suites.length > 0 ? new CoverageSuitesBundle(suites) : null);
    }
  }
 @NotNull
 private File getStorageDirectory() {
   String dirName =
       myProject.getName() + "." + Integer.toHexString(myProject.getPresentableUrl().hashCode());
   File dir = new File(PathManager.getSystemPath(), "refs/" + dirName);
   FileUtil.createDirectory(dir);
   return dir;
 }
 public static File getCompilerSystemDirectory() {
   //noinspection HardCodedStringLiteral
   final String systemPath =
       ourSystemPath != null
           ? ourSystemPath
           : (ourSystemPath = PathUtil.getCanonicalPath(PathManager.getSystemPath()));
   return new File(systemPath, "compiler");
 }
 @NotNull
 public static String baseTestDiscoveryPathForProject(Project project) {
   return PathManager.getSystemPath()
       + File.separator
       + "testDiscovery"
       + File.separator
       + project.getName()
       + "."
       + project.getLocationHash();
 }
  private static File dumpModulesPaths(@NotNull Project project) throws IOException {
    ApplicationManager.getApplication().assertReadAccessAllowed();

    Properties res = new Properties();

    MavenProjectsManager manager = MavenProjectsManager.getInstance(project);

    for (Module module : ModuleManager.getInstance(project).getModules()) {
      if (manager.isMavenizedModule(module)) {
        MavenProject mavenProject = manager.findProject(module);
        if (mavenProject != null && !manager.isIgnored(mavenProject)) {
          res.setProperty(
              mavenProject.getMavenId().getGroupId()
                  + ':'
                  + mavenProject.getMavenId().getArtifactId()
                  + ":pom"
                  + ':'
                  + mavenProject.getMavenId().getVersion(),
              mavenProject.getFile().getPath());

          res.setProperty(
              mavenProject.getMavenId().getGroupId()
                  + ':'
                  + mavenProject.getMavenId().getArtifactId()
                  + ':'
                  + mavenProject.getPackaging()
                  + ':'
                  + mavenProject.getMavenId().getVersion(),
              mavenProject.getOutputDirectory());
        }
      }
    }

    File file =
        new File(
            PathManager.getSystemPath(),
            "Maven/idea-projects-state-" + project.getLocationHash() + ".properties");
    file.getParentFile().mkdirs();

    OutputStream out = new BufferedOutputStream(new FileOutputStream(file));
    try {
      res.store(out, null);
    } finally {
      out.close();
    }

    return file;
  }
  private static synchronized boolean lockSystemFolders(String[] args) {
    if (ourLock == null) {
      ourLock = new SocketLock();
    }

    SocketLock.ActivateStatus activateStatus =
        ourLock.lock(PathManager.getConfigPath(false), true, args);
    if (activateStatus == SocketLock.ActivateStatus.NO_INSTANCE) {
      activateStatus = ourLock.lock(PathManager.getSystemPath(), false);
    }

    if (activateStatus != SocketLock.ActivateStatus.NO_INSTANCE) {
      if (isHeadless() || activateStatus == SocketLock.ActivateStatus.CANNOT_ACTIVATE) {
        showError(
            "Error",
            "Only one instance of "
                + ApplicationNamesInfo.getInstance().getFullProductName()
                + " can be run at a time.");
      }
      return false;
    }

    return true;
  }
 private static String getCachesDir() {
   String dir = System.getProperty("caches_dir");
   return dir == null ? PathManager.getSystemPath() + "/caches/" : dir;
 }
/**
 * {@code CertificatesManager} is responsible for negotiation SSL connection with server and deals
 * with untrusted/self-singed/expired and other kinds of digital certificates.
 *
 * <h1>Integration details:</h1>
 *
 * If you're using httpclient-3.1 without custom {@code Protocol} instance for HTTPS you don't have
 * to do anything at all: default {@code HttpClient} will use "Default" {@code SSLContext}, which is
 * set up by this component itself.
 *
 * <p>However for httpclient-4.x you have several of choices:
 *
 * <pre>
 * <ol>
 *  <li>Client returned by {@code HttpClients.createSystem()} will use "Default" SSL context as it does in httpclient-3.1.</li>
 *  <li>If you want to customize {@code HttpClient} using {@code HttpClients.custom()}, you can use the following methods of the builder
 *  (in the order of increasing complexity/flexibility)
 *    <ol>
 *      <li>{@code useSystemProperties()} methods makes {@code HttpClient} use "Default" SSL context again</li>
 *      <li>{@code setSSLContext()} and pass result of the {@link #getSslContext()}</li>
 *      <li>{@code setSSLSocketFactory()} and specify instance {@code SSLConnectionSocketFactory} which uses result of {@link #getSslContext()}.</li>
 *      <li>{@code setConnectionManager} and initialize it with {@code Registry} that binds aforementioned {@code SSLConnectionSocketFactory} to HTTPS protocol</li>
 *      </ol>
 *    </li>
 * </ol>
 * </pre>
 *
 * @author Mikhail Golubev
 */
@State(
    name = "CertificatesManager",
    storages = @Storage(file = StoragePathMacros.APP_CONFIG + "/other.xml"))
public class CertificatesManager
    implements ApplicationComponent, PersistentStateComponent<CertificatesManager.Config> {

  @NonNls public static final String COMPONENT_NAME = "Certificates Manager";

  @NonNls
  private static final String DEFAULT_PATH =
      FileUtil.join(PathManager.getSystemPath(), "tasks", "cacerts");

  @NonNls private static final String DEFAULT_PASSWORD = "******";

  private static final Logger LOG = Logger.getInstance(CertificatesManager.class);

  /**
   * Special version of hostname verifier, that asks user whether he accepts certificate, which
   * subject's common name doesn't match requested hostname.
   */
  public static final HostnameVerifier HOSTNAME_VERIFIER =
      new ConfirmingHostnameVerifier(BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

  public static CertificatesManager getInstance() {
    return (CertificatesManager) ApplicationManager.getApplication().getComponent(COMPONENT_NAME);
  }

  private final String myCacertsPath;
  private final String myPassword;
  private final Config myConfig;

  private final ConfirmingTrustManager myTrustManager;

  /** Lazy initialized */
  private SSLContext mySslContext;

  /** Component initialization constructor */
  public CertificatesManager() {
    myCacertsPath = DEFAULT_PATH;
    myPassword = DEFAULT_PASSWORD;
    myConfig = new Config();
    myTrustManager = ConfirmingTrustManager.createForStorage(myCacertsPath, myPassword);
  }

  @Override
  public void initComponent() {
    try {
      // Don't do this: protocol created this way will ignore SSL tunnels. See IDEA-115708.
      // Protocol.registerProtocol("https", CertificatesManager.createDefault().createProtocol());
      SSLContext.setDefault(getSslContext());
      LOG.debug("Default SSL context initialized");
    } catch (Exception e) {
      LOG.error(e);
    }
  }

  @Override
  public void disposeComponent() {
    // empty
  }

  @NotNull
  @Override
  public String getComponentName() {
    return COMPONENT_NAME;
  }

  /**
   * Creates special kind of {@code SSLContext}, which X509TrustManager first checks certificate
   * presence in in default system-wide trust store (usually located at {@code
   * ${JAVA_HOME}/lib/security/cacerts} or specified by {@code javax.net.ssl.trustStore} property)
   * and when in the one specified by field {@link #myCacertsPath}. If certificate wasn't found in
   * either, manager will ask user, whether it can be accepted (like web-browsers do) and then, if
   * it does, certificate will be added to specified trust store.
   *
   * <p>If any error occurred during creation its message will be logged and system default SSL
   * context will be returned so clients don't have to deal with awkward JSSE errors. This method
   * may be used for transition to HttpClient 4.x (see {@code
   * HttpClientBuilder#setSslContext(SSLContext)}) and {@code
   * org.apache.http.conn.ssl.SSLConnectionSocketFactory()}.
   *
   * @return instance of SSLContext with described behavior or default SSL context in case of error
   */
  @NotNull
  public synchronized SSLContext getSslContext() {
    if (mySslContext == null) {
      try {
        mySslContext = createSslContext();
      } catch (Exception e) {
        LOG.error(e);
        mySslContext = getSystemSslContext();
      }
    }
    return mySslContext;
  }

  @NotNull
  public SSLContext createSslContext() throws Exception {
    // SSLContext context = SSLContext.getDefault();
    // can also check, that default trust store exists, on this step
    // assert systemManager.getAcceptedIssuers().length != 0

    SSLContext context = getSystemSslContext();
    context.init(null, new TrustManager[] {getTrustManager()}, null);
    return context;
  }

  @NotNull
  public static SSLContext getSystemSslContext() {
    // NOTE SSLContext.getDefault() should not be called because it automatically creates
    // default context with can't be initialized twice
    try {
      // actually TLSv1 support is mandatory for Java platform
      return SSLContext.getInstance(CertificateUtil.TLS);
    } catch (NoSuchAlgorithmException e) {
      LOG.error(e);
      throw new AssertionError("Can't get system SSL context");
    }
  }

  @NotNull
  public String getCacertsPath() {
    return myCacertsPath;
  }

  @NotNull
  public String getPassword() {
    return myPassword;
  }

  @NotNull
  public ConfirmingTrustManager getTrustManager() {
    return myTrustManager;
  }

  @NotNull
  public ConfirmingTrustManager.MutableTrustManager getCustomTrustManager() {
    return myTrustManager.getCustomManager();
  }

  public static boolean showAcceptDialog(
      final @NotNull Callable<? extends DialogWrapper> dialogFactory) {
    Application app = ApplicationManager.getApplication();
    final CountDownLatch proceeded = new CountDownLatch(1);
    final AtomicBoolean accepted = new AtomicBoolean();
    app.invokeLater(
        new Runnable() {
          @Override
          public void run() {
            try {
              DialogWrapper dialog = dialogFactory.call();
              accepted.set(dialog.showAndGet());
            } catch (Exception e) {
              LOG.error("Unexpected error", e);
            } finally {
              proceeded.countDown();
            }
          }
        },
        ModalityState.any());
    try {
      proceeded.await();
    } catch (InterruptedException e) {
      LOG.error("Interrupted", e);
    }
    return accepted.get();
  }

  @NotNull
  @Override
  public Config getState() {
    return myConfig;
  }

  @Override
  public void loadState(Config state) {
    XmlSerializerUtil.copyBean(state, myConfig);
  }

  public static class Config {
    // ensure that request's hostname matches certificate's common name (CN)
    public volatile boolean checkHostname;
    // ensure that certificate is neither expired nor not yet eligible
    public volatile boolean checkValidity;

    @Tag("expired")
    @Property(surroundWithTag = false)
    @AbstractCollection(elementTag = "commonName")
    public volatile LinkedHashSet<String> brokenCertificates = new LinkedHashSet<String>();
  }
}
  static void loadSystemLibraries(final Logger log) {
    // load JNA and Snappy in own temp directory - to avoid collisions and work around no-exec /tmp
    final File ideaTempDir = new File(PathManager.getSystemPath(), "tmp");
    if (!(ideaTempDir.mkdirs() || ideaTempDir.exists())) {
      throw new RuntimeException("Unable to create temp directory '" + ideaTempDir + "'");
    }

    final String javaTempDir = System.getProperty(JAVA_IO_TEMP_DIR);
    try {
      System.setProperty(JAVA_IO_TEMP_DIR, ideaTempDir.getPath());
      if (System.getProperty("jna.nosys") == null && System.getProperty("jna.nounpack") == null) {
        // force using bundled JNA dispatcher (if not explicitly stated)
        System.setProperty("jna.nosys", "true");
        System.setProperty("jna.nounpack", "false");
      }
      try {
        final long t = System.currentTimeMillis();
        log.info(
            "JNA library loaded ("
                + (Native.POINTER_SIZE * 8)
                + "-bit) in "
                + (System.currentTimeMillis() - t)
                + " ms");
      } catch (Throwable t) {
        logError(log, "Unable to load JNA library", t);
      }
    } finally {
      System.setProperty(JAVA_IO_TEMP_DIR, javaTempDir);
    }

    if (!NO_SNAPPY) {
      if (System.getProperty(SnappyLoader.KEY_SNAPPY_TEMPDIR) == null) {
        System.setProperty(SnappyLoader.KEY_SNAPPY_TEMPDIR, ideaTempDir.getPath());
      }
      try {
        final long t = System.currentTimeMillis();
        loadSnappyForJRockit();
        log.info(
            "Snappy library loaded ("
                + Snappy.getNativeLibraryVersion()
                + ") in "
                + (System.currentTimeMillis() - t)
                + " ms");
      } catch (Throwable t) {
        logError(log, "Unable to load Snappy library", t);
      }
    }

    if (SystemInfo.isWin2kOrNewer) {
      IdeaWin32.isAvailable(); // logging is done there
    }

    if (SystemInfo.isWin2kOrNewer && !isHeadless) {
      try {
        System.loadLibrary(SystemInfo.isAMD64 ? "focusKiller64" : "focusKiller");
        log.info("Using \"FocusKiller\" library to prevent focus stealing.");
      } catch (Throwable t) {
        log.info("\"FocusKiller\" library not found or there were problems loading it.", t);
      }
    }
  }
 public static String getExternalResourcesPath() {
   return PathManager.getSystemPath() + File.separator + EXT_RESOURCES_FOLDER;
 }
  public BuildManager(final ProjectManager projectManager) {
    myProjectManager = projectManager;
    final String systemPath = PathManager.getSystemPath();
    File system = new File(systemPath);
    try {
      system = system.getCanonicalFile();
    } catch (IOException e) {
      LOG.info(e);
    }
    mySystemDirectory = system;

    projectManager.addProjectManagerListener(new ProjectWatcher());
    final MessageBusConnection conn = ApplicationManager.getApplication().getMessageBus().connect();
    conn.subscribe(
        VirtualFileManager.VFS_CHANGES,
        new BulkFileListener() {
          private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
          private final AtomicBoolean myAutoMakeInProgress = new AtomicBoolean(false);

          @Override
          public void before(@NotNull List<? extends VFileEvent> events) {}

          @Override
          public void after(@NotNull List<? extends VFileEvent> events) {
            if (shouldTriggerMake(events)) {
              scheduleMake(
                  new Runnable() {
                    @Override
                    public void run() {
                      if (!myAutoMakeInProgress.getAndSet(true)) {
                        try {
                          ApplicationManager.getApplication()
                              .executeOnPooledThread(
                                  new Runnable() {
                                    @Override
                                    public void run() {
                                      try {
                                        runAutoMake();
                                      } finally {
                                        myAutoMakeInProgress.set(false);
                                      }
                                    }
                                  });
                        } catch (RejectedExecutionException ignored) {
                          // we were shut down
                        }
                      } else {
                        scheduleMake(this);
                      }
                    }
                  });
            }
          }

          private void scheduleMake(Runnable runnable) {
            myAlarm.cancelAllRequests();
            myAlarm.addRequest(runnable, MAKE_TRIGGER_DELAY);
          }

          private boolean shouldTriggerMake(List<? extends VFileEvent> events) {
            if (!CompilerWorkspaceConfiguration.useServerlessOutOfProcessBuild()) {
              return false;
            }
            for (VFileEvent event : events) {
              if (event.isFromRefresh() || event.getRequestor() instanceof SavingRequestor) {
                return true;
              }
            }
            return false;
          }
        });

    ShutDownTracker.getInstance()
        .registerShutdownTask(
            new Runnable() {
              @Override
              public void run() {
                stopListening();
              }
            });
  }
Example #13
0
 // TODO remove in IDEA 15
 private static void cleanupOldNaming(
     @NotNull Project project, @NotNull Map<VirtualFile, VcsLogProvider> providers) {
   int hashcode = calcLogProvidersHash(providers);
   String oldLogId = project.getName() + "." + hashcode;
   FileUtil.delete(new File(new File(PathManager.getSystemPath(), "vcs-log"), oldLogId));
 }
Example #14
0
/** Supports the int <-> Hash persistent mapping. */
public class VcsLogHashMap implements Disposable {

  private static final File LOG_CACHE_APP_DIR =
      new File(new File(PathManager.getSystemPath(), "vcs-log"), "hashes");
  private static final Logger LOG = Logger.getInstance(VcsLogHashMap.class);
  private static final int VERSION = 1;

  private final PersistentEnumerator<Hash> myPersistentEnumerator;

  VcsLogHashMap(@NotNull Project project, @NotNull Map<VirtualFile, VcsLogProvider> logProviders)
      throws IOException {
    cleanupOldNaming(project, logProviders);
    String logId = calcLogId(project, logProviders);
    final File mapFile = new File(LOG_CACHE_APP_DIR, logId + "." + VERSION);
    if (!mapFile.exists()) {
      IOUtil.deleteAllFilesStartingWith(new File(LOG_CACHE_APP_DIR, logId));
    }

    Disposer.register(project, this);
    myPersistentEnumerator =
        IOUtil.openCleanOrResetBroken(
            new ThrowableComputable<PersistentEnumerator<Hash>, IOException>() {
              @Override
              public PersistentEnumerator<Hash> compute() throws IOException {
                return new PersistentEnumerator<Hash>(
                    mapFile, new MyHashKeyDescriptor(), Page.PAGE_SIZE);
              }
            },
            mapFile);
  }

  @NotNull
  private static String calcLogId(
      @NotNull Project project, @NotNull final Map<VirtualFile, VcsLogProvider> logProviders) {
    int hashcode = calcLogProvidersHash(logProviders);
    return project.getLocationHash() + "." + Integer.toHexString(hashcode);
  }

  // TODO remove in IDEA 15
  private static void cleanupOldNaming(
      @NotNull Project project, @NotNull Map<VirtualFile, VcsLogProvider> providers) {
    int hashcode = calcLogProvidersHash(providers);
    String oldLogId = project.getName() + "." + hashcode;
    FileUtil.delete(new File(new File(PathManager.getSystemPath(), "vcs-log"), oldLogId));
  }

  private static int calcLogProvidersHash(
      @NotNull final Map<VirtualFile, VcsLogProvider> logProviders) {
    List<VirtualFile> sortedRoots =
        ContainerUtil.sorted(
            logProviders.keySet(),
            new Comparator<VirtualFile>() {
              @Override
              public int compare(@NotNull VirtualFile o1, @NotNull VirtualFile o2) {
                return o1.getPath().compareTo(o2.getPath());
              }
            });
    return StringUtil.join(
            sortedRoots,
            new Function<VirtualFile, String>() {
              @Override
              public String fun(VirtualFile root) {
                return root.getPath() + "." + logProviders.get(root).getSupportedVcs().getName();
              }
            },
            ".")
        .hashCode();
  }

  @Nullable
  private Hash doGetHash(int index) throws IOException {
    return myPersistentEnumerator.valueOf(index);
  }

  private int getOrPut(@NotNull Hash hash) throws IOException {
    return myPersistentEnumerator.enumerate(hash);
  }

  public int getCommitIndex(@NotNull Hash hash) {
    try {
      return getOrPut(hash);
    } catch (IOException e) {
      throw new RuntimeException(e); // TODO the map is corrupted => need to rebuild
    }
  }

  @NotNull
  public Hash getHash(int commitIndex) {
    try {
      Hash hash = doGetHash(commitIndex);
      if (hash == null) {
        throw new RuntimeException(
            "Unknown commit index: "
                + commitIndex); // TODO this shouldn't happen => need to recreate the map
      }
      return hash;
    } catch (IOException e) {
      throw new RuntimeException(e); // TODO map is corrupted => need to recreate it
    }
  }

  @Nullable
  public Hash findHashByString(@NotNull String string) {
    final String pHash = string.toLowerCase();
    try {
      return findHash(
          new Condition<Hash>() {
            @Override
            public boolean value(@NotNull Hash hash) {
              return hash.toString().toLowerCase().startsWith(pHash);
            }
          });
    } catch (IOException e) {
      LOG.error(e);
      return null;
    }
  }

  @NotNull
  public NotNullFunction<Hash, Integer> asIndexGetter() {
    return new NotNullFunction<Hash, Integer>() {
      @NotNull
      @Override
      public Integer fun(Hash hash) {
        return getCommitIndex(hash);
      }
    };
  }

  @NotNull
  public NotNullFunction<Integer, Hash> asHashGetter() {
    return new NotNullFunction<Integer, Hash>() {
      @NotNull
      @Override
      public Hash fun(Integer commitIndex) {
        return getHash(commitIndex);
      }
    };
  }

  public void flush() {
    myPersistentEnumerator.force();
  }

  @Override
  public void dispose() {
    try {
      myPersistentEnumerator.close();
    } catch (IOException e) {
      LOG.warn(e);
    }
  }

  @Nullable
  Hash findHash(@NotNull final Condition<Hash> condition) throws IOException {
    final Ref<Hash> hashRef = Ref.create();
    myPersistentEnumerator.iterateData(
        new CommonProcessors.FindProcessor<Hash>() {
          @Override
          protected boolean accept(Hash hash) {
            boolean matches = condition.value(hash);
            if (matches) {
              hashRef.set(hash);
            }
            return matches;
          }
        });
    return hashRef.get();
  }

  private static class MyHashKeyDescriptor implements KeyDescriptor<Hash> {
    @Override
    public void save(@NotNull DataOutput out, Hash value) throws IOException {
      ((HashImpl) value).write(out);
    }

    @Override
    public Hash read(@NotNull DataInput in) throws IOException {
      return HashImpl.read(in);
    }

    @Override
    public int getHashCode(Hash value) {
      return value.hashCode();
    }

    @Override
    public boolean isEqual(Hash val1, Hash val2) {
      return val1.equals(val2);
    }
  }
}
Example #15
0
 @NotNull
 private static String getJarsDir() {
   String dir = System.getProperty("jars_dir");
   return dir == null ? PathManager.getSystemPath() + File.separatorChar + JARS_FOLDER : dir;
 }
Example #16
0
 public static File getPluginSystemDir(String folder) {
   // PathManager.getSystemPath() may return relative path
   return new File(PathManager.getSystemPath(), "Maven" + "/" + folder).getAbsoluteFile();
 }