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 Counter counter; private final ProgressBar progressBar; private Scan(Stream hosts, String ports, boolean quiet) { this.hosts = hosts; this.ports = ports; this.counter = new Counter(); this.progressBar = new ProgressBar(quiet); } public int getPeakConcurrentConnects() { return counter.max(); } public static Scan create(ScanOptions options) throws IOException { if (options.hostsFile() != null) { return create(options.hostsFile(), options.ports(), options.quiet()); } return create(options.hostsArgv(), options.ports(), options.quiet()); } /** * Create Scan based on either a source file or stdin * * @param sourceFile * @param ports * @param quiet * @return * @throws IOException */ public static Scan create(String sourceFile, String ports, boolean quiet) throws IOException { Stream hosts; if ("-".equals(sourceFile)) { BufferedReader stdinReader = new BufferedReader(new InputStreamReader(System.in)); hosts = stdinReader.lines(); } else { BufferedReader reader = Files.newBufferedReader(Path.of(sourceFile)); hosts = reader.lines().onClose(() -> { try { reader.close(); } catch (IOException e) { // ignored } }); } return create(hosts, ports, quiet); } private static Scan create(Stream lines, String ports, boolean quiet) { return new Scan(lines, ports, quiet); } public static Scan create(List hostsArgv, String ports, boolean quiet) { return new Scan(hostsArgv.stream(), ports, quiet); } public Stream getHosts() { return hosts; } public String getPorts() { return ports; } public void start() { progressBar.start(); } public void stop() { progressBar.stop(); hosts.close(); // close stream } public void addHostProgress(Progress progress) { progressBar.add(progress); } public void incSocketCounter() { counter.inc(); } public void decSocketCounter() { counter.dec(); } }