package com.it_jaros.jscanner; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.nio.file.Files; import java.nio.file.Path; import java.util.List; import java.util.stream.Stream; /** * Object holder for stateful volatile data during scan */ public class Scan { private final Stream hosts; private final String ports; private final Runnable onDone; private final Counter hostCounter; private final Counter hostTotalCounter; private final Counter socketCounter; private final Counter threadCounter; private long start = 0; private long stop = 0; private Scan(Stream hosts, String ports) { this(hosts, ports, () -> {}); } private Scan(Stream hosts, String ports, Runnable onDone) { this.hosts = hosts; this.ports = ports; this.onDone = onDone; this.hostCounter = new Counter(); this.hostTotalCounter = new Counter(); this.socketCounter = new Counter(); this.threadCounter = new Counter(); } public static Scan create(ScanOptions options) throws IOException { if (options.hostsFile() != null) { return create(options.hostsFile(), options.ports()); } return create(options.hostsArgv(), options.ports()); } /** * Create Scan based on either a source file or stdin * * @param sourceFile * @param ports * @return * @throws IOException */ public static Scan create(String sourceFile, String ports) { Stream hosts; if (sourceFile == null || sourceFile.isEmpty()) { throw new IllegalArgumentException("Source file is null or empty"); } if ("-".equals(sourceFile)) { BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in)); hosts = stdinReader.lines(); return new Scan(hosts, ports); } try { BufferedReader reader = Files.newBufferedReader(Path.of(sourceFile)); return new Scan(reader.lines(), ports, () -> { try { reader.close(); } catch (IOException ignore) { // we ignore it because at this moment the program is shutting down anyway } }); } catch (IOException e) { throw new ScanException("Error while trying to open source File", e); } } public static Scan create(List hostsArgv, String ports) { return new Scan(hostsArgv.stream(), ports); } public Stream getHosts() { return hosts; } public String getPorts() { return ports; } public void stop() { stop = System.currentTimeMillis(); onDone.run(); } public Counter getThreadCounter() { return threadCounter; } public Counter getHostCounter() { return hostCounter; } public Counter getSocketCounter() { return socketCounter; } public Counter getHostTotalCounter() { return hostTotalCounter; } public void start() { start = System.currentTimeMillis(); } public long getDurationMillis() { if (stop == 0) { if (start == 0) { return 0; } return System.currentTimeMillis() - start; } return stop - start; } }