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.

8.3 KB
Raw Blame
package opensuite.core;

import java.io.IOException;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;

/**
 * How much of the machine's memory Open Suite is using, all of it: the
 * application, the programs it has started (the scan engine and the browsers),
 * and any working data it keeps on a filesystem that is held in memory.
 *
 * <p>The application's own heap is a small part of that. A scan runs in the
 * engine, a separate program several times the size, and the engine's
 * working folder is in the temporary directory, which on many systems is
 * memory and not disk. A figure that left those out would say a tenth of the
 * truth.
 *
 * <p>A program's share is its proportional set size, which counts memory it
 * shares with others once between them, where the system gives it; its
 * resident size otherwise. Where the system gives neither (not Linux), the
 * figure is the application's heap alone and {@link Reading#whole} is false.
 */
public final class MemoryUse {

    /** One reading, in bytes. {@code machine} and {@code available} are 0 where the system does not say. */
    public record Reading(long app, long engine, long others, long data, long machine, long available, boolean whole) {
        public long total() { return app + engine + others + data; }
    }

    private static volatile Reading last;
    private static volatile Supplier<Long> enginePid = () -> -1L;
    private static volatile Supplier<Path> engineData = () -> null;
    private static Thread sampler;

    private MemoryUse() {}

    /** Say where the scan engine is: its process and its working folder, either absent while it is not running. */
    public static void engine(Supplier<Long> pid, Supplier<Path> data) {
        enginePid = pid;
        engineData = data;
    }

    /** The latest reading. The first call takes one and starts taking another every few seconds. */
    public static synchronized Reading latest() {
        if (last == null) last = read();
        if (sampler == null) {
            sampler = new Thread(() -> {
                while (true) {
                    try { Thread.sleep(3000); } catch (InterruptedException e) { return; }
                    try { last = read(); } catch (RuntimeException e) { /* the last reading stands */ }
                }
            }, "memory-use");
            sampler.setDaemon(true);
            sampler.start();
        }
        return last;
    }

    static Reading read() {
        // By system, not by whether /proc is there: on Windows that name is a folder anyone can make.
        if (Os.MAC || Os.WINDOWS || !java.nio.file.Files.isDirectory(Path.of("/proc"))) psSizes = ps();
        Runtime rt = Runtime.getRuntime();
        long heap = rt.totalMemory() - rt.freeMemory();
        ProcessHandle me = ProcessHandle.current();
        long app = share(me.pid());
        if (app < 0) return new Reading(heap, 0, 0, 0, 0, 0, false);
        long engineAt = -1;
        try { Long p = enginePid.get(); engineAt = p == null ? -1 : p; } catch (RuntimeException e) { /* none */ }
        List<Long> engineTree = new ArrayList<>();
        if (engineAt > 0) {
            engineTree.add(engineAt);
            ProcessHandle.of(engineAt).ifPresent(h -> h.descendants().forEach(d -> engineTree.add(d.pid())));
        }
        long engine = 0, others = 0;
        List<Long> seen = new ArrayList<>();
        for (ProcessHandle d : me.descendants().toList()) {
            long s = share(d.pid());
            if (s <= 0) continue;
            seen.add(d.pid());
            if (engineTree.contains(d.pid())) engine += s; else others += s;
        }
        // An engine started through a shell that has gone is no longer a descendant; it is still ours.
        for (long p : engineTree) if (!seen.contains(p)) { long s = share(p); if (s > 0) engine += s; }
        long data = 0;
        try { Path dir = engineData.get(); if (dir != null && inMemory(dir)) data = size(dir); } catch (RuntimeException e) { /* none */ }
        long[] machine = machine();
        return new Reading(app, engine, others, data, machine[0], machine[1], true);
    }

    /** A process's share of memory in bytes, or -1 where the system does not give it. */
    static long share(long pid) {
        long pss = field(Path.of("/proc", String.valueOf(pid), "smaps_rollup"), "Pss:");
        if (pss >= 0) return pss;
        long rss = field(Path.of("/proc", String.valueOf(pid), "status"), "VmRSS:");
        if (rss >= 0) return rss;
        Long ps = psSizes.get(pid);
        return ps == null ? -1 : ps;
    }

    /** Resident sizes from ps, where there is no /proc (macOS); taken once per reading. */
    private static volatile java.util.Map<Long, Long> psSizes = java.util.Map.of();

    static java.util.Map<Long, Long> ps() {
        java.util.Map<Long, Long> out = new java.util.HashMap<>();
        if (Os.WINDOWS) {
            // "name","pid","session","number","12,345 K": the size's separators follow the system's language.
            try {
                Process p = new ProcessBuilder("tasklist", "/fo", "csv", "/nh").redirectErrorStream(true).start();
                p.getOutputStream().close();
                for (String line : new String(p.getInputStream().readAllBytes()).split("\n")) {
                    String[] f = line.trim().split("\",\"");
                    if (f.length < 5) continue;
                    String kb = f[4].replaceAll("[^0-9]", "");
                    try { if (!kb.isEmpty()) out.put(Long.parseLong(f[1].trim()), Long.parseLong(kb) * 1024); } catch (NumberFormatException e) { /* not a process line */ }
                }
                p.waitFor();
            } catch (IOException | InterruptedException e) {
                // no tasklist: the reading falls back to the heap alone
            }
            return out;
        }
        try {
            Process p = new ProcessBuilder("ps", "-A", "-o", "pid=,rss=").redirectErrorStream(true).start();
            for (String line : new String(p.getInputStream().readAllBytes()).split("\n")) {
                String[] f = line.trim().split("\\s+");
                if (f.length == 2) try { out.put(Long.parseLong(f[0]), Long.parseLong(f[1]) * 1024); } catch (NumberFormatException e) { /* a heading */ }
            }
            p.waitFor();
        } catch (IOException | InterruptedException e) {
            // no ps: the reading falls back to the heap alone
        }
        return out;
    }

    /** The value in kB of a line "Name:   1234 kB" of a /proc file, as bytes; -1 where there is none. */
    static long field(Path file, String name) {
        try {
            for (String line : Files.readAllLines(file)) {
                if (!line.startsWith(name)) continue;
                String[] f = line.substring(name.length()).trim().split("\\s+");
                return Long.parseLong(f[0]) * 1024;
            }
        } catch (IOException | RuntimeException e) {
            // not readable: the process has gone, or this is not Linux
        }
        return -1;
    }

    /** Whether a folder is on a filesystem that is held in memory. */
    static boolean inMemory(Path dir) {
        try {
            FileStore store = Files.getFileStore(dir);
            String type = store.type();
            return "tmpfs".equals(type) || "ramfs".equals(type);
        } catch (IOException | RuntimeException e) {
            return false;
        }
    }

    static long size(Path dir) {
        long[] sum = {0};
        try (var walk = Files.walk(dir)) {
            walk.forEach(p -> { try { if (Files.isRegularFile(p)) sum[0] += Files.size(p); } catch (IOException e) { /* gone */ } });
        } catch (IOException | RuntimeException e) {
            // what was counted stands
        }
        return sum[0];
    }

    /** The machine's memory and how much of it is available, in bytes; zeros where the system does not say. */
    static long[] machine() {
        Path info = Path.of("/proc/meminfo");
        long total = field(info, "MemTotal:"), free = field(info, "MemAvailable:");
        if (total < 0 && java.lang.management.ManagementFactory.getOperatingSystemMXBean() instanceof com.sun.management.OperatingSystemMXBean os) {
            total = os.getTotalMemorySize();
            free = os.getFreeMemorySize();
        }
        return new long[] {Math.max(0, total), Math.max(0, free)};
    }
}