Skip to content

Commit

Permalink
maked plugin usable by better-security as module, new properties for …
Browse files Browse the repository at this point in the history
…online services for using it when no tokens and a trust priority
  • Loading branch information
ZetaMap committed Dec 23, 2023
1 parent 9526a1c commit 9fdc4e3
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 36 deletions.
20 changes: 11 additions & 9 deletions src/main/java/avs/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -49,24 +49,26 @@ public void init() {
// TODO: better welcome message

mindustry.mod.Mods.ModMeta meta = Vars.mods.getMod(getClass()).meta;
PVars.setPluginFolder(Vars.modDirectory.child(meta.name));
DynamicSettings.logFile = PVars.settingsFolder.child("avs-logs.log");
DynamicSettings.autosaveTimeout = mindustry.net.Administration.Config.autosaveSpacing.num();

checkForUpdates(meta.repo, meta.version);
initPlugin(Vars.modDirectory.child(meta.name));

Log.info("");
Log.info("Loading finished in @ seconds", ((float) (System.currentTimeMillis()-start)/1000));
Log.info("&lg----------------------------------------------------------------");
Log.info("");
}

public void initPlugin(arc.files.Fi workingDirectory) {
PVars.setPluginFolder(workingDirectory);
DynamicSettings.logFile = PVars.settingsFolder.child(workingDirectory.name() + "_files.log");
DynamicSettings.autosaveTimeout = mindustry.net.Administration.Config.autosaveSpacing.num();

if (ServiceManager.registerServerListeners()) {
PVars.loadSettings();
AntiVpnService.loadProviders();
AntiVpnService.logger.debug("Forcing autosave...");
DynamicSettings.forceGlobalAutosave();
}

Log.info("");
Log.info("Loading finished in @ seconds", ((float) (System.currentTimeMillis()-start)/1000));
Log.info("&lg----------------------------------------------------------------");
Log.info("");
}

public void checkForUpdates(String repo, String currentVersion) {
Expand Down
7 changes: 5 additions & 2 deletions src/main/java/avs/service/AntiVpnService.java
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ public static AddressValidity checkIP(String ip) {
if (whitelist != null) {
result = whitelist.checkIP(ip);
if (result != null) {
logger.debug("Ignoring this ip, because it is whitelisted");
logger.debug("Ignoring this ip, because it's whitelisted");
return null;
}
}
Expand All @@ -101,7 +101,10 @@ public static AddressValidity checkIP(String ip, Seq<? extends AddressProvider>
for (int i=0; i<providers.size; i++) {
if (predicate != null && !predicate.get(providers.items[i])) continue;
result = providers.items[i].checkIP(ip);
if (result != null && result.type.isNotValid()) return result;
if (result != null && (result.type.isNotValid() ||
(providers.items[i] instanceof OnlineServiceAddressProvider &&
((OnlineServiceAddressProvider) providers.items[i]).isTrusted())))
return result;
}

return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,9 @@
public class VpnApiService extends avs.service.providers.types.OnlineServiceAddressProvider {
public VpnApiService() {
super("VpnAPI.io Service", "vpnapi", "https://vpnapi.io/api/{0}?key={1}");
hasTokens = true;
canUseTokens = true;
urlWithoutTokens = "https://vpnapi.io/api/{0}";
isTrusted = true;
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,16 @@ public abstract class OnlineServiceAddressProvider extends AddressProvider {
* Don't forgot to add '{0}' = the ip, '{1}' = the token (optional), in the URL.
*/
public final String url;
/*
* The url of service, to use when 'needTokens' is false and no tokens in list.
*/
public String urlWithoutTokens = "";

protected ObjectMap<String, Integer> tokens = new ObjectMap<>();
// TODO: needTokens, if service can work without tokens
protected boolean hasTokens = false, available = true;
protected boolean canUseTokens = false,
needTokens = false,
// Define whether the service is trusted when reporting that the IP valid, so the IP will be not checked by other services.
isTrusted = false;
protected int unavailableTimeout = 0;

public OnlineServiceAddressProvider(String name, String url) {
Expand All @@ -64,6 +70,18 @@ public OnlineServiceAddressProvider(String displayName, String name, String url)
fileExt = "txt";
}

@Override
public boolean load() {
// No tokens needed. skip tokens loading
if (!useTokens()) {
urlWithoutTokens = url;
logger.info("Service loaded");
return true;

} else if (!needTokens && urlWithoutTokens.isBlank()) urlWithoutTokens = url;
return loadCache();
}

@Override
public boolean reload() {
tokens.clear();
Expand All @@ -73,12 +91,6 @@ public boolean reload() {
//Cache are tokens for online services
@Override
protected boolean loadCache() {
// No tokens needed. skip this
if (!hasTokens) {
logger.info("Service loaded");
return true;
}

boolean loaded = true;
Fi tokensFile = getFile();
Seq<String> tokens_ = new Seq<>();
Expand All @@ -96,7 +108,8 @@ protected boolean loadCache() {
tokens_.each(t -> tokens.put(t, 0));

if (!loaded) logger.err("Failed to load tokens! Skipping this service...");
else if (tokens.isEmpty()) logger.warn("Service requires tokens, but the list is empty.");
else if (tokens.isEmpty() && needTokens) logger.warn("Service requires tokens, but the list is empty.");
else if (tokens.isEmpty()) logger.warn("No tokens found for this service, it will be used without.");
else logger.info("Loaded @ token" + (tokens.size > 1 ? "s" : "") + ".", tokens.size);

return loaded;
Expand All @@ -106,7 +119,7 @@ protected boolean loadCache() {
@Override
protected boolean saveCache() {
// No tokens needed. skip this
if (!hasTokens) return true;
if (!useTokens()) return true;

Fi tokensFile = getFile();

Expand All @@ -123,22 +136,30 @@ protected boolean saveCache() {
}

public boolean isAvailable() {
return available;
return unavailableTimeout <= 0;
}

public boolean isTrusted() {
return isTrusted;
}

public boolean useTokens() {
return hasTokens;
return canUseTokens;
}

public boolean willUseTokens() {
return useTokens() && !tokens.isEmpty();
}

public boolean addToken(String token) {
if (!hasTokens || tokens.containsKey(token.strip())) return false;
if (!useTokens() || tokens.containsKey(token.strip())) return false;
tokens.put(token.strip(), 0);
save();
return true;
}

public boolean removeToken(String token) {
if (!hasTokens || !tokens.containsKey(token.strip())) return false;
if (!useTokens() || !tokens.containsKey(token.strip())) return false;
tokens.remove(token.strip());
save();
return true;
Expand All @@ -152,20 +173,21 @@ public AddressValidity checkIP(String ip) {
}

// if service is unavailable for moment, don't use it
if (unavailableTimeout > 0 && unavailableTimeout-- > 0) {
if (!isAvailable()) {
unavailableTimeout--;
logger.debug("Service unavailable for moment. @ IP checks before availability verification", unavailableTimeout);
return null;
}

logger.debug("Checking ip '@'", ip);
ServiceReply reply = new ServiceReply();

if (hasTokens) {
if (tokens.isEmpty()) {
logger.debug("Service requires tokens, but the list is empty.");
return null;
}
if (!willUseTokens() && needTokens) {
logger.debug("Service requires tokens, but the list is empty.");
return null;
}

if (willUseTokens()) {
for (ObjectMap.Entry<String, Integer> token : tokens.entries()) {
if (token.value > 0) {
token.value--;
Expand Down Expand Up @@ -210,7 +232,7 @@ public AddressValidity checkIP(String ip) {
logger.warn("Cannot check ip, all tokens has been skipped!");

} else {
reply = request(MessageFormat.format(url, ip));
reply = request(MessageFormat.format(urlWithoutTokens, ip));

if (reply.type != ServiceReplyType.OK) {
if (reply.type == ServiceReplyType.UNAVAILABLE ||
Expand All @@ -236,7 +258,7 @@ public AddressValidity checkIP(String ip) {
return reply.result;
}

private ServiceReply request(String url) {
public ServiceReply request(String url) {
ServiceReply reply = new ServiceReply();

AwaitHttp.get(url, success -> {
Expand Down Expand Up @@ -274,7 +296,8 @@ else if (status.status.code == 498)


String message = status.response.getResultAsString();
if (message.isBlank()) reply.message = status.getLocalizedMessage();
// Use the exception message if result is empty or if is too long
if (message.isBlank() || message.length() > 512) reply.message = status.getLocalizedMessage();
else reply.message = message.strip();
return;
}
Expand Down

0 comments on commit 9fdc4e3

Please sign in to comment.