Skip to content

A free, open-source alternative to Burp Suite: an intercepting proxy and web app security testing suite with Repeater, Intruder, Collaborator and a built-in OWASP ZAP scanner. Linux, AGPL-3.0.

6.1 KB
Raw Blame
package opensuite.core;

import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * The Settings > Suite choices that act on the process itself: where
 * temporary files go, how much memory the next launch may use, and the local
 * performance log.
 */
public final class Launch {

    public static final String TEMP_MODE = "temp.mode", TEMP_DIR = "temp.dir";
    public static final String MEMORY_MODE = "perf.memory.mode", MEMORY_MB = "perf.memory.mb";
    public static final String LOG_LOCAL = "perf.logLocal", LOG_DIR = "perf.logDir";
    /** The launchers read this file under the home directory: one number, the heap limit in MB. */
    public static final String MEMORY_FILE = "memory-mb";

    private Launch() { }

    /**
     * Point the runtime's temporary directory at the chosen folder. Called
     * first thing at startup, before anything makes a temporary file. Returns
     * the folder now in use.
     */
    public static String applyTempDir(Settings s) {
        if ("custom".equals(s.get(TEMP_MODE, "default"))) {
            String dir = s.get(TEMP_DIR, "").trim();
            if (!dir.isEmpty()) {
                Path p = Path.of(dir);
                try {
                    Files.createDirectories(p);
                    if (Files.isDirectory(p) && Files.isWritable(p)) {
                        System.setProperty("java.io.tmpdir", p.toAbsolutePath().toString());
                        System.setProperty("opensuite.tempMode", "custom");   // the engine then works there too
                    }
                    else Debug.log("temporary files location is not a writable folder, using the default: " + dir);
                } catch (IOException | RuntimeException e) {
                    Debug.log("temporary files location cannot be used, using the default: " + dir + " (" + e.getMessage() + ")");
                }
            }
        }
        return System.getProperty("java.io.tmpdir");
    }

    /** Half of the machine's memory in MB: what the launchers allow unless told otherwise. */
    public static int halfOfSystemMemoryMb() {
        try {
            if (ManagementFactory.getOperatingSystemMXBean() instanceof com.sun.management.OperatingSystemMXBean os)
                return (int) (os.getTotalMemorySize() / (2L * 1024 * 1024));
        } catch (RuntimeException | LinkageError ignored) { }
        return (int) (Runtime.getRuntime().maxMemory() / (1024 * 1024));
    }

    /**
     * Write, or remove, the file through which the launchers learn the memory
     * limit; it applies from the next launch. Returns the limit written in MB,
     * or 0 when the launchers are left to use half of the system memory.
     */
    public static int writeMemoryFile(Settings s, Path home) {
        Path file = home.resolve(MEMORY_FILE);
        int mb = "custom".equals(s.get(MEMORY_MODE, "half")) ? s.getInt(MEMORY_MB, 0) : 0;
        // Below this the suite cannot start at all; a typo must not lock the owner out.
        if (mb != 0 && mb < 256) mb = 256;
        try {
            if (mb == 0) Files.deleteIfExists(file);
            else {
                Files.createDirectories(home);
                Files.writeString(file, mb + "\n", StandardCharsets.US_ASCII);
            }
        } catch (IOException e) {
            Debug.error("could not record the memory limit for the next launch", e);
        }
        return mb;
    }

    /** The limit in the launchers' memory file in MB, or 0 when there is none. */
    public static int memoryFileMb() {
        try {
            String v = Files.readString(Path.of(System.getProperty("user.home"), ".opensuite", MEMORY_FILE), StandardCharsets.US_ASCII).trim();
            int mb = Integer.parseInt(v);
            return mb >= 256 ? mb : 0;
        } catch (IOException | RuntimeException e) {
            return 0;
        }
    }

    // ---- the local performance log ----

    private static Thread logger;

    /** Start the performance log; it writes only while the setting is on. */
    public static synchronized void startPerformanceLog(SuiteContext ctx) {
        if (logger != null) return;
        logger = new Thread(() -> {
            while (true) {
                try { Thread.sleep(60_000); } catch (InterruptedException e) { return; }
                try { logPerformance(ctx); } catch (RuntimeException e) { Debug.error("performance log", e); }
            }
        }, "performance-log");
        logger.setDaemon(true);
        logger.start();
    }

    /** One line of the log, if the setting is on. Returns the file written to, or null. */
    public static Path logPerformance(SuiteContext ctx) {
        Settings s = ctx.settings();
        if (!s.getBool(LOG_LOCAL, false)) return null;
        String dir = s.get(LOG_DIR, System.getProperty("user.home") + "/.opensuite/logs").trim();
        if (dir.isEmpty()) return null;
        Runtime rt = Runtime.getRuntime();
        long mb = 1024 * 1024;
        LocalDateTime now = LocalDateTime.now();
        String line = now.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME).substring(0, 19)
                + "\theap_used_mb=" + (rt.totalMemory() - rt.freeMemory()) / mb
                + "\theap_max_mb=" + rt.maxMemory() / mb
                + "\tthreads=" + Thread.activeCount()
                + "\thistory_items=" + ctx.store().all().size()
                + "\tissues=" + ctx.issues().size()
                + "\ttasks=" + ctx.tasks().size() + "\n";
        try {
            Path folder = Path.of(dir);
            Files.createDirectories(folder);
            Path file = folder.resolve("performance-" + now.format(DateTimeFormatter.ISO_LOCAL_DATE) + ".log");
            Files.writeString(file, line, StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            return file;
        } catch (IOException | RuntimeException e) {
            Debug.error("could not write the performance log to " + dir, e);
            return null;
        }
    }
}