Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 9 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ program side is meant to stay one call.
TraceClient trace = TraceClient.builder("https://trace.danielstephenson.dev", "MyPlugin",
getDescription().getVersion())
.key(config.getString("usage-reporting.key"))
.enabled(config.getBoolean("usage-reporting.enabled", true))
.enabled(TraceClient.allowsReporting(config.get("usage-reporting.enabled")))
.serverWideConfig(getDataFolder().getParentFile()) // plugins/ -- Bukkit plugins only
.logger(getLogger())
.build();
Expand Down Expand Up @@ -99,7 +99,7 @@ chooses it; there is no default location:

```java
TraceClient trace = TraceClient.builder(url, "mycli", version).key(key)
.enabled(settings.usageReportingEnabled())
.enabled(TraceClient.allowsReporting(settings.usageReportingEnabled()))
.installIdFile(new File(dataDir, "trace-install-id")) // e.g. ~/.local/share/mycli/
.build();
```
Expand Down Expand Up @@ -191,14 +191,16 @@ finer than that anyway.
## Opting out

Reporting is **opt-out**, and the person running the program always has the
last word. `build()` checks these in order; the first match wins and is what
last word. **Every switch fails closed:** a value that does not clearly mean
"on" — a typo, a quoted `"false"`, an empty value — turns reporting off, and
nothing in this client ever turns a switch back on. `build()` checks these in order; the first match wins and is what
`disabledReason()` returns, verbatim, so the program can log it:

| Switch | `disabledReason()` |
|---|---|
| Environment: `TRACE_USAGE_REPORTING=off` (or `false`, `0`, `no`) or `DO_NOT_TRACK=1` (or `true`, `yes`), case-insensitive. Always checked. | `environment` |
| Server-wide, when `serverWideConfig(pluginsDirectory)` was given: `enabled: false` in `plugins/trace/config.yml`. `build()` creates the file with `enabled: true` (and a commented-out [`tags:`](#server-wide-tags) example) if it is missing; afterwards the only change it ever makes is appending a [`server-id:`](#every-event-carries-a-random-server-id) line when an enabled client finds none. When the environment has already opted out, the file is neither read nor created. It is read with a line regex, no YAML library. An IO failure is logged at `FINE` and counts as enabled. | `server-wide config: plugins/trace/config.yml` |
| The program's own setting: `enabled(false)`. | `config.yml` |
| Environment, case-insensitive, always checked: `TRACE_USAGE_REPORTING` set to anything but blank, `true`, `on`, `yes` or `1` (so `off`, `false`, `0`, `no`, `disabled`, …); or `DO_NOT_TRACK` set to anything but blank, `0`, `false`, `off` or `no` (so `1`, `true`, `yes`, …). An environment that cannot be read (e.g. a `SecurityManager` denying `getenv`) counts as opting out. | `environment` |
| Server-wide, when `serverWideConfig(pluginsDirectory)` was given: any `enabled:` line in `plugins/trace/config.yml` whose value, bare or quoted, is not `true`, `on`, `yes` or `1` — `enabled: false`, `enabled: "off"`, `enabled: no`, an empty `enabled:`, a typo. With several `enabled:` lines, any one that is not on turns reporting off. `build()` creates the file with `enabled: true` (and a commented-out [`tags:`](#server-wide-tags) example) if it is missing; afterwards the only change it ever makes is appending a [`server-id:`](#every-event-carries-a-random-server-id) line when an enabled client finds none. When the environment has already opted out, the file is neither read nor created. It is read with a line regex, no YAML library. A file that is not UTF-8 is read as ISO-8859-1 (and not appended to). A file that is there but cannot be read counts as **disabled** — it may say `enabled: false`; a file that is missing and cannot be created counts as enabled, since the operator has said nothing. Failures are logged at `FINE`. | `server-wide config: plugins/trace/config.yml` |
| The program's own setting: `enabled(false)`. Read it with `TraceClient.allowsReporting(value)`, which fails closed the same way: only `true`, or a string `true`/`on`/`yes`/`1`, allows reporting. On Bukkit pass `getConfig().get(path)`, not `getBoolean(path, true)` — `getBoolean` returns its default for a quoted `"false"`. | `config.yml` |
| No key, or a blank one. | `no key` |

`disabledReason()` is `null` when the client is enabled. A disabled client does
Expand Down Expand Up @@ -262,7 +264,7 @@ plugins already vendor bStats' `Metrics.java`.
<dependency>
<groupId>com.github.Stephenson-Software</groupId>
<artifactId>trace-client-java</artifactId>
<version>0.7.0</version>
<version>0.8.0</version>
</dependency>
```

Expand Down
2 changes: 1 addition & 1 deletion pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

<groupId>software.stephenson</groupId>
<artifactId>trace-client</artifactId>
<version>0.7.0</version>
<version>0.8.0</version>
<packaging>jar</packaging>

<name>trace-client</name>
Expand Down
171 changes: 129 additions & 42 deletions src/main/java/software/stephenson/trace/TraceClient.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
* trace-client 0.7.0 -- https://github.com/Stephenson-Software/trace-client-java
* trace-client 0.8.0 -- https://github.com/Stephenson-Software/trace-client-java
*
* One call to report that a program was used. Copy this file into a project as
* is, or depend on the artifact; either way there is nothing else to add.
Expand All @@ -14,7 +14,9 @@
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileAlreadyExistsException;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;
Expand All @@ -23,6 +25,7 @@
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.UUID;
Expand Down Expand Up @@ -66,19 +69,27 @@
* </ul>
*
* <p>Reporting is opt-out, and the person running the program always has the
* last word. {@link Builder#build()} checks, in this order, and the first
* match is what {@link #disabledReason()} reports:
* last word. Every switch fails closed: a value that does not clearly mean
* "on" -- a typo, a quoted {@code "false"}, an empty value -- turns reporting
* off, and nothing in this client ever turns a switch back on.
* {@link Builder#build()} checks, in this order, and the first match is what
* {@link #disabledReason()} reports:
*
* <ol>
* <li>the environment: {@code TRACE_USAGE_REPORTING=off} (or {@code false},
* {@code 0}, {@code no}) or {@code DO_NOT_TRACK=1} (or {@code true},
* {@code yes}), case-insensitive -- reason {@code environment};</li>
* <li>the environment: {@code TRACE_USAGE_REPORTING} set to anything but
* blank, {@code true}, {@code on}, {@code yes} or {@code 1}; or
* {@code DO_NOT_TRACK} set to anything but blank, {@code 0},
* {@code false}, {@code off} or {@code no}; case-insensitive -- reason
* {@code environment};</li>
* <li>the server-wide switch, when {@link Builder#serverWideConfig(File)}
* was given: {@code enabled: false} (or {@code off}, {@code 0},
* {@code no}, case-insensitive) in {@code plugins/trace/config.yml}
* -- reason {@code server-wide config: plugins/trace/config.yml};</li>
* was given: any {@code enabled:} line in {@code plugins/trace/config.yml}
* whose value, bare or quoted, is not {@code true}, {@code on},
* {@code yes} or {@code 1} (case-insensitive); or that file existing but
* being unreadable -- reason
* {@code server-wide config: plugins/trace/config.yml};</li>
* <li>the program's own setting, {@link Builder#enabled(boolean)
* enabled(false)} -- reason {@code config.yml};</li>
* enabled(false)} -- reason {@code config.yml}. Read it with
* {@link #allowsReporting(Object)} so it fails closed too;</li>
* <li>no key -- reason {@code no key}.</li>
* </ol>
*
Expand Down Expand Up @@ -117,7 +128,7 @@
* TraceClient trace = TraceClient.builder("https://trace.example.org", "MyPlugin",
* getDescription().getVersion())
* .key(config.getString("usage-reporting.key"))
* .enabled(config.getBoolean("usage-reporting.enabled", true))
* .enabled(TraceClient.allowsReporting(config.get("usage-reporting.enabled")))
* .serverWideConfig(getDataFolder().getParentFile()) // plugins/
* .logger(getLogger())
* .build();
Expand All @@ -138,7 +149,7 @@
public final class TraceClient {

/** This client's version, as sent in the User-Agent. */
public static final String VERSION = "0.7.0";
public static final String VERSION = "0.8.0";

/** How many reports may wait to be sent before new ones are dropped. */
public static final int QUEUE_CAPACITY = 256;
Expand Down Expand Up @@ -219,7 +230,7 @@ public final class TraceClient {
/** What {@link #installIdFromFile(File)} accepts as an ID on a line of its file. */
private static final Pattern INSTALL_ID_LINE = Pattern.compile("[A-Za-z0-9_.\\-]{1,255}");

private static final Pattern ENABLED_LINE = Pattern.compile("^\\s*enabled\\s*:\\s*(\\S+)");
private static final Pattern ENABLED_LINE = Pattern.compile("^\\s*enabled\\s*:(.*)$");
private static final Pattern TAGS_LINE = Pattern.compile("^tags\\s*:\\s*(#.*)?$");
private static final Pattern SERVER_ID_LINE = Pattern.compile("^server-id\\s*:(.*)$");

Expand Down Expand Up @@ -458,30 +469,71 @@ private static String disabledReason(Builder builder, ServerWideConfig serverWid
return null;
}

// Both variables fail closed: once set to anything but blank, only a value
// that clearly means "keep reporting" keeps it on.
private static boolean environmentDisables() {
return isOff(environment.apply(ENV_USAGE_REPORTING)) || isYes(environment.apply(ENV_DO_NOT_TRACK));
try {
return environmentSaysOff();
} catch (RuntimeException unreadable) {
// e.g. a SecurityManager denying getenv: an environment that cannot
// be read may hold DO_NOT_TRACK=1, so it counts as opting out.
return true;
}
}

private static boolean isOff(String value) {
if (value == null) {
return false;
private static boolean environmentSaysOff() {
String usageReporting = environment.apply(ENV_USAGE_REPORTING);
if (usageReporting != null && !usageReporting.trim().isEmpty() && !isOn(usageReporting)) {
return true;
}
String v = value.trim().toLowerCase();
return v.equals("off") || v.equals("false") || v.equals("0") || v.equals("no");
String doNotTrack = environment.apply(ENV_DO_NOT_TRACK);
return doNotTrack != null && !doNotTrack.trim().isEmpty() && !isNegative(doNotTrack);
}

private static boolean isYes(String value) {
/** {@code true}, {@code on}, {@code yes} or {@code 1}, ignoring case and surrounding space. */
private static boolean isOn(String value) {
if (value == null) {
return false;
}
String v = value.trim().toLowerCase();
return v.equals("1") || v.equals("true") || v.equals("yes");
String v = value.trim().toLowerCase(Locale.ROOT);
return v.equals("true") || v.equals("on") || v.equals("yes") || v.equals("1");
}

/** {@code false}, {@code off}, {@code no} or {@code 0}, ignoring case and surrounding space. */
private static boolean isNegative(String value) {
String v = value.trim().toLowerCase(Locale.ROOT);
return v.equals("false") || v.equals("off") || v.equals("no") || v.equals("0");
}

/**
* Whether a program's own reporting setting, as read from its
* configuration, allows reporting -- for {@link Builder#enabled(boolean)}.
* Fails closed: only {@link Boolean#TRUE}, or a string reading
* {@code true}, {@code on}, {@code yes} or {@code 1} (any case), allows it.
* Anything else turns reporting off: {@code false}, a quoted
* {@code "false"}, {@code off}, {@code no}, a typo, a number, or
* {@code null}.
*
* <p>Prefer this over {@code getBoolean(path, true)}: Bukkit's
* {@code getBoolean} returns its default for a value that is not a YAML
* boolean, so an operator's {@code enabled: "false"} would read as on.
* Pass the raw value -- on Bukkit, {@code getConfig().get(path)}, which
* still falls through to the defaults bundled in the jar when the
* operator's file has no such key.
*/
public static boolean allowsReporting(Object setting) {
if (setting instanceof Boolean) {
return (Boolean) setting;
}
return setting instanceof String && isOn((String) setting);
}

/** What {@code plugins/trace/config.yml} says: the switch, the server-wide tags and the server-id. */
static final class ServerWideConfig {
/** No file was read: none was asked for, or it could not be read. */
static final ServerWideConfig NONE = new ServerWideConfig(false, Collections.<String, String>emptyMap(), null);
/** The file is there but could not be read: whatever it says, it may say off. */
static final ServerWideConfig UNREADABLE = new ServerWideConfig(true, Collections.<String, String>emptyMap(), null);

final boolean disables;
final Map<String, String> tags;
Expand Down Expand Up @@ -510,35 +562,65 @@ ServerWideConfig readFromDisk(boolean created) {
* Ensures {@code <pluginsDirectory>/trace/config.yml} exists and reads its
* {@code enabled:} line, {@code tags:} block and {@code server-id:} line.
* Not called when the environment opts out. No YAML library: the file
* is ours, shallow, and a line scan is enough. Anything going wrong on
* disk is logged at FINE and counts as enabled with no tags -- a
* read-only plugins directory must not silently switch reporting off,
* nor stop the host program.
* is ours, shallow, and a line scan is enough. Nothing here throws.
* A file that is missing and cannot be created counts as enabled with no
* tags: the operator has said nothing, and a read-only plugins directory
* must not silently switch reporting off. A file that is there but cannot
* be read counts as disabled: it may say {@code enabled: false}. A file
* that is not valid UTF-8 is read as ISO-8859-1.
*/
private ServerWideConfig readServerWideConfig(File pluginsDirectory) {
File location = new File(pluginsDirectory, SERVER_WIDE_CONFIG_PATH);
Path file;
try {
// toPath() throws InvalidPathException for a path the file system
// cannot represent. No file can be there, so the operator has said
// nothing; and build() never throws.
file = location.toPath();
} catch (RuntimeException unrepresentable) {
log("could not read server-wide config " + location + ": " + unrepresentable);
return ServerWideConfig.NONE;
}
try {
// Inside the try: toPath() throws InvalidPathException for a path
// the file system cannot represent, and build() never throws.
Path file = location.toPath();
boolean created = false;
if (!Files.exists(file)) {
Files.createDirectories(file.getParent());
Files.write(file, SERVER_WIDE_CONFIG_CONTENT.getBytes(StandardCharsets.UTF_8));
// just written: enabled: true, and the tags example commented out
created = true;
try {
Files.createDirectories(file.getParent());
Files.write(file, SERVER_WIDE_CONFIG_CONTENT.getBytes(StandardCharsets.UTF_8),
StandardOpenOption.CREATE_NEW);
// just written: enabled: true, and the tags example commented out
created = true;
} catch (FileAlreadyExistsException raced) {
// another plugin wrote it first: read theirs
} catch (IOException | RuntimeException failure) {
// No file, and none can be made: the operator has said nothing.
log("could not create server-wide config " + location + ": " + failure);
return ServerWideConfig.NONE;
}
}
try {
return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.UTF_8)).readFromDisk(created);
} catch (CharacterCodingException notUtf8) {
// Saved in another encoding, e.g. with an accented comment. The
// switch is still read; nothing is appended to the file, so the
// install ID lives in memory for this process.
log("server-wide config " + location + " is not UTF-8; reading it as ISO-8859-1");
return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.ISO_8859_1));
}
return parseServerWideConfig(Files.readAllLines(file, StandardCharsets.UTF_8)).readFromDisk(created);
} catch (IOException | RuntimeException failure) {
log("could not read server-wide config " + location + ": " + failure);
return ServerWideConfig.NONE;
// The file is there but cannot be read. It may say enabled: false,
// so reporting stays off rather than guessing.
log("could not read server-wide config " + location + ", so reporting is off: " + failure);
return ServerWideConfig.UNREADABLE;
}
}


/**
* Reads the switch and the tags from the lines of the server-wide file.
* The first {@code enabled:} line outside a {@code tags:} block is the
* switch. A {@code tags:} line at column 0 opens a block of indented
* Every {@code enabled:} line outside a {@code tags:} block is a switch,
* and reporting stays on only if each one reads, bare or quoted,
* {@code true}, {@code on}, {@code yes} or {@code 1}. A {@code tags:} line at column 0 opens a block of indented
* {@code key: value} lines, which ends at the next line that is not
* blank, a comment or indented; blank and {@code #} lines inside it are
* skipped, at any indent, as are lines indented differently from its
Expand Down Expand Up @@ -593,10 +675,15 @@ static ServerWideConfig parseServerWideConfig(List<String> lines) {
continue;
}
}
if (disables == null) {
Matcher matcher = ENABLED_LINE.matcher(line);
if (matcher.find()) {
disables = isOff(matcher.group(1));
Matcher enabled = ENABLED_LINE.matcher(line);
if (enabled.matches()) {
// Fails closed: every enabled: line counts, and only a value
// that clearly means "on" keeps reporting on.
String value = scalar(enabled.group(1).trim());
if (value == null || !isOn(value)) {
disables = true;
} else if (disables == null) {
disables = false;
}
}
}
Expand Down
Loading