-
Notifications
You must be signed in to change notification settings - Fork 18
/
engine.go
104 lines (96 loc) · 2.35 KB
/
engine.go
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
package engine
import (
"context"
"fmt"
"net/netip"
"strings"
"time"
"github.com/bepass-org/ipscanner/internal/iterator"
"github.com/bepass-org/ipscanner/internal/ping"
"github.com/bepass-org/ipscanner/internal/statute"
)
type Engine struct {
generator *iterator.IpGenerator
ipQueue *IPQueue
ctx context.Context
cancelFunc context.CancelFunc
ping func(netip.Addr) (int, error)
statute.Logger
}
func NewScannerEngine(opts *statute.ScannerOptions, ctx ...context.Context) *Engine {
queue := NewIPQueue(opts)
var contextToUse context.Context
var cancel context.CancelFunc
if len(ctx) > 0 {
contextToUse = ctx[0]
} else {
contextToUse, cancel = context.WithCancel(context.Background())
}
p := ping.Ping{
Options: opts,
}
return &Engine{
ipQueue: queue,
ctx: contextToUse,
cancelFunc: cancel,
ping: p.DoPing,
generator: iterator.NewIterator(opts),
Logger: opts.Logger,
}
}
func (e *Engine) GetAvailableIPs(desc bool) []netip.Addr {
if e.ipQueue != nil {
return e.ipQueue.AvailableIPs(desc)
}
return nil
}
func (e *Engine) Run() {
for {
select {
case <-e.ctx.Done():
fmt.Println("Context Done!")
return
case <-e.ipQueue.available:
e.Logger.Debug("New Scanning Round Started")
batch, err := e.generator.NextBatch()
if err != nil {
e.Logger.Error("Error while generating IP: %v", err)
// in case of disastrous error, to prevent resource draining wait for 2 seconds and try again
time.Sleep(2 * time.Second)
continue
}
for _, ip := range batch {
select {
case <-e.ctx.Done():
fmt.Println("Context Done!")
return
default:
e.Logger.Debug("Pinging IP: %s", ip)
if rtt, err := e.ping(ip); err == nil {
ipInfo := statute.IPInfo{
IP: ip,
RTT: rtt,
CreatedAt: time.Now(),
}
e.Logger.Debug("IP: %s, RTT: %d", ip, rtt)
e.ipQueue.Enqueue(ipInfo)
} else if err != nil {
// if timeout error
if strings.Contains(err.Error(), ": i/o timeout") {
e.Logger.Debug("Timeout Error: %s", ip)
continue
}
e.Logger.Error("Error while pinging IP: %s, Error: %v", ip, err)
}
}
}
default:
e.Logger.Debug("Engine: call the expire function")
e.ipQueue.Expire()
time.Sleep(200 * time.Millisecond)
}
}
}
func (e *Engine) Cancel() {
e.cancelFunc()
}