summaryrefslogtreecommitdiff
path: root/src/main/java/com/it_jaros/networkScanner/Scanner.java
blob: 53e1dcf677668f5eb5246d837837496f447d6f04 (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
package com.it_jaros.networkScanner;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.LockSupport;

public class Scanner {
                
    private final Counter counter = new Counter();
    private final ProgressBar progressBar = new ProgressBar();
    private final Semaphore socketLimit;
    private final int timeoutInMillis;
    private final long delayInNanos;
    
    public Scanner(int socketLimit, int timeoutInMillis, int delayInMillis) {
        this.timeoutInMillis = timeoutInMillis;
        this.delayInNanos = TimeUnit.MILLISECONDS.toNanos(Math.max(0, delayInMillis));
        this.socketLimit = new Semaphore(socketLimit);
    }

    public List<ScanResult> scan(ScanOptions target) {
        return scanTargets(target.targets(), target.ports());
    }

    public List<ScanResult> scanTargets(List<String> targets, String ports) {
        List<ScanResult> results = new ArrayList<>();
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();) {
            List<Progress> hosts = new ArrayList<>();
            for (String target : targets) {
                PortRange portRange = new PortRange(ports);
                Progress progress = new Progress(target, portRange.getTotal(), new AtomicInteger(),
                        new AtomicInteger());
                hosts.add(progress);
                results.add(scanTargetPorts(target, portRange, executor, progress));
            }
            progressBar.start(hosts);
        }

        progressBar.stop();
        System.out.println("Peak concurrent connects: " + counter.max());
        return results;
    }

    private ScanResult scanTargetPorts(String target, PortRange portRange, ExecutorService executor,
            Progress p) {
        AtomicLong scanSlotFactory = new AtomicLong(System.nanoTime());
        Queue<Integer> openPorts = new ConcurrentLinkedQueue<>();
        while (portRange.hasNext()) {
            final int currentPort = portRange.next();
            executor.submit(() -> {
                try {
                    waitForSlot(scanSlotFactory);
                    if (isTargetPortOpen(target, currentPort)) {
                        openPorts.add(currentPort);
                        progressBar.onPortOpen(p);
                    }
                } finally {
                    progressBar.onPortFinished(p);
                }
            });
        }
        return new ScanResult(target, openPorts);
    }

    private void waitForSlot(AtomicLong scanSlotFactory) {
        if (delayInNanos > 0) {
            long slot = scanSlotFactory.getAndAdd(delayInNanos);
            long wait = slot - System.nanoTime();
            if (wait > 0)
                LockSupport.parkNanos(wait);
        }
    }

    private boolean isTargetPortOpen(String target, int port) {
        socketLimit.acquireUninterruptibly();
        counter.inc();
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(target, port), timeoutInMillis);
            return true;
        } catch (SocketException | SocketTimeoutException ignored) {
        } catch (IOException e) {
            System.out.println(e.getClass().getSimpleName() + ": " + e.getMessage());
        } finally {
            counter.dec();
            socketLimit.release();
        }

        return false;
    }
}