-
Notifications
You must be signed in to change notification settings - Fork 122
Expand file tree
/
Copy pathutils.go
More file actions
240 lines (211 loc) · 5.21 KB
/
utils.go
File metadata and controls
240 lines (211 loc) · 5.21 KB
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package utils
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"log"
"math"
"math/big"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
pb "github.com/cheggaaa/pb/v3"
"github.com/parnurzeal/gorequest"
"golang.org/x/xerrors"
)
var vulnListDir = filepath.Join(CacheDir(), "vuln-list")
func CacheDir() string {
cacheDir, err := os.UserCacheDir()
if err != nil {
cacheDir = os.TempDir()
}
dir := filepath.Join(cacheDir, "vuln-list-update")
return dir
}
func SetVulnListDir(dir string) {
vulnListDir = dir
}
func VulnListDir() string {
return vulnListDir
}
func SaveCVEPerYear(dirPath string, cveID string, data interface{}) error {
s := strings.Split(cveID, "-")
if len(s) != 3 {
return xerrors.Errorf("invalid CVE-ID format: %s\n", cveID)
}
yearDir := filepath.Join(dirPath, s[1])
if err := os.MkdirAll(yearDir, os.ModePerm); err != nil {
return err
}
filePath := filepath.Join(yearDir, fmt.Sprintf("%s.json", cveID))
if err := Write(filePath, data); err != nil {
return xerrors.Errorf("failed to write file: %w", err)
}
return nil
}
func Write(filePath string, data interface{}) error {
dir := filepath.Dir(filePath)
if err := os.MkdirAll(dir, os.ModePerm); err != nil {
return xerrors.Errorf("failed to create %s: %w", dir, err)
}
f, err := os.Create(filePath)
if err != nil {
return xerrors.Errorf("file create error: %w", err)
}
defer f.Close()
b, err := json.MarshalIndent(data, "", " ")
if err != nil {
return xerrors.Errorf("JSON marshal error: %w", err)
}
_, err = f.Write(b)
if err != nil {
return xerrors.Errorf("file write error: %w", err)
}
return nil
}
// GenWorkers generate workders
func GenWorkers(num, wait int) chan<- func() {
tasks := make(chan func())
for i := 0; i < num; i++ {
go func() {
for f := range tasks {
f()
time.Sleep(time.Duration(wait) * time.Second)
}
}()
}
return tasks
}
// DeleteNil deletes nil in errs
func DeleteNil(errs []error) (new []error) {
for _, err := range errs {
if err != nil {
new = append(new, err)
}
}
return new
}
// TrimSpaceNewline deletes space character and newline character(CR/LF)
func TrimSpaceNewline(str string) string {
str = strings.TrimSpace(str)
return strings.Trim(str, "\r\n")
}
// FetchURL returns HTTP response body with retry
func FetchURL(url, apikey string, retry int) (res []byte, err error) {
for i := 0; i <= retry; i++ {
if i > 0 {
wait := math.Pow(float64(i), 2) + float64(RandInt()%10)
log.Printf("retry after %f seconds\n", wait)
time.Sleep(time.Duration(time.Duration(wait) * time.Second))
}
res, err = fetchURL(url, map[string]string{"api-key": apikey})
if err == nil {
return res, nil
}
}
return nil, xerrors.Errorf("failed to fetch URL: %w", err)
}
func RandInt() int {
seed, _ := rand.Int(rand.Reader, big.NewInt(math.MaxInt64))
return int(seed.Int64())
}
func fetchURL(url string, headers map[string]string) ([]byte, error) {
req := gorequest.New().Get(url)
for key, value := range headers {
req.Header.Add(key, value)
}
resp, body, errs := req.Type("text").EndBytes()
if len(errs) > 0 {
return nil, xerrors.Errorf("HTTP error. url: %s, err: %w", url, errs[0])
}
if resp.StatusCode != 200 {
return nil, xerrors.Errorf("HTTP error. status code: %d, url: %s", resp.StatusCode, url)
}
return body, nil
}
// FetchConcurrently fetches concurrently
func FetchConcurrently(urls []string, concurrency, wait, retry int) (responses [][]byte, err error) {
reqChan := make(chan string, len(urls))
resChan := make(chan []byte, len(urls))
errChan := make(chan error, len(urls))
defer close(reqChan)
defer close(resChan)
defer close(errChan)
go func() {
for _, url := range urls {
reqChan <- url
}
}()
bar := pb.StartNew(len(urls))
tasks := GenWorkers(concurrency, wait)
for range urls {
tasks <- func() {
url := <-reqChan
res, err := FetchURL(url, "", retry)
if err != nil {
errChan <- err
return
}
resChan <- res
}
bar.Increment()
}
bar.Finish()
var errs []error
timeout := time.After(10 * 60 * time.Second)
for range urls {
select {
case res := <-resChan:
responses = append(responses, res)
case err := <-errChan:
errs = append(errs, err)
case <-timeout:
return nil, xerrors.New("Timeout Fetching URL")
}
}
if 0 < len(errs) {
return responses, fmt.Errorf("%s", errs)
}
return responses, nil
}
// Major returns major version
func Major(osVer string) (majorVersion string) {
return strings.Split(osVer, ".")[0]
}
func IsCommandAvailable(name string) bool {
cmd := exec.Command(name, "--help")
if err := cmd.Run(); err != nil {
return false
}
return true
}
func Exists(path string) (bool, error) {
_, err := os.Stat(path)
if err == nil {
return true, nil
}
if os.IsNotExist(err) {
return false, nil
}
return true, err
}
func Exec(command string, args []string) (string, error) {
cmd := exec.Command(command, args...)
var stdoutBuf, stderrBuf bytes.Buffer
cmd.Stdout = &stdoutBuf
cmd.Stderr = &stderrBuf
if err := cmd.Run(); err != nil {
log.Println(stderrBuf.String())
return "", xerrors.Errorf("failed to exec: %w", err)
}
return stdoutBuf.String(), nil
}
func LookupEnv(key, defaultValue string) string {
if val, ok := os.LookupEnv(key); ok {
return val
}
return defaultValue
}