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