summaryrefslogtreecommitdiff
path: root/src/main/java/com/it_jaros/jscanner/ProgressBar.java
blob: bc37c1296de48c9d211d5c78186bf925c1d08839 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
package com.it_jaros.jscanner;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.BitSet;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class ProgressBar {

    private final ScheduledExecutorService ui = Executors.newSingleThreadScheduledExecutor();
    private final Scan scan;
    private final boolean quiet;
    private final int columnWidth = ProgressBar.getColumnWidth();
    private final Object outputLock = new Object();

    public ProgressBar(Scan scan, boolean quiet) {
        this.scan = scan;
        this.quiet = quiet;
    }

    private void clearStatusLine() {
        System.err.print("\r\033[2K");
        System.err.flush();
    }

    public void printResult(ScanResult result, boolean showFilteredPorts) {
        synchronized (outputLock) {
            if (result.openPorts().isEmpty()
                    && (!showFilteredPorts || result.filteredPorts().isEmpty())
                    && result.errors().isEmpty()) {
                return;
            }

            clearStatusLine();
            printErrors(result);
            printPortsResults(result, showFilteredPorts);
        }
    }

    private void printErrors(ScanResult result) {
        if (result.errors().isEmpty()) return;

        System.err.printf(
                "error: host scan failed | host=%s | errors: %d%n",
                result.host(),
                result.errors().size()
        );

        for (ScanFailure error : result.errors()) {
            System.err.printf(
                    "port: %s: %s %s%n",
                    error.port(),
                    error.exception().type(),
                    error.exception().message()
            );
        }
    }

    private void printPortsResults(ScanResult result, boolean showFilteredPorts) {
        if (result.openPorts().isEmpty() && (!showFilteredPorts || result.filteredPorts().isEmpty())) {
            return;
        }

        System.out.println(result.host());
        if (!result.openPorts().isEmpty()) {
            System.out.printf("\t (%d) open:\t%s%n", result.openPorts().cardinality(), map(result.openPorts(), result.bannerRecognition()));
        }
        if (showFilteredPorts && !result.filteredPorts().isEmpty()) {
            System.out.printf("\t (%d) filtered:\t%s%n", result.filteredPorts().cardinality(), map(result.filteredPorts()));
        }
        System.out.println();
        System.out.flush();
    }

    private static String map(BitSet ports) {
        return ports.stream().mapToObj(String::valueOf).collect(Collectors.joining(","));
    }

    private static String map(BitSet ports, java.util.HashMap<Integer, ServiceType> bannerRecognition) {
        return ports.stream().mapToObj(port -> {
            ServiceType serviceType = bannerRecognition.getOrDefault(port, ServiceType.UNKNOWN);

            if (serviceType == ServiceType.UNKNOWN) {
                return String.valueOf(port);
            }

            return port + "/" + serviceType.name().toLowerCase();
        }).collect(Collectors.joining(","));
    }

    private static int getColumnWidth() {
        try {
            Process process = new ProcessBuilder("sh", "-c", "stty size < /dev/tty").start();

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(process.getInputStream()))) {
                String line = reader.readLine();
                if (line != null && !line.isBlank()) {
                    Matcher matcher = Pattern.compile("^\\d+\\s+(\\d+)").matcher(line.trim());
                    if (matcher.matches()) {
                        return Integer.parseInt(matcher.group(1));
                    }
                }
            }
        } catch (Exception ignored) {
            // does not matter why it did not work
        }

        return 120;
    }

    public void start() {
        if (quiet) {
            return;
        }

        // although we don't print anything, we still need to
        // gc all the done hosts
        System.err.print("Scanning targets...\n\n");
        ui.scheduleAtFixedRate(() -> {
            synchronized (outputLock) {
                printStatusLine(scan);
            }
        }, 1, 1000, TimeUnit.MILLISECONDS);
    }

    public void stop() {
        ui.shutdownNow();
        try {
            ui.awaitTermination(1, TimeUnit.SECONDS);
        } catch (InterruptedException ignored) {
            Thread.currentThread().interrupt();
        }
        printStats();
    }

    private void printStats() {
        System.out.println("\n--------------------");
        System.out.println("Stats:");
        System.out.println("Total hosts scanned: " + scan.getHostTotalCounter().max());
        System.out.println("Peak concurrent connects: " + scan.getSocketCounter().max());
        System.out.println("Peak concurrent threads: " + scan.getThreadCounter().max());
        System.out.println("--------------------\n");
    }

    private void printStatusLine(final Scan scan) {
        this.printStatusLine(scan.getHostCounter(), scan.getHostTotalCounter(), scan.getSocketCounter(), scan.getThreadCounter());
    }

    private void printStatusLine(
            Counter hostCounter, Counter hostTotalCounter, Counter
                    socketCounter, Counter
                    threadCounter) {
        int total = hostTotalCounter.current();
        int running = hostCounter.current();
        int done = total - running;
        long percent = total == 0 ? 100 : done * 100L / total;

        String line = String.format(
                "hosts: %d running, %d done | sockets: %d active, %d peak | workers: %d active, %d peak",
                running,
                done,
                socketCounter.current(),
                socketCounter.max(),
                threadCounter.current(),
                threadCounter.max()
        );

        String barFormat = " | [%s] %3d%%";
        int barWidth = Math.max(5, ProgressBar.getColumnWidth() - line.length() - barFormat.length());
        String progressBar = progressBar(percent, barWidth);
        String status = line + String.format(barFormat, progressBar, percent);
        System.err.print("\r" + status);
        System.err.flush();
    }

    private static String progressBar(long percent, int width) {
        int filled = (int) (percent * width / 100);

        return "#".repeat(filled) + "-".repeat(width - filled);
    }
}