-
Notifications
You must be signed in to change notification settings - Fork 46
/
onrstack.go
109 lines (87 loc) · 2.35 KB
/
onrstack.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
105
106
107
108
109
package finscan
import (
"context"
uuid "github.com/google/uuid"
"github.com/pkg/errors"
"net"
"time"
)
type rstAckHandler func(ip net.IP, port int)
type noRspHandler func(ip net.IP, port int)
func (s *Scanner) onRstAck(ip net.IP, port int) {
s.rstAckHandlerMutex.Lock()
defer s.rstAckHandlerMutex.Unlock()
for _, handler := range s.rstAckHandlers {
handler(ip, port)
}
}
func (s *Scanner) onNoRsp(ip net.IP, port int) {
s.noRspHandlerMutex.Lock()
defer s.noRspHandlerMutex.Unlock()
for _, handler := range s.noRspHandlers {
handler(ip, port)
}
}
func (s *Scanner) RegisterRstAckHandler(tag string, handler rstAckHandler) error {
s.rstAckHandlerMutex.Lock()
defer s.rstAckHandlerMutex.Unlock()
_, ok := s.rstAckHandlers[tag]
if ok {
return errors.Errorf("existed handler for %v", tag)
}
s.rstAckHandlers[tag] = handler
return nil
}
func (s *Scanner) RegisterNoRspHandler(tag string, handler noRspHandler) error {
s.noRspHandlerMutex.Lock()
defer s.noRspHandlerMutex.Unlock()
_, ok := s.noRspHandlers[tag]
if ok {
return errors.Errorf("existed handler for %v", tag)
}
s.noRspHandlers[tag] = handler
return nil
}
func (s *Scanner) UnregisterRstAckHandler(tag string) {
s.rstAckHandlerMutex.Lock()
defer s.rstAckHandlerMutex.Unlock()
delete(s.rstAckHandlers, tag)
}
func (s *Scanner) UnregisterNoRspHandler(tag string) {
s.noRspHandlerMutex.Lock()
defer s.noRspHandlerMutex.Unlock()
delete(s.noRspHandlers, tag)
}
func (s *Scanner) waitOpenPort(ctx context.Context, handler rstAckHandler, async bool) error {
id := uuid.New()
err := s.RegisterRstAckHandler(id.String(), handler)
if err != nil {
return errors.Errorf("register failed: %s", err)
}
if async {
go func() {
select {
case <-ctx.Done():
s.UnregisterRstAckHandler(id.String())
return
}
}()
return nil
} else {
defer s.UnregisterRstAckHandler(id.String())
select {
case <-ctx.Done():
return nil
}
}
}
func (s *Scanner) WaitOpenPort(ctx context.Context, handler rstAckHandler) error {
return s.waitOpenPort(ctx, handler, false)
}
func (s *Scanner) WaitOpenPortAsync(ctx context.Context, handler rstAckHandler) error {
return s.waitOpenPort(ctx, handler, true)
}
func (s *Scanner) WaitOpenPortWithTimeout(timeout time.Duration, handler rstAckHandler) error {
ctx, _ := context.WithTimeout(s.ctx, timeout)
return s.WaitOpenPort(ctx, handler)
}