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 Counter hostCounter; private final Counter hostTotalCounter; private final Counter socketCounter; private final Counter threadCounter; private final Stream hosts; private final String ports; private final boolean closeStream; private Scan(Stream hosts, String ports) { this(hosts, ports, false); } private Scan(Stream hosts, String ports, boolean closeStream) { this.hosts = hosts; this.ports = ports; this.hostCounter = new Counter(); this.socketCounter = new Counter(); this.threadCounter = new Counter(); this.hostTotalCounter = new Counter(); this.closeStream = closeStream; } 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) throws IOException { Stream hosts; boolean closeStream = false; if ("-".equals(sourceFile)) { BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in)); hosts = stdinReader.lines(); } else { BufferedReader reader = Files.newBufferedReader(Path.of(sourceFile)); closeStream = true; hosts = reader.lines().onClose(() -> { try { reader.close(); } catch (IOException e) { // ignored } }); } return create(hosts, ports, closeStream); } private static Scan create(Stream lines, String ports, boolean closeStream) { return new Scan(lines, ports, closeStream); } 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 start() { // start } public void stop() { if (closeStream) { hosts.close(); // close stream } } public Counter getThreadCounter() { return threadCounter; } public Counter getHostCounter() { return hostCounter; } public Counter getSocketCounter() { return socketCounter; } public Counter getHostTotalCounter() { return hostTotalCounter; } }