-
Notifications
You must be signed in to change notification settings - Fork 14
/
discover.go
111 lines (102 loc) · 2.23 KB
/
discover.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
//
// Use and distribution licensed under the Apache license version 2.
//
// See the COPYING file in the root project directory for full text.
//
package pcidb
import (
"bufio"
"compress/gzip"
"io"
"net/http"
"os"
"path/filepath"
"strings"
)
const (
PCIIDS_URI = "https://pci-ids.ucw.cz/v2.2/pci.ids.gz"
USER_AGENT = "golang-jaypipes-pcidb"
)
func (db *PCIDB) load(ctx *context) error {
var foundPath string
for _, fp := range ctx.searchPaths {
if _, err := os.Stat(fp); err == nil {
foundPath = fp
break
}
}
if foundPath == "" {
if !ctx.enableNetworkFetch {
return ERR_NO_DB
}
// OK, so we didn't find any host-local copy of the pci-ids DB file. Let's
// try fetching it from the network and storing it
if err := cacheDBFile(ctx.cachePath); err != nil {
return err
}
foundPath = ctx.cachePath
}
f, err := os.Open(foundPath)
if err != nil {
return err
}
defer f.Close()
var scanner *bufio.Scanner
if strings.HasSuffix(foundPath, ".gz") {
var zipReader *gzip.Reader
if zipReader, err = gzip.NewReader(f); err != nil {
return err
}
defer zipReader.Close()
scanner = bufio.NewScanner(zipReader)
} else {
scanner = bufio.NewScanner(f)
}
return parseDBFile(db, scanner)
}
func ensureDir(fp string) error {
fpDir := filepath.Dir(fp)
if _, err := os.Stat(fpDir); os.IsNotExist(err) {
err = os.MkdirAll(fpDir, os.ModePerm)
if err != nil {
return err
}
}
return nil
}
// Pulls down the latest copy of the pci-ids file from the network and stores
// it in the local host filesystem
func cacheDBFile(cacheFilePath string) error {
ensureDir(cacheFilePath)
client := new(http.Client)
request, err := http.NewRequest("GET", PCIIDS_URI, nil)
if err != nil {
return err
}
request.Header.Set("User-Agent", USER_AGENT)
response, err := client.Do(request)
if err != nil {
return err
}
defer response.Body.Close()
f, err := os.Create(cacheFilePath)
if err != nil {
return err
}
defer func() {
if err != nil {
os.Remove(cacheFilePath)
}
}()
defer f.Close()
// write the gunzipped contents to our local cache file
zr, err := gzip.NewReader(response.Body)
if err != nil {
return err
}
defer zr.Close()
if _, err = io.Copy(f, zr); err != nil {
return err
}
return err
}