Remove sloppy java with enterprise java horrors

Since the amount of mind numbing boiler plate has been increased, this
must be the proper way to do things.

Signed-off-by: Jason A. Donenfeld <Jason@zx2c4.com>
This commit is contained in:
Jason A. Donenfeld 2018-04-17 05:20:17 +02:00
parent e40c579b0e
commit b5360871e8
7 changed files with 151 additions and 99 deletions

View File

@ -21,7 +21,6 @@ import java.net.InetSocketAddress;
import java.util.Collections; import java.util.Collections;
import java.util.Formatter; import java.util.Formatter;
import java.util.Set; import java.util.Set;
import java.util.Vector;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException; import java.util.concurrent.TimeoutException;
@ -127,16 +126,15 @@ public final class GoBackend implements Backend {
private String parseEndpoint(String string) throws Exception { private String parseEndpoint(String string) throws Exception {
String[] part; String[] part;
if (string.charAt(0) == '[') { // ipv6 if (string.charAt(0) == '[') {
int end = string.indexOf(']'); int end = string.indexOf(']');
if (end == -1 || string.charAt(end+1) != ':') if (end == -1 || end >= string.length() - 2 || string.charAt(end + 1) != ':')
throw new Exception("Invalid endpoint " + string); throw new Exception("Invalid endpoint " + string);
part = new String[2]; part = new String[2];
part[0] = string.substring(1, end); part[0] = string.substring(1, end);
part[1] = string.substring(end + 2); part[1] = string.substring(end + 2);
Log.d(TAG, "PP " + part[0] + " " + part[1]); } else {
} else { // ipv4
part = string.split(":", 2); part = string.split(":", 2);
} }
@ -144,7 +142,13 @@ public final class GoBackend implements Backend {
throw new Exception("Invalid endpoint " + string); throw new Exception("Invalid endpoint " + string);
InetAddress address = InetAddress.getByName(part[0]); InetAddress address = InetAddress.getByName(part[0]);
int port = Integer.valueOf(part[1]); int port = -1;
try {
port = Integer.parseInt(part[1], 10);
} catch (Exception e) {
}
if (port < 1)
throw new Exception("Invalid endpoint port " + part[1]);
InetSocketAddress socketAddress = new InetSocketAddress(address, port); InetSocketAddress socketAddress = new InetSocketAddress(address, port);
if (socketAddress.getAddress() instanceof Inet4Address) if (socketAddress.getAddress() instanceof Inet4Address)
return socketAddress.getAddress().getHostAddress() + ":" + socketAddress.getPort(); return socketAddress.getAddress().getHostAddress() + ":" + socketAddress.getPort();
@ -152,31 +156,23 @@ public final class GoBackend implements Backend {
return "[" + socketAddress.getAddress().getHostAddress() + "]:" + socketAddress.getPort(); return "[" + socketAddress.getAddress().getHostAddress() + "]:" + socketAddress.getPort();
} }
private Vector<Pair<String, Integer>> parseAllowedIps(String string) throws Exception { private Pair<String, Integer> parseAddressWithCidr(String in) {
Vector<Pair<String, Integer>> ret = new Vector<>(); int cidr = -1;
for (final String allowedIp : string.split(" *, *")) { String addr = in;
String[] part = allowedIp.split("/", 2); int slash = in.lastIndexOf('/');
if (part.length > 2) if (slash != -1 && slash < in.length() - 1) {
throw new Exception("Invalid allowed ips string " + string);
try { try {
InetAddress address = InetAddress.getByName(part[0]); cidr = Integer.parseInt(in.substring(slash + 1), 10);
int networkPrefixLength; addr = in.substring(0, slash);
if (part.length == 2) {
networkPrefixLength = Integer.valueOf(part[1]);
if (networkPrefixLength < 0 || networkPrefixLength > 128
|| (address instanceof Inet4Address && networkPrefixLength > 32))
throw new Exception();
} else {
networkPrefixLength = (address instanceof Inet4Address) ? 32 : 128;
}
ret.add(new Pair<>(address.getHostAddress(), networkPrefixLength));
} catch (Exception e) { } catch (Exception e) {
throw new Exception("Invalid allowed ips string " + string);
} }
} }
return ret; boolean isV6 = addr.indexOf(':') != -1;
if (isV6 && (cidr > 128 || cidr < 0))
cidr = 128;
else if (!isV6 && (cidr > 32 || cidr < 0))
cidr = 32;
return new Pair<>(addr, cidr);
} }
private void setStateInternal(final Tunnel tunnel, final Config config, final State state) private void setStateInternal(final Tunnel tunnel, final Config config, final State state)
@ -216,15 +212,13 @@ public final class GoBackend implements Backend {
fmt.format("public_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPublicKey()))); fmt.format("public_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPublicKey())));
if (peer.getPreSharedKey() != null) if (peer.getPreSharedKey() != null)
fmt.format("preshared_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPreSharedKey()))); fmt.format("preshared_key=%s\n", KeyEncoding.keyToHex(KeyEncoding.keyFromBase64(peer.getPreSharedKey())));
if (peer.getEndpoint() != null) { if (peer.getEndpoint() != null)
fmt.format("endpoint=%s\n", parseEndpoint(peer.getEndpoint())); fmt.format("endpoint=%s\n", parseEndpoint(peer.getEndpoint()));
}
if (peer.getPersistentKeepalive() != null) if (peer.getPersistentKeepalive() != null)
fmt.format("persistent_keepalive_interval=%d\n", Integer.parseInt(peer.getPersistentKeepalive())); fmt.format("persistent_keepalive_interval=%d\n", Integer.parseInt(peer.getPersistentKeepalive(), 10));
if (peer.getAllowedIPs() != null) { for (final String addr : peer.getAllowedIPs()) {
for (final Pair<String, Integer> allowedIp : parseAllowedIps(peer.getAllowedIPs())) { final Pair<String, Integer> addressCidr = parseAddressWithCidr(addr);
fmt.format("allowed_ip=%s\n", allowedIp.first + "/" + allowedIp.second); fmt.format("allowed_ip=%s\n", addressCidr.first + "/" + addressCidr.second);
}
} }
} }
@ -232,22 +226,21 @@ public final class GoBackend implements Backend {
VpnService.Builder builder = service.getBuilder(); VpnService.Builder builder = service.getBuilder();
builder.setSession(tunnel.getName()); builder.setSession(tunnel.getName());
for (final String addressString : config.getInterface().getAddress().split(" *, *")) { for (final String addr : config.getInterface().getAddresses()) {
InetAddress address = InetAddress.getByName(addressString); final Pair<String, Integer> addressCidr = parseAddressWithCidr(addr);
builder.addAddress(address.getHostAddress(), (address instanceof Inet4Address) ? 32 : 128); final InetAddress address = InetAddress.getByName(addressCidr.first);
builder.addAddress(address.getHostAddress(), addressCidr.second);
} }
if (config.getInterface().getDns() != null) { for (final String addr : config.getInterface().getDnses()) {
for (final String dnsString : config.getInterface().getDns().split(" *, *")) { final InetAddress address = InetAddress.getByName(addr);
builder.addDnsServer(InetAddress.getByName(dnsString).getHostAddress()); builder.addDnsServer(address.getHostAddress());
}
} }
for (final Peer peer : config.getPeers()) { for (final Peer peer : config.getPeers()) {
if (peer.getAllowedIPs() != null) { for (final String addr : peer.getAllowedIPs()) {
for (final Pair<String, Integer> allowedIp : parseAllowedIps(peer.getAllowedIPs())) { final Pair<String, Integer> addressCidr = parseAddressWithCidr(addr);
builder.addRoute(allowedIp.first, allowedIp.second); builder.addRoute(addressCidr.first, addressCidr.second);
}
} }
} }

View File

@ -1,5 +1,7 @@
package com.wireguard.config; package com.wireguard.config;
import android.text.TextUtils;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.regex.Matcher; import java.util.regex.Matcher;
@ -43,10 +45,22 @@ enum Attribute {
return KEY_MAP.get(SEPARATOR_PATTERN.split(line)[0]); return KEY_MAP.get(SEPARATOR_PATTERN.split(line)[0]);
} }
public static String listToString(final String[] list) {
return TextUtils.join(", ", list);
}
public static String[] stringToList(final String string) {
return string.trim().split("\\s*,\\s*");
}
public String composeWith(final Object value) { public String composeWith(final Object value) {
return String.format("%s = %s%n", token, value); return String.format("%s = %s%n", token, value);
} }
public String composeWith(final String[] value) {
return String.format("%s = %s%n", token, listToString(value));
}
public String getToken() { public String getToken() {
return token; return token;
} }
@ -55,4 +69,9 @@ enum Attribute {
final Matcher matcher = pattern.matcher(line); final Matcher matcher = pattern.matcher(line);
return matcher.matches() ? matcher.group(1) : null; return matcher.matches() ? matcher.group(1) : null;
} }
public String[] parseList(final CharSequence line) {
final Matcher matcher = pattern.matcher(line);
return matcher.matches() ? stringToList(matcher.group(1)) : null;
}
} }

View File

@ -26,20 +26,21 @@ public class Interface extends BaseObservable implements Parcelable {
} }
}; };
private String address; private String[] addressList;
private String dns; private String[] dnsList;
private Keypair keypair; private Keypair keypair;
private String listenPort; private String listenPort;
private String mtu; private String mtu;
private String privateKey; private String privateKey;
public Interface() { public Interface() {
// Do nothing. addressList = new String[0];
dnsList = new String[0];
} }
private Interface(final Parcel in) { private Interface(final Parcel in) {
address = in.readString(); addressList = in.createStringArray();
dns = in.readString(); dnsList = in.createStringArray();
listenPort = in.readString(); listenPort = in.readString();
mtu = in.readString(); mtu = in.readString();
setPrivateKey(in.readString()); setPrivateKey(in.readString());
@ -58,13 +59,23 @@ public class Interface extends BaseObservable implements Parcelable {
} }
@Bindable @Bindable
public String getAddress() { public String getAddressString() {
return address; return Attribute.listToString(addressList);
} }
@Bindable @Bindable
public String getDns() { public String[] getAddresses() {
return dns; return addressList;
}
@Bindable
public String getDnsString() {
return Attribute.listToString(dnsList);
}
@Bindable
public String[] getDnses() {
return dnsList;
} }
@Bindable @Bindable
@ -90,9 +101,9 @@ public class Interface extends BaseObservable implements Parcelable {
public void parse(final String line) { public void parse(final String line) {
final Attribute key = Attribute.match(line); final Attribute key = Attribute.match(line);
if (key == Attribute.ADDRESS) if (key == Attribute.ADDRESS)
addAddress(key.parse(line)); addAddresses(key.parseList(line));
else if (key == Attribute.DNS) else if (key == Attribute.DNS)
addDns(key.parse(line)); addDnses(key.parseList(line));
else if (key == Attribute.LISTEN_PORT) else if (key == Attribute.LISTEN_PORT)
setListenPort(key.parse(line)); setListenPort(key.parse(line));
else if (key == Attribute.MTU) else if (key == Attribute.MTU)
@ -103,32 +114,44 @@ public class Interface extends BaseObservable implements Parcelable {
throw new IllegalArgumentException(line); throw new IllegalArgumentException(line);
} }
public void addAddress(String address) { public void addAddresses(String[] addresses) {
if (address != null && address.isEmpty()) if (addresses == null || addresses.length == 0)
address = null; return;
setAddress((this.address == null) ? address String[] both = new String[addresses.length + this.addressList.length];
: this.address + ", " + address); System.arraycopy(this.addressList, 0, both, 0, this.addressList.length);
System.arraycopy(addresses, 0, both, this.addressList.length, addresses.length);
setAddresses(both);
} }
public void setAddress(String address) { public void setAddresses(String[] addresses) {
if (address != null && address.isEmpty()) if (addresses == null)
address = null; addresses = new String[0];
this.address = address; this.addressList = addresses;
notifyPropertyChanged(BR.address); notifyPropertyChanged(BR.addresses);
} }
public void addDns(String dns) { public void setAddressString(String addressString) {
if (dns != null && dns.isEmpty()) setAddresses(Attribute.stringToList(addressString));
dns = null;
setDns((this.dns == null) ? dns
: this.dns + ", " + dns);
} }
public void setDns(String dns) { public void addDnses(String[] dnses) {
if (dns != null && dns.isEmpty()) if (dnses == null || dnses.length == 0)
dns = null; return;
this.dns = dns; String[] both = new String[dnses.length + this.dnsList.length];
notifyPropertyChanged(BR.dns); System.arraycopy(this.dnsList, 0, both, 0, this.dnsList.length);
System.arraycopy(dnses, 0, both, this.dnsList.length, dnses.length);
setDnses(both);
}
public void setDnses(String[] dnses) {
if (dnses == null)
dnses = new String[0];
this.dnsList = dnses;
notifyPropertyChanged(BR.dnses);
}
public void setDnsString(String dnsString) {
setDnses(Attribute.stringToList(dnsString));
} }
public void setListenPort(String listenPort) { public void setListenPort(String listenPort) {
@ -165,10 +188,10 @@ public class Interface extends BaseObservable implements Parcelable {
@Override @Override
public String toString() { public String toString() {
final StringBuilder sb = new StringBuilder().append("[Interface]\n"); final StringBuilder sb = new StringBuilder().append("[Interface]\n");
if (address != null) if (addressList != null && addressList.length > 0)
sb.append(Attribute.ADDRESS.composeWith(address)); sb.append(Attribute.ADDRESS.composeWith(addressList));
if (dns != null) if (dnsList != null && dnsList.length > 0)
sb.append(Attribute.DNS.composeWith(dns)); sb.append(Attribute.DNS.composeWith(dnsList));
if (listenPort != null) if (listenPort != null)
sb.append(Attribute.LISTEN_PORT.composeWith(listenPort)); sb.append(Attribute.LISTEN_PORT.composeWith(listenPort));
if (mtu != null) if (mtu != null)
@ -180,8 +203,8 @@ public class Interface extends BaseObservable implements Parcelable {
@Override @Override
public void writeToParcel(final Parcel dest, final int flags) { public void writeToParcel(final Parcel dest, final int flags) {
dest.writeString(address); dest.writeStringArray(addressList);
dest.writeString(dns); dest.writeStringArray(dnsList);
dest.writeString(listenPort); dest.writeString(listenPort);
dest.writeString(mtu); dest.writeString(mtu);
dest.writeString(privateKey); dest.writeString(privateKey);

View File

@ -24,18 +24,18 @@ public class Peer extends BaseObservable implements Parcelable {
} }
}; };
private String allowedIPs; private String[] allowedIPList;
private String endpoint; private String endpoint;
private String persistentKeepalive; private String persistentKeepalive;
private String preSharedKey; private String preSharedKey;
private String publicKey; private String publicKey;
public Peer() { public Peer() {
// Do nothing. allowedIPList = new String[0];
} }
private Peer(final Parcel in) { private Peer(final Parcel in) {
allowedIPs = in.readString(); allowedIPList = in.createStringArray();
endpoint = in.readString(); endpoint = in.readString();
persistentKeepalive = in.readString(); persistentKeepalive = in.readString();
preSharedKey = in.readString(); preSharedKey = in.readString();
@ -51,9 +51,13 @@ public class Peer extends BaseObservable implements Parcelable {
return 0; return 0;
} }
@Bindable @Bindable
public String getAllowedIPs() { public String getAllowedIPsString() { return Attribute.listToString(allowedIPList); }
return allowedIPs;
@Bindable
public String[] getAllowedIPs() {
return allowedIPList;
} }
@Bindable @Bindable
@ -79,7 +83,7 @@ public class Peer extends BaseObservable implements Parcelable {
public void parse(final String line) { public void parse(final String line) {
final Attribute key = Attribute.match(line); final Attribute key = Attribute.match(line);
if (key == Attribute.ALLOWED_IPS) if (key == Attribute.ALLOWED_IPS)
setAllowedIPs(key.parse(line)); addAllowedIPs(key.parseList(line));
else if (key == Attribute.ENDPOINT) else if (key == Attribute.ENDPOINT)
setEndpoint(key.parse(line)); setEndpoint(key.parse(line));
else if (key == Attribute.PERSISTENT_KEEPALIVE) else if (key == Attribute.PERSISTENT_KEEPALIVE)
@ -92,13 +96,26 @@ public class Peer extends BaseObservable implements Parcelable {
throw new IllegalArgumentException(line); throw new IllegalArgumentException(line);
} }
public void setAllowedIPs(String allowedIPs) { public void addAllowedIPs(String[] allowedIPs) {
if (allowedIPs != null && allowedIPs.isEmpty()) if (allowedIPs == null || allowedIPs.length == 0)
allowedIPs = null; return;
this.allowedIPs = allowedIPs; String[] both = new String[allowedIPs.length + this.allowedIPList.length];
System.arraycopy(this.allowedIPList, 0, both, 0, this.allowedIPList.length);
System.arraycopy(allowedIPs, 0, both, this.allowedIPList.length, allowedIPs.length);
setAllowedIPs(both);
}
public void setAllowedIPs(String[] allowedIPs) {
if (allowedIPs == null)
allowedIPs = new String[0];
this.allowedIPList = allowedIPs;
notifyPropertyChanged(BR.allowedIPs); notifyPropertyChanged(BR.allowedIPs);
} }
public void setAllowedIPsString(String allowedIPsString) {
setAllowedIPs(Attribute.stringToList(allowedIPsString));
}
public void setEndpoint(String endpoint) { public void setEndpoint(String endpoint) {
if (endpoint != null && endpoint.isEmpty()) if (endpoint != null && endpoint.isEmpty())
endpoint = null; endpoint = null;
@ -130,8 +147,8 @@ public class Peer extends BaseObservable implements Parcelable {
@Override @Override
public String toString() { public String toString() {
final StringBuilder sb = new StringBuilder().append("[Peer]\n"); final StringBuilder sb = new StringBuilder().append("[Peer]\n");
if (allowedIPs != null) if (allowedIPList != null)
sb.append(Attribute.ALLOWED_IPS.composeWith(allowedIPs)); sb.append(Attribute.ALLOWED_IPS.composeWith(allowedIPList));
if (endpoint != null) if (endpoint != null)
sb.append(Attribute.ENDPOINT.composeWith(endpoint)); sb.append(Attribute.ENDPOINT.composeWith(endpoint));
if (persistentKeepalive != null) if (persistentKeepalive != null)
@ -145,7 +162,7 @@ public class Peer extends BaseObservable implements Parcelable {
@Override @Override
public void writeToParcel(final Parcel dest, final int flags) { public void writeToParcel(final Parcel dest, final int flags) {
dest.writeString(allowedIPs); dest.writeStringArray(allowedIPList);
dest.writeString(endpoint); dest.writeString(endpoint);
dest.writeString(persistentKeepalive); dest.writeString(persistentKeepalive);
dest.writeString(preSharedKey); dest.writeString(preSharedKey);

View File

@ -69,7 +69,7 @@
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_below="@+id/allowed_ips_label" android:layout_below="@+id/allowed_ips_label"
android:text="@{item.allowedIPs}" /> android:text="@{item.allowedIPsString}" />
<TextView <TextView
android:id="@+id/endpoint_label" android:id="@+id/endpoint_label"

View File

@ -143,7 +143,7 @@
android:layout_below="@+id/addresses_label" android:layout_below="@+id/addresses_label"
android:layout_toStartOf="@+id/listen_port_text" android:layout_toStartOf="@+id/listen_port_text"
android:inputType="textNoSuggestions|textVisiblePassword" android:inputType="textNoSuggestions|textVisiblePassword"
android:text="@={config.interface.address}" /> android:text="@={config.interface.addressString}" />
<TextView <TextView
android:id="@+id/listen_port_label" android:id="@+id/listen_port_label"
@ -185,7 +185,7 @@
android:layout_below="@+id/dns_servers_label" android:layout_below="@+id/dns_servers_label"
android:layout_toStartOf="@+id/mtu_text" android:layout_toStartOf="@+id/mtu_text"
android:inputType="textNoSuggestions|textVisiblePassword" android:inputType="textNoSuggestions|textVisiblePassword"
android:text="@={config.interface.dns}" /> android:text="@={config.interface.dnsString}" />
<TextView <TextView
android:id="@+id/mtu_label" android:id="@+id/mtu_label"

View File

@ -96,7 +96,7 @@
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_below="@+id/allowed_ips_label" android:layout_below="@+id/allowed_ips_label"
android:inputType="textNoSuggestions|textVisiblePassword" android:inputType="textNoSuggestions|textVisiblePassword"
android:text="@={item.allowedIPs}" /> android:text="@={item.allowedIPsString}" />
<TextView <TextView
android:id="@+id/endpoint_label" android:id="@+id/endpoint_label"