Files
wirevpn/app/src/main/java/com/wireguard/config/Attribute.java
T
Samuel Holland 748d780a47 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>
2017-07-29 17:30:33 -05:00

58 lines
1.4 KiB
Java

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;
}
}