Skip to content

Commit

Permalink
#3: ClientDetector (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
KirillSmirnow authored Aug 27, 2024
1 parent ec2022f commit fd11719
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 0 deletions.
2 changes: 2 additions & 0 deletions vpn-router-bootstrap/src/main/resources/application.yml
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
storage:
clients-file-path: ${HOME}/vpn-router/storage/clients.yml
network:
address: 192.168.0.0/24
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package vpnrouter.core.infrastructure.shell;

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;

@Data
@ConfigurationProperties("network")
public class NetworkProperties {
private final String address;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package vpnrouter.core.infrastructure.shell;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;
import vpnrouter.core.service.client.detection.ClientDetector;

import java.util.List;

@Primary
@Component
@Profile("prod")
@RequiredArgsConstructor
public class RealClientDetector implements ClientDetector {

private final NetworkProperties networkProperties;
private final ShellExecutor shellExecutor;

@Override
public List<String> detectIpAddresses() {
return shellExecutor.execute("nmap -sn -n %s -oG - | awk '/Host/{print $2}'".formatted(
networkProperties.getAddress()
));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package vpnrouter.core.infrastructure.shell;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import vpnrouter.core.exception.UserException;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class ShellExecutor {

@SneakyThrows
public List<String> execute(String command) {
var process = new ProcessBuilder("sh", "-c", command).start();
var completed = process.waitFor(1, TimeUnit.MINUTES);
if (!completed) {
log.warn("[{}] -> [TIME OUT]", command);
throw new UserException("Shell command execution timed out");
}
var success = process.exitValue() == 0;
try (var reader = process.inputReader()) {
var output = reader.lines().toList();
if (success) {
log.info("[{}] -> [SUCCESS]\n{}", command, String.join("\n", output));
} else {
log.warn("[{}] -> [FAILURE]\n{}", command, String.join("\n", output));
}
return output;
}
}
}

0 comments on commit fd11719

Please sign in to comment.