package com.sunlicense.sdk;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Random;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.BooleanSupplier;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
* Built-in product analytics (spec 185 §4): every 30 minutes, on a background thread, this install tells
* SunLicense its product version, OS, architecture, CPU cores, locale, Java version and platform (Paper,
* Velocity, Fabric, Forge, a Discord bot or standalone, with the server software's version). Sellers see the
* totals on the product's Analytics tab.
*
*
{@code
* // A licensed product: the same API key, license key and machine id it validates with.
* SunLicenseAnalytics analytics = SunLicenseAnalytics.builder()
* .apiKey(apiKey).licenseKey(licenseKey).fingerprint(machineId)
* .productVersion("2.3.1")
* .enabled(config.getBoolean("analytics", true))
* .start();
* // A free product: its public product analytics id (Product → Analytics), no license needed. The install id lives
* // in a hidden per-user dir by default (SunLicenseAnalytics.defaultStateDir()), not next to your product.
* SunLicenseAnalytics analytics = SunLicenseAnalytics.builder()
* .productAnalyticsId("pa_7Hk2mQ9xZr4LbN8vT1wYcD").start();
* // On shutdown or plugin disable:
* analytics.close();
* }
*
* Feature usage and custom charts (bStats' chart types; shown on Lite and Standard plans):
*
*
{@code
* analytics.feature("auto-sell"); // each time the feature runs
* analytics.simplePie("storage", () -> config.getString("storage")) // "mysql"
* .singleLine("players", () -> server.getOnlinePlayers().size())
* .advancedPie("hooks", () -> Map.of("vault", 1, "placeholderapi", 1))
* .drilldownPie("java", () -> Map.of("Java 21", Map.of("21.0.4", 1)))
* .multiLine("worlds", () -> Map.of("overworld", 30, "nether", 12))
* .simpleBar("shops", () -> Map.of("sell", 12, "buy", 3))
* .advancedBar("prices", () -> Map.of("diamond", new int[] {120, 95}));
* }
*
* It never blocks, delays or fails a license check and never throws: errors are swallowed (one debug log
* line when the outcome changes). Nothing is sent while the product's config switch is off, while the
* environment variable {@code SUNLICENSE_ANALYTICS} is {@code off}/{@code false}/{@code 0}, or while the
* system property {@code sunlicense.analytics} is {@code false}; each is checked before every report. No
* personal data is sent: no user names, host names, IP addresses, file paths or player names.
*
*
This file needs nothing but the JDK (Java 11+). SunLicense's starter templates ship a copy of the Java
* SDK's {@code SunLicenseAnalytics}, identical apart from the package line: to update it, copy the SDK's file
* again rather than editing it.
*/
public final class SunLicenseAnalytics implements AutoCloseable {
/** Sent as {@code sdk.name}/{@code sdk.version}; bump the version with each SDK release. */
public static final String SDK_NAME = "java";
public static final String SDK_VERSION = "0.1.0";
public static final String DEFAULT_BASE_URL = "https://api.sunlicense.com";
/** Environment variable and system property that switch analytics off on a machine. */
public static final String ENV_SWITCH = "SUNLICENSE_ANALYTICS";
public static final String PROPERTY_SWITCH = "sunlicense.analytics";
static final String PATH = "/api/v2/analytics/report";
static final Duration INTERVAL = Duration.ofMinutes(30);
static final Duration MIN_WAIT = Duration.ofMinutes(1);
static final Duration MAX_WAIT = Duration.ofHours(24);
static final Duration TIMEOUT = Duration.ofSeconds(10);
static final int MAX_BODY = 16 * 1024;
static final String INSTALL_ID_FILE = ".sunlicense-install-id";
/** Report keys every report keeps; anything else (feature usage, custom charts) goes first when a report is too big. */
static final Set CORE_KEYS = new HashSet<>(Arrays.asList(
"schema", "licenseKey", "fingerprint", "productAnalyticsId", "installId", "sdk", "metrics"));
private static final Pattern INSTALL_ID = Pattern.compile("[A-Za-z0-9_-]{8,64}");
/** Feature names and chart ids (spec 185 §4.3), after lower-casing. */
private static final Pattern NAME = Pattern.compile("[a-z0-9][a-z0-9._-]{0,47}");
static final int MAX_FEATURES = 50;
static final int MAX_CHARTS = 30;
static final int MAX_ENTRIES = 50;
static final int MAX_BAR_NUMBERS = 20;
static final long MAX_NUMBER = 1_000_000_000L;
private static final Set OFF = new HashSet<>(Arrays.asList("off", "false", "0", "no", "disabled"));
private static final System.Logger LOG = System.getLogger("com.sunlicense.analytics");
/** Something that adds to each report (feature usage and custom charts, #188) and hears whether it was taken. */
interface Section {
void write(Map report);
default void sent(boolean accepted) {
}
}
/** One HTTP answer: status (-1 = no answer) and its Retry-After header. */
static final class Answer {
final int status;
final String retryAfter;
Answer(int status, String retryAfter) {
this.status = status;
this.retryAfter = retryAfter;
}
}
interface Transport {
Answer post(String url, Map headers, byte[] body) throws IOException, InterruptedException;
}
/** What platform the product runs on, from the classes the JVM can see. */
static final class Platform {
final String name;
final String version;
Platform(String name, String version) {
this.name = name;
this.version = version;
}
}
private final String endpoint;
private final String apiKey;
private final Supplier licenseKey;
private final String fingerprint;
private final String productAnalyticsId;
private final Path installIdFile;
private final List legacyIdFiles;
private final Supplier productVersion;
private final Platform platformOverride;
private final BooleanSupplier enabled;
private final Function env;
private final Function props;
private final Transport transport;
private final Random random;
private final Duration firstDelay;
private final List sections = new CopyOnWriteArrayList<>();
/** Uses per feature since the last accepted report. */
private final Map features = new ConcurrentHashMap<>();
/** Custom charts by id, in the order they were added. */
private final Map charts = new LinkedHashMap<>();
private volatile boolean closed;
private ScheduledExecutorService scheduler;
private Map systemMetrics;
private String installId;
private String lastOutcome;
private SunLicenseAnalytics(Builder b) {
this.endpoint = b.baseUrl.replaceAll("/+$", "") + PATH;
this.apiKey = clean(b.apiKey, 512);
this.licenseKey = b.licenseKey;
this.fingerprint = clean(b.fingerprint, 255);
this.productAnalyticsId = clean(b.productAnalyticsId, 64);
this.installIdFile = b.installIdFile;
this.legacyIdFiles = b.legacyIdFiles;
this.productVersion = b.productVersion;
this.platformOverride = b.platformName == null ? null : new Platform(b.platformName, b.platformVersion);
this.enabled = b.enabled;
this.env = b.env;
this.props = b.props;
this.transport = b.transport != null ? b.transport : new HttpTransport();
this.random = b.random;
this.firstDelay = b.firstDelay;
this.sections.add(new Custom());
}
public static Builder builder() {
return new Builder();
}
/** A free product: reports with its public product analytics id (Product → Analytics in the dashboard). */
public static SunLicenseAnalytics forProduct(String productAnalyticsId) {
return builder().productAnalyticsId(productAnalyticsId).start();
}
/** True unless the product's switch, {@code SUNLICENSE_ANALYTICS} or {@code -Dsunlicense.analytics} turns it off. */
public boolean isEnabled() {
return !optedOut();
}
/** Stops reporting. Call it when the product shuts down (a plugin's onDisable), so the thread goes too. */
@Override
public void close() {
closed = true;
ScheduledExecutorService s = scheduler;
if (s != null) {
s.shutdownNow();
}
}
/**
* Sends one report now, on the caller's thread, and returns the HTTP status (204 = stored, 0 = nothing sent
* because analytics is off or the product isn't identified, -1 = no answer). For tests and the CLI; a
* product leaves it to the schedule.
*/
public int sendNow() {
return send().status;
}
// ---- feature usage and custom charts (spec 185 §4.5, §4.6, §13) ----
/** Counts one use of a feature (e.g. {@code "auto-sell"}); call it each time the feature runs. Cheap, never throws. */
public void feature(String name) {
feature(name, 1);
}
/**
* Counts {@code uses} uses of a feature. Names are lower-cased and must be 1–48 letters, digits, {@code . _ -}
* (starting with a letter or digit); others are ignored. Counts go with the next report and are kept until one is
* accepted. At most 50 different features per report.
*/
public void feature(String name, int uses) {
String n = name(name);
if (n == null || uses < 1 || closed || (!features.containsKey(n) && features.size() >= MAX_FEATURES)) {
return;
}
features.merge(n, (long) uses, (a, b) -> Math.min(MAX_NUMBER, a + b));
}
/** A pie of one value per install, e.g. {@code simplePie("storage", () -> "mysql")}. */
public SunLicenseAnalytics simplePie(String id, Supplier value) {
return chart(id, "simple_pie", value, v -> {
String s = clean(v, 64);
return s == null ? null : single("value", s);
});
}
/** A pie of several weighted values per install, e.g. {@code {"mysql": 2, "sqlite": 1}} (weights ≥ 1). */
public SunLicenseAnalytics advancedPie(String id, Supplier> values) {
return chart(id, "advanced_pie", values, v -> values(numbers(v, 1)));
}
/** A pie with a second level, e.g. {@code {"Java 21": {"21.0.4": 1}}}: shows the outer values, then each one's inner values. */
public SunLicenseAnalytics drilldownPie(String id, Supplier>> values) {
return chart(id, "drilldown_pie", values, v -> {
Map out = new LinkedHashMap<>();
for (Map.Entry> e : v.entrySet()) {
String key = clean(e.getKey(), 64);
Map inner = e.getValue() == null ? null : numbers(e.getValue(), 1);
if (key != null && inner != null && !inner.isEmpty() && out.size() < MAX_ENTRIES) {
out.put(key, inner);
}
}
return values(out);
});
}
/** A line of one number per install, summed over installs, e.g. {@code singleLine("players", () -> online)}. */
public SunLicenseAnalytics singleLine(String id, Supplier value) {
return chart(id, "single_line", value, v -> Math.abs((long) v) > MAX_NUMBER ? null : single("value", v));
}
/** Several lines, one number per key per install, e.g. {@code {"overworld": 30, "nether": 12}}. */
public SunLicenseAnalytics multiLine(String id, Supplier> values) {
return chart(id, "multi_line", values, v -> values(numbers(v, -MAX_NUMBER)));
}
/** Bars, one number per key per install. */
public SunLicenseAnalytics simpleBar(String id, Supplier> values) {
return chart(id, "simple_bar", values, v -> values(numbers(v, -MAX_NUMBER)));
}
/** Groups of bars, up to 20 numbers per key per install, e.g. {@code {"diamond": new int[] {120, 95}}}. */
public SunLicenseAnalytics advancedBar(String id, Supplier> values) {
return chart(id, "advanced_bar", values, v -> {
Map out = new LinkedHashMap<>();
for (Map.Entry e : v.entrySet()) {
String key = clean(e.getKey(), 64);
if (key == null || e.getValue() == null || out.size() >= MAX_ENTRIES) {
continue;
}
List numbers = new ArrayList<>();
for (int n : e.getValue()) {
if (numbers.size() >= MAX_BAR_NUMBERS || Math.abs((long) n) > MAX_NUMBER) {
break;
}
numbers.add(n);
}
if (!numbers.isEmpty()) {
out.put(key, numbers);
}
}
return values(out);
});
}
/** Stops sending a custom chart. */
public SunLicenseAnalytics removeChart(String id) {
String n = name(id);
if (n != null) {
synchronized (charts) {
charts.remove(n);
}
}
return this;
}
/** One custom chart: its type and how to turn the callback's answer into the report's {@code data} (null = leave out). */
private static final class Chart {
final String type;
final Supplier> data;
Chart(String type, Supplier> data) {
this.type = type;
this.data = data;
}
}
private SunLicenseAnalytics chart(String id, String type, Supplier callback, Function> data) {
String n = name(id);
if (n == null || callback == null) {
outcome("bad-chart", "chart id \"" + id + "\" isn't 1-48 letters, digits, '.', '_' or '-': ignored");
return this;
}
synchronized (charts) {
charts.remove(n); // the same id again replaces it, at the end
charts.put(n, new Chart(type, () -> {
T v = callback.get();
return v == null ? null : data.apply(v);
}));
}
return this;
}
private static Map single(String key, Object value) {
Map m = new LinkedHashMap<>();
m.put(key, value);
return m;
}
private static Map values(Map values) {
return values == null || values.isEmpty() ? null : single("values", values);
}
/** Up to 50 entries with clean keys and numbers from {@code min} to 10⁹. */
private static Map numbers(Map in, long min) {
Map out = new LinkedHashMap<>();
for (Map.Entry e : in.entrySet()) {
String key = clean(e.getKey(), 64);
Integer v = e.getValue();
if (key != null && v != null && v >= min && v <= MAX_NUMBER && out.size() < MAX_ENTRIES) {
out.put(key, v);
}
}
return out;
}
static String name(String raw) {
String s = raw == null ? null : raw.trim().toLowerCase(Locale.ROOT);
return s != null && NAME.matcher(s).matches() ? s : null;
}
/** Adds features and charts to each report; feature counts sent in an accepted report are taken off. */
private final class Custom implements Section {
private Map pending = new LinkedHashMap<>();
private Map report;
@Override
public void write(Map r) {
report = r;
pending = new LinkedHashMap<>();
for (Map.Entry e : features.entrySet()) {
if (pending.size() >= MAX_FEATURES) {
break;
}
pending.put(e.getKey(), e.getValue());
}
if (!pending.isEmpty()) {
r.put("features", new LinkedHashMap<>(pending));
}
List> list;
synchronized (charts) {
list = new ArrayList<>(charts.entrySet());
}
List out = new ArrayList<>();
for (Map.Entry e : list) {
if (out.size() >= MAX_CHARTS) {
break;
}
Map data;
try {
data = e.getValue().data.get();
} catch (RuntimeException ex) {
continue; // a broken callback leaves its chart out
}
if (data != null) {
Map c = new LinkedHashMap<>();
c.put("id", e.getKey());
c.put("type", e.getValue().type);
c.put("data", data);
out.add(c);
}
}
if (!out.isEmpty()) {
r.put("charts", out);
}
}
@Override
public void sent(boolean accepted) {
if (accepted && report != null && report.containsKey("features")) {
pending.forEach((name, uses) -> features.computeIfPresent(name, (k, v) -> v - uses <= 0 ? null : v - uses));
}
pending = new LinkedHashMap<>();
report = null;
}
}
void add(Section section) {
sections.add(section);
}
private SunLicenseAnalytics begin() {
if (productAnalyticsId == null && (apiKey == null || fingerprint == null)) {
outcome("no-identity", "no product analytics id, and no API key and machine id: not reporting");
return this;
}
try {
scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = new Thread(r, "SunLicense analytics");
t.setDaemon(true);
t.setPriority(Thread.MIN_PRIORITY);
return t;
});
schedule(firstDelay != null ? firstDelay : firstDelay(random));
} catch (RuntimeException e) {
outcome("no-thread", "can't start the analytics thread: " + e);
}
return this;
}
/** First report after a random 1–30 minutes, so a fleet restarted together doesn't report together. */
static Duration firstDelay(Random random) {
return Duration.ofSeconds(60 + random.nextInt(29 * 60 + 1));
}
private void schedule(Duration delay) {
ScheduledExecutorService s = scheduler;
if (closed || s == null) {
return;
}
try {
s.schedule(this::tick, delay.toMillis(), TimeUnit.MILLISECONDS);
} catch (RejectedExecutionException e) {
// closed meanwhile
}
}
private void tick() {
Duration next = INTERVAL;
try {
Answer a = send();
next = nextDelay(a.status, a.retryAfter);
} catch (Throwable t) {
if (t instanceof VirtualMachineError) {
throw (VirtualMachineError) t;
}
outcome("error", "report failed: " + t);
} finally {
schedule(next);
}
}
/** 30 minutes after a 204 or no answer; else the server's Retry-After, between 1 minute and 24 hours. */
static Duration nextDelay(int status, String retryAfter) {
if (status == 204 || retryAfter == null) {
return INTERVAL;
}
long seconds;
try {
seconds = Long.parseLong(retryAfter.trim());
} catch (NumberFormatException e) {
return INTERVAL; // an HTTP date: not something our server sends
}
Duration d = Duration.ofSeconds(Math.max(0, seconds));
return d.compareTo(MIN_WAIT) < 0 ? MIN_WAIT : d.compareTo(MAX_WAIT) > 0 ? MAX_WAIT : d;
}
private Answer send() {
if (closed) {
return new Answer(0, null);
}
if (optedOut()) {
features.clear(); // nothing is counted while it's off
outcome("off", "analytics is switched off; nothing sent");
return new Answer(0, null);
}
Map report = report();
if (report == null) {
outcome("no-identity", "no license key yet and no product analytics id; nothing sent");
return new Answer(0, null);
}
byte[] body = json(report).getBytes(StandardCharsets.UTF_8);
if (body.length > MAX_BODY && report.remove("charts") != null) { // charts go first, then features
body = json(report).getBytes(StandardCharsets.UTF_8);
}
if (body.length > MAX_BODY) {
report.keySet().retainAll(CORE_KEYS);
body = json(report).getBytes(StandardCharsets.UTF_8);
}
Map headers = new LinkedHashMap<>();
headers.put("Content-Type", "application/json");
headers.put("User-Agent", "sunlicense-" + SDK_NAME + "/" + SDK_VERSION + " analytics");
if (report.containsKey("licenseKey")) {
headers.put("Authorization", "Bearer " + apiKey);
}
Answer answer;
try {
answer = transport.post(endpoint, headers, body);
} catch (IOException | RuntimeException e) {
answer = new Answer(-1, null);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
answer = new Answer(-1, null);
}
boolean accepted = answer.status == 204;
for (Section s : sections) {
try {
s.sent(accepted);
} catch (RuntimeException e) {
// a section's bookkeeping never stops reporting
}
}
if (accepted) {
outcome("204", "report accepted");
} else if (answer.status < 0) {
outcome("no-answer", "SunLicense didn't answer; next report in 30 minutes");
} else {
outcome("http-" + answer.status, "report answered HTTP " + answer.status + "; next in "
+ nextDelay(answer.status, answer.retryAfter).getSeconds() + " s");
}
return answer;
}
private boolean optedOut() {
if (isOff(env.apply(ENV_SWITCH)) || isOff(props.apply(PROPERTY_SWITCH))) {
return true;
}
try {
return !enabled.getAsBoolean();
} catch (RuntimeException e) {
return true; // a config that can't be read counts as off
}
}
static boolean isOff(String value) {
return value != null && OFF.contains(value.trim().toLowerCase(Locale.ROOT));
}
/** The report body (§4.2), or null when this install can't say who it is yet. */
Map report() {
String key = clean(get(licenseKey), 128);
boolean licensed = key != null && apiKey != null && fingerprint != null;
if (!licensed && productAnalyticsId == null) {
return null;
}
Map r = new LinkedHashMap<>();
r.put("schema", 1);
if (licensed) {
r.put("licenseKey", key);
r.put("fingerprint", fingerprint);
}
if (productAnalyticsId != null) {
r.put("productAnalyticsId", productAnalyticsId);
r.put("installId", installId()); // also with a license: an unknown key then still counts (§4.1)
}
Map sdk = new LinkedHashMap<>();
sdk.put("name", SDK_NAME);
sdk.put("version", SDK_VERSION);
r.put("sdk", sdk);
Map metrics = new LinkedHashMap<>();
put(metrics, "productVersion", clean(get(productVersion), 64));
metrics.putAll(systemMetrics());
r.put("metrics", metrics);
for (Section s : sections) {
try {
s.write(r);
} catch (RuntimeException e) {
// a broken section is left out, the built-in metrics still go
}
}
return r;
}
private synchronized Map systemMetrics() {
if (systemMetrics == null) {
systemMetrics = collect(props, platformOverride != null ? platformOverride : detectPlatform());
}
return systemMetrics;
}
/** Raw values; the server maps them to families and majors (§4.4). */
static Map collect(Function props, Platform platform) {
Map m = new LinkedHashMap<>();
put(m, "os", clean(props.apply("os.name"), 64));
put(m, "osVersion", clean(props.apply("os.version"), 64));
put(m, "arch", clean(props.apply("os.arch"), 64));
m.put("cores", Math.max(1, Math.min(1024, Runtime.getRuntime().availableProcessors())));
put(m, "locale", clean(Locale.getDefault().toString(), 64));
m.put("runtime", "java");
put(m, "runtimeVersion", clean(props.apply("java.version"), 64));
if (platform != null) {
put(m, "platform", clean(platform.name == null ? null : platform.name.toLowerCase(Locale.ROOT), 32));
put(m, "platformVersion", clean(platform.version, 64));
}
return m;
}
private synchronized String installId() {
if (installId != null) {
return installId;
}
String existing = readStoredId(installIdFile);
if (existing != null) {
return installId = existing;
}
// Carry an id over from a legacy location once (the old ~/.sunlicense default, or the product folder a developer
// used to pass), so upgrading keeps the same install (§4.1) — the server's machine/install counts stay right —
// then delete the old file so nothing is left behind. Silent on any error.
for (Path legacy : legacyIdFiles) {
String carried = readStoredId(legacy);
if (carried != null) {
installId = carried;
writeInstallId(installId);
try {
Files.deleteIfExists(legacy);
} catch (IOException | RuntimeException e) {
// leaving the old file is harmless; the new one is authoritative
}
return installId;
}
}
installId = UUID.randomUUID().toString();
writeInstallId(installId);
return installId;
}
private static String readStoredId(Path file) {
try {
if (file != null && Files.isRegularFile(file)) {
String stored = new String(Files.readAllBytes(file), StandardCharsets.UTF_8).trim();
if (INSTALL_ID.matcher(stored).matches()) {
return stored;
}
}
} catch (IOException | RuntimeException e) {
// unreadable: treat as absent
}
return null;
}
private void writeInstallId(String id) {
try {
Path dir = installIdFile.toAbsolutePath().getParent();
if (dir != null) {
Files.createDirectories(dir);
}
Files.write(installIdFile, id.getBytes(StandardCharsets.UTF_8));
} catch (IOException | RuntimeException e) {
// read-only disk: this run still has an id, the next start makes another
}
}
// ---- where SunLicense keeps its hidden per-user state (mirrors SunLicenseProtection.defaultStateDir) ----
/**
* The per-user directory SunLicense keeps its state in by default — a hidden, out-of-the-way place, never
* the product's own folder, so a product leaves nothing visible next to it. The OS per-user cache directory:
* Windows {@code %LOCALAPPDATA%\SunLicense} (then {@code %APPDATA%\SunLicense}); macOS {@code ~/Library/Caches/
* SunLicense}; Linux and the rest {@code $XDG_CACHE_HOME/sunlicense} or {@code ~/.cache/sunlicense}; falling back
* to {@code ~/.sunlicense} then the system temp dir. On a host whose home is the server folder (Pterodactyl's
* {@code /home/container}) this still lands in a nested {@code .cache} folder, not the server root.
*/
public static Path defaultStateDir() {
return stateDir(System::getProperty, System::getenv);
}
/** {@link #defaultStateDir()} over injectable system properties/environment (for tests and the copied SDK). */
static Path stateDir(Function props, Function env) {
String os = props.apply("os.name");
os = os == null ? "" : os.toLowerCase(Locale.ROOT);
String home = props.apply("user.home");
List candidates = new ArrayList<>();
if (os.contains("win")) {
addDir(candidates, env.apply("LOCALAPPDATA"), "SunLicense");
addDir(candidates, env.apply("APPDATA"), "SunLicense");
if (home != null) {
addDir(candidates, home + "/AppData/Local", "SunLicense");
}
} else if (os.contains("mac") || os.contains("darwin")) {
if (home != null) {
addDir(candidates, home + "/Library/Caches", "SunLicense");
}
} else {
addDir(candidates, env.apply("XDG_CACHE_HOME"), "sunlicense");
if (home != null) {
addDir(candidates, home + "/.cache", "sunlicense");
}
}
if (home != null && !home.isBlank()) {
candidates.add(Paths.get(home, ".sunlicense"));
}
String tmp = props.apply("java.io.tmpdir");
if (tmp != null && !tmp.isBlank()) {
candidates.add(Paths.get(tmp, "sunlicense"));
}
return candidates.isEmpty() ? Paths.get(".sunlicense") : candidates.get(0);
}
private static void addDir(List out, String base, String name) {
if (base != null && !base.isBlank()) {
out.add(Paths.get(base, name));
}
}
/** The default install-id file: one small hidden file per product in {@link #defaultStateDir()}. */
static Path defaultInstallIdFile(Function props, Function env, String productAnalyticsId) {
Path dir = stateDir(props, env);
String pa = clean(productAnalyticsId, 64);
if (pa == null) {
return dir.resolve(INSTALL_ID_FILE); // not used without a product analytics id, but give it a stable name
}
String safe = pa.replaceAll("[^A-Za-z0-9_-]", "");
return dir.resolve("install-" + (safe.isEmpty() ? "default" : safe) + ".id");
}
/** Older locations an install id may already sit in (the pre-OS-cache default), to carry over once then delete. */
static List legacyInstallIdFiles(Function props, Path current) {
List out = new ArrayList<>();
String home = props.apply("user.home");
if (home != null && !home.isBlank()) {
Path old = Paths.get(home, ".sunlicense", INSTALL_ID_FILE);
if (!old.equals(current)) {
out.add(old);
}
}
return out;
}
private void outcome(String kind, String message) {
if (!kind.equals(lastOutcome)) {
lastOutcome = kind;
LOG.log(System.Logger.Level.DEBUG, "SunLicense analytics: " + message);
}
}
// ---- platform detection, by class presence and reflection: no compile-time dependency on any platform ----
static Platform detectPlatform() {
try {
return platform();
} catch (Throwable t) {
if (t instanceof VirtualMachineError) {
throw (VirtualMachineError) t;
}
return new Platform("standalone", null);
}
}
private static Platform platform() {
if (present("org.bukkit.Bukkit")) { // Bukkit, Spigot, Paper, Purpur, Folia, hybrids: the server says its name
String name = str(callStatic("org.bukkit.Bukkit", "getName"));
if (name == null) {
name = present("io.papermc.paper.threadedregions.RegionizedServer") ? "folia"
: present("com.destroystokyo.paper.PaperConfig") || present("io.papermc.paper.configuration.Configuration") ? "paper"
: present("org.spigotmc.SpigotConfig") ? "spigot" : "bukkit";
}
return new Platform(name, str(callStatic("org.bukkit.Bukkit", "getBukkitVersion")));
}
if (present("net.md_5.bungee.api.ProxyServer")) { // BungeeCord, Waterfall
Object proxy = callStatic("net.md_5.bungee.api.ProxyServer", "getInstance");
String name = str(call(proxy, "getName"));
return new Platform(name == null ? "bungeecord" : name, bungeeVersion(str(call(proxy, "getVersion"))));
}
if (present("com.velocitypowered.api.proxy.ProxyServer")) {
return new Platform("velocity", implementationVersion("com.velocitypowered.proxy.VelocityServer",
"com.velocitypowered.api.proxy.ProxyServer"));
}
if (present("org.spongepowered.api.Sponge")) {
Object p = first(callStatic("org.spongepowered.api.Sponge", "platform"), callStatic("org.spongepowered.api.Sponge", "getPlatform"));
Object mc = first(call(p, "minecraftVersion"), call(p, "getMinecraftVersion"));
return new Platform("sponge", str(first(call(mc, "name"), call(mc, "getName"))));
}
if (present("net.neoforged.fml.loading.FMLLoader")) {
return new Platform("neoforge", str(first(fmlMinecraftVersion("net.neoforged.fml.loading.FMLLoader"),
callStatic("net.neoforged.neoforge.internal.versions.neoform.NeoFormVersion", "getMCVersion"))));
}
if (present("net.minecraftforge.fml.loading.FMLLoader")) {
return new Platform("forge", str(first(callStatic("net.minecraftforge.versions.mcp.MCPVersion", "getMCVersion"),
fmlMinecraftVersion("net.minecraftforge.fml.loading.FMLLoader"))));
}
if (present("org.quiltmc.loader.api.QuiltLoader")) { // before Fabric: Quilt also has Fabric's loader API
return new Platform("quilt", fabricMinecraftVersion());
}
if (present("net.fabricmc.loader.api.FabricLoader")) {
return new Platform("fabric", fabricMinecraftVersion());
}
if (present("net.dv8tion.jda.api.JDA")) {
return new Platform("discord", str(staticField("net.dv8tion.jda.api.JDAInfo", "VERSION")));
}
if (present("org.javacord.api.Javacord")) {
return new Platform("discord", str(staticField("org.javacord.api.Javacord", "VERSION")));
}
return new Platform("standalone", null);
}
private static String fabricMinecraftVersion() {
Object loader = callStatic("net.fabricmc.loader.api.FabricLoader", "getInstance");
Object found = call(loader, "getModContainer", "minecraft");
Object container = found instanceof Optional ? ((Optional>) found).orElse(null) : null;
return str(call(call(call(container, "getMetadata"), "getVersion"), "getFriendlyString"));
}
private static Object fmlMinecraftVersion(String loader) {
Object info = first(callStatic(loader, "versionInfo"), call(callStatic(loader, "getCurrent"), "getVersionInfo"));
return call(info, "mcVersion");
}
/** {@code git:BungeeCord-Bootstrap:1.21-R0.1-SNAPSHOT:fd8eb79:1893} → {@code 1.21-R0.1-SNAPSHOT}. */
static String bungeeVersion(String version) {
if (version == null) {
return null;
}
for (String part : version.split(":")) {
if (!part.isEmpty() && Character.isDigit(part.charAt(0))) {
return part;
}
}
return version;
}
private static String implementationVersion(String... classNames) {
for (String name : classNames) {
Class> c = find(name);
Package p = c == null ? null : c.getPackage();
if (p != null && p.getImplementationVersion() != null) {
return p.getImplementationVersion();
}
}
return null;
}
static boolean present(String className) {
return find(className) != null;
}
private static Class> find(String className) {
List loaders = new ArrayList<>();
loaders.add(SunLicenseAnalytics.class.getClassLoader());
ClassLoader context = Thread.currentThread().getContextClassLoader();
if (context != null && !loaders.contains(context)) {
loaders.add(context);
}
for (ClassLoader loader : loaders) {
try {
return Class.forName(className, false, loader);
} catch (ClassNotFoundException | LinkageError e) {
// not here
}
}
return null;
}
private static Object callStatic(String className, String method) {
Class> c = find(className);
if (c == null) {
return null;
}
try {
Method m = c.getMethod(method);
return Modifier.isStatic(m.getModifiers()) ? m.invoke(null) : null;
} catch (ReflectiveOperationException | RuntimeException | LinkageError e) {
return null;
}
}
private static Object staticField(String className, String field) {
Class> c = find(className);
if (c == null) {
return null;
}
try {
Field f = c.getField(field);
return Modifier.isStatic(f.getModifiers()) ? f.get(null) : null;
} catch (ReflectiveOperationException | RuntimeException | LinkageError e) {
return null;
}
}
/** Calls a public no-arg (or one String arg) method through a public type, so non-public implementations work. */
private static Object call(Object target, String method, String... args) {
if (target == null) {
return null;
}
Class>[] types = new Class>[args.length];
Arrays.fill(types, String.class);
Method m = publicMethod(target.getClass(), method, types);
if (m == null) {
return null;
}
try {
return m.invoke(target, (Object[]) args);
} catch (ReflectiveOperationException | RuntimeException | LinkageError e) {
return null;
}
}
private static Method publicMethod(Class> c, String name, Class>[] types) {
if (c == null) {
return null;
}
if (Modifier.isPublic(c.getModifiers())) {
try {
Method m = c.getMethod(name, types);
if (Modifier.isPublic(m.getDeclaringClass().getModifiers())) {
return m;
}
} catch (NoSuchMethodException e) {
// look further up
}
}
for (Class> i : c.getInterfaces()) {
Method m = publicMethod(i, name, types);
if (m != null) {
return m;
}
}
return publicMethod(c.getSuperclass(), name, types);
}
private static Object first(Object a, Object b) {
return a != null ? a : b;
}
private static String str(Object o) {
return o == null ? null : o.toString();
}
// ---- values and JSON (no JSON library, so the file can be copied anywhere) ----
/** Trimmed, control characters removed, cut at {@code max}; null when empty. */
static String clean(String s, int max) {
if (s == null) {
return null;
}
StringBuilder b = new StringBuilder(s.length());
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (!Character.isISOControl(c)) {
b.append(c);
}
}
String t = b.toString().trim();
if (t.isEmpty()) {
return null;
}
if (t.length() > max) {
int end = Character.isHighSurrogate(t.charAt(max - 1)) ? max - 1 : max;
t = t.substring(0, end).trim();
}
return t;
}
private static String get(Supplier supplier) {
try {
return supplier.get();
} catch (RuntimeException e) {
return null;
}
}
private static void put(Map m, String key, String value) {
if (value != null) {
m.put(key, value);
}
}
static String json(Object value) {
StringBuilder b = new StringBuilder(512);
write(b, value);
return b.toString();
}
private static void write(StringBuilder b, Object v) {
if (v == null) {
b.append("null");
} else if (v instanceof Boolean || v instanceof Integer || v instanceof Long || v instanceof Short || v instanceof Byte) {
b.append(v);
} else if (v instanceof Number) {
double d = ((Number) v).doubleValue();
b.append(Double.isFinite(d) ? v.toString() : "null");
} else if (v instanceof Map) {
b.append('{');
boolean firstEntry = true;
for (Map.Entry, ?> e : ((Map, ?>) v).entrySet()) {
if (!firstEntry) {
b.append(',');
}
firstEntry = false;
quote(b, String.valueOf(e.getKey()));
b.append(':');
write(b, e.getValue());
}
b.append('}');
} else if (v instanceof Collection) {
b.append('[');
boolean firstItem = true;
for (Object item : (Collection>) v) {
if (!firstItem) {
b.append(',');
}
firstItem = false;
write(b, item);
}
b.append(']');
} else {
quote(b, v.toString());
}
}
private static void quote(StringBuilder b, String s) {
b.append('"');
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
switch (c) {
case '"':
b.append("\\\"");
break;
case '\\':
b.append("\\\\");
break;
case '\n':
b.append("\\n");
break;
case '\r':
b.append("\\r");
break;
case '\t':
b.append("\\t");
break;
default:
if (c < 0x20 || c == 0x2028 || c == 0x2029) {
b.append(String.format("\\u%04x", (int) c));
} else {
b.append(c);
}
}
}
b.append('"');
}
private static final class HttpTransport implements Transport {
private final HttpClient http = HttpClient.newBuilder().connectTimeout(TIMEOUT).build();
@Override
public Answer post(String url, Map headers, byte[] body) throws IOException, InterruptedException {
HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(url)).timeout(TIMEOUT)
.POST(HttpRequest.BodyPublishers.ofByteArray(body));
for (Map.Entry h : headers.entrySet()) {
request.header(h.getKey(), h.getValue());
}
HttpResponse res = http.send(request.build(), HttpResponse.BodyHandlers.discarding());
return new Answer(res.statusCode(), res.headers().firstValue("Retry-After").orElse(null));
}
}
/** Settings for one product's reporter; {@link #start()} never throws. */
public static final class Builder {
private String baseUrl = DEFAULT_BASE_URL;
private String apiKey;
private Supplier licenseKey = () -> null;
private String fingerprint;
private String productAnalyticsId;
private Path installIdFile;
private List legacyIdFiles = List.of();
private Supplier productVersion = () -> null;
private String platformName;
private String platformVersion;
private BooleanSupplier enabled = () -> true;
private Function env = System::getenv;
private Function props = System::getProperty;
private Transport transport;
private Random random = new Random();
private Duration firstDelay;
private Builder() {
}
/** Defaults to {@value #DEFAULT_BASE_URL}. */
public Builder baseUrl(String baseUrl) {
if (baseUrl != null && !baseUrl.isBlank()) {
this.baseUrl = baseUrl.trim();
}
return this;
}
/** Licensed products: the API key the product validates with ({@code slk_…}). */
public Builder apiKey(String apiKey) {
this.apiKey = apiKey;
return this;
}
/** Licensed products: the license key it validates. */
public Builder licenseKey(String licenseKey) {
return licenseKey(() -> licenseKey);
}
/** The license key, read before each report (for products that pick up a new key while running). */
public Builder licenseKey(Supplier licenseKey) {
this.licenseKey = licenseKey == null ? () -> null : licenseKey;
return this;
}
/** Licensed products: the machine id it validates with ({@code fingerprint}, or {@code host} in /api/v2). */
public Builder fingerprint(String fingerprint) {
this.fingerprint = fingerprint;
return this;
}
/** The product's public analytics id ({@code pa_…}): all a free product needs. */
public Builder productAnalyticsId(String productAnalyticsId) {
this.productAnalyticsId = productAnalyticsId;
return this;
}
/**
* Where this install keeps its random install id. Set it only to keep the id somewhere specific — one small
* file ({@value #INSTALL_ID_FILE}) is written there. By default the id lives in a hidden per-user directory
* ({@link #defaultStateDir()}), not the product's folder, so nothing shows up next to your product.
* Only used with a product analytics id.
*/
public Builder dataDirectory(Path directory) {
if (directory != null) {
this.installIdFile = directory.resolve(INSTALL_ID_FILE);
}
return this;
}
public Builder productVersion(String version) {
return productVersion(() -> version);
}
public Builder productVersion(Supplier version) {
this.productVersion = version == null ? () -> null : version;
return this;
}
/** Overrides the detected platform, e.g. {@code platform("myengine", "4.2")}. */
public Builder platform(String name, String version) {
this.platformName = name;
this.platformVersion = version;
return this;
}
/** The product's own switch (its config's {@code analytics: false}); false = nothing is sent. */
public Builder enabled(boolean enabled) {
return enabled(() -> enabled);
}
/** The product's switch, read before each report (for configs reloaded at runtime). */
public Builder enabled(BooleanSupplier enabled) {
this.enabled = enabled == null ? () -> true : enabled;
return this;
}
Builder env(Function env) {
this.env = env;
return this;
}
Builder props(Function props) {
this.props = props;
return this;
}
Builder transport(Transport transport) {
this.transport = transport;
return this;
}
Builder random(Random random) {
this.random = random;
return this;
}
Builder firstDelay(Duration firstDelay) {
this.firstDelay = firstDelay;
return this;
}
/** A reporter that isn't started: it only sends when you call {@link SunLicenseAnalytics#sendNow()}. */
public SunLicenseAnalytics build() {
if (installIdFile == null) {
installIdFile = defaultInstallIdFile(props, env, productAnalyticsId);
legacyIdFiles = legacyInstallIdFiles(props, installIdFile);
}
return new SunLicenseAnalytics(this);
}
/** Starts reporting in the background (first report in 1–30 minutes). Never throws. */
public SunLicenseAnalytics start() {
try {
return build().begin();
} catch (RuntimeException e) {
LOG.log(System.Logger.Level.DEBUG, "SunLicense analytics: not started: " + e);
return new Builder().enabled(false).build();
}
}
}
}