This repository was archived by the owner on Dec 1, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsniff.go
116 lines (97 loc) · 2.31 KB
/
sniff.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
110
111
112
113
114
115
116
package gonetmon
import (
"os"
"sync"
"time"
)
// log2File switches logging to be output to file only
func log2File() {
file, err := os.OpenFile(defLogFile, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0666)
if err == nil {
log.Out = file
} else {
log.Info("Failed to log to file, using default stderr")
}
}
// Sniff holds examples of initialising a session and manage different routines to perform monitoring
func Sniff(testWait *sync.WaitGroup, result chan<- error) error {
if testWait != nil {
defer testWait.Done()
}
// Initialise, and fail if conditions are not met
devices, err := InitialiseCapture()
if err != nil {
log.Errorf("Initialising capture failed : %s", err)
if result != nil {
result <- err
}
return err
}
// Past this point, log to file
log2File()
// IPCs
syn := &synchronisation{
wg: sync.WaitGroup{},
syncChan: make(chan struct{}),
nbReceivers: 0,
}
syn.addRoutine() // add this main process
packetChan := make(chan packetMsg, 1000)
reportChan := make(chan *report, 1)
alertChan := make(chan alertMsg, 1)
// Run Sniffer/Collector
syn.addRoutine()
go Collector(devices, packetChan, syn)
// Run monitoring
syn.addRoutine()
go Monitor(packetChan, reportChan, alertChan, syn)
// Run display to print result
syn.addRoutine()
go Display(reportChan, alertChan, syn)
// Run CLI
syn.addRoutine()
go CLI(syn)
log.Info("Capturing set up.")
// synchronisation and shutdown
syn.wg.Done()
<-syn.syncChan
log.Info("Waiting for all processes to stop.")
syn.wg.Wait()
log.Info("Monitoring successfully stopped.")
if result != nil {
result <- nil
}
return nil
}
// SnifferTest is a wrapper function for Sniffer use with a timeout
func SnifferTest(duration time.Duration) error {
testWait := sync.WaitGroup{}
testWait.Add(1)
result := make(chan error)
go Sniff(&testWait, result)
// Send interrupt signal after timeout
p, _ := os.FindProcess(os.Getpid())
var err error
loop:
for {
select {
case err = <-result:
if err != nil {
log.Error("Sniffing returned with an error.")
log.Error(err)
}
break loop
case <-time.After(duration):
_ = p.Signal(os.Interrupt)
res := <-result
if res != nil {
log.Error("Sniffing returned with an error.")
log.Error(res)
}
err = res
break loop
}
}
testWait.Wait()
return err
}