diff options
author | Samuel Holland <samuel@sholland.org> | 2017-07-29 17:30:33 -0500 |
---|---|---|
committer | Samuel Holland <samuel@sholland.org> | 2017-07-29 17:30:33 -0500 |
commit | ea3f17084441d8ebd76de66231801ff61f1a858e (patch) | |
tree | 028cf53f279c354db64ec1c7f32bc17ae1c9bc09 /app/src/main/java/com/wireguard/config/Attribute.java | |
parent | Profile: Add minimal implementation (diff) | |
download | wireguard-android-ea3f17084441d8ebd76de66231801ff61f1a858e.tar.xz wireguard-android-ea3f17084441d8ebd76de66231801ff61f1a858e.zip |
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.
Diffstat (limited to 'app/src/main/java/com/wireguard/config/Attribute.java')
-rw-r--r-- | app/src/main/java/com/wireguard/config/Attribute.java | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/app/src/main/java/com/wireguard/config/Attribute.java b/app/src/main/java/com/wireguard/config/Attribute.java new file mode 100644 index 00000000..7629456a --- /dev/null +++ b/app/src/main/java/com/wireguard/config/Attribute.java @@ -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; + } +} |