Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
projectdiscovery
GitHub Repository: projectdiscovery/nuclei
Path: blob/dev/pkg/scan/events/stats_build.go
2852 views
1
//go:build stats
2
3
package events
4
5
import (
6
"fmt"
7
"os"
8
"path/filepath"
9
"sync"
10
"time"
11
12
"github.com/projectdiscovery/nuclei/v3/pkg/utils/json"
13
)
14
15
var _ ScanEventWorker = &ScanStatsWorker{}
16
17
var defaultWorker = &ScanStatsWorker{}
18
19
// ScanStatsWorker is a worker for scanning stats
20
// This tracks basic stats in jsonlines format
21
// in given directory or a default directory with name stats_{timestamp} in the current directory
22
type ScanStatsWorker struct {
23
config *ScanConfig
24
m *sync.Mutex
25
directory string
26
file *os.File
27
enc json.Encoder
28
}
29
30
// Init initializes the scan stats worker
31
func InitWithConfig(config *ScanConfig, statsDirectory string) {
32
currentTime := time.Now().Format("20060102150405")
33
dirName := fmt.Sprintf("nuclei-stats-%s", currentTime)
34
err := os.Mkdir(dirName, 0755)
35
if err != nil {
36
panic(err)
37
}
38
// save the config to the directory
39
bin, err := json.MarshalIndent(config, "", " ")
40
if err != nil {
41
panic(err)
42
}
43
err = os.WriteFile(filepath.Join(dirName, ConfigFile), bin, 0755)
44
if err != nil {
45
panic(err)
46
}
47
defaultWorker = &ScanStatsWorker{config: config, m: &sync.Mutex{}, directory: dirName}
48
err = defaultWorker.initEventsFile()
49
if err != nil {
50
panic(err)
51
}
52
}
53
54
// initEventsFile initializes the events file for the worker
55
func (s *ScanStatsWorker) initEventsFile() error {
56
f, err := os.Create(filepath.Join(s.directory, EventsFile))
57
if err != nil {
58
return err
59
}
60
s.file = f
61
s.enc = json.NewEncoder(f)
62
return nil
63
}
64
65
// AddScanEvent adds a scan event to the worker
66
func (s *ScanStatsWorker) AddScanEvent(event ScanEvent) {
67
s.m.Lock()
68
defer s.m.Unlock()
69
70
err := s.enc.Encode(event)
71
if err != nil {
72
panic(err)
73
}
74
}
75
76
// AddScanEvent adds a scan event to the worker
77
func AddScanEvent(event ScanEvent) {
78
if defaultWorker == nil {
79
return
80
}
81
defaultWorker.AddScanEvent(event)
82
}
83
84
// Close closes the file associated with the worker
85
func (s *ScanStatsWorker) Close() {
86
s.m.Lock()
87
defer s.m.Unlock()
88
89
if s.file != nil {
90
_ = s.file.Close()
91
s.file = nil
92
}
93
}
94
95
// Close closes the file associated with the worker
96
func Close() {
97
if defaultWorker == nil {
98
return
99
}
100
defaultWorker.Close()
101
}
102
103