Profile: Parse config file to a string per attribute

This parser should be able to handle any valid WireGuard or wg-quick
configuration file. It separates the file into a single interface object
and a peer object for each peer. All "[Interface]" sections in the file
are combined into the one object.

For now, later lines in a block with the same key overwrite earlier
lines. This is only relevant for attributes that are lists, such as
Address and AllowedIPs, where additional lines may be expected to append
to the list.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Samuel Holland
2017-07-29 17:30:33 -05:00
parent 0494dd1404
commit 748d780a47
4 changed files with 274 additions and 26 deletions
@@ -0,0 +1,57 @@
package com.wireguard.config;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* The set of valid attributes for an interface or peer in a WireGuard configuration file.
*/
enum Attribute {
ADDRESS("Address"),
ALLOWED_IPS("AllowedIPs"),
DNS("DNS"),
ENDPOINT("Endpoint"),
LISTEN_PORT("ListenPort"),
MTU("MTU"),
PERSISTENT_KEEPALIVE("PersistentKeepalive"),
PRIVATE_KEY("PrivateKey"),
PUBLIC_KEY("PublicKey");
private static final Map<String, Attribute> map;
static {
map = new HashMap<>(Attribute.values().length);
for (Attribute key : Attribute.values())
map.put(key.getToken(), key);
}
public static Attribute match(String line) {
return map.get(line.split("\\s|=")[0]);
}
private final String token;
private final Pattern pattern;
Attribute(String token) {
this.pattern = Pattern.compile(token + "\\s*=\\s*(\\S.*)");
this.token = token;
}
public String composeWith(String value) {
return token + " = " + value + "\n";
}
public String getToken() {
return token;
}
public String parseFrom(String line) {
final Matcher matcher = pattern.matcher(line);
if (matcher.matches())
return matcher.group(1);
return null;
}
}